Files
pipelines/app/lib/features/artifacts/ui/artifact_viewer_page.dart
T
alan 339cce0424 Page through a folder's files in the file viewer
Opening a file from the Files panel now passes the folder's previewable
files in their shown order, so the arrows, swipes and Previous/Next step
through them and Escape closes the viewer. Download follows the file on
screen.
2026-11-10 00:14:18 +00:00

326 lines
11 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/input/arrow_key_pager.dart';
import 'artifact_selection_facts.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_preview_failure.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_external_open.dart';
import 'artifact_fullscreen.dart';
import 'artifact_fullscreen_host.dart';
import 'artifact_html_view.dart';
import 'artifact_viewer_body.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_viewer_scaffold.dart';
import 'artifact_visit_list.dart';
/// The full-screen viewer's title, matching the web client's wording.
const String artifactViewerTitle = 'Artifact viewer';
/// One artifact of a recorded visit, previewed in-app.
///
/// Images are drawn from bytes fetched from the already-resolved safe url, a
/// `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 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.
class ArtifactViewerPage extends StatefulWidget {
const ArtifactViewerPage({
super.key,
required this.groups,
required this.selectedIdentity,
this.includeExternalDocuments = false,
this.configuredEndpoint = '',
this.downloadUrl,
this.previewFormat = artifactPreviewFormat,
this.fetch = fetchArtifact,
this.markdownBuilder = defaultArtifactMarkdown,
this.openExternal = openArtifactExternally,
this.fileBridge = const ArtifactFileBridge(),
this.htmlBuilder = defaultArtifactHtml,
});
final List<ArtifactGroup> groups;
/// [artifactVisitIdentityOf] of the row the operator selected.
final String selectedIdentity;
/// Search can select a turn document that is hidden from the normal gallery,
/// including the external-only session export.
final bool includeExternalDocuments;
final String configuredEndpoint;
/// Where Download fetches the shown file. An artifact whose `raw` carries
/// `download_url` (the Files panel's per-file links) overrides it, so paging
/// through a folder downloads the file on screen.
final String? downloadUrl;
/// The preview rule; the Files panel passes its own (every HTML previews).
final ArtifactPreviewFormat Function(String contentType, String name)
previewFormat;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
final ArtifactExternalOpen openExternal;
final ArtifactFileBridge fileBridge;
/// The inert HTML renderer; tests inject a plain stand-in.
final ArtifactHtmlBuilder htmlBuilder;
@override
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
}
class _FetchedPreview {
const _FetchedPreview({this.text, this.bytes});
final String? text;
final Uint8List? bytes;
}
class _ArtifactViewerPageState extends State<ArtifactViewerPage>
with ArtifactFullscreenHost<ArtifactViewerPage> {
late final List<PagedArtifact> _pages = pagedArtifacts(
widget.groups,
includeExternalDocuments: widget.includeExternalDocuments,
);
final Map<String, _FetchedPreview> _cache = <String, _FetchedPreview>{};
late int _index = _initialIndex();
int _generation = 0;
bool _loading = false;
bool _imageZoomed = false;
String? _error;
_FetchedPreview? _fetched;
String? _status;
int _initialIndex() {
final found = _pages.indexWhere(
(page) =>
artifactVisitIdentityOf(page.group, page.artifact) ==
widget.selectedIdentity,
);
return found < 0 ? 0 : found;
}
PagedArtifact? get _page => _index < _pages.length ? _pages[_index] : null;
ArtifactPreviewPlan? get _plan {
final page = _page;
if (page == null) return null;
return planArtifactPreview(
artifact: page.artifact,
configuredEndpoint: widget.configuredEndpoint,
format: widget.previewFormat,
);
}
@override
void initState() {
super.initState();
_beginLoad(initial: true);
}
void _beginLoad({bool initial = false}) {
final generation = ++_generation;
final plan = _plan;
// The first load runs in initState, before there is anything to redraw.
void update(VoidCallback change) => initial ? change() : setState(change);
if (plan == null || !plan.canFetch) {
update(() {
_loading = false;
_error = null;
_fetched = null;
});
return;
}
final key = plan.resolved!.url;
final cached = _cache[key];
if (cached != null) {
update(() {
_loading = false;
_error = null;
_fetched = cached;
});
return;
}
update(() {
_loading = true;
_error = null;
_fetched = null;
});
widget
.fetch(plan.resolved!.uri)
.then(
(result) {
if (!mounted || generation != _generation) return;
if (!result.ok) {
setState(() {
_loading = false;
_error = artifactPreviewFailureMessage(status: result.status);
});
return;
}
final fetched = _decode(plan.kind, result.bytes);
_cache[key] = fetched;
setState(() {
_loading = false;
_fetched = fetched;
});
},
onError: (Object _) {
if (!mounted || generation != _generation) return;
setState(() {
_loading = false;
_error = artifactPreviewFailureMessage();
});
},
);
}
static _FetchedPreview _decode(ArtifactPreviewKind kind, Uint8List bytes) {
if (kind == ArtifactPreviewKind.image) {
return _FetchedPreview(bytes: bytes);
}
return _FetchedPreview(text: utf8.decode(bytes, allowMalformed: true));
}
void _step(int delta) {
final next = pagedIndex(_index, delta, _pages.length);
if (next == _index) return;
setState(() {
_index = next;
_status = null;
_imageZoomed = false;
});
_beginLoad();
}
Future<void> _open(ResolvedArtifactUrl resolved) async {
final opened = await widget.openExternal(resolved.uri);
if (!mounted) return;
setState(
() =>
_status = opened ? 'Link opened externally.' : 'Could not open link.',
);
}
Future<void> _copy(ResolvedArtifactUrl resolved) async {
String message;
try {
await Clipboard.setData(ClipboardData(text: resolved.url));
message = 'Link copied.';
} catch (_) {
message = 'Could not copy link.';
}
if (!mounted) return;
setState(() => _status = message);
}
@override
Widget build(BuildContext context) => buildFrame(context, fullscreen: false);
/// The viewer's scaffold, inline or as the full-screen view: the same top
/// bar, preview and bottom actions; full screen adds HTML zoom on the web
/// and gives the preview every gesture over it.
@override
Widget buildFrame(BuildContext context, {required bool fullscreen}) {
final page = _page;
final plan = _plan;
final pageDownload = page?.artifact.raw['download_url'];
final download = pageDownload is String && pageDownload.isNotEmpty
? pageDownload
: widget.downloadUrl;
final downloadResolved = download == null
? null
: resolveArtifactUrl(widget.configuredEndpoint, download);
final title = page == null
? artifactViewerTitle
: artifactDisplayName(page.artifact);
final subtitle = page == null
? null
: artifactViewerPositionLabel(
_index,
_pages.length,
page.artifact.contentType,
);
final info = page == null || plan == null
? const <Widget>[]
: <Widget>[
if (fullscreen &&
artifactHtmlZoomButtons &&
plan.kind == ArtifactPreviewKind.html &&
_fetched?.text != null)
...artifactHtmlZoomActions(htmlZoom),
ArtifactViewerInfoAction(
facts: ArtifactSelectionFacts(
group: page.group,
artifact: page.artifact,
step: null,
resolved: plan.resolved,
),
),
];
final body = page == null || plan == null
? const Center(child: Text('No previewable artifacts recorded.'))
: ArtifactViewerBody(
page: page,
plan: plan,
index: _index,
count: _pages.length,
loading: _loading,
markdownBuilder: widget.markdownBuilder,
text: _fetched?.text,
bytes: _fetched?.bytes,
error: _error,
status: _status,
fetch: widget.fetch,
fileBridge: widget.fileBridge,
downloadResolved: downloadResolved,
onPrevious: () => _step(-1),
onNext: () => _step(1),
// A failure is never cached, so loading again fetches afresh.
onRetry: _beginLoad,
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!),
htmlBuilder: widget.htmlBuilder,
imageZoomed: _imageZoomed,
onImageZoomChanged: (zoomed) {
if (_imageZoomed == zoomed || !mounted) return;
setState(() => _imageZoomed = zoomed);
},
fullscreen: fullscreen,
onFullscreen: fullscreen
? () => Navigator.of(context).maybePop()
: enterFullscreen,
);
// Left/right arrows walk the same list as the Previous/Next buttons,
// wherever focus is on the page, its top bar's controls included.
return ArrowKeyPager(
onPrevious: () => _step(-1),
onNext: () => _step(1),
// Escape closes the viewer (or leaves full screen), like the web's
// overlay.
onEscape: () => Navigator.of(context).maybePop(),
child: ArtifactViewerScaffold(
title: title,
subtitle: subtitle,
actions: info,
body: body,
),
);
}
}