72 lines
2.0 KiB
Dart
72 lines
2.0 KiB
Dart
import 'dart:async';
|
|
import 'dart:js_interop';
|
|
|
|
import 'package:web/web.dart' as web;
|
|
|
|
import 'chat_attachment_picker.dart';
|
|
|
|
/// The web file picker: one explicit pick action creates the host's native
|
|
/// file input, opens it and reads the files the operator chose.
|
|
///
|
|
/// The input is `multiple` and has no `accept` filter, matching the web
|
|
/// composer's attach control. Only a selection or a cancel completes the
|
|
/// future; a document without a body has nothing to open and yields null.
|
|
ChatAttachmentPicker get hostChatAttachmentPicker =>
|
|
const ChatAttachmentPicker(select: _selectFiles);
|
|
|
|
Future<List<ChatPickedFile>?> _selectFiles() {
|
|
final input = web.HTMLInputElement()
|
|
..type = 'file'
|
|
..multiple = true;
|
|
input.style.display = 'none';
|
|
|
|
final completer = Completer<List<ChatPickedFile>?>();
|
|
|
|
void finish(List<ChatPickedFile>? files) {
|
|
if (completer.isCompleted) return;
|
|
input.remove();
|
|
completer.complete(files);
|
|
}
|
|
|
|
Future<void> readSelection() async {
|
|
final selected = input.files;
|
|
if (selected == null || selected.length == 0) {
|
|
finish(null);
|
|
return;
|
|
}
|
|
try {
|
|
final files = <ChatPickedFile>[];
|
|
for (var index = 0; index < selected.length; index += 1) {
|
|
final file = selected.item(index);
|
|
if (file == null) continue;
|
|
final buffer = await file.arrayBuffer().toDart;
|
|
files.add(
|
|
ChatPickedFile(
|
|
name: file.name,
|
|
mime: file.type,
|
|
bytes: buffer.toDart.asUint8List(),
|
|
),
|
|
);
|
|
}
|
|
finish(files);
|
|
} catch (error, stackTrace) {
|
|
if (completer.isCompleted) return;
|
|
input.remove();
|
|
completer.completeError(error, stackTrace);
|
|
}
|
|
}
|
|
|
|
input.addEventListener('change', ((web.Event _) {
|
|
unawaited(readSelection());
|
|
}).toJS);
|
|
input.addEventListener('cancel', ((web.Event _) {
|
|
finish(null);
|
|
}).toJS);
|
|
|
|
final body = web.document.body;
|
|
if (body == null) return Future.value(null);
|
|
body.appendChild(input);
|
|
input.click();
|
|
return completer.future;
|
|
}
|