feat(app): download and share artifacts as named files
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../domain/artifact_record.dart';
|
||||
|
||||
/// A recorded artifact's exact bytes, named and typed as the host must save or
|
||||
/// share them.
|
||||
///
|
||||
/// The name is the recorded file name's basename, never a url or a directory
|
||||
/// path. The MIME type is the recorded media type without parameters. Only when
|
||||
/// the recorded value is missing or malformed does the fallback apply: the
|
||||
/// server url's basename, then `artifact`, and `application/octet-stream`.
|
||||
class ArtifactFile {
|
||||
const ArtifactFile({
|
||||
required this.name,
|
||||
required this.mimeType,
|
||||
required this.bytes,
|
||||
});
|
||||
|
||||
final String name;
|
||||
final String mimeType;
|
||||
final Uint8List bytes;
|
||||
|
||||
int get byteLength => bytes.length;
|
||||
}
|
||||
|
||||
const String artifactFileFallbackName = 'artifact';
|
||||
const String artifactFileFallbackMimeType = 'application/octet-stream';
|
||||
|
||||
/// Names and types one recorded artifact's fetched bytes for a file transfer.
|
||||
ArtifactFile artifactFileFor({
|
||||
required ArtifactRecord artifact,
|
||||
required Uri url,
|
||||
required Uint8List bytes,
|
||||
}) => ArtifactFile(
|
||||
name: artifactFileName(artifact, url),
|
||||
mimeType: artifactFileMimeType(artifact),
|
||||
bytes: bytes,
|
||||
);
|
||||
|
||||
/// The recorded name without any `public/` prefix or directory component, with
|
||||
/// control characters replaced. An absent, dot-only or unusable name falls
|
||||
/// back to the resolved url's last path segment and then to `artifact`.
|
||||
String artifactFileName(ArtifactRecord artifact, Uri url) {
|
||||
final recorded = _usableBasename(artifact.name);
|
||||
if (recorded.isNotEmpty) return recorded;
|
||||
final fromUrl = _usableBasename(
|
||||
url.pathSegments.isEmpty ? '' : url.pathSegments.last,
|
||||
);
|
||||
return fromUrl.isEmpty ? artifactFileFallbackName : fromUrl;
|
||||
}
|
||||
|
||||
/// The recorded MIME type without parameters, lowercased, or
|
||||
/// `application/octet-stream` when nothing usable was recorded.
|
||||
String artifactFileMimeType(ArtifactRecord artifact) {
|
||||
final mediaType = artifact.contentType.split(';').first.trim().toLowerCase();
|
||||
return _mediaType.hasMatch(mediaType)
|
||||
? mediaType
|
||||
: artifactFileFallbackMimeType;
|
||||
}
|
||||
|
||||
final RegExp _mediaType = RegExp(
|
||||
r"^[a-z0-9!#$&'*+.^_`|~-]+/[a-z0-9!#$&'*+.^_`|~-]+$",
|
||||
);
|
||||
|
||||
/// Whether the record carries a usable file name of its own.
|
||||
bool hasRecordedArtifactName(ArtifactRecord artifact) =>
|
||||
_usableBasename(artifact.name).isNotEmpty;
|
||||
|
||||
/// Whether the record carries a usable MIME type of its own.
|
||||
bool hasRecordedArtifactMimeType(ArtifactRecord artifact) {
|
||||
final mediaType = artifact.contentType.split(';').first.trim().toLowerCase();
|
||||
return _mediaType.hasMatch(mediaType);
|
||||
}
|
||||
|
||||
/// An explicit note when the recorded name or MIME type cannot be used, so the
|
||||
/// fallback file name/type is never silent. Null for a complete record.
|
||||
String? artifactFileRecordingNotice(ArtifactRecord artifact, Uri url) {
|
||||
final nameMissing = !hasRecordedArtifactName(artifact);
|
||||
final typeMissing = !hasRecordedArtifactMimeType(artifact);
|
||||
if (!nameMissing && !typeMissing) return null;
|
||||
final name = artifactFileName(artifact, url);
|
||||
if (nameMissing && typeMissing) {
|
||||
return 'No usable recorded name or MIME type; the file is saved as '
|
||||
'$name ($artifactFileFallbackMimeType).';
|
||||
}
|
||||
if (nameMissing) {
|
||||
return 'No usable recorded name; the file is saved as $name.';
|
||||
}
|
||||
return 'No usable recorded MIME type; the file is saved as '
|
||||
'$artifactFileFallbackMimeType.';
|
||||
}
|
||||
|
||||
String _usableBasename(String value) {
|
||||
final segments = value.trim().split(RegExp(r'[\\/]'));
|
||||
final name = segments.isEmpty ? '' : segments.last;
|
||||
final cleaned = name.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), '_').trim();
|
||||
if (cleaned == '.' || cleaned == '..') return '';
|
||||
return cleaned;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../domain/artifact_record.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../ui/artifact_viewer_fetch.dart';
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_file_bridge.dart';
|
||||
import 'artifact_file_controller.dart';
|
||||
|
||||
/// Download and Share for one selected artifact, backed by its exact bytes.
|
||||
///
|
||||
/// The controls are standard native buttons. Download creates a named file;
|
||||
/// Share passes a named file to the host share sheet and never falls back to
|
||||
/// the artifact url. A host without a capability shows a disabled control and
|
||||
/// the exact reason, while the other action keeps working. One tap starts at
|
||||
/// most one transfer; a slow fetch shows progress and can be cancelled.
|
||||
class ArtifactFileActions extends StatefulWidget {
|
||||
const ArtifactFileActions({
|
||||
super.key,
|
||||
required this.artifact,
|
||||
required this.resolved,
|
||||
this.fetch = fetchArtifact,
|
||||
this.bridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final ResolvedArtifactUrl resolved;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge bridge;
|
||||
|
||||
@override
|
||||
State<ArtifactFileActions> createState() => _ArtifactFileActionsState();
|
||||
}
|
||||
|
||||
class _ArtifactFileActionsState extends State<ArtifactFileActions> {
|
||||
late ArtifactFileActionsController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = _create();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ArtifactFileActions oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.resolved.url != widget.resolved.url ||
|
||||
oldWidget.artifact.url != widget.artifact.url ||
|
||||
oldWidget.artifact.name != widget.artifact.name ||
|
||||
oldWidget.artifact.contentType != widget.artifact.contentType ||
|
||||
oldWidget.fetch != widget.fetch ||
|
||||
oldWidget.bridge != widget.bridge) {
|
||||
_controller.dispose();
|
||||
_controller = _create();
|
||||
}
|
||||
}
|
||||
|
||||
ArtifactFileActionsController _create() => ArtifactFileActionsController(
|
||||
artifact: widget.artifact,
|
||||
resolved: widget.resolved,
|
||||
fetch: widget.fetch,
|
||||
bridge: widget.bridge,
|
||||
);
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: _controller,
|
||||
builder: (context, _) => _ActionBar(
|
||||
controller: _controller,
|
||||
cupertino: usesCupertinoHost(context),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ActionBar extends StatelessWidget {
|
||||
const _ActionBar({required this.controller, required this.cupertino});
|
||||
|
||||
final ArtifactFileActionsController controller;
|
||||
final bool cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final status = controller.status;
|
||||
final notice = artifactFileRecordingNotice(
|
||||
controller.artifact,
|
||||
controller.resolved.uri,
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
_button(
|
||||
label: 'Download',
|
||||
icon: Icons.download_outlined,
|
||||
onPressed: controller.canDownload && !controller.busy
|
||||
? controller.download
|
||||
: null,
|
||||
),
|
||||
_button(
|
||||
label: 'Share',
|
||||
icon: Icons.ios_share,
|
||||
onPressed: controller.canShare && !controller.busy
|
||||
? controller.share
|
||||
: null,
|
||||
),
|
||||
if (controller.canCancel)
|
||||
_button(
|
||||
label: 'Cancel',
|
||||
icon: Icons.close,
|
||||
onPressed: controller.cancel,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (controller.busy && status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
container: true,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (cupertino)
|
||||
const CupertinoActivityIndicator(radius: 8)
|
||||
else
|
||||
const SizedBox(
|
||||
width: 14,
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Flexible(child: Text(status)),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Semantics(liveRegion: true, child: Text(status)),
|
||||
),
|
||||
if (!controller.canDownload)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(controller.bridge.downloadUnavailableMessage),
|
||||
),
|
||||
if (!controller.canShare)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(controller.bridge.shareUnavailableMessage),
|
||||
),
|
||||
if (notice != null)
|
||||
Padding(padding: const EdgeInsets.only(top: 6), child: Text(notice)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button({
|
||||
required String label,
|
||||
required IconData icon,
|
||||
required VoidCallback? onPressed,
|
||||
}) {
|
||||
if (cupertino) {
|
||||
return CupertinoButton(onPressed: onPressed, child: Text(label));
|
||||
}
|
||||
return TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, size: 18),
|
||||
label: Text(label),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// The host file capabilities one action row uses.
|
||||
///
|
||||
/// The defaults are the real conditional-import bridge: a web Blob/anchor
|
||||
/// download plus `navigator.share`, and honest `unsupported` results on native
|
||||
/// hosts until a platform launcher exists. Tests inject both functions and the
|
||||
/// capability flags without touching a browser.
|
||||
class ArtifactFileBridge {
|
||||
const ArtifactFileBridge({
|
||||
this.download,
|
||||
this.share,
|
||||
this.downloadSupported,
|
||||
this.shareSupported,
|
||||
this.downloadUnsupportedMessage,
|
||||
this.shareUnsupportedMessage,
|
||||
});
|
||||
|
||||
final ArtifactSaveFile? download;
|
||||
final ArtifactShareFile? share;
|
||||
final bool? downloadSupported;
|
||||
final bool? shareSupported;
|
||||
final String? downloadUnsupportedMessage;
|
||||
final String? shareUnsupportedMessage;
|
||||
|
||||
bool get canDownload => downloadSupported ?? artifactDownloadSupported;
|
||||
|
||||
bool get canShare => shareSupported ?? artifactShareSupported;
|
||||
|
||||
String get downloadUnavailableMessage =>
|
||||
downloadUnsupportedMessage ?? artifactDownloadUnsupportedMessage;
|
||||
|
||||
String get shareUnavailableMessage =>
|
||||
shareUnsupportedMessage ?? artifactShareUnsupportedMessage;
|
||||
|
||||
Future<ArtifactTransferResult> saveFile(ArtifactFile file) =>
|
||||
(download ?? saveArtifactFile)(file);
|
||||
|
||||
Future<ArtifactTransferResult> shareFile(ArtifactFile file) =>
|
||||
(share ?? shareArtifactFile)(file);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../domain/artifact_record.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../ui/artifact_viewer_fetch.dart';
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_file_bridge.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// Which host file action is currently in flight.
|
||||
enum ArtifactFileAction { download, share }
|
||||
|
||||
/// The words shown while bytes are being fetched.
|
||||
const String artifactPreparingFile = 'Preparing file…';
|
||||
|
||||
/// Saves or shares one selected artifact's fetched bytes.
|
||||
///
|
||||
/// The controller owns exactly one transfer at a time: a tap while [busy] is
|
||||
/// ignored, so a double tap cannot start two fetches or two share sheets. The
|
||||
/// same fetch seam the viewer uses obtains the bytes, so the same-origin
|
||||
/// credential policy and HTTP status handling apply. Fetched bytes are kept
|
||||
/// after a ready/blocked/canceled share so the next tap can retry with a fresh
|
||||
/// user activation without another transfer.
|
||||
///
|
||||
/// Cancelling stops the action from continuing: a late fetch result is ignored
|
||||
/// by generation, and the host transfer is never started. The underlying HTTP
|
||||
/// request is not aborted because the shared fetch seam has no cancellation
|
||||
/// token; the app never reports those bytes as a completed transfer.
|
||||
class ArtifactFileActionsController extends ChangeNotifier {
|
||||
ArtifactFileActionsController({
|
||||
required this.artifact,
|
||||
required this.resolved,
|
||||
required this.fetch,
|
||||
this.bridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final ArtifactRecord artifact;
|
||||
final ResolvedArtifactUrl resolved;
|
||||
final ArtifactFileBridge bridge;
|
||||
|
||||
final ArtifactFetch fetch;
|
||||
ArtifactFile? _prepared;
|
||||
String? _preparedUrl;
|
||||
ArtifactFileAction? _active;
|
||||
bool _preparing = false;
|
||||
int _generation = 0;
|
||||
bool _disposed = false;
|
||||
String? _status;
|
||||
|
||||
String? get status => _status;
|
||||
|
||||
bool get busy => _active != null;
|
||||
|
||||
/// Cancel is offered only while the fetch is still running; once the host
|
||||
/// share sheet is open the OS owns the transfer.
|
||||
bool get canCancel => _active != null && _preparing;
|
||||
|
||||
bool get canDownload => bridge.canDownload;
|
||||
|
||||
bool get canShare => bridge.canShare;
|
||||
|
||||
Future<void> download() async {
|
||||
if (busy) return;
|
||||
if (!canDownload) {
|
||||
_setStatus(bridge.downloadUnavailableMessage);
|
||||
return;
|
||||
}
|
||||
final generation = _begin(ArtifactFileAction.download);
|
||||
final file = await _prepare(generation);
|
||||
if (file == null || generation != _generation) return;
|
||||
_preparing = false;
|
||||
_notify();
|
||||
ArtifactTransferResult result;
|
||||
try {
|
||||
result = await bridge.saveFile(file);
|
||||
} catch (_) {
|
||||
_fail(generation, 'Could not download the file. Try again.');
|
||||
return;
|
||||
}
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_status = result.state == ArtifactTransferState.saved
|
||||
? 'Downloaded ${file.name}.'
|
||||
: result.message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
Future<void> share() async {
|
||||
if (busy) return;
|
||||
if (!canShare) {
|
||||
_setStatus(bridge.shareUnavailableMessage);
|
||||
return;
|
||||
}
|
||||
final generation = _begin(ArtifactFileAction.share);
|
||||
final file = await _prepare(generation);
|
||||
if (file == null || generation != _generation) return;
|
||||
_preparing = false;
|
||||
_notify();
|
||||
ArtifactTransferResult result;
|
||||
try {
|
||||
result = await bridge.shareFile(file);
|
||||
} catch (_) {
|
||||
_fail(
|
||||
generation,
|
||||
'Could not share the file. Use Download to save it, or try Share again.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_status = result.state == ArtifactTransferState.shared
|
||||
? 'File shared.'
|
||||
: result.message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Stops waiting for the fetch. Nothing is handed to the host afterwards.
|
||||
void cancel() {
|
||||
if (!canCancel) return;
|
||||
final action = _active;
|
||||
_generation += 1;
|
||||
_active = null;
|
||||
_preparing = false;
|
||||
_status = action == ArtifactFileAction.share
|
||||
? 'Sharing canceled.'
|
||||
: 'Download canceled.';
|
||||
_notify();
|
||||
}
|
||||
|
||||
int _begin(ArtifactFileAction action) {
|
||||
final generation = ++_generation;
|
||||
_active = action;
|
||||
_preparing = true;
|
||||
_status = artifactPreparingFile;
|
||||
_notify();
|
||||
return generation;
|
||||
}
|
||||
|
||||
Future<ArtifactFile?> _prepare(int generation) async {
|
||||
final cached = _prepared;
|
||||
if (cached != null && _preparedUrl == resolved.url) {
|
||||
_preparing = false;
|
||||
_notify();
|
||||
return cached;
|
||||
}
|
||||
try {
|
||||
final fetched = await fetch(resolved.uri);
|
||||
if (generation != _generation) return null;
|
||||
if (!fetched.ok) {
|
||||
_fail(
|
||||
generation,
|
||||
'Could not fetch the artifact (HTTP ${fetched.status}).',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
final file = artifactFileFor(
|
||||
artifact: artifact,
|
||||
url: resolved.uri,
|
||||
bytes: fetched.bytes,
|
||||
);
|
||||
_prepared = file;
|
||||
_preparedUrl = resolved.url;
|
||||
return file;
|
||||
} on ArtifactFetchException catch (error) {
|
||||
_fail(generation, 'Could not fetch the artifact: ${error.message}');
|
||||
return null;
|
||||
} catch (error) {
|
||||
_fail(generation, 'Could not fetch the artifact: $error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _fail(int generation, String message) {
|
||||
if (generation != _generation) return;
|
||||
_active = null;
|
||||
_preparing = false;
|
||||
_status = message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _setStatus(String message) {
|
||||
_status = message;
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation += 1;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer_stub.dart'
|
||||
if (dart.library.js_interop) 'artifact_transfer_web.dart'
|
||||
as impl;
|
||||
|
||||
/// The outcome of a host file transfer.
|
||||
enum ArtifactTransferState {
|
||||
/// The host accepted a browser download.
|
||||
saved,
|
||||
|
||||
/// The host share sheet accepted the file.
|
||||
shared,
|
||||
|
||||
/// The bytes are ready but the browser needed a fresh user activation.
|
||||
ready,
|
||||
|
||||
/// The operator or the host canceled the transfer.
|
||||
canceled,
|
||||
|
||||
/// The host cannot save/share this file.
|
||||
unsupported,
|
||||
|
||||
/// The host refused the share for a policy or activation reason.
|
||||
blocked,
|
||||
|
||||
/// The transfer failed for any other reason.
|
||||
failed,
|
||||
}
|
||||
|
||||
/// A transfer result plus the exact words the action row reports.
|
||||
class ArtifactTransferResult {
|
||||
const ArtifactTransferResult(this.state, this.message);
|
||||
|
||||
final ArtifactTransferState state;
|
||||
final String message;
|
||||
}
|
||||
|
||||
typedef ArtifactSaveFile =
|
||||
Future<ArtifactTransferResult> Function(ArtifactFile file);
|
||||
typedef ArtifactShareFile =
|
||||
Future<ArtifactTransferResult> Function(ArtifactFile file);
|
||||
|
||||
/// Whether the host can save an artifact's bytes as a named file.
|
||||
bool get artifactDownloadSupported => impl.artifactDownloadSupported;
|
||||
|
||||
/// Whether the host can share a file (not merely a link).
|
||||
bool get artifactShareSupported => impl.artifactShareSupported;
|
||||
|
||||
String get artifactDownloadUnsupportedMessage =>
|
||||
impl.artifactDownloadUnsupportedMessage;
|
||||
|
||||
String get artifactShareUnsupportedMessage =>
|
||||
impl.artifactShareUnsupportedMessage;
|
||||
|
||||
/// Saves [file] through the host's download capability.
|
||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) =>
|
||||
impl.saveArtifactFile(file);
|
||||
|
||||
/// Shares [file] through the host's file-sharing capability.
|
||||
Future<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) =>
|
||||
impl.shareArtifactFile(file);
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'artifact_file.dart';
|
||||
import 'artifact_transfer.dart';
|
||||
|
||||
/// Native fallback for artifact file actions.
|
||||
///
|
||||
/// A save/share plugin is not a dependency of this slice, so a non-web host
|
||||
/// reports `unsupported` instead of pretending to save a file. The action row
|
||||
/// disables the control and shows this exact explanation.
|
||||
bool get artifactDownloadSupported => false;
|
||||
|
||||
bool get artifactShareSupported => false;
|
||||
|
||||
String get artifactDownloadUnsupportedMessage =>
|
||||
'Downloading files is not supported on this platform yet.';
|
||||
|
||||
String get artifactShareUnsupportedMessage =>
|
||||
'File sharing is not supported on this platform yet.';
|
||||
|
||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async =>
|
||||
ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactDownloadUnsupportedMessage,
|
||||
);
|
||||
|
||||
Future<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) async =>
|
||||
ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactShareUnsupportedMessage,
|
||||
);
|
||||
@@ -0,0 +1,206 @@
|
||||
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<JSAny> 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<JSAny> parts,
|
||||
JSString name,
|
||||
_FileOptions options,
|
||||
);
|
||||
}
|
||||
|
||||
extension type _ShareData._(JSObject _) implements JSObject {
|
||||
external factory _ShareData({JSArray<JSAny> files});
|
||||
}
|
||||
|
||||
extension type _UserActivation._(JSObject _) implements JSObject {
|
||||
external bool get isActive;
|
||||
}
|
||||
|
||||
extension type _Navigator._(JSObject _) implements JSObject {
|
||||
external JSPromise<JSAny?> 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<ArtifactTransferResult> 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<void>.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<ArtifactTransferResult> shareArtifactFile(ArtifactFile file) async {
|
||||
if (!artifactShareSupported) {
|
||||
return ArtifactTransferResult(
|
||||
ArtifactTransferState.unsupported,
|
||||
artifactShareUnsupportedMessage,
|
||||
);
|
||||
}
|
||||
final data = _ShareData(files: <JSAny>[_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(
|
||||
<JSAny>[file.bytes.toJS].toJS,
|
||||
_BlobOptions(type: file.mimeType.toJS),
|
||||
);
|
||||
|
||||
_File _fileFor(ArtifactFile file) => _File(
|
||||
<JSAny>[_blobFor(file)].toJS,
|
||||
file.name.toJS,
|
||||
_FileOptions(type: file.mimeType.toJS),
|
||||
);
|
||||
|
||||
bool _hasFunction(String name) {
|
||||
final value = _navigator.getProperty<JSAny?>(name.toJS);
|
||||
return value != null && value.isA<JSFunction>();
|
||||
}
|
||||
|
||||
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 <String>['AbortError', 'NotAllowedError']) {
|
||||
if (text.contains(candidate)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import 'package:flutter/services.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../../chat/ui/transcript/chat_markdown_view.dart';
|
||||
import '../actions/artifact_file_actions.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import '../domain/artifact_kind.dart';
|
||||
import '../domain/artifact_record.dart';
|
||||
@@ -28,8 +30,9 @@ const String artifactGalleryTitle = 'Artifacts';
|
||||
/// never fetched); any other selection opens a native dialog with the recorded
|
||||
/// name, MIME and size, the visit's capture facts and, only when the recorded
|
||||
/// url resolves through [resolveArtifactUrl], native `Open` and `Copy link`
|
||||
/// actions. Markdown previews use the same chat markdown renderer by default.
|
||||
/// It never downloads, shares or filters.
|
||||
/// actions plus file `Download`/`Share` for a server-served url. Markdown
|
||||
/// previews use the same chat markdown renderer by default. It never filters,
|
||||
/// and an external url is never fetched for preview or file transfer.
|
||||
class ArtifactGalleryPage extends StatefulWidget {
|
||||
const ArtifactGalleryPage({
|
||||
super.key,
|
||||
@@ -39,6 +42,7 @@ class ArtifactGalleryPage extends StatefulWidget {
|
||||
this.openExternal = openArtifactExternally,
|
||||
this.fetch = fetchArtifact,
|
||||
this.markdownBuilder = chatMarkdownText,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final List<JsonMap> steps;
|
||||
@@ -47,6 +51,7 @@ class ArtifactGalleryPage extends StatefulWidget {
|
||||
final ArtifactExternalOpen openExternal;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactMarkdownBuilder markdownBuilder;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
|
||||
@override
|
||||
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
|
||||
@@ -89,6 +94,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
openExternal: widget.openExternal,
|
||||
fetch: widget.fetch,
|
||||
markdownBuilder: widget.markdownBuilder,
|
||||
fileBridge: widget.fileBridge,
|
||||
),
|
||||
)
|
||||
: MaterialPageRoute<void>(
|
||||
@@ -99,6 +105,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
openExternal: widget.openExternal,
|
||||
fetch: widget.fetch,
|
||||
markdownBuilder: widget.markdownBuilder,
|
||||
fileBridge: widget.fileBridge,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -120,12 +127,31 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
step: step,
|
||||
resolved: resolved,
|
||||
);
|
||||
final content = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
facts,
|
||||
if (resolved != null && !resolved.external) ...[
|
||||
const SizedBox(height: 12),
|
||||
ArtifactFileActions(
|
||||
key: ValueKey<String>(
|
||||
'artifact-files-${artifactVisitIdentity(group, artifact)}',
|
||||
),
|
||||
artifact: artifact,
|
||||
resolved: resolved,
|
||||
fetch: widget.fetch,
|
||||
bridge: widget.fileBridge,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
if (usesCupertinoHost(context)) {
|
||||
return showCupertinoDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) => CupertinoAlertDialog(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
content: facts,
|
||||
content: content,
|
||||
actions: [
|
||||
if (resolved != null)
|
||||
CupertinoDialogAction(
|
||||
@@ -150,7 +176,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(artifactDisplayName(artifact)),
|
||||
content: SingleChildScrollView(child: facts),
|
||||
content: SingleChildScrollView(child: content),
|
||||
actions: [
|
||||
if (resolved != null)
|
||||
TextButton(
|
||||
|
||||
@@ -4,17 +4,21 @@ import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../actions/artifact_file_actions.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
import '../domain/gallery_navigation.dart';
|
||||
import 'artifact_selection_facts.dart';
|
||||
import 'artifact_viewer_content.dart';
|
||||
import 'artifact_viewer_fetch.dart';
|
||||
|
||||
/// One viewer page: the recorded facts, position, live status, preview surface,
|
||||
/// external actions and paging controls.
|
||||
/// file transfer actions, external actions and paging controls.
|
||||
///
|
||||
/// It is stateless so the page owns loading, fetch generations and focus; this
|
||||
/// surface only draws the current page and reports the operator's intent.
|
||||
/// surface only draws the current page and reports the operator's intent. The
|
||||
/// page content scrolls as one column at large text sizes; paging stays fixed.
|
||||
class ArtifactViewerBody extends StatelessWidget {
|
||||
const ArtifactViewerBody({
|
||||
super.key,
|
||||
@@ -28,6 +32,8 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
required this.onNext,
|
||||
required this.onOpen,
|
||||
required this.onCopy,
|
||||
this.fetch = fetchArtifact,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
this.text,
|
||||
this.bytes,
|
||||
this.error,
|
||||
@@ -44,6 +50,8 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
final VoidCallback onNext;
|
||||
final VoidCallback onOpen;
|
||||
final VoidCallback onCopy;
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
final String? text;
|
||||
final Uint8List? bytes;
|
||||
final String? error;
|
||||
@@ -54,42 +62,67 @@ class ArtifactViewerBody extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
|
||||
child: ArtifactSelectionFacts(
|
||||
group: page.group,
|
||||
artifact: page.artifact,
|
||||
step: null,
|
||||
resolved: plan.resolved,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: Text(
|
||||
artifactViewerPositionLabel(
|
||||
index,
|
||||
count,
|
||||
page.artifact.contentType,
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
|
||||
child: ArtifactSelectionFacts(
|
||||
group: page.group,
|
||||
artifact: page.artifact,
|
||||
step: null,
|
||||
resolved: plan.resolved,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: Text(
|
||||
artifactViewerPositionLabel(
|
||||
index,
|
||||
count,
|
||||
page.artifact.contentType,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
|
||||
child: Semantics(liveRegion: true, child: Text(status!)),
|
||||
),
|
||||
ArtifactPreviewBody(
|
||||
plan: plan,
|
||||
loading: loading,
|
||||
markdownBuilder: markdownBuilder,
|
||||
text: text,
|
||||
bytes: bytes,
|
||||
error: error,
|
||||
),
|
||||
if (plan.resolved != null && !plan.resolved!.external)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
|
||||
child: ArtifactFileActions(
|
||||
key: ValueKey<String>(
|
||||
'viewer-files-${page.group.stageKey}\u0000'
|
||||
'${page.group.visit}\u0000${page.artifact.url}',
|
||||
),
|
||||
artifact: page.artifact,
|
||||
resolved: plan.resolved!,
|
||||
fetch: fetch,
|
||||
bridge: fileBridge,
|
||||
),
|
||||
),
|
||||
if (plan.resolved != null)
|
||||
_Actions(
|
||||
resolved: plan.resolved!,
|
||||
onOpen: onOpen,
|
||||
onCopy: onCopy,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (status != null)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
|
||||
child: Semantics(liveRegion: true, child: Text(status!)),
|
||||
),
|
||||
Expanded(
|
||||
child: ArtifactPreviewBody(
|
||||
plan: plan,
|
||||
loading: loading,
|
||||
markdownBuilder: markdownBuilder,
|
||||
text: text,
|
||||
bytes: bytes,
|
||||
error: error,
|
||||
),
|
||||
),
|
||||
if (plan.resolved != null)
|
||||
_Actions(resolved: plan.resolved!, onOpen: onOpen, onCopy: onCopy),
|
||||
_Pager(
|
||||
index: index,
|
||||
count: count,
|
||||
|
||||
@@ -62,9 +62,9 @@ class ArtifactPreviewBody extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
case ArtifactPreviewKind.text:
|
||||
return _ScrollingText(child: SelectableText(text ?? ''));
|
||||
return _PreviewPadding(child: SelectableText(text ?? ''));
|
||||
case ArtifactPreviewKind.markdown:
|
||||
return _ScrollingText(child: markdownBuilder(context, text ?? ''));
|
||||
return _PreviewPadding(child: markdownBuilder(context, text ?? ''));
|
||||
case ArtifactPreviewKind.unsupported:
|
||||
case ArtifactPreviewKind.unavailable:
|
||||
return const SizedBox.shrink();
|
||||
@@ -93,14 +93,16 @@ class _Loading extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _ScrollingText extends StatelessWidget {
|
||||
const _ScrollingText({required this.child});
|
||||
/// Preview text at its natural height; the viewer body owns the page scroll so
|
||||
/// a long document and its actions scroll together instead of nested scrolls.
|
||||
class _PreviewPadding extends StatelessWidget {
|
||||
const _PreviewPadding({required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
return Padding(
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16),
|
||||
child: child,
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../ui/adaptive/host.dart';
|
||||
import '../actions/artifact_file_bridge.dart';
|
||||
import '../domain/artifact_groups.dart';
|
||||
import '../domain/artifact_preview.dart';
|
||||
import '../domain/artifact_url.dart';
|
||||
@@ -24,8 +25,9 @@ const String artifactViewerTitle = 'Artifact viewer';
|
||||
/// `text/plain` artifact is selectable text, and a `.md`/`.markdown` or
|
||||
/// `text/markdown` artifact is handed to [markdownBuilder]. The selected page
|
||||
/// keeps its recorded facts visible and offers the existing external Open and
|
||||
/// Copy link actions. Previous/Next walk the same filtered list the gallery
|
||||
/// draws and stop at both ends; closing returns to the gallery row.
|
||||
/// Copy link actions plus Download/Share of the same-origin bytes as a named
|
||||
/// file. Previous/Next walk the same filtered list the gallery draws and stop at
|
||||
/// both ends; closing returns to the gallery row.
|
||||
///
|
||||
/// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer
|
||||
/// reports the exact state instead. External urls are never fetched.
|
||||
@@ -38,6 +40,7 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
this.fetch = fetchArtifact,
|
||||
this.markdownBuilder = defaultArtifactMarkdown,
|
||||
this.openExternal = openArtifactExternally,
|
||||
this.fileBridge = const ArtifactFileBridge(),
|
||||
});
|
||||
|
||||
final List<ArtifactGroup> groups;
|
||||
@@ -49,6 +52,7 @@ class ArtifactViewerPage extends StatefulWidget {
|
||||
final ArtifactFetch fetch;
|
||||
final ArtifactMarkdownBuilder markdownBuilder;
|
||||
final ArtifactExternalOpen openExternal;
|
||||
final ArtifactFileBridge fileBridge;
|
||||
|
||||
@override
|
||||
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
|
||||
@@ -228,6 +232,8 @@ class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
|
||||
bytes: _fetched?.bytes,
|
||||
error: _error,
|
||||
status: _status,
|
||||
fetch: widget.fetch,
|
||||
fileBridge: widget.fileBridge,
|
||||
onPrevious: () => _step(-1),
|
||||
onNext: () => _step(1),
|
||||
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
|
||||
|
||||
Reference in New Issue
Block a user