Merge branch 'main' into flutter/s1-list

This commit is contained in:
2026-10-21 17:02:00 +01:00
29 changed files with 4312 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}';
}
@@ -0,0 +1,105 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// One vertical-corridor request from a wrapping route.
///
/// A route needs a track right of its source and a track beside its target;
/// both gaps are 0-based column gaps (`rankCount` is the right free gap).
class CorridorRequest {
const CorridorRequest({
required this.edgeId,
required this.sourceGap,
required this.targetGap,
});
final int edgeId;
final int sourceGap;
final int targetGap;
}
/// Assigned x coordinates for every wrapping route's two vertical tracks.
class CorridorPlan {
CorridorPlan({
required Map<int, double> sourceX,
required Map<int, double> targetX,
}) : sourceX = Map.unmodifiable(sourceX),
targetX = Map.unmodifiable(targetX);
final Map<int, double> sourceX;
final Map<int, double> targetX;
}
/// Spreads corridor requests across the free band of each column gap.
///
/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks
/// are distinct inside a gap; a narrow gap compresses the spacing instead of
/// pushing a corridor into a node column.
CorridorPlan planCorridors({
required GraphLayout layout,
required List<CorridorRequest> requests,
required RoutingConfig config,
}) {
final ordered = <CorridorRequest>[...requests]
..sort((a, b) => a.edgeId.compareTo(b.edgeId));
final slots = <int, List<_Slot>>{};
for (final request in ordered) {
slots
.putIfAbsent(request.sourceGap, () => <_Slot>[])
.add(_Slot(request.edgeId, source: true));
slots
.putIfAbsent(request.targetGap, () => <_Slot>[])
.add(_Slot(request.edgeId, source: false));
}
final gaps = ColumnGaps(
nodes: layout.nodes,
rankCount: layout.rankCount,
layoutWidth: layout.width,
);
final sourceX = <int, double>{};
final targetX = <int, double>{};
final gapKeys = slots.keys.toList()..sort();
for (final gapKey in gapKeys) {
final gapSlots = slots[gapKey]!;
final band = gaps.band(gapKey, config.nodeClearance);
final positions = _trackPositions(
band,
gapSlots.length,
config.corridorSpacing,
);
for (var index = 0; index < gapSlots.length; index += 1) {
if (gapSlots[index].source) {
sourceX[gapSlots[index].edgeId] = positions[index];
} else {
targetX[gapSlots[index].edgeId] = positions[index];
}
}
}
return CorridorPlan(sourceX: sourceX, targetX: targetX);
}
List<double> _trackPositions(GapBand band, int count, double spacing) {
if (count == 0) return const <double>[];
if (band.open) {
return <double>[
for (var index = 0; index < count; index += 1) band.lo + spacing * index,
];
}
final width = band.hi - band.lo;
if (count == 1) return <double>[(band.lo + band.hi) / 2];
if (width <= 0) return List<double>.filled(count, band.lo);
final step = math.min(spacing, width / (count - 1));
return <double>[
for (var index = 0; index < count; index += 1) band.lo + step * index,
];
}
class _Slot {
const _Slot(this.edgeId, {required this.source});
final int edgeId;
final bool source;
}
@@ -0,0 +1,175 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// Places one measured edge label without overlapping a node or another label.
///
/// Candidates are tried in a deterministic order: the midpoint of each
/// horizontal run (above, then below), then each vertical run (right, then
/// left), sliding along the run before giving up. A run too narrow for the
/// box pushes the label to a free shelf below the drawing, which expands the
/// routing bounds instead of covering a node.
EdgeLabelBox placeEdgeLabel({
required EdgeRoute route,
required LabelExtent extent,
required List<GraphNodeBox> nodes,
required List<EdgeLabelBox> placed,
required RoutingConfig config,
required double floorY,
}) {
final width = extent.width;
final height = extent.height;
for (final candidate in _candidates(route, width, height, config.labelGap)) {
final box = EdgeLabelBox(
edgeId: route.id,
x: candidate.x,
y: candidate.y,
width: width,
height: height,
);
if (_fits(box, nodes, placed, config)) return box;
}
// The fallback shelf is below every route and every existing label, so it
// cannot cover a node. Growing it down expands the returned bounds.
var top = math.max(
floorY,
placed.fold<double>(0, (bottom, box) => math.max(bottom, box.bottom)),
);
top += config.labelGap;
final centre = _routeCentreX(route);
final step = math.max(height + config.labelGap, 1.0);
for (var attempt = 0; attempt < 100000; attempt += 1) {
final x = math.max(0.0, centre - width / 2);
final box = EdgeLabelBox(
edgeId: route.id,
x: x,
y: top,
width: width,
height: height,
);
if (_fits(box, nodes, placed, config)) return box;
top += step;
}
// A zero-sized label cannot collide; this is unreachable for real extents.
return EdgeLabelBox(
edgeId: route.id,
x: math.max(0.0, centre - width / 2),
y: top,
width: width,
height: height,
);
}
bool _fits(
EdgeLabelBox box,
List<GraphNodeBox> nodes,
List<EdgeLabelBox> placed,
RoutingConfig config,
) {
if (box.x < 0 || box.y < 0) return false;
for (final node in nodes) {
if (boxIntersectsNode(
x: box.x,
y: box.y,
width: box.width,
height: box.height,
node: node,
gap: config.labelGap,
)) {
return false;
}
}
for (final other in placed) {
if (boxesOverlap(
ax: box.x,
ay: box.y,
aw: box.width,
ah: box.height,
bx: other.x,
by: other.y,
bw: other.width,
bh: other.height,
gap: config.labelGap,
)) {
return false;
}
}
return true;
}
List<_LabelCandidate> _candidates(
EdgeRoute route,
double width,
double height,
double gap,
) {
const fractions = <double>[0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92];
final horizontals = <_Run>[];
final verticals = <_Run>[];
for (var index = 1; index < route.points.length; index += 1) {
final a = route.points[index - 1];
final b = route.points[index];
if (a.y == b.y) {
horizontals.add(_Run(a, b, (b.x - a.x).abs(), index));
} else if (a.x == b.x) {
verticals.add(_Run(a, b, (b.y - a.y).abs(), index));
}
}
horizontals.sort((a, b) {
final length = b.length.compareTo(a.length);
return length != 0 ? length : a.order.compareTo(b.order);
});
verticals.sort((a, b) {
final length = b.length.compareTo(a.length);
return length != 0 ? length : a.order.compareTo(b.order);
});
final candidates = <_LabelCandidate>[];
for (final run in horizontals) {
for (final fraction in fractions) {
final x = run.a.x + (run.b.x - run.a.x) * fraction;
final left = x - width / 2;
candidates.add(_LabelCandidate(left, run.a.y - gap - height));
candidates.add(_LabelCandidate(left, run.a.y + gap));
}
}
for (final run in verticals) {
for (final fraction in fractions) {
final y = run.a.y + (run.b.y - run.a.y) * fraction;
final top = y - height / 2;
candidates.add(_LabelCandidate(run.a.x + gap, top));
candidates.add(_LabelCandidate(run.a.x - gap - width, top));
}
}
return candidates;
}
double _routeCentreX(EdgeRoute route) {
if (route.points.isEmpty) return 0;
var lo = route.points.first.x;
var hi = lo;
for (final point in route.points) {
lo = math.min(lo, point.x);
hi = math.max(hi, point.x);
}
return (lo + hi) / 2;
}
class _Run {
const _Run(this.a, this.b, this.length, this.order);
final RoutePoint a;
final RoutePoint b;
final double length;
final int order;
}
class _LabelCandidate {
const _LabelCandidate(this.x, this.y);
final double x;
final double y;
}
@@ -0,0 +1,265 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import '../layout/layout_models.dart';
import 'corridor_plan.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// One routed edge before labels and bounds are assembled.
///
/// Internal to the routing library: callers receive the immutable public
/// [EdgeRoute] instead.
class PlannedEdgeRoute {
PlannedEdgeRoute({
required this.edge,
required this.kind,
required this.straight,
required this.sourcePort,
required this.targetPort,
required List<RoutePoint> points,
}) : points = List.unmodifiable(points);
final GraphEdge edge;
final RouteKind kind;
final bool straight;
final RoutePort sourcePort;
final RoutePort targetPort;
final List<RoutePoint> points;
EdgeRoute toRoute() => EdgeRoute(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
label: edge.label,
fallback: edge.fallback,
kind: kind,
straight: straight,
sourcePort: sourcePort,
targetPort: targetPort,
points: points,
);
}
/// Plans orthogonal polylines for every edge whose endpoints have placed boxes.
///
/// [edges] must already be filtered to known endpoints and sorted by id. The
/// plan is deterministic: forward one-rank routes take a straight horizontal
/// run when the measured boxes and labels leave room, and every other route
/// gets a unique lane below the node grid plus vertical corridors inside the
/// column gaps. Corridors and lanes never enter a node column.
///
/// All horizontal stubs share one [AxisTrackAllocator], so two different edges
/// cannot occupy the same run in a column gap even when they touch different
/// nodes on the same row.
List<PlannedEdgeRoute> planEdgeRoutes({
required GraphLayout layout,
required List<GraphEdge> edges,
required double maxLabelHeight,
required RoutingConfig config,
}) {
if (edges.isEmpty) return const <PlannedEdgeRoute>[];
final nodes = <String, GraphNodeBox>{
for (final node in layout.nodes) node.key: node,
};
final kinds = <int, RouteKind>{};
for (final edge in edges) {
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
kinds[edge.id] = _kindFor(edge, source, target, layout);
}
final trackSpacing = math.max(
config.portSpacing,
maxLabelHeight + config.labelGap,
);
final runs = AxisTrackAllocator(trackSpacing);
final straightY = <int, double>{};
for (final edge in edges) {
if (kinds[edge.id] != RouteKind.forward) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
if (target.rank != source.rank + 1) continue;
if (target.x <= source.right) continue;
final sourceInset = portInset(source, config.portSpacing);
final targetInset = portInset(target, config.portSpacing);
final lo = math.max(source.y + sourceInset, target.y + targetInset);
final hi = math.min(
source.bottom - sourceInset,
target.bottom - targetInset,
);
if (hi <= lo) continue;
final y = runs.allocate(
desired: (lo + hi) / 2,
min: lo,
max: hi,
spanLo: source.right,
spanHi: target.x,
);
if (y != null) straightY[edge.id] = y;
}
final laneStep = math.max(
config.laneSpacing,
maxLabelHeight + config.labelGap,
);
final contentBottom = layout.nodes.fold<double>(
0,
(bottom, node) => math.max(bottom, node.bottom),
);
final wrapPlans = <_WrapPlan>[];
final corridorRequests = <CorridorRequest>[];
var laneIndex = 0;
for (final edge in edges) {
if (straightY.containsKey(edge.id)) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
final kind = kinds[edge.id]!;
final laneY =
contentBottom + config.nodeClearance + laneStep * (laneIndex + 1);
laneIndex += 1;
final sourceGap = (source.rank + 1).clamp(0, layout.rankCount);
final targetGap = kind == RouteKind.forward
? target.rank.clamp(0, layout.rankCount)
: (target.rank + 1).clamp(0, layout.rankCount);
corridorRequests.add(
CorridorRequest(
edgeId: edge.id,
sourceGap: sourceGap,
targetGap: targetGap,
),
);
wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY));
}
final corridors = planCorridors(
layout: layout,
requests: corridorRequests,
config: config,
);
final sourceTrackX = corridors.sourceX;
final targetTrackX = corridors.targetX;
final sourcePorts = <int, RoutePort>{};
final targetPorts = <int, RoutePort>{};
for (final edge in edges) {
final y = straightY[edge.id];
if (y == null) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
sourcePorts[edge.id] = RoutePort(
side: RoutePortSide.right,
point: RoutePoint(source.right, y),
);
targetPorts[edge.id] = RoutePort(
side: RoutePortSide.left,
point: RoutePoint(target.x, y),
);
}
for (final plan in wrapPlans) {
final edge = plan.edge;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
final sourceTrack = sourceTrackX[edge.id]!;
final targetTrack = targetTrackX[edge.id]!;
final sourceInset = portInset(source, config.portSpacing);
final targetInset = portInset(target, config.portSpacing);
final sourceY = runs.allocate(
desired: source.y + source.height / 2,
min: source.y + sourceInset,
max: source.bottom - sourceInset,
spanLo: source.right,
spanHi: sourceTrack,
);
final targetSide = plan.kind == RouteKind.forward
? RoutePortSide.left
: RoutePortSide.right;
final targetBorder = targetSide == RoutePortSide.left
? target.x
: target.right;
final targetY = runs.allocate(
desired: target.y + target.height / 2,
min: target.y + targetInset,
max: target.bottom - targetInset,
spanLo: math.min(targetBorder, targetTrack),
spanHi: math.max(targetBorder, targetTrack),
);
sourcePorts[edge.id] = RoutePort(
side: RoutePortSide.right,
point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2),
);
targetPorts[edge.id] = RoutePort(
side: targetSide,
point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2),
);
}
final planned = <int, PlannedEdgeRoute>{};
for (final edge in edges) {
final value = straightY[edge.id];
if (value != null) {
planned[edge.id] = PlannedEdgeRoute(
edge: edge,
kind: kinds[edge.id]!,
straight: true,
sourcePort: sourcePorts[edge.id]!,
targetPort: targetPorts[edge.id]!,
points: _collapse(<RoutePoint>[
sourcePorts[edge.id]!.point,
targetPorts[edge.id]!.point,
]),
);
}
}
for (final plan in wrapPlans) {
final sourceTrack = sourceTrackX[plan.edge.id]!;
final targetTrack = targetTrackX[plan.edge.id]!;
planned[plan.edge.id] = PlannedEdgeRoute(
edge: plan.edge,
kind: plan.kind,
straight: false,
sourcePort: sourcePorts[plan.edge.id]!,
targetPort: targetPorts[plan.edge.id]!,
points: _collapse(<RoutePoint>[
sourcePorts[plan.edge.id]!.point,
RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y),
RoutePoint(sourceTrack, plan.laneY),
RoutePoint(targetTrack, plan.laneY),
RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y),
targetPorts[plan.edge.id]!.point,
]),
);
}
return <PlannedEdgeRoute>[for (final edge in edges) planned[edge.id]!];
}
RouteKind _kindFor(
GraphEdge edge,
GraphNodeBox source,
GraphNodeBox target,
GraphLayout layout,
) {
if (edge.source == edge.target) return RouteKind.selfLoop;
final sourceRank = layout.ranks[edge.source] ?? source.rank;
final targetRank = layout.ranks[edge.target] ?? target.rank;
if (targetRank > sourceRank) return RouteKind.forward;
if (targetRank < sourceRank) return RouteKind.back;
return RouteKind.sameRank;
}
List<RoutePoint> _collapse(List<RoutePoint> points) {
final result = <RoutePoint>[];
for (final point in points) {
if (result.isEmpty || result.last != point) result.add(point);
}
return result;
}
class _WrapPlan {
_WrapPlan({required this.edge, required this.kind, required this.laneY});
final GraphEdge edge;
final RouteKind kind;
final double laneY;
}
@@ -0,0 +1,135 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import '../layout/layout_models.dart';
import 'edge_label_placement.dart';
import 'edge_route_planner.dart';
import 'route_models.dart';
/// Routes every definition edge that has a placed source and target.
///
/// The node boxes and ranks come from the landed [GraphLayout]; this function
/// never moves them, invents a node or assumes a node size. Callers supply one
/// measured [LabelExtent] for every routed edge, plus the clearances and lane
/// spacing in [RoutingConfig].
///
/// Edges with an unknown, empty or missing endpoint are returned in
/// [GraphRouting.skipped] with their definition identity intact. A routed edge
/// keeps its id, source, outcome, target, label and fallback flag. Results are
/// ordered by definition edge id and are stable for repeated input.
GraphRouting routeGraphEdges({
required GraphLayout layout,
required List<GraphEdge> edges,
required Map<int, LabelExtent> labelExtents,
required RoutingConfig config,
}) {
final ordered = <GraphEdge>[...edges]..sort((a, b) => a.id.compareTo(b.id));
final seenIds = <int>{};
for (final edge in ordered) {
if (!seenIds.add(edge.id)) {
throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id');
}
}
final nodes = <String, GraphNodeBox>{
for (final node in layout.nodes) node.key: node,
};
final routed = <GraphEdge>[];
final skipped = <RouteDiagnostic>[];
for (final edge in ordered) {
if (!nodes.containsKey(edge.source)) {
skipped.add(
RouteDiagnostic(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
reason: RouteSkipReason.unknownSource,
message: 'source "${edge.source}" has no placed node',
),
);
continue;
}
if (!edge.knownTarget || !nodes.containsKey(edge.target)) {
skipped.add(
RouteDiagnostic(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
reason: RouteSkipReason.unknownTarget,
message: edge.target.isEmpty
? 'edge target is empty'
: 'target "${edge.target}" has no placed node',
),
);
continue;
}
routed.add(edge);
}
final missing = <int>[
for (final edge in routed)
if (!labelExtents.containsKey(edge.id)) edge.id,
];
if (missing.isNotEmpty) {
throw ArgumentError.value(
missing,
'labelExtents',
'missing measured label extents for routed edges',
);
}
var maxLabelHeight = 0.0;
for (final edge in routed) {
maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height);
}
final planned = planEdgeRoutes(
layout: layout,
edges: routed,
maxLabelHeight: maxLabelHeight,
config: config,
);
final routes = <EdgeRoute>[for (final plan in planned) plan.toRoute()];
var floorY = layout.height;
for (final route in routes) {
for (final point in route.points) {
floorY = math.max(floorY, point.y);
}
}
final labels = <EdgeLabelBox>[];
for (var index = 0; index < routes.length; index += 1) {
labels.add(
placeEdgeLabel(
route: routes[index],
extent: labelExtents[routes[index].id]!,
nodes: layout.nodes,
placed: labels,
config: config,
floorY: floorY,
),
);
}
var width = layout.width;
var height = layout.height;
for (final route in routes) {
for (final point in route.points) {
width = math.max(width, point.x);
height = math.max(height, point.y);
}
}
for (final label in labels) {
width = math.max(width, label.right);
height = math.max(height, label.bottom);
}
return GraphRouting(
routes: routes,
labels: labels,
skipped: skipped,
width: width + config.boundsPadding,
height: height + config.boundsPadding,
);
}
@@ -0,0 +1,175 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
/// Geometry helpers for deterministic orthogonal routing.
///
/// Everything here is plain numbers: no Flutter types, no drawing and no
/// assumed metrics. The helpers are internal to the routing library.
/// Reserves horizontal or vertical tracks without collinear overlap.
///
/// A track is a position on [axis] plus the interval it spans on the other
/// axis. Two tracks only conflict when both their positions and their spans
/// overlap, so a long cross lane and a short stub may share a coordinate when
/// their runs do not meet.
class AxisTrackAllocator {
AxisTrackAllocator(this.step);
final double step;
final List<_Track> _placed = <_Track>[];
/// The nearest free position to [desired], or null when none is found.
double? allocate({
required double desired,
required double min,
required double max,
required double spanLo,
required double spanHi,
}) {
if (max < min) return null;
final start = desired.clamp(min, max);
var spacing = step;
while (spacing > 0.0001) {
for (var attempt = 0; attempt <= 512; attempt += 1) {
final candidates = attempt == 0
? <double>[start]
: <double>[start + attempt * spacing, start - attempt * spacing];
for (final candidate in candidates) {
if (candidate < min || candidate > max) continue;
if (_isFree(candidate, spanLo, spanHi, spacing)) {
_placed.add(_Track(candidate, spanLo, spanHi));
return candidate;
}
}
}
spacing /= 2;
}
return null;
}
bool _isFree(double position, double spanLo, double spanHi, double spacing) {
for (final track in _placed) {
if ((track.position - position).abs() >= spacing) continue;
final overlaps = track.lo <= spanHi && spanLo <= track.hi;
if (overlaps) return false;
}
return true;
}
}
class _Track {
const _Track(this.position, this.lo, this.hi);
final double position;
final double lo;
final double hi;
}
/// The x band available for vertical corridors in each column gap.
///
/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the
/// last column. Left/right bounds come from the placed boxes themselves, so a
/// corridor never crosses a column, including heterogeneous node widths.
class ColumnGaps {
ColumnGaps({
required List<GraphNodeBox> nodes,
required this.rankCount,
required this.layoutWidth,
}) : _left = List<double>.filled(rankCount + 1, 0),
_right = List<double>.filled(rankCount + 1, layoutWidth) {
final rankRight = List<double>.filled(rankCount, 0);
final rankLeft = List<double>.filled(rankCount, layoutWidth);
for (final node in nodes) {
if (node.rank < 0 || node.rank >= rankCount) continue;
rankRight[node.rank] = math.max(rankRight[node.rank], node.right);
rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x);
}
var left = 0.0;
for (var rank = 0; rank < rankCount; rank += 1) {
_left[rank] = left;
left = math.max(left, rankRight[rank]);
}
_left[rankCount] = left;
var right = layoutWidth;
_right[rankCount] = right;
for (var rank = rankCount - 1; rank >= 0; rank -= 1) {
right = math.min(right, rankLeft[rank]);
_right[rank] = right;
}
}
final int rankCount;
final double layoutWidth;
final List<double> _left;
final List<double> _right;
/// The usable band in gap [index], inset by at most [clearance].
///
/// The rightmost gap is open-ended because a loop may expand the canvas;
/// every other gap is bounded by the neighbouring columns.
GapBand band(int index, double clearance) {
final gap = index.clamp(0, rankCount);
final left = _left[gap];
final right = _right[gap];
if (gap == rankCount) {
return GapBand(lo: left + clearance, hi: double.infinity, open: true);
}
if (gap == 0) {
return GapBand(
lo: double.negativeInfinity,
hi: right - clearance,
open: true,
);
}
final width = math.max(0.0, right - left);
final inset = math.min(clearance, width / 4);
return GapBand(lo: left + inset, hi: right - inset, open: false);
}
}
/// One usable corridor band.
class GapBand {
const GapBand({required this.lo, required this.hi, required this.open});
final double lo;
final double hi;
final bool open;
}
/// The inset a port keeps from a node corner.
double portInset(GraphNodeBox node, double portSpacing) =>
math.min(portSpacing / 2, node.height / 2);
/// True when an axis-aligned box overlaps [node], optionally inflated by [gap].
bool boxIntersectsNode({
required double x,
required double y,
required double width,
required double height,
required GraphNodeBox node,
double gap = 0,
}) {
return x < node.right + gap &&
x + width > node.x - gap &&
y < node.bottom + gap &&
y + height > node.y - gap;
}
/// True when two label-sized boxes overlap, optionally inflated by [gap].
bool boxesOverlap({
required double ax,
required double ay,
required double aw,
required double ah,
required double bx,
required double by,
required double bw,
required double bh,
double gap = 0,
}) {
return ax < bx + bw + gap &&
ax + aw + gap > bx &&
ay < by + bh + gap &&
ay + ah + gap > by;
}
@@ -0,0 +1,261 @@
/// Pure orthogonal geometry for a workflow graph's edges and labels.
///
/// The caller owns every measurement: node boxes come from the landed
/// `GraphLayout`, label extents are measured after text layout, and clearances
/// or spacings come from [RoutingConfig]. This library never assumes a font,
/// widget style, device class or CSS value, and it has no Flutter imports.
///
/// The same result can be built into a painter, native widgets or a test
/// fixture; no drawing decision lives here.
library;
export 'routing_inputs.dart';
/// One point on an orthogonal route, in graph space.
class RoutePoint {
const RoutePoint(this.x, this.y);
final double x;
final double y;
@override
bool operator ==(Object other) =>
other is RoutePoint && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
@override
String toString() => 'RoutePoint($x, $y)';
}
/// The border an edge leaves or enters through.
enum RoutePortSide { top, right, bottom, left }
/// A route endpoint on a node's border.
///
/// [side] is the edge's outward direction: a right port leaves to the right
/// (or enters from the right), a left port leaves to the left, and so on.
class RoutePort {
const RoutePort({required this.side, required this.point});
final RoutePortSide side;
final RoutePoint point;
@override
bool operator ==(Object other) =>
other is RoutePort && other.side == side && other.point == point;
@override
int get hashCode => Object.hash(side, point);
@override
String toString() => 'RoutePort($side, ${point.x}, ${point.y})';
}
/// How an edge relates to the layer it comes from.
enum RouteKind {
/// The target is in a later rank.
forward,
/// Both endpoints share a rank (a cycle or strongly connected component).
sameRank,
/// The target is in an earlier rank. Ranks from `assignGraphRanks` only
/// produce this for a caller-supplied layout; it is still routed honestly.
back,
/// The source and target are the same node.
selfLoop,
}
/// Why an edge has no route.
enum RouteSkipReason {
/// The source key has no placed node.
unknownSource,
/// The target key has no placed node, including an empty/unknown target.
unknownTarget,
}
/// One edge's deterministic orthogonal route.
///
/// [id], [source], [outcome], [target], [label] and [fallback] are copied from
/// the definition edge unchanged. [points] starts at [sourcePort] and ends at
/// [targetPort]; every consecutive pair shares one coordinate.
class EdgeRoute {
EdgeRoute({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.label,
required this.fallback,
required this.kind,
required this.straight,
required this.sourcePort,
required this.targetPort,
required List<RoutePoint> points,
}) : points = List.unmodifiable(points);
final int id;
final String source;
final String outcome;
final String target;
final String label;
final bool fallback;
final RouteKind kind;
/// True when the route is one straight horizontal segment.
final bool straight;
final RoutePort sourcePort;
final RoutePort targetPort;
final List<RoutePoint> points;
@override
bool operator ==(Object other) =>
other is EdgeRoute &&
other.id == id &&
other.source == source &&
other.outcome == outcome &&
other.target == target &&
other.label == label &&
other.fallback == fallback &&
other.kind == kind &&
other.straight == straight &&
other.sourcePort == sourcePort &&
other.targetPort == targetPort &&
_samePoints(other.points, points);
@override
int get hashCode => Object.hash(
id,
source,
outcome,
target,
label,
fallback,
kind,
straight,
sourcePort,
targetPort,
Object.hashAll(points),
);
}
/// One measured label box placed clear of node interiors.
class EdgeLabelBox {
const EdgeLabelBox({
required this.edgeId,
required this.x,
required this.y,
required this.width,
required this.height,
});
final int edgeId;
final double x;
final double y;
final double width;
final double height;
double get right => x + width;
double get bottom => y + height;
@override
bool operator ==(Object other) =>
other is EdgeLabelBox &&
other.edgeId == edgeId &&
other.x == x &&
other.y == y &&
other.width == width &&
other.height == height;
@override
int get hashCode => Object.hash(edgeId, x, y, width, height);
}
/// An edge the router deliberately did not draw.
///
/// The definition identity is preserved so a caller can present a diagnostic
/// instead of inventing a node, route or visit.
class RouteDiagnostic {
const RouteDiagnostic({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.reason,
required this.message,
});
final int id;
final String source;
final String outcome;
final String target;
final RouteSkipReason reason;
final String message;
@override
bool operator ==(Object other) =>
other is RouteDiagnostic &&
other.id == id &&
other.source == source &&
other.outcome == outcome &&
other.target == target &&
other.reason == reason &&
other.message == message;
@override
int get hashCode => Object.hash(id, source, outcome, target, reason, message);
}
/// The complete immutable routing result.
///
/// [width] and [height] include every route point and label box as well as the
/// landed layout bounds, so a loop that leaves the node grid expands the
/// returned box instead of being clipped. [routes] and [skipped] are ordered by
/// definition edge id; [labels] follows the same order.
class GraphRouting {
GraphRouting({
required List<EdgeRoute> routes,
required List<EdgeLabelBox> labels,
required List<RouteDiagnostic> skipped,
required this.width,
required this.height,
}) : routes = List.unmodifiable(routes),
labels = List.unmodifiable(labels),
skipped = List.unmodifiable(skipped);
final List<EdgeRoute> routes;
final List<EdgeLabelBox> labels;
final List<RouteDiagnostic> skipped;
final double width;
final double height;
bool get isEmpty => routes.isEmpty;
/// The route for [id], or null when that edge was skipped.
EdgeRoute? routeFor(int id) {
for (final route in routes) {
if (route.id == id) return route;
}
return null;
}
/// The label box for [id], or null when the edge was skipped.
EdgeLabelBox? labelFor(int id) {
for (final label in labels) {
if (label.edgeId == id) return label;
}
return null;
}
}
bool _samePoints(List<RoutePoint> a, List<RoutePoint> b) {
if (a.length != b.length) return false;
for (var index = 0; index < a.length; index += 1) {
if (a[index] != b[index]) return false;
}
return true;
}
@@ -0,0 +1,64 @@
/// Caller-supplied measurements and clearances for graph-edge routing.
///
/// No font, widget style, device class or CSS value is assumed: every size is
/// measured or chosen by the caller.
library;
void _requireFiniteNonNegative(String name, double value) {
if (!value.isFinite || value < 0) {
throw ArgumentError.value(value, name, 'must be finite and non-negative');
}
}
void _requireFinitePositive(String name, double value) {
if (!value.isFinite || value <= 0) {
throw ArgumentError.value(value, name, 'must be finite and positive');
}
}
/// A caller-measured edge label extent, in logical pixels.
class LabelExtent {
LabelExtent({required this.width, required this.height}) {
_requireFiniteNonNegative('width', width);
_requireFiniteNonNegative('height', height);
}
final double width;
final double height;
}
/// Clearances and spacings a caller reserves for edge geometry.
///
/// [nodeClearance] is the distance a lane or corridor keeps from every node
/// edge. [laneSpacing] separates the horizontal tracks used by wrapping
/// routes, [corridorSpacing] separates vertical tracks inside one column gap,
/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label
/// box off its wire; [boundsPadding] is added to the returned bounds.
///
/// The router may widen a lane step beyond [laneSpacing] when the measured
/// label heights need the room. Inside a narrow column gap it compresses
/// corridor or port spacing rather than routing a track into a node column.
class RoutingConfig {
RoutingConfig({
required this.nodeClearance,
required this.laneSpacing,
required this.corridorSpacing,
required this.portSpacing,
required this.labelGap,
this.boundsPadding = 0,
}) {
_requireFiniteNonNegative('nodeClearance', nodeClearance);
_requireFinitePositive('laneSpacing', laneSpacing);
_requireFinitePositive('corridorSpacing', corridorSpacing);
_requireFinitePositive('portSpacing', portSpacing);
_requireFiniteNonNegative('labelGap', labelGap);
_requireFiniteNonNegative('boundsPadding', boundsPadding);
}
final double nodeClearance;
final double laneSpacing;
final double corridorSpacing;
final double portSpacing;
final double labelGap;
final double boundsPadding;
}