Files
pipelines/app/lib/features/graph/widgets/run_graph_view.dart
T

332 lines
11 KiB
Dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/graph_definition.dart';
import '../domain/run_graph_state.dart';
import '../domain/stage_visits.dart';
import '../layout/graph_node_layout.dart';
import '../layout/layout_models.dart';
import '../routing/graph_edge_routing.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'run_graph_canvas.dart';
/// The run tab's exact missing-graph wording (web `RUN_GRAPH_MISSING`).
const String runGraphMissing = 'This server did not include the run graph.';
/// The run legend's route-class words (web graph legend).
const String runGraphExecuted = 'Executed';
const String runGraphNotExecuted = 'Not executed';
/// One run's definition drawn as evidence: visited stages carry their recorded
/// status, only taken routes are solid and arrowed, and every other route stays
/// dashed and muted.
///
/// [run] is the run detail map whose recorded steps are the only source of
/// visits, statuses and routes. A node with no recorded visit is not a control:
/// tapping it does nothing, and no visit, session or status is manufactured for
/// it. A visited stage reports its exact key through [onStageSelected] so the
/// caller can open that stage's latest recorded visit. Visited terminals are
/// shown with the outcome that resolved there but have no recorded visit to
/// open, so they stay non-interactive.
///
/// The view fills its bounded constraints with a stock [InteractiveViewer] for
/// pan and zoom; the elapsed line appears only while the run is executing and
/// is static (no invented progress or timer).
class RunGraphView extends StatefulWidget {
const RunGraphView({
super.key,
required this.graph,
required this.run,
required this.onStageSelected,
this.selectedStage,
this.now,
});
/// The run's definition graph, or null when the server omitted it.
final JsonMap? graph;
/// The run detail whose recorded steps supply all execution evidence.
final JsonMap run;
/// Reports one visited stage's exact key; never called for an unvisited node.
final ValueChanged<String> onStageSelected;
final String? selectedStage;
/// Injectable clock for deterministic elapsed labels; defaults to now.
final DateTime Function()? now;
@override
State<RunGraphView> createState() => _RunGraphViewState();
}
class _RunGraphViewState extends State<RunGraphView> {
final Map<String, Size> _nodeSizes = {};
final Map<String, Size> _labelSizes = {};
final Map<String, String?> _measuredStatuses = {};
TextScaler? _scaler;
bool _rebuildScheduled = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final scaler = MediaQuery.textScalerOf(context);
if (scaler != _scaler) {
_scaler = scaler;
_nodeSizes.clear();
_labelSizes.clear();
}
}
void _record(Map<String, Size> sizes, String key, Size size) {
if (sizes[key] == size) return;
sizes[key] = size;
if (_rebuildScheduled) return;
_rebuildScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_rebuildScheduled = false;
if (mounted) setState(() {});
});
}
(GraphLayout, GraphRouting)? _geometry(
List<GraphNode> nodes,
List<GraphEdge> edges,
) {
final extents = <String, NodeExtent>{};
for (final node in nodes) {
final size = _nodeSizes[node.key];
if (size == null) return null;
extents[node.key] = NodeExtent(width: size.width, height: size.height);
}
final labelExtents = <int, LabelExtent>{};
for (final edge in edges) {
final size = _labelSizes[edge.label];
if (size == null) return null;
labelExtents[edge.id] = LabelExtent(
width: size.width,
height: size.height,
);
}
final layout = layoutGraphNodes(
nodes: nodes,
edges: edges,
extents: extents,
config: graphCanvasLayoutConfig(labelExtents.values),
);
final routing = routeGraphEdges(
layout: layout,
edges: edges,
labelExtents: labelExtents,
config: graphCanvasRoutingConfig(),
);
return (layout, routing);
}
/// Executed evidence shown by the native node's recorded-status affordance.
///
/// A stage shows its latest recorded status (sequence order) verbatim. A
/// terminal has no step; it shows the recorded route outcome that resolved
/// there. Null means no recorded execution, so an unvisited node cannot be
/// mistaken for a visit.
String? _recordedStatus(
GraphNode node,
RunGraphState state,
Map<String, List<JsonMap>> visits,
) {
if (!state.isStageVisited(node.key)) return null;
if (!node.terminal) {
final stageVisits = visits[node.key];
if (stageVisits == null || stageVisits.isEmpty) return null;
final status = '${stageVisits.last['status'] ?? ''}'.trim();
return status.isEmpty ? null : status;
}
for (final route in state.takenRoutes) {
final parts = route.split('\u0000');
if (parts.length == 3 && parts[2] == node.key) return parts[1];
}
return null;
}
@override
Widget build(BuildContext context) {
final graph = widget.graph;
final nodes = graph == null ? const <GraphNode>[] : graphNodes(graph);
final edges = graph == null ? const <GraphEdge>[] : graphEdges(graph);
final style = GraphCanvasStyle.of(context);
final state = runGraphState(widget.run);
final rawSteps = widget.run['steps'];
final steps = rawSteps is List
? rawSteps.whereType<Map>().map(JsonMap.from).toList()
: const <JsonMap>[];
final visits = visitsByStage(steps);
final statuses = <String, String?>{
for (final node in nodes) node.key: _recordedStatus(node, state, visits),
};
// A status line changes the node's measured height. Drop only the stale
// extents so this frame never places a taller node in its old box; the
// offstage measurement reports the new extent and schedules the placement.
for (final entry in statuses.entries) {
if (_measuredStatuses[entry.key] != entry.value) {
_nodeSizes.remove(entry.key);
_measuredStatuses[entry.key] = entry.value;
}
}
_measuredStatuses.removeWhere((key, _) => !statuses.containsKey(key));
return LayoutBuilder(
builder: (context, constraints) {
assert(
constraints.hasBoundedWidth && constraints.hasBoundedHeight,
'RunGraphView needs a bounded viewport; constrain it, for example '
'with a SizedBox or an Expanded slot.',
);
if (nodes.isEmpty) return _message(runGraphMissing, style);
final geometry = _geometry(nodes, edges);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_header(state, style),
Expanded(
child: Stack(
fit: StackFit.expand,
children: [
if (geometry != null)
RunGraphCanvas(
nodes: nodes,
layout: geometry.$1,
routing: geometry.$2,
state: state,
style: style,
recordedStatuses: statuses,
selectedStage: widget.selectedStage,
onStageSelected: widget.onStageSelected,
)
else
const SizedBox.shrink(),
RunGraphMeasurements(
nodes: nodes,
edges: edges,
maxNodeWidth: constraints.maxWidth,
labelStyle: style.labelStyle,
recordedStatuses: statuses,
onNodeSize: (key, size) => _record(_nodeSizes, key, size),
onLabelSize: (key, size) => _record(_labelSizes, key, size),
),
],
),
),
if (geometry != null && geometry.$2.skipped.isNotEmpty)
Flexible(
child: SingleChildScrollView(
child: _message(
[
for (final diagnostic in geometry.$2.skipped)
'${diagnostic.source} → ${diagnostic.outcome}: '
'${diagnostic.message}',
].join('\n'),
style,
),
),
),
],
);
},
);
}
Widget _message(String message, GraphCanvasStyle style) => Padding(
padding: const EdgeInsets.all(24),
child: Align(
alignment: AlignmentDirectional.topStart,
child: Text(message, style: style.messageStyle),
),
);
Widget _header(RunGraphState state, GraphCanvasStyle style) {
final cupertino = usesCupertinoHost(context);
final executedColor = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final mutedColor = style.edgeColor;
final active = state.activeStage;
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0),
child: Wrap(
spacing: 16,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Semantics(
container: true,
label: 'Route kinds',
child: Wrap(
spacing: 12,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_LegendEntry(
icon: cupertino
? CupertinoIcons.arrow_right
: Icons.arrow_forward,
label: runGraphExecuted,
color: executedColor,
),
_LegendEntry(
icon: cupertino ? CupertinoIcons.minus : Icons.remove,
label: runGraphNotExecuted,
color: mutedColor,
),
],
),
),
if (active != null) _elapsed(active, state.currentStageStartedAt),
],
),
);
}
Widget _elapsed(String active, String? startedAt) {
final started = startedAt == null ? null : DateTime.tryParse(startedAt);
final duration = started == null
? null
: _formatElapsed((widget.now ?? DateTime.now)().difference(started));
final text = duration == null
? 'Current stage $active'
: 'Current stage $active · elapsed $duration';
return Text(text, style: GraphCanvasStyle.of(context).labelStyle);
}
}
class _LegendEntry extends StatelessWidget {
const _LegendEntry({
required this.icon,
required this.label,
required this.color,
});
final IconData icon;
final String label;
final Color color;
@override
Widget build(BuildContext context) => Wrap(
spacing: 4,
runSpacing: 2,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
ExcludeSemantics(child: Icon(icon, color: color)),
Text(label),
],
);
}
String _formatElapsed(Duration duration) {
final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds;
if (seconds < 60) return '${seconds}s';
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
}