merge(app): land in-app artifact preview after retained-deadline recovery

This commit is contained in:
2026-10-21 23:19:30 +01:00
18 changed files with 1754 additions and 39 deletions
@@ -196,13 +196,17 @@ bool isMarkdownArtifact(String contentType, String name) {
return _markdownExtensions.contains(_extensionOf(name));
}
/// Whether an artifact opens inside the full-screen viewer: images, videos, and
/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays
/// an external file because those are evidence, not prose.
/// Whether an artifact opens inside the viewer: images, videos, markdown/text
/// documents and any recorded `text/plain` file. The viewer draws text/plain as
/// selectable text; a CSV, source file or spreadsheet with its own type stays an
/// external file because it is evidence, not prose. Videos are pageable but the
/// viewer reports that it cannot draw them rather than faking a player.
bool isViewerArtifact(String contentType, String name) {
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
return true;
}
final mime = contentType.split(';').first.trim().toLowerCase();
if (mime == 'text/plain') return true;
return artifactKind(contentType, name) == ArtifactKind.document &&
isMarkdownArtifact(contentType, name);
}
@@ -0,0 +1,118 @@
import 'artifact_kind.dart';
import 'artifact_record.dart';
import 'artifact_url.dart';
/// What the in-app viewer can do with one recorded artifact.
enum ArtifactPreviewKind {
image,
text,
markdown,
/// A recorded file the viewer cannot draw (video, CSV, archives, ...).
unsupported,
/// No safe same-origin url to fetch: absent, unsafe or another origin.
unavailable,
}
/// One artifact's preview decision: the safe resolved url, the content kind and
/// the exact wording for a state that cannot be previewed.
///
/// An external url is deliberately [ArtifactPreviewKind.unavailable]: the viewer
/// never fetches another origin, so a recorded url on a different host is marked
/// instead of being requested with the app's credentials. [canFetch] is the one
/// gate the viewer's fetch consults.
class ArtifactPreviewPlan {
const ArtifactPreviewPlan({
required this.kind,
required this.resolved,
required this.message,
});
final ArtifactPreviewKind kind;
final ResolvedArtifactUrl? resolved;
/// The explicit reason a non-previewable artifact is not drawn; empty for an
/// image, text or markdown document that may be fetched.
final String message;
bool get canFetch =>
resolved != null &&
resolved!.external == false &&
(kind == ArtifactPreviewKind.image ||
kind == ArtifactPreviewKind.text ||
kind == ArtifactPreviewKind.markdown);
}
const String artifactPreviewNoUrl = 'No artifact URL recorded.';
const String artifactPreviewUnsafeUrl =
'The recorded artifact URL cannot be opened safely.';
const String artifactPreviewExternalUrl =
'This artifact is hosted on another origin and is not previewed here.';
/// Classifies [artifact] against the configured server origin.
///
/// Images are drawn from the resolved bytes; `text/plain` is selectable text; a
/// `.md`/`.markdown` name or `text/markdown` is handed to the injected markdown
/// builder. Everything else is explicitly unsupported rather than faked.
ArtifactPreviewPlan planArtifactPreview({
required ArtifactRecord artifact,
required String configuredEndpoint,
}) {
if (!artifact.hasUrl) {
return const ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: null,
message: artifactPreviewNoUrl,
);
}
final resolved = resolveArtifactUrl(configuredEndpoint, artifact.url);
if (resolved == null) {
return const ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: null,
message: artifactPreviewUnsafeUrl,
);
}
if (resolved.external) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: resolved,
message: artifactPreviewExternalUrl,
);
}
final mime = artifact.contentType.split(';').first.trim().toLowerCase();
if (isImageContentType(mime)) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.image,
resolved: resolved,
message: '',
);
}
if (mime == 'text/markdown' || _isMarkdownName(artifact.name)) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.markdown,
resolved: resolved,
message: '',
);
}
if (mime == 'text/plain') {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.text,
resolved: resolved,
message: '',
);
}
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unsupported,
resolved: resolved,
message: 'This file type cannot be previewed here.',
);
}
bool _isMarkdownName(String name) {
final dot = name.lastIndexOf('.');
if (dot == -1) return false;
final extension = name.substring(dot + 1).toLowerCase();
return extension == 'md' || extension == 'markdown';
}
@@ -7,24 +7,34 @@ import 'artifact_record.dart';
/// a visit-scoped key so two url-less records never collapse into one page.
class PagedArtifact {
const PagedArtifact({
required this.stageKey,
required this.visit,
required this.group,
required this.artifact,
required this.pageIndex,
});
final String stageKey;
final int visit;
final ArtifactGroup group;
final ArtifactRecord artifact;
/// Position in the filtered page list.
final int pageIndex;
String get stageKey => group.stageKey;
int get visit => group.visit;
String get identity => artifact.hasUrl
? artifact.url
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
}
/// The gallery row identity of [artifact] inside [group], shared by the row
/// list and the viewer so selecting a row opens exactly that page. The recorded
/// visit is part of the key, so two visits that recorded the same name stay
/// distinct even when their recorded urls match.
String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) {
final recorded = artifact.hasUrl ? artifact.url : artifact.name;
return '${group.stageKey}\u0000${group.visit}\u0000$recorded';
}
/// The artifacts the viewer can page through, in gallery order: group by group,
/// each group's images, videos and markdown/text documents in recorded order.
/// Other artifacts open externally and are not part of this list. Pure: it only
@@ -36,8 +46,7 @@ List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
pages.add(
PagedArtifact(
stageKey: group.stageKey,
visit: group.visit,
group: group,
artifact: artifact,
pageIndex: pages.length,
),
@@ -5,11 +5,15 @@ import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/artifact_summary.dart';
import '../domain/artifact_url.dart';
import 'artifact_external_open.dart';
import 'artifact_selection_facts.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_viewer_page.dart';
import 'artifact_visit_list.dart';
/// The gallery page title.
@@ -18,10 +22,12 @@ const String artifactGalleryTitle = 'Artifacts';
/// A read-only page of recorded stage/visit artifact groups.
///
/// Selection uses [artifactVisitIdentity], so the same filename in two visits
/// stays two distinct selections. Selecting a row 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. It never previews, downloads, shares or filters.
/// stays two distinct selections. Selecting a viewer artifact with a resolved
/// url opens the native [ArtifactViewerPage] (an external origin is marked and
/// 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. It never downloads, shares or filters.
class ArtifactGalleryPage extends StatefulWidget {
const ArtifactGalleryPage({
super.key,
@@ -29,12 +35,16 @@ class ArtifactGalleryPage extends StatefulWidget {
this.executing = false,
this.configuredEndpoint = '',
this.openExternal = openArtifactExternally,
this.fetch = fetchArtifact,
this.markdownBuilder = defaultArtifactMarkdown,
});
final List<JsonMap> steps;
final bool executing;
final String configuredEndpoint;
final ArtifactExternalOpen openExternal;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
@override
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
@@ -44,22 +54,64 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
late final Map<String, JsonMap> _stepsByGroup = recordedStepsByGroup(
widget.steps,
);
late final List<ArtifactGroup> _groups = artifactGroups(widget.steps);
String? _selectedIdentity;
String? _status;
void _select(ArtifactGroup group, ArtifactRecord artifact) {
setState(() {
_selectedIdentity = artifactVisitIdentity(group, artifact);
_status = null;
});
_showSelected(group, artifact);
}
Future<void> _showSelected(ArtifactGroup group, ArtifactRecord artifact) {
final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)];
Future<void> _select(ArtifactGroup group, ArtifactRecord artifact) async {
final identity = artifactVisitIdentity(group, artifact);
final resolved = artifact.hasUrl
? resolveArtifactUrl(widget.configuredEndpoint, artifact.url)
: null;
setState(() {
_selectedIdentity = identity;
_status = null;
});
if (resolved != null &&
isViewerArtifact(artifact.contentType, artifact.name)) {
await _openViewer(identity);
return;
}
await _showSelected(group, artifact, resolved);
}
Future<void> _openViewer(String identity) async {
final previousFocus = FocusManager.instance.primaryFocus;
await Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: _groups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
),
)
: MaterialPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: _groups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
),
),
);
if (!mounted) return;
if (previousFocus != null && previousFocus.canRequestFocus) {
previousFocus.requestFocus();
}
}
Future<void> _showSelected(
ArtifactGroup group,
ArtifactRecord artifact,
ResolvedArtifactUrl? resolved,
) {
final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)];
final facts = ArtifactSelectionFacts(
group: group,
artifact: artifact,
@@ -149,7 +201,7 @@ class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
@override
Widget build(BuildContext context) {
final groups = artifactGroups(widget.steps);
final groups = _groups;
final summary = widget.steps.isEmpty
? 'No steps recorded for this run.'
: artifactsHeader(widget.steps, executing: widget.executing);
@@ -0,0 +1,210 @@
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.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';
/// One viewer page: the recorded facts, position, live status, preview surface,
/// 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.
class ArtifactViewerBody extends StatelessWidget {
const ArtifactViewerBody({
super.key,
required this.page,
required this.plan,
required this.index,
required this.count,
required this.loading,
required this.markdownBuilder,
required this.onPrevious,
required this.onNext,
required this.onOpen,
required this.onCopy,
this.text,
this.bytes,
this.error,
this.status,
});
final PagedArtifact page;
final ArtifactPreviewPlan plan;
final int index;
final int count;
final bool loading;
final ArtifactMarkdownBuilder markdownBuilder;
final VoidCallback onPrevious;
final VoidCallback onNext;
final VoidCallback onOpen;
final VoidCallback onCopy;
final String? text;
final Uint8List? bytes;
final String? error;
final String? status;
@override
Widget build(BuildContext context) {
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,
),
),
),
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,
onPrevious: onPrevious,
onNext: onNext,
),
],
);
}
}
class _Actions extends StatelessWidget {
const _Actions({
required this.resolved,
required this.onOpen,
required this.onCopy,
});
final ResolvedArtifactUrl resolved;
final VoidCallback onOpen;
final VoidCallback onCopy;
@override
Widget build(BuildContext context) {
if (usesCupertinoHost(context)) {
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
children: [
CupertinoButton(onPressed: onOpen, child: const Text('Open')),
CupertinoButton(onPressed: onCopy, child: const Text('Copy link')),
],
),
);
}
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
children: [
TextButton.icon(
onPressed: onOpen,
icon: const Icon(Icons.open_in_new),
label: const Text('Open'),
),
TextButton.icon(
onPressed: onCopy,
icon: const Icon(Icons.content_copy),
label: const Text('Copy link'),
),
],
),
);
}
}
class _Pager extends StatelessWidget {
const _Pager({
required this.index,
required this.count,
required this.onPrevious,
required this.onNext,
});
final int index;
final int count;
final VoidCallback onPrevious;
final VoidCallback onNext;
@override
Widget build(BuildContext context) {
if (count <= 1) return const SizedBox.shrink();
final hasPrevious = pagedIndex(index, -1, count) != index;
final hasNext = pagedIndex(index, 1, count) != index;
if (usesCupertinoHost(context)) {
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
CupertinoButton(
onPressed: hasPrevious ? onPrevious : null,
child: const Text('Previous artifact'),
),
CupertinoButton(
onPressed: hasNext ? onNext : null,
child: const Text('Next artifact'),
),
],
),
);
}
return SafeArea(
top: false,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton.icon(
onPressed: hasPrevious ? onPrevious : null,
icon: const Icon(Icons.arrow_back),
label: const Text('Previous artifact'),
),
TextButton.icon(
onPressed: hasNext ? onNext : null,
icon: const Icon(Icons.arrow_forward),
label: const Text('Next artifact'),
),
],
),
),
);
}
}
@@ -0,0 +1,122 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../domain/artifact_preview.dart';
/// Renders fetched markdown text for the viewer. The gallery's default builder
/// returns plain selectable text, so the viewer is honest before the markdown
/// lane supplies a real renderer.
typedef ArtifactMarkdownBuilder = Widget Function(String text);
Widget defaultArtifactMarkdown(String text) => SelectableText(text);
/// The viewer's preview surface for one page.
///
/// It draws only what was actually fetched: image bytes as an [Image], text as
/// selectable text, markdown through [markdownBuilder], and an explicit message
/// for unsupported/unavailable pages. It never substitutes a placeholder that
/// looks like a preview.
class ArtifactPreviewBody extends StatelessWidget {
const ArtifactPreviewBody({
super.key,
required this.plan,
required this.loading,
required this.markdownBuilder,
this.text,
this.bytes,
this.error,
});
final ArtifactPreviewPlan plan;
final bool loading;
final ArtifactMarkdownBuilder markdownBuilder;
final String? text;
final Uint8List? bytes;
final String? error;
@override
Widget build(BuildContext context) {
if (plan.kind == ArtifactPreviewKind.unavailable ||
plan.kind == ArtifactPreviewKind.unsupported) {
return _Message(plan.message);
}
if (loading) {
return const _Loading();
}
if (error != null) {
return _Message(error!);
}
switch (plan.kind) {
case ArtifactPreviewKind.image:
final data = bytes;
if (data == null) return const _Message('The image is empty.');
return Center(
child: Image.memory(
data,
fit: BoxFit.contain,
errorBuilder: (_, _, _) =>
const _Message('The image could not be decoded.'),
),
);
case ArtifactPreviewKind.text:
return _ScrollingText(child: SelectableText(text ?? ''));
case ArtifactPreviewKind.markdown:
return _ScrollingText(child: markdownBuilder(text ?? ''));
case ArtifactPreviewKind.unsupported:
case ArtifactPreviewKind.unavailable:
return const SizedBox.shrink();
}
}
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 12),
Text(
'Loading preview…',
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
);
}
}
class _ScrollingText extends StatelessWidget {
const _ScrollingText({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16),
child: child,
);
}
}
class _Message extends StatelessWidget {
const _Message(this.message);
final String message;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(message, textAlign: TextAlign.center),
),
);
}
}
@@ -0,0 +1,35 @@
import 'dart:typed_data';
import 'artifact_viewer_fetch_stub.dart'
if (dart.library.js_interop) 'artifact_viewer_fetch_web.dart'
as impl;
/// One artifact fetch result: the status the server answered and the bytes.
class ArtifactFetchResult {
const ArtifactFetchResult({required this.status, required this.bytes});
final int status;
final Uint8List bytes;
bool get ok => status >= 200 && status < 300;
}
/// A fetch that did not reach an HTTP response (network, TLS, blocked, ...).
class ArtifactFetchException implements Exception {
const ArtifactFetchException(this.message);
final String message;
@override
String toString() => message;
}
/// Fetches an already resolved same-origin artifact.
///
/// The viewer only calls this for [planArtifactPreview]'s safe local urls; the
/// platform implementation sends no credentials to a different origin.
typedef ArtifactFetch = Future<ArtifactFetchResult> Function(Uri uri);
/// The host fetch used when a caller does not inject one. Web uses `fetch` with
/// same-origin credentials; native uses an HttpClient with no stored cookies.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) => impl.fetchArtifact(uri);
@@ -0,0 +1,29 @@
import 'dart:io';
import 'dart:typed_data';
import 'artifact_viewer_fetch.dart';
/// Native fetch for an already resolved same-origin artifact.
///
/// No cookie jar, authorization header or userinfo is attached, redirects are
/// not followed across origins, and the caller only passes safe local urls.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final request = await client.getUrl(uri);
request.followRedirects = false;
final response = await request.close();
final bytes = BytesBuilder(copy: false);
await for (final chunk in response) {
bytes.add(chunk);
}
return ArtifactFetchResult(
status: response.statusCode,
bytes: bytes.takeBytes(),
);
} on IOException catch (error) {
throw ArtifactFetchException('$error');
} finally {
client.close(force: true);
}
}
@@ -0,0 +1,37 @@
import 'dart:js_interop';
import 'artifact_viewer_fetch.dart';
@JS('fetch')
external JSPromise<_FetchResponse> _fetch(JSString input, _FetchInit init);
extension type _FetchInit._(JSObject _) implements JSObject {
external factory _FetchInit({JSString credentials});
}
extension type _FetchResponse._(JSObject _) implements JSObject {
external int get status;
external JSPromise<JSArrayBuffer> arrayBuffer();
}
/// Web fetch for an already resolved same-origin artifact.
///
/// `credentials: 'same-origin'` attaches the browser's credentials only to this
/// server's origin; the viewer never asks for another origin. The status is
/// returned verbatim so a failed preview can report the HTTP failure.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) async {
try {
final response = await _fetch(
uri.toString().toJS,
_FetchInit(credentials: 'same-origin'.toJS),
).toDart;
final buffer = await response.arrayBuffer().toDart;
return ArtifactFetchResult(
status: response.status,
bytes: buffer.toDart.asUint8List(),
);
} catch (error) {
throw ArtifactFetchException('$error');
}
}
@@ -0,0 +1,250 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_external_open.dart';
import 'artifact_viewer_body.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.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. 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.configuredEndpoint = '',
this.fetch = fetchArtifact,
this.markdownBuilder = defaultArtifactMarkdown,
this.openExternal = openArtifactExternally,
});
final List<ArtifactGroup> groups;
/// [artifactVisitIdentityOf] of the row the operator selected.
final String selectedIdentity;
final String configuredEndpoint;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
final ArtifactExternalOpen openExternal;
@override
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
}
class _FetchedPreview {
const _FetchedPreview({this.text, this.bytes});
final String? text;
final Uint8List? bytes;
}
class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
late final List<PagedArtifact> _pages = pagedArtifacts(widget.groups);
final Map<String, _FetchedPreview> _cache = <String, _FetchedPreview>{};
late int _index = _initialIndex();
int _generation = 0;
bool _loading = 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,
);
}
@override
void initState() {
super.initState();
_beginLoad(initial: true);
}
void _beginLoad({bool initial = false}) {
final generation = ++_generation;
final plan = _plan;
if (plan == null || !plan.canFetch) {
void clear() {
_loading = false;
_error = null;
_fetched = null;
}
if (initial) {
clear();
} else {
setState(clear);
}
return;
}
final key = plan.resolved!.url;
final cached = _cache[key];
if (cached != null) {
void apply() {
_loading = false;
_error = null;
_fetched = cached;
}
if (initial) {
apply();
} else {
setState(apply);
}
return;
}
void start() {
_loading = true;
_error = null;
_fetched = null;
}
if (initial) {
start();
} else {
setState(start);
}
widget
.fetch(plan.resolved!.uri)
.then(
(result) {
if (!mounted || generation != _generation) return;
if (!result.ok) {
setState(() {
_loading = false;
_error = 'The server answered ${result.status}.';
});
return;
}
final fetched = _decode(plan.kind, result.bytes);
_cache[key] = fetched;
setState(() {
_loading = false;
_fetched = fetched;
});
},
onError: (Object error) {
if (!mounted || generation != _generation) return;
setState(() {
_loading = false;
_error = 'Could not load preview: $error';
});
},
);
}
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;
});
_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) {
final page = _page;
final plan = _plan;
final title = page == null
? artifactViewerTitle
: artifactDisplayName(page.artifact);
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,
onPrevious: () => _step(-1),
onNext: () => _step(1),
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!),
);
if (usesCupertinoHost(context)) {
return CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground,
navigationBar: CupertinoNavigationBar(
middle: Text(title, overflow: TextOverflow.ellipsis),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(title: Text(title, overflow: TextOverflow.ellipsis)),
body: SafeArea(top: false, child: body),
);
}
}
@@ -5,6 +5,7 @@ import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/gallery_navigation.dart';
/// A selection callback carrying the recorded group and the exact record the
/// operator chose, so the visit is never lost when two groups share a name.
@@ -17,10 +18,8 @@ typedef ArtifactSelected =
/// The recorded stage visit is part of the key, so two visits that both
/// recorded `result.csv` stay distinct even when their urls are identical.
/// A filename alone is never an identity.
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) {
final recorded = artifact.hasUrl ? artifact.url : artifact.name;
return '${group.stageKey}\u0000${group.visit}\u0000$recorded';
}
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) =>
artifactVisitIdentityOf(group, artifact);
/// The recorded group heading, matching the web client's group vocabulary.
String artifactGroupLabel(ArtifactGroup group) =>