feat(app): add artifact records, grouping and safe url navigation

Pure Dart A1a artifact domain slice mirroring web/src/artifacts.js and
artifactNavigation.js: record parsing, capture facts, stage/visit grouping,
public attribution, kind vocabulary, summaries, viewer paging and safe
artifact url resolution. Tests mirror the domain directory; nothing is
wired into a screen or transport.
This commit is contained in:
2026-10-21 16:56:11 +01:00
parent 2227faad40
commit ff0f812e00
16 changed files with 2084 additions and 0 deletions
@@ -0,0 +1,63 @@
import '../../../core/api_gateway.dart';
import 'artifact_record.dart';
/// Whether a step actually carried an artifact list.
///
/// An absent (or null) field means the capture is unavailable: an older step, a
/// running visit, or a reply that did not include the field. It must never be
/// reported as an empty capture. An explicitly recorded empty list is a known,
/// empty capture.
enum ArtifactCaptureAvailability { unavailable, recorded }
/// The recorded capture facts of one step: availability, files, and how many
/// files the bounded scan excluded or omitted. Pure: it reads the step and adds
/// no server call.
class ArtifactCapture {
const ArtifactCapture._({
required this.availability,
required this.artifacts,
required this.skipped,
required this.truncated,
});
factory ArtifactCapture.fromStep(JsonMap step) {
final value = step['artifacts'];
final available = step.containsKey('artifacts') && value is List;
final artifacts = available
? <ArtifactRecord>[
for (final item in value)
if (item is Map)
ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
]
: const <ArtifactRecord>[];
return ArtifactCapture._(
availability: available
? ArtifactCaptureAvailability.recorded
: ArtifactCaptureAvailability.unavailable,
artifacts: List<ArtifactRecord>.unmodifiable(artifacts),
skipped: _countOf(step['artifacts_skipped']),
truncated: _countOf(step['artifacts_truncated']),
);
}
final ArtifactCaptureAvailability availability;
/// Every recorded file, including utility and retired files.
final List<ArtifactRecord> artifacts;
/// Files excluded from the bounded per-step scan.
final int skipped;
/// Files omitted by the capture's total budget.
final int truncated;
bool get isAvailable => availability == ArtifactCaptureAvailability.recorded;
bool get isPartial => skipped > 0 || truncated > 0;
static int _countOf(dynamic value) {
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value.trim()) ?? 0;
return 0;
}
}
@@ -0,0 +1,109 @@
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_visits.dart';
import 'artifact_record.dart';
import 'artifact_selection.dart';
/// One gallery group: the stage-produced artifacts of a recorded stage visit.
class ArtifactGroup {
const ArtifactGroup({
required this.stageKey,
required this.visit,
required this.artifacts,
});
final String stageKey;
/// The display visit number: `control.visit` when positive, else the position
/// within the stage's ordered visits. Never a synthetic visit.
final int visit;
final List<ArtifactRecord> artifacts;
}
int _sequenceOf(JsonMap step) {
final sequence = step['sequence'];
return sequence is num ? sequence.toInt() : 0;
}
/// Sequence order with recorded order as the tie-break, matching the web
/// client's stable sort.
List<JsonMap> _orderedBySequence(List<JsonMap> steps) {
final indexed = <({int position, JsonMap step})>[
for (var index = 0; index < steps.length; index += 1)
(position: index, step: steps[index]),
];
indexed.sort((a, b) {
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
});
return <JsonMap>[for (final entry in indexed) entry.step];
}
/// Groups a run's stage artifacts by stage and recorded visit.
///
/// Stages keep first-appearance order and each stage's visits are ordered by
/// sequence. A shared `public/` file is attributed to the visit that first
/// recorded it, because the server records the whole public directory on every
/// model visit. Only visits with at least one presented stage artifact produce a
/// group, so an unavailable or empty capture never yields an empty group. An
/// artifact-less run yields an empty list rather than a fabricated stage.
List<ArtifactGroup> artifactGroups(List<JsonMap> steps) {
if (steps.isEmpty) return const <ArtifactGroup>[];
final attributed = <JsonMap, List<ArtifactRecord>>{};
final seenPublic = <String>{};
for (final recordedStep in _orderedBySequence(steps)) {
final repairs = repairArtifactNames(recordedStep);
final kept = <ArtifactRecord>[];
for (final artifact in stageArtifactsFrom(
artifactsOf(recordedStep),
repairs: repairs,
)) {
if (artifact.isPublicName) {
if (seenPublic.contains(artifact.name)) continue;
seenPublic.add(artifact.name);
}
kept.add(artifact);
}
attributed[recordedStep] = List<ArtifactRecord>.unmodifiable(kept);
}
final groups = <ArtifactGroup>[];
for (final entry in visitsByStage(steps).entries) {
final visits = entry.value;
for (var index = 0; index < visits.length; index += 1) {
final artifacts = attributed[visits[index]];
if (artifacts == null || artifacts.isEmpty) continue;
groups.add(
ArtifactGroup(
stageKey: entry.key,
visit: displayVisit(visits[index], index),
artifacts: artifacts,
),
);
}
}
return List<ArtifactGroup>.unmodifiable(groups);
}
/// One visit's stage artifacts, excluding shared public files that an earlier
/// visit already recorded. A repeated non-public name in a later visit stays
/// because it is a different recorded artifact, not the same shared file.
List<ArtifactRecord> visitArtifacts(JsonMap step, List<JsonMap> runSteps) {
final all = stageArtifacts(step);
if (runSteps.isEmpty) return all;
final seen = <String>{};
for (final candidate in _orderedBySequence(runSteps)) {
if (identical(candidate, step) ||
_sequenceOf(candidate) == _sequenceOf(step)) {
break;
}
for (final artifact in stageArtifacts(candidate)) {
if (artifact.isPublicName) seen.add(artifact.name);
}
}
return <ArtifactRecord>[
for (final artifact in all)
if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact,
];
}
@@ -0,0 +1,225 @@
/// What an artifact is from the gallery's point of view: the two media kinds it
/// previews and the file kinds it labels with a type word. Mirrors the web
/// client's `ArtifactKind` vocabulary.
enum ArtifactKind {
image,
video,
audio,
pdf,
json,
archive,
spreadsheet,
log,
code,
document,
other,
}
const Set<String> _archiveExtensions = <String>{
'zip',
'tar',
'gz',
'tgz',
'bz2',
'xz',
'rar',
'7z',
'jar',
'war',
};
const Set<String> _archiveMimes = <String>{
'application/zip',
'application/gzip',
'application/x-tar',
'application/x-7z-compressed',
'application/x-rar-compressed',
'application/java-archive',
};
const Set<String> _spreadsheetExtensions = <String>{
'csv',
'tsv',
'xls',
'xlsx',
'ods',
};
const Set<String> _spreadsheetMimes = <String>{
'text/csv',
'text/tab-separated-values',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
const Set<String> _codeExtensions = <String>{
'kt',
'kts',
'java',
'go',
'py',
'rb',
'php',
'rs',
'c',
'h',
'cc',
'cpp',
'hpp',
'cs',
'js',
'jsx',
'ts',
'tsx',
'mjs',
'cjs',
'swift',
'scala',
'sh',
'bash',
'zsh',
'fish',
'ps1',
'sql',
'yaml',
'yml',
'toml',
'ini',
'xml',
'gradle',
'properties',
'proto',
};
const Set<String> _codeMimes = <String>{
'application/xml',
'application/x-yaml',
'application/javascript',
'text/javascript',
'text/x-python',
'text/x-java-source',
'text/x-kotlin',
'application/x-sh',
'application/x-httpd-php',
'application/sql',
};
const Set<String> _documentExtensions = <String>{
'txt',
'md',
'markdown',
'rst',
'doc',
'docx',
'odt',
'rtf',
'html',
'htm',
};
const Set<String> _markdownExtensions = <String>{'md', 'markdown', 'txt'};
const Set<String> _documentMimes = <String>{
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/rtf',
};
const Map<ArtifactKind, String> _kindLabels = <ArtifactKind, String>{
ArtifactKind.image: 'Image',
ArtifactKind.video: 'Video',
ArtifactKind.audio: 'Audio',
ArtifactKind.pdf: 'PDF',
ArtifactKind.json: 'JSON',
ArtifactKind.archive: 'Archive',
ArtifactKind.spreadsheet: 'Spreadsheet',
ArtifactKind.log: 'Log',
ArtifactKind.code: 'Code',
ArtifactKind.document: 'Document',
ArtifactKind.other: 'File',
};
/// Whether a recorded content type is an image the gallery previews.
bool isImageContentType(String contentType) => contentType.startsWith('image/');
/// Whether a recorded content type is a video; videos get a poster tile and are
/// never decoded inline or autoplayed.
bool isVideoContentType(String contentType) => contentType.startsWith('video/');
/// The lowercased extension of [name], or '' when it carries none.
String _extensionOf(String name) {
final dot = name.lastIndexOf('.');
return dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
}
/// The gallery kind for a recorded content type and name.
///
/// Image and video come straight from the content type; the other kinds match
/// the normalised MIME first, then the name's extension. Pure and total: an
/// unknown type is [ArtifactKind.other], never a guess that changes an action.
ArtifactKind artifactKind(String contentType, String name) {
if (isImageContentType(contentType)) return ArtifactKind.image;
if (isVideoContentType(contentType)) return ArtifactKind.video;
final mime = contentType.split(';').first.trim().toLowerCase();
final ext = _extensionOf(name);
if (mime.startsWith('audio/')) return ArtifactKind.audio;
if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf;
if (mime.contains('json') || ext == 'json') return ArtifactKind.json;
if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) {
return ArtifactKind.archive;
}
if (_spreadsheetMimes.contains(mime) ||
_spreadsheetExtensions.contains(ext)) {
return ArtifactKind.spreadsheet;
}
if (ext == 'log') return ArtifactKind.log;
if (mime == 'text/html') return ArtifactKind.document;
if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) {
return ArtifactKind.code;
}
if (mime.startsWith('text/') ||
_documentMimes.contains(mime) ||
_documentExtensions.contains(ext)) {
return ArtifactKind.document;
}
return ArtifactKind.other;
}
/// The prose word naming [kind], so a type glyph never has to be read alone.
String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File';
/// Whether an artifact is text the viewer can render as markdown: `text/markdown`
/// or `text/plain` (parameters ignored), or an md/markdown/txt name.
bool isMarkdownArtifact(String contentType, String name) {
final mime = contentType.split(';').first.trim().toLowerCase();
if (mime == 'text/markdown' || mime == 'text/plain') return true;
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.
bool isViewerArtifact(String contentType, String name) {
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
return true;
}
return artifactKind(contentType, name) == ArtifactKind.document &&
isMarkdownArtifact(contentType, name);
}
/// Human-readable byte size, matching the web client: whole bytes under 1 KiB,
/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB).
String humanBytes(num size) {
final value = size.truncate();
const unit = 1024;
if (value < unit) return '$value B';
var div = unit;
var exp = 0;
var scaled = value ~/ unit;
while (scaled >= unit) {
div *= unit;
exp++;
scaled ~/= unit;
}
return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB';
}
@@ -0,0 +1,85 @@
import '../../../core/api_gateway.dart';
/// The retired markdown session export file name. Nothing writes it any more,
/// but a run recorded before the HTML-only change still lists `session.md`: it
/// is dated evidence that is never presented beside `session.html`.
const String legacySessionMarkdownArtifact = 'session.md';
/// The files the turn protocol itself writes for every visit. They are audit
/// evidence, not stage output, so the artifact gallery lists stage files first
/// and keeps these for an audit/debug surface.
const List<String> systemArtifactNames = <String>[
'input.md',
'memory.md',
'output.md',
'session.html',
];
/// One recorded artifact of a stage visit.
///
/// The server is the authority: [name], [url], [contentType] and [sizeBytes]
/// are read verbatim and every other field is kept in [raw]. A record is never
/// inferred or completed locally; a missing url stays empty rather than being
/// fabricated from the name. Two records with the same name stay distinct
/// because only the recorded url identifies an artifact.
class ArtifactRecord {
const ArtifactRecord({
required this.name,
required this.url,
required this.contentType,
required this.sizeBytes,
required this.raw,
});
factory ArtifactRecord.fromJson(JsonMap json) {
final raw = _frozenMap(json);
return ArtifactRecord(
name: _text(raw['name']),
url: _text(raw['url']),
contentType: _text(raw['content_type']),
sizeBytes: _intOf(raw['size_bytes']),
raw: raw,
);
}
/// The recorded file name, including any `public/` prefix.
final String name;
/// The recorded artifact url exactly as the server sent it.
final String url;
/// The server-sniffed content type, possibly with parameters.
final String contentType;
/// The recorded byte size; 0 when the server recorded none.
final int sizeBytes;
/// Every field the server sent, including fields this slice does not model.
/// Deeply unmodifiable, so a view cannot mutate the server reply.
final JsonMap raw;
bool get hasUrl => url.trim().isNotEmpty;
bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact;
bool get isSystem => isSystemArtifactName(name);
bool get isPublicName => name.startsWith('public/');
static String _text(dynamic value) => value == null ? '' : '$value';
static int _intOf(dynamic value) {
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value.trim()) ?? 0;
return 0;
}
static JsonMap _frozenMap(JsonMap json) => Map<String, dynamic>.unmodifiable(
json.map((key, value) => MapEntry(key, _frozen(value))),
);
static dynamic _frozen(dynamic value) {
if (value is Map) return _frozenMap(Map<String, dynamic>.from(value));
if (value is List) return List<dynamic>.unmodifiable(value.map(_frozen));
return value;
}
}
bool isSystemArtifactName(String name) => systemArtifactNames.contains(name);
@@ -0,0 +1,67 @@
import '../../../core/api_gateway.dart';
import 'artifact_record.dart';
/// Parses one step's recorded artifact list. An absent, null or malformed list
/// yields no records; the capture state (and its unavailable wording) is
/// reported by `artifact_capture.dart`, never treated as an empty capture here.
List<ArtifactRecord> artifactsOf(JsonMap step) {
final value = step['artifacts'];
if (value is! List) return const <ArtifactRecord>[];
return <ArtifactRecord>[
for (final item in value)
if (item is Map) ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
];
}
/// The html names a visit's session-export repairs produced.
Set<String> repairArtifactNames(JsonMap step) {
final value = step['session_export_repairs'];
if (value is! List) return const <String>{};
return <String>{
for (final entry in value)
if (entry is Map &&
entry['html'] is String &&
'${entry['html']}'.trim().isNotEmpty)
'${entry['html']}',
};
}
/// The artifacts of one visit as presented: the recorded files with the retired
/// markdown session export filtered out. Duplicate names are kept because an
/// artifact's identity is its recorded url, not its name.
List<ArtifactRecord> presentedArtifacts(Iterable<ArtifactRecord> artifacts) {
return <ArtifactRecord>[
for (final artifact in artifacts)
if (!artifact.isLegacySessionMarkdown) artifact,
];
}
/// A visit's stage-produced artifacts: everything except the turn-owned files
/// and repaired session exports. Order is preserved.
List<ArtifactRecord> stageArtifactsFrom(
Iterable<ArtifactRecord> artifacts, {
Set<String> repairs = const <String>{},
}) {
return <ArtifactRecord>[
for (final artifact in presentedArtifacts(artifacts))
if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact,
];
}
/// A visit's system files and repaired exports, in recorded order.
List<ArtifactRecord> systemArtifactsFrom(
Iterable<ArtifactRecord> artifacts, {
Set<String> repairs = const <String>{},
}) {
return <ArtifactRecord>[
for (final artifact in presentedArtifacts(artifacts))
if (artifact.isSystem || repairs.contains(artifact.name)) artifact,
];
}
/// Convenience for callers holding a raw step rather than parsed records.
List<ArtifactRecord> stageArtifacts(JsonMap step) =>
stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
List<ArtifactRecord> systemArtifacts(JsonMap step) =>
systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
@@ -0,0 +1,78 @@
import '../../../core/api_gateway.dart';
import 'artifact_capture.dart';
import 'artifact_groups.dart';
import 'artifact_selection.dart';
/// The "capture pending" wording shared by a running visit's summary and the
/// run-level empty state, so the two never spell it differently.
const String artifactCapturePending = 'capture pending';
/// The explicit message shown where the run's gallery would be when there are
/// no recorded artifacts. A running run says capture pending; a finished run
/// with available captures says plainly that nothing was recorded.
String artifactsEmptyMessage(bool executing) => executing
? 'Artifacts · $artifactCapturePending'
: 'No artifacts recorded for this run.';
/// The run summary's Artifacts section header.
///
/// The recorded count is exactly the number of tiles [artifactGroups] yields;
/// the title takes its singular form for one. A run whose capture is unavailable
/// says so instead of claiming that nothing was recorded. Partial capture is
/// flagged when any visit excluded or omitted files.
String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
final recorded = artifactGroups(
steps,
).fold<int>(0, (sum, group) => sum + group.artifacts.length);
if (recorded == 0) {
if (executing) return artifactsEmptyMessage(true);
final unavailable = steps.any(
(step) => !ArtifactCapture.fromStep(step).isAvailable,
);
return unavailable
? 'Artifacts · capture unavailable'
: artifactsEmptyMessage(false);
}
final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial);
var label =
'${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded';
if (partial) label += ' · partial capture';
return label;
}
/// The per-visit artifacts label.
///
/// A running visit says capture pending. A finished visit whose capture field was
/// absent says capture unavailable rather than "not recorded"; only an explicitly
/// empty capture says "not recorded for this visit". Recorded counts exclude the
/// turn-owned files and the retired session markdown, so the words match tiles.
String artifactsSummary(JsonMap step, {int? count}) {
final capture = ArtifactCapture.fromStep(step);
final recorded = count ?? stageArtifacts(step).length;
if (recorded == 0) {
if (step['status'] == 'running') {
return 'Artifacts · $artifactCapturePending';
}
if (!capture.isAvailable) return 'Artifacts · capture unavailable';
return 'Artifacts · not recorded for this visit';
}
var label = 'Artifacts · $recorded recorded';
if (capture.isPartial) label += ' · partial capture';
return label;
}
/// The partial-capture notes, one line per non-zero count and nothing when the
/// capture was complete or had no presented files. An unavailable capture yields
/// no notes because there is no evidence to quantify.
List<String> artifactCaptureNotes(JsonMap step) {
final notes = <String>[];
if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes;
final capture = ArtifactCapture.fromStep(step);
if (capture.skipped > 0) {
notes.add('${capture.skipped} files excluded from artifact capture.');
}
if (capture.truncated > 0) {
notes.add('${capture.truncated} files omitted by artifact capture limits.');
}
return notes;
}
@@ -0,0 +1,78 @@
import '../../../core/transport/server_url.dart';
/// A validated artifact url plus whether it points outside the configured
/// server origin.
class ResolvedArtifactUrl {
const ResolvedArtifactUrl({required this.uri, required this.external});
final Uri uri;
/// True when the url's origin differs from the configured server origin (or
/// the configured origin is unusable). A future authenticated fetch must send
/// no cookies, authorization header or other server credentials for an
/// external url.
final bool external;
String get url => uri.toString();
}
const List<String> _unsafePrefixes = <String>['//', r'\\', r'\/', '/\\'];
/// Resolves a recorded artifact url for display and opening.
///
/// A server-relative path (`/artifacts/...`, or a path without the leading
/// slash) resolves against the configured websocket endpoint's http(s) origin,
/// dropping the endpoint path and query. An absolute http(s) url is preserved,
/// including its encoded path and query. Output is always http(s): protocol-
/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls
/// are rejected with null. A blank or invalid configured endpoint resolves no
/// relative path; it never invents a host.
ResolvedArtifactUrl? resolveArtifactUrl(
String configuredEndpoint,
String artifactUrl,
) {
final raw = artifactUrl.trim();
if (raw.isEmpty) return null;
for (final prefix in _unsafePrefixes) {
if (raw.startsWith(prefix)) return null;
}
final parsed = Uri.tryParse(raw);
if (parsed == null) return null;
final configured = _httpOrigin(configuredEndpoint);
if (parsed.hasScheme) {
final scheme = parsed.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (!parsed.hasAuthority || parsed.host.isEmpty) return null;
if (parsed.userInfo.isNotEmpty) return null;
return ResolvedArtifactUrl(
uri: parsed,
external: configured == null || parsed.origin != configured.origin,
);
}
if (configured == null) return null;
final relative = raw.startsWith('/') ? raw : '/$raw';
final resolved = Uri.tryParse('${configured.origin}$relative');
if (resolved == null) return null;
final scheme = resolved.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (!resolved.hasAuthority || resolved.host.isEmpty) return null;
if (resolved.userInfo.isNotEmpty) return null;
return ResolvedArtifactUrl(uri: resolved, external: false);
}
/// The http(s) origin of a configured websocket endpoint, or null when the
/// endpoint is blank, malformed, or not a ws/wss url.
Uri? _httpOrigin(String configuredEndpoint) {
try {
final endpoint = ServerUrl.validate(configuredEndpoint);
final http = Uri.parse(endpoint.httpUrl);
final scheme = http.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (http.host.isEmpty) return null;
return Uri.parse(http.origin);
} on FormatException {
return null;
}
}
@@ -0,0 +1,76 @@
import 'artifact_groups.dart';
import 'artifact_kind.dart';
import 'artifact_record.dart';
/// One artifact in the viewer's filtered page list, with the stage visit it
/// belongs to. [identity] is the recorded url when there is one; otherwise it is
/// 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.artifact,
required this.pageIndex,
});
final String stageKey;
final int visit;
final ArtifactRecord artifact;
/// Position in the filtered page list.
final int pageIndex;
String get identity => artifact.hasUrl
? artifact.url
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
}
/// 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
/// filters and orders records the gallery already holds.
List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
final pages = <PagedArtifact>[];
for (final group in groups) {
for (final artifact in group.artifacts) {
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
pages.add(
PagedArtifact(
stageKey: group.stageKey,
visit: group.visit,
artifact: artifact,
pageIndex: pages.length,
),
);
}
}
return List<PagedArtifact>.unmodifiable(pages);
}
/// Each page's recorded url mapped to its page index, so a tile and the viewer
/// derive from the same ordered list. The first occurrence of a url wins. A
/// record with no recorded url has no fetchable identity and is omitted.
Map<String, int> viewerIndexByUrl(List<ArtifactGroup> groups) {
final indices = <String, int>{};
for (final page in pagedArtifacts(groups)) {
if (!page.artifact.hasUrl) continue;
indices.putIfAbsent(page.artifact.url, () => page.pageIndex);
}
return indices;
}
/// Paging from [current] by [delta] within `count` pages, clamped at both ends
/// so a page never wraps and an empty list is index 0.
int pagedIndex(int current, int delta, int count) {
if (count <= 0) return 0;
final wanted = current + delta;
if (wanted < 0) return 0;
if (wanted >= count) return count - 1;
return wanted;
}
/// The viewer's position label, e.g. `2 of 5 · image/png`.
String artifactViewerPositionLabel(int index, int count, String contentType) {
final type = contentType.split(';').first.trim();
return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}';
}