Files
pipelines/app/lib/ui/theme/custom_fonts/font_file_picker.dart
T
alan 081ae0957d Add font: own web file chooser, so a picked font is never dropped silently
file_picker's web picker treated the window regaining focus as a cancel when
the files arrived more than 500 ms later, so a real dialog could return an
empty pick and Add font did nothing. The web now uses its own file input that
completes only on change or cancel; mobile browsers get no accept filter.
Picker, check and save failures are shown in a dialog, and the row is busy
only after files were chosen.
2026-11-04 20:47:43 +00:00

57 lines
1.9 KiB
Dart

import 'dart:typed_data';
import 'custom_font_draft.dart';
export 'font_file_picker_native.dart'
if (dart.library.js_interop) 'font_file_picker_web.dart'
show pickFontFiles;
/// Opens the host's file picker for font files; null when the user cancels.
/// Throws [CustomFontRejected] when a chosen file cannot be used as picked
/// (too large, unreadable); any other error means the picker itself failed.
typedef FontFilePicker = Future<List<PickedFontFile>?> Function();
/// One file the host picker returned, before its bytes are read.
class FontFileSource {
const FontFileSource({required this.name, required this.read, this.size});
final String name;
/// The size the host reports, if any; checked before [read].
final int? size;
/// Reads the file; null when the host could not provide its content.
final Future<Uint8List?> Function() read;
}
/// Turns a picker's selection into [PickedFontFile]s. An empty selection is
/// a cancel (null). A file over [CustomFontLimits.maxFileBytes] is refused
/// before it is read; a file whose bytes cannot be read is refused by name.
/// Whether each file is a font is [CustomFontDraft.inspect]'s job.
Future<List<PickedFontFile>?> readFontSelection(
List<FontFileSource> selection,
) async {
if (selection.isEmpty) return null;
final files = <PickedFontFile>[];
for (final source in selection) {
final size = source.size;
if (size != null && size > CustomFontLimits.maxFileBytes) {
throw CustomFontRejected(
'“${source.name}” is larger than '
'${CustomFontLimits.maxFileBytes ~/ (1024 * 1024)} MB.',
);
}
final Uint8List? bytes;
try {
bytes = await source.read();
} catch (_) {
throw CustomFontRejected('“${source.name}” could not be read.');
}
if (bytes == null) {
throw CustomFontRejected('“${source.name}” could not be read.');
}
files.add(PickedFontFile(name: source.name, bytes: bytes));
}
return files;
}