import 'dart:async'; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'artifact_file.dart'; import 'artifact_transfer.dart'; /// Web file actions: the artifact's bytes become a named `Blob`/`File`. /// /// Download creates an object url and clicks a native anchor with the recorded /// name; share passes a real `File` to `navigator.share`. Neither path ever /// substitutes the artifact url or opens a blob page. No package:web import is /// used, so the same source compiles for JavaScript and WebAssembly. @JS('document') external _Document get _document; @JS('navigator') external _Navigator get _navigator; @JS('URL.createObjectURL') external JSString _createObjectUrl(JSObject blob); @JS('URL.revokeObjectURL') external void _revokeObjectUrl(JSString url); extension type _Document._(JSObject _) implements JSObject { external _Anchor createElement(JSString tag); external _Element get body; } extension type _Anchor._(JSObject _) implements JSObject { external set href(JSString value); external set download(JSString value); external void click(); external void remove(); } extension type _Element._(JSObject _) implements JSObject { external void appendChild(JSObject node); } extension type _BlobOptions._(JSObject _) implements JSObject { external factory _BlobOptions({JSString type}); } @JS('Blob') extension type _Blob._(JSObject _) implements JSObject { external factory _Blob(JSArray parts, _BlobOptions options); } extension type _FileOptions._(JSObject _) implements JSObject { external factory _FileOptions({JSString type}); } @JS('File') extension type _File._(JSObject _) implements JSObject { external factory _File( JSArray parts, JSString name, _FileOptions options, ); } extension type _ShareData._(JSObject _) implements JSObject { external factory _ShareData({JSArray files}); } extension type _UserActivation._(JSObject _) implements JSObject { external bool get isActive; } extension type _Navigator._(JSObject _) implements JSObject { external JSPromise share(_ShareData data); external bool canShare(_ShareData data); external _UserActivation? get userActivation; } bool get artifactDownloadSupported => true; bool get artifactShareSupported => _hasFunction('share') && _hasFunction('canShare'); String get artifactDownloadUnsupportedMessage => 'Downloading files is not supported in this browser.'; String get artifactShareUnsupportedMessage => 'File sharing is not supported in this browser. Use Download to save the file.'; const String _fileReadyMessage = 'File ready. Tap Share again to choose where to send it.'; Future saveArtifactFile(ArtifactFile file) async { try { final blob = _blobFor(file); final url = _createObjectUrl(blob); final anchor = _document.createElement('a'.toJS) ..href = url ..download = file.name.toJS; _document.body.appendChild(anchor); try { anchor.click(); } finally { anchor.remove(); // Revoking immediately can cancel a download in some browsers. unawaited( Future.delayed( const Duration(seconds: 1), () => _revokeObjectUrl(url), ), ); } return ArtifactTransferResult( ArtifactTransferState.saved, 'Downloaded ${file.name}.', ); } catch (_) { return const ArtifactTransferResult( ArtifactTransferState.failed, 'Could not download the file. Try again.', ); } } Future shareArtifactFile(ArtifactFile file) async { if (!artifactShareSupported) { return ArtifactTransferResult( ArtifactTransferState.unsupported, artifactShareUnsupportedMessage, ); } final data = _ShareData(files: [_fileFor(file)].toJS); try { if (!_navigator.canShare(data)) { return ArtifactTransferResult( ArtifactTransferState.unsupported, 'This browser cannot share this file type. Use Download to save the file.', ); } } catch (_) { return ArtifactTransferResult( ArtifactTransferState.unsupported, artifactShareUnsupportedMessage, ); } // Fetching may outlast the browser's transient activation. Do not attempt a // doomed share or substitute a url: the prepared bytes stay cached in the // controller and the next tap shares them. final activation = _navigator.userActivation; if (activation != null && !activation.isActive) { return const ArtifactTransferResult( ArtifactTransferState.ready, _fileReadyMessage, ); } try { await _navigator.share(data).toDart; return const ArtifactTransferResult( ArtifactTransferState.shared, 'File shared.', ); } catch (error) { final name = _errorName(error); if (name == 'AbortError') { return const ArtifactTransferResult( ArtifactTransferState.canceled, 'Sharing canceled.', ); } if (name == 'NotAllowedError') { return const ArtifactTransferResult( ArtifactTransferState.blocked, 'Sharing was blocked. Tap Share again, or use Download to save the file.', ); } return const ArtifactTransferResult( ArtifactTransferState.failed, 'Could not share the file. Use Download to save it, or try Share again.', ); } } _Blob _blobFor(ArtifactFile file) => _Blob( [file.bytes.toJS].toJS, _BlobOptions(type: file.mimeType.toJS), ); _File _fileFor(ArtifactFile file) => _File( [_blobFor(file)].toJS, file.name.toJS, _FileOptions(type: file.mimeType.toJS), ); bool _hasFunction(String name) { final value = _navigator.getProperty(name.toJS); return value != null && value.isA(); } String? _errorName(Object error) { // A rejected JS promise arrives as a Dart error whose text carries the DOM // exception name; the web's AbortError/NotAllowedError branches use those. final text = '$error'; for (final candidate in const ['AbortError', 'NotAllowedError']) { if (text.contains(candidate)) return candidate; } return null; }