diff --git a/app/lib/features/graph/layout/linear_graph_layout.dart b/app/lib/features/graph/layout/linear_graph_layout.dart index 1269f6cc..bc4aec74 100644 --- a/app/lib/features/graph/layout/linear_graph_layout.dart +++ b/app/lib/features/graph/layout/linear_graph_layout.dart @@ -4,6 +4,7 @@ import '../domain/graph_definition.dart'; import '../domain/graph_protocol.dart'; import '../routing/route_models.dart'; import 'layout_models.dart'; +import 'linear_label_placement.dart'; /// Graph-space spacings for [layoutLinearGraph], the web's /// `DEFAULT_GRAPH_METRICS` tightened for a phone-sized canvas. @@ -27,19 +28,71 @@ class LinearGraphMetrics { final double portSpacing; final double labelPadding; final double labelGap; + + /// These metrics with every column gap and lane widened by [width] and + /// [height], making room for one more label in each. + LinearGraphMetrics widenedBy(double width, double height) => + LinearGraphMetrics( + hGap: hGap + width, + pad: pad, + laneSpacing: laneSpacing + height, + terminalGap: terminalGap, + trackStep: trackStep, + portSpacing: portSpacing, + labelPadding: labelPadding, + labelGap: labelGap, + ); } +/// How many times [layoutLinearGraph] widens its gaps for a crowded label +/// before it falls back to the free shelf below the drawing. +const int _maxWidening = 4; + /// The web's `layoutGraph` (web/src/graph.js): stages keep their declaration /// order on one row; Failure and Success share a lower row, Failure on the /// left, the pair centred. Every edge that is not a straight step to the next /// stage gets its own lane below the stage row, in stable edge-id order, so no /// two runs share a track. Pure: measured extents in, geometry out. +/// +/// No label box comes within [edgeLabelClearance] of a node or another label. +/// When a label finds no such spot on its own route, the column gaps and lanes +/// grow by the widest and tallest label and the layout runs again, rather than +/// letting a label cover a node. (GraphLayout, GraphRouting) layoutLinearGraph({ required List nodes, required List edges, required Map extents, required Map labelExtents, LinearGraphMetrics metrics = const LinearGraphMetrics(), +}) { + var widest = 0.0, tallest = 0.0; + for (final extent in labelExtents.values) { + widest = math.max(widest, extent.width); + tallest = math.max(tallest, extent.height); + } + var m = metrics; + for (var attempt = 0; ; attempt++) { + final (result, misfits) = _layoutPass( + nodes: nodes, + edges: edges, + extents: extents, + labelExtents: labelExtents, + metrics: m, + ); + if (misfits.isEmpty || attempt == _maxWidening) return result; + m = m.widenedBy( + widest + 2 * edgeLabelClearance, + tallest + 2 * edgeLabelClearance, + ); + } +} + +((GraphLayout, GraphRouting), Set) _layoutPass({ + required List nodes, + required List edges, + required Map extents, + required Map labelExtents, + required LinearGraphMetrics metrics, }) { final m = metrics; final stages = [ @@ -90,20 +143,23 @@ class LinearGraphMetrics { } if (stages.isEmpty) { return ( - GraphLayout( - nodes: const [], - width: 0, - height: 0, - rankCount: 0, - ranks: const {}, - ), - GraphRouting( - routes: const [], - labels: const [], - skipped: skipped, - width: 0, - height: 0, + ( + GraphLayout( + nodes: const [], + width: 0, + height: 0, + rankCount: 0, + ranks: const {}, + ), + GraphRouting( + routes: const [], + labels: const [], + skipped: skipped, + width: 0, + height: 0, + ), ), + const {}, ); } @@ -228,15 +284,6 @@ class LinearGraphMetrics { return (left.right, stageXs[gap]); } - (double, double) gapContaining(double x) { - if (x < contentLeft) return (m.pad, contentLeft); - for (var gap = 1; gap < stageCount; gap++) { - final (lo, hi) = gapBounds(gap); - if (x <= hi) return (lo, hi); - } - return gapBounds(stageCount); - } - // Forward edges first: a straight route keeps one horizontal run by sharing // its y between source and target, fanned per source so two labels clear. final forwardY = {}; @@ -277,7 +324,6 @@ class LinearGraphMetrics { edge.outcome == 'error' && edge.target == failureEnd; final routes = []; - final labels = []; for (final edge in placed) { final source = byKey[edge.source]!; final target = byKey[edge.target]!; @@ -423,40 +469,18 @@ class LinearGraphMetrics { points: points, ), ); - - final extent = labelOf(edge); - if (edge.label.isEmpty || extent.width == 0) continue; - final spot = _labelSpot(points, extent.width); - if (spot.vertical) { - // Beside a vertical run, kept inside its own gap clear of both boxes. - final (lo, hi) = gapContaining(spot.x); - final left = math.max( - lo + 2, - math.min(spot.x + m.labelGap, hi - extent.width - 2), - ); - labels.add( - EdgeLabelBox( - edgeId: edge.id, - x: left, - y: spot.y - extent.height / 2, - width: extent.width, - height: extent.height, - ), - ); - } else { - // Above a horizontal run, centred on it. - labels.add( - EdgeLabelBox( - edgeId: edge.id, - x: spot.x - extent.width / 2, - y: spot.y - extent.height - m.labelGap, - width: extent.width, - height: extent.height, - ), - ); - } } + // Every label keeps clear of every node and earlier label; one that finds + // no spot on its own route is a misfit, and the caller grows the gaps. + final placement = placeLinearLabels( + routes: routes, + extents: {for (final edge in placed) edge.id: labelOf(edge)}, + nodes: boxes, + labelGap: m.labelGap, + ); + final labels = placement.labels; + final contentBottom = hasTerminal ? boxes .where((box) => box.terminal) @@ -476,14 +500,17 @@ class LinearGraphMetrics { ranks: {for (final box in boxes) box.key: box.rank}, ); return ( - layout, - GraphRouting( - routes: routes, - labels: labels, - skipped: skipped, - width: right, - height: height, + ( + layout, + GraphRouting( + routes: routes, + labels: labels, + skipped: skipped, + width: right, + height: height, + ), ), + placement.misfits, ); } @@ -502,44 +529,6 @@ List _collapse(List points) { return result; } -/// The web's `labelPointFor`: the middle of the widest horizontal run that -/// holds the label, else the longest run, flagged when it is vertical. -({double x, double y, bool vertical}) _labelSpot( - List points, - double labelWidth, -) { - if (points.length < 2) { - return (x: points.first.x, y: points.first.y, vertical: false); - } - (RoutePoint, RoutePoint)? bestH; - var bestHw = -1.0; - (RoutePoint, RoutePoint)? bestV; - var bestVh = -1.0; - for (var i = 1; i < points.length; i++) { - final a = points[i - 1]; - final b = points[i]; - if (a.y == b.y && (b.x - a.x).abs() > bestHw) { - bestHw = (b.x - a.x).abs(); - bestH = (a, b); - } else if (a.x == b.x && (b.y - a.y).abs() > bestVh) { - bestVh = (b.y - a.y).abs(); - bestV = (a, b); - } - } - ({double x, double y, bool vertical}) horizontal( - (RoutePoint, RoutePoint) run, - ) => (x: (run.$1.x + run.$2.x) / 2, y: run.$1.y, vertical: false); - ({double x, double y, bool vertical}) vertical( - (RoutePoint, RoutePoint) run, - ) => (x: run.$1.x, y: (run.$1.y + run.$2.y) / 2, vertical: true); - if (bestH != null && bestHw >= math.max(labelWidth, 24)) { - return horizontal(bestH); - } - if (bestV != null && bestVh >= bestHw) return vertical(bestV); - if (bestH != null) return horizontal(bestH); - return vertical(bestV!); -} - /// Places a run at the first position from `desired`, stepping outward, that /// keeps `eps` from every placed run whose cross-interval overlaps. class _SegmentAllocator { diff --git a/app/lib/features/graph/layout/linear_label_placement.dart b/app/lib/features/graph/layout/linear_label_placement.dart new file mode 100644 index 00000000..a6790627 --- /dev/null +++ b/app/lib/features/graph/layout/linear_label_placement.dart @@ -0,0 +1,260 @@ +import 'dart:math' as math; + +import '../routing/route_models.dart'; +import 'layout_models.dart'; + +/// The space every placed edge label keeps from every node box and from every +/// other label, in logical pixels. +const double edgeLabelClearance = 4; + +/// The labels for one set of routes, and the edges that found no spot on +/// their own route. +class LinearLabelPlacement { + const LinearLabelPlacement({required this.labels, required this.misfits}); + + /// One box per labelled route, in route order. + final List labels; + + /// Edge ids whose label had to leave its route for the free shelf below the + /// drawing. A layout grows its gaps and tries again while this is non-empty. + final Set misfits; +} + +/// Places one measured label per route so no label box comes within +/// [clearance] of a node box or of an earlier label. +/// +/// Each label tries positions along its own route, beside a run with +/// [labelGap] to the wire: the longest horizontal run first (above, then +/// below), sliding from the middle towards both ends, then the other +/// horizontal runs, then vertical runs (right, then left). A first pass also +/// keeps the box off every wire; a second pass allows crossing a wire but +/// never a node or a label. A label with no free spot on its route goes to a +/// shelf below everything and is reported in [LinearLabelPlacement.misfits]. +LinearLabelPlacement placeLinearLabels({ + required List routes, + required Map extents, + required List nodes, + required double labelGap, + double clearance = edgeLabelClearance, +}) { + final labels = []; + final misfits = {}; + final pending = <(EdgeRoute, LabelExtent)>[]; + for (final route in routes) { + final extent = extents[route.id]; + if (route.label.isEmpty || extent == null || extent.width == 0) continue; + final candidates = _candidates(route, extent, labelGap); + _Rect? chosen; + for (final avoidWires in const [true, false]) { + for (final rect in candidates) { + if (_free(rect, nodes, labels, clearance) && + (!avoidWires || !_crossesWire(rect, routes))) { + chosen = rect; + break; + } + } + if (chosen != null) break; + } + if (chosen == null) { + misfits.add(route.id); + pending.add((route, extent)); + continue; + } + labels.add(_box(route.id, chosen)); + } + + // The shelf sits below every node, wire and label, so it cannot overlap. + var shelf = 0.0; + for (final node in nodes) { + shelf = math.max(shelf, node.bottom); + } + for (final route in routes) { + for (final point in route.points) { + shelf = math.max(shelf, point.y); + } + } + for (final label in labels) { + shelf = math.max(shelf, label.bottom); + } + for (final (route, extent) in pending) { + var top = shelf + clearance + labelGap; + final left = math.max(0.0, _centreX(route) - extent.width / 2); + var rect = _Rect(left, top, extent.width, extent.height); + while (!_free(rect, nodes, labels, clearance)) { + top += extent.height + clearance; + rect = _Rect(left, top, extent.width, extent.height); + } + labels.add(_box(route.id, rect)); + } + labels.sort( + (a, b) => _indexOf(routes, a.edgeId).compareTo(_indexOf(routes, b.edgeId)), + ); + return LinearLabelPlacement(labels: labels, misfits: misfits); +} + +/// Whether two axis-aligned boxes come within [clearance] of each other. +bool labelRectsClash( + double ax, + double ay, + double aw, + double ah, + double bx, + double by, + double bw, + double bh, + double clearance, +) => + ax < bx + bw + clearance && + bx < ax + aw + clearance && + ay < by + bh + clearance && + by < ay + ah + clearance; + +int _indexOf(List routes, int id) => + routes.indexWhere((route) => route.id == id); + +EdgeLabelBox _box(int id, _Rect rect) => EdgeLabelBox( + edgeId: id, + x: rect.x, + y: rect.y, + width: rect.w, + height: rect.h, +); + +bool _free( + _Rect rect, + List nodes, + List labels, + double clearance, +) { + if (rect.x < 0 || rect.y < 0) return false; + for (final node in nodes) { + if (labelRectsClash( + rect.x, + rect.y, + rect.w, + rect.h, + node.x, + node.y, + node.width, + node.height, + clearance, + )) { + return false; + } + } + for (final label in labels) { + if (labelRectsClash( + rect.x, + rect.y, + rect.w, + rect.h, + label.x, + label.y, + label.width, + label.height, + clearance, + )) { + return false; + } + } + return true; +} + +/// True when a wire passes through the label's interior. +bool _crossesWire(_Rect rect, List routes) { + for (final route in routes) { + for (var i = 1; i < route.points.length; i++) { + final a = route.points[i - 1], b = route.points[i]; + final x0 = math.min(a.x, b.x), x1 = math.max(a.x, b.x); + final y0 = math.min(a.y, b.y), y1 = math.max(a.y, b.y); + final right = rect.x + rect.w, bottom = rect.y + rect.h; + // Orthogonal segments: one axis is a line, the other an interval. + final acrossX = x0 == x1 + ? x0 > rect.x && x0 < right + : x0 < right && x1 > rect.x; + final acrossY = y0 == y1 + ? y0 > rect.y && y0 < bottom + : y0 < bottom && y1 > rect.y; + if (acrossX && acrossY) return true; + } + } + return false; +} + +List<_Rect> _candidates(EdgeRoute route, LabelExtent extent, double gap) { + const fractions = [0.5, 0.35, 0.65, 0.2, 0.8, 0, 1]; + final w = extent.width, h = extent.height; + final horizontals = <_Run>[]; + final verticals = <_Run>[]; + for (var i = 1; i < route.points.length; i++) { + final a = route.points[i - 1], b = route.points[i]; + if (a.y == b.y && a.x != b.x) { + horizontals.add(_Run(math.min(a.x, b.x), math.max(a.x, b.x), a.y, i)); + } else if (a.x == b.x && a.y != b.y) { + verticals.add(_Run(math.min(a.y, b.y), math.max(a.y, b.y), a.x, i)); + } + } + int longestFirst(_Run a, _Run b) { + final byLength = b.length.compareTo(a.length); + return byLength != 0 ? byLength : a.order.compareTo(b.order); + } + + horizontals.sort(longestFirst); + verticals.sort(longestFirst); + final rects = <_Rect>[]; + for (final run in horizontals) { + for (final fraction in fractions) { + final left = _along(run, fraction, w); + rects + ..add(_Rect(left, run.at - gap - h, w, h)) + ..add(_Rect(left, run.at + gap, w, h)); + } + } + for (final run in verticals) { + for (final fraction in fractions) { + final top = _along(run, fraction, h); + rects + ..add(_Rect(run.at + gap, top, w, h)) + ..add(_Rect(run.at - gap - w, top, w, h)); + } + } + return rects; +} + +/// The start of a [size]-long label centred at [fraction] of [run], kept on +/// the run when it is long enough to hold the whole label. +double _along(_Run run, double fraction, double size) { + final centre = run.lo + run.length * fraction; + if (run.length < size) return run.lo + run.length / 2 - size / 2; + return math.min(math.max(centre - size / 2, run.lo), run.hi - size); +} + +double _centreX(EdgeRoute route) { + var lo = double.infinity, hi = double.negativeInfinity; + for (final point in route.points) { + lo = math.min(lo, point.x); + hi = math.max(hi, point.x); + } + return route.points.isEmpty ? 0 : (lo + hi) / 2; +} + +/// One straight run: [lo]..[hi] along its axis, at [at] across it. +class _Run { + const _Run(this.lo, this.hi, this.at, this.order); + + final double lo; + final double hi; + final double at; + final int order; + + double get length => hi - lo; +} + +class _Rect { + const _Rect(this.x, this.y, this.w, this.h); + + final double x; + final double y; + final double w; + final double h; +} diff --git a/app/lib/features/graph/widgets/run_graph_canvas.dart b/app/lib/features/graph/widgets/run_graph_canvas.dart index c0fb925e..953bb2ba 100644 --- a/app/lib/features/graph/widgets/run_graph_canvas.dart +++ b/app/lib/features/graph/widgets/run_graph_canvas.dart @@ -248,20 +248,46 @@ class RunGraphCanvas extends StatelessWidget { ], ); } + + Widget _takenLabel(EdgeRoute route, Color color) => RunRouteLabel( + edgeId: route.id, + label: route.label, + order: state.routeOrder(route.source, route.outcome, route.target), + style: style.labelStyle, + color: color, + ); } /// A taken route's label led by its place in the run (`2`, or `2, 5` for a /// loop), so the path reads in order. -extension on RunGraphCanvas { - Widget _takenLabel(EdgeRoute route, Color color) { - final order = state.routeOrder(route.source, route.outcome, route.target); - final text = Text(route.label, style: style.labelStyle); +/// +/// The canvas places this widget and [RunGraphMeasurements] measures the same +/// one, so the routed label box covers the order badge as well as the text. +class RunRouteLabel extends StatelessWidget { + const RunRouteLabel({ + super.key, + required this.edgeId, + required this.label, + required this.order, + required this.style, + required this.color, + }); + + final int edgeId; + final String label; + final List order; + final TextStyle style; + final Color color; + + @override + Widget build(BuildContext context) { + final text = Text(label, style: style); if (order.isEmpty) return text; return Row( mainAxisSize: MainAxisSize.min, children: [ Container( - key: ValueKey('run-route-order:${route.id}'), + key: ValueKey('run-route-order:$edgeId'), padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), decoration: BoxDecoration( color: color, @@ -348,6 +374,7 @@ class RunGraphMeasurements extends StatelessWidget { required this.maxNodeWidth, required this.labelStyle, required this.recordedStatuses, + required this.state, required this.onNodeSize, required this.onLabelSize, }); @@ -357,8 +384,14 @@ class RunGraphMeasurements extends StatelessWidget { final double maxNodeWidth; final TextStyle labelStyle; final Map recordedStatuses; + + /// The run whose route order badges lead the taken labels. + final RunGraphState state; final void Function(String, Size) onNodeSize; - final void Function(String, Size) onLabelSize; + + /// Receives each edge's label size keyed by its edge id, because two edges + /// with the same outcome can carry different order badges. + final void Function(int, Size) onLabelSize; @override Widget build(BuildContext context) => Offstage( @@ -391,8 +424,14 @@ class RunGraphMeasurements extends StatelessWidget { for (final edge in edges) MeasuredChild( key: ValueKey('run-label:${edge.id}'), - onSize: (size) => onLabelSize(edge.label, size), - child: Text(edge.label, style: labelStyle), + onSize: (size) => onLabelSize(edge.id, size), + child: RunRouteLabel( + edgeId: edge.id, + label: edge.label, + order: state.routeOrder(edge.source, edge.outcome, edge.target), + style: labelStyle, + color: const Color(0x00000000), + ), ), ], ), diff --git a/app/lib/features/graph/widgets/run_graph_view.dart b/app/lib/features/graph/widgets/run_graph_view.dart index 3ce95beb..f1494a73 100644 --- a/app/lib/features/graph/widgets/run_graph_view.dart +++ b/app/lib/features/graph/widgets/run_graph_view.dart @@ -76,7 +76,7 @@ class RunGraphView extends StatefulWidget { class _RunGraphViewState extends State { final Map _nodeSizes = {}; - final Map _labelSizes = {}; + final Map _labelSizes = {}; final Map _measuredStatuses = {}; final GraphViewportController _viewport = GraphViewportController(); TextScaler? _scaler; @@ -99,7 +99,7 @@ class _RunGraphViewState extends State { } } - void _record(Map sizes, String key, Size size) { + void _record(Map sizes, K key, Size size) { if (sizes[key] == size) return; sizes[key] = size; if (_rebuildScheduled) return; @@ -122,7 +122,7 @@ class _RunGraphViewState extends State { } final labelExtents = {}; for (final edge in edges) { - final size = _labelSizes[edge.label]; + final size = _labelSizes[edge.id]; if (size == null) return null; labelExtents[edge.id] = LabelExtent( width: size.width, @@ -239,6 +239,7 @@ class _RunGraphViewState extends State { maxNodeWidth: constraints.maxWidth, labelStyle: style.labelStyle, recordedStatuses: statuses, + state: state, onNodeSize: (key, size) => _record(_nodeSizes, key, size), onLabelSize: (key, size) => _record(_labelSizes, key, size), ), diff --git a/app/test/features/graph/layout/linear_label_placement_test.dart b/app/test/features/graph/layout/linear_label_placement_test.dart new file mode 100644 index 00000000..11a8fd45 --- /dev/null +++ b/app/test/features/graph/layout/linear_label_placement_test.dart @@ -0,0 +1,230 @@ +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/layout/linear_graph_layout.dart'; +import 'package:pipelines_app/features/graph/layout/linear_label_placement.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +GraphNodeBox _node(String key, double x, double y, double w, double h) => + GraphNodeBox( + key: key, + terminal: false, + stageIndex: 0, + rank: 0, + x: x, + y: y, + width: w, + height: h, + ); + +EdgeRoute _route(int id, String label, List<(double, double)> points) { + final route = [for (final (x, y) in points) RoutePoint(x, y)]; + return EdgeRoute( + id: id, + source: 'a', + outcome: label, + target: 'b', + label: label, + fallback: false, + kind: RouteKind.forward, + straight: route.length == 2, + sourcePort: RoutePort(side: RoutePortSide.right, point: route.first), + targetPort: RoutePort(side: RoutePortSide.left, point: route.last), + points: route, + ); +} + +/// The gap between two boxes, 0 when they touch or overlap. +double _gap(EdgeLabelBox label, double x, double y, double w, double h) { + final dx = math.max(0.0, math.max(x - label.right, label.x - (x + w))); + final dy = math.max(0.0, math.max(y - label.bottom, label.y - (y + h))); + return math.max(dx, dy); +} + +void _expectClear(List labels, List nodes) { + for (final label in labels) { + for (final node in nodes) { + expect( + _gap(label, node.x, node.y, node.width, node.height), + greaterThanOrEqualTo(edgeLabelClearance), + reason: 'label ${label.edgeId} is within clearance of ${node.key}', + ); + } + for (final other in labels) { + if (identical(other, label)) continue; + expect( + _gap(label, other.x, other.y, other.width, other.height), + greaterThanOrEqualTo(edgeLabelClearance), + reason: 'labels ${label.edgeId} and ${other.edgeId} collide', + ); + } + } +} + +/// The distance from a label box to the nearest point of its own route. +double _distanceToRoute(EdgeLabelBox label, EdgeRoute route) { + var best = double.infinity; + for (var i = 1; i < route.points.length; i++) { + final a = route.points[i - 1], b = route.points[i]; + best = math.min( + best, + _gap( + label, + math.min(a.x, b.x), + math.min(a.y, b.y), + (a.x - b.x).abs(), + (a.y - b.y).abs(), + ), + ); + } + return best; +} + +void main() { + test('a node just above the wire pushes the label below it', () { + final nodes = [_node('crowd', 60, 20, 80, 28)]; + final route = _route(1, 'success', [(0, 50), (200, 50)]); + final placement = placeLinearLabels( + routes: [route], + extents: {1: LabelExtent(width: 50, height: 16)}, + nodes: nodes, + labelGap: 3, + ); + expect(placement.misfits, isEmpty); + final label = placement.labels.single; + _expectClear(placement.labels, nodes); + expect(_distanceToRoute(label, route), lessThanOrEqualTo(3)); + }); + + test('nodes on both sides of a run slide the label to a free stretch', () { + final nodes = [ + _node('above', 40, 10, 120, 36), + _node('below', 40, 54, 120, 36), + ]; + final route = _route(1, 'retry', [(0, 50), (300, 50)]); + final placement = placeLinearLabels( + routes: [route], + extents: {1: LabelExtent(width: 40, height: 16)}, + nodes: nodes, + labelGap: 3, + ); + expect(placement.misfits, isEmpty); + _expectClear(placement.labels, nodes); + expect(placement.labels.single.x, greaterThanOrEqualTo(164)); + }); + + test('labels sharing a run never overlap each other', () { + final routes = [ + _route(1, 'success', [(0, 50), (240, 50)]), + _route(2, 'error', [(0, 50), (240, 50)]), + _route(3, 'blocked', [(0, 50), (240, 50)]), + ]; + final placement = placeLinearLabels( + routes: routes, + extents: { + for (final route in routes) + route.id: LabelExtent(width: 60, height: 16), + }, + nodes: const [], + labelGap: 3, + ); + expect(placement.labels, hasLength(3)); + expect(placement.misfits, isEmpty); + _expectClear(placement.labels, const []); + }); + + test('a label longer than every run still keeps clear of the nodes', () { + final nodes = [ + _node('left', 0, 0, 100, 40), + _node('right', 130, 0, 100, 40), + ]; + final route = _route(1, 'implementer-with-an-unusually-long-outcome', [ + (100, 20), + (130, 20), + ]); + final placement = placeLinearLabels( + routes: [route], + extents: {1: LabelExtent(width: 260, height: 16)}, + nodes: nodes, + labelGap: 3, + ); + // No spot on a 30px run holds a 260px label between two boxes, so it is a + // reported misfit on the shelf rather than a label covering a node. + expect(placement.misfits, {1}); + _expectClear(placement.labels, nodes); + expect(placement.labels.single.y, greaterThan(40)); + }); + + test('a tight corner between three nodes finds the open side', () { + // An L route: down beside `left`, then along under `below`'s top edge. + final nodes = [ + _node('left', 0, 0, 96, 120), + _node('top', 104, 0, 120, 40), + _node('below', 160, 92, 100, 40), + ]; + final route = _route(1, 'error', [(100, 20), (100, 80), (300, 80)]); + final placement = placeLinearLabels( + routes: [route], + extents: {1: LabelExtent(width: 36, height: 16)}, + nodes: nodes, + labelGap: 3, + ); + expect(placement.misfits, isEmpty); + _expectClear(placement.labels, nodes); + expect( + _distanceToRoute(placement.labels.single, route), + lessThanOrEqualTo(3), + ); + }); + + test('the linear layout widens its gaps instead of covering a node', () { + GraphNode stage(String key, int index) => + GraphNode(key: key, terminal: false, stageIndex: index); + final nodes = [stage('plan', 0), stage('build', 1)]; + GraphEdge edge(int id, String source, String outcome, String target) => + GraphEdge( + id: id, + source: source, + outcome: outcome, + target: target, + label: outcome, + fallback: false, + knownTarget: true, + ); + final edges = [ + edge(0, 'plan', 'success', 'build'), + edge(1, 'build', 'retry', 'build'), + edge(2, 'build', 'rework', 'plan'), + ]; + final extents = { + 'plan': NodeExtent(width: 60, height: 40), + 'build': NodeExtent(width: 60, height: 40), + }; + // Back-edge labels far wider than the default column gaps. + final labels = { + 0: LabelExtent(width: 50, height: 16), + 1: LabelExtent(width: 220, height: 16), + 2: LabelExtent(width: 240, height: 16), + }; + final (layout, routing) = layoutLinearGraph( + nodes: nodes, + edges: edges, + extents: extents, + labelExtents: labels, + ); + expect(routing.labels, hasLength(3)); + _expectClear(routing.labels, layout.nodes); + for (final label in routing.labels) { + expect(label.right, lessThanOrEqualTo(routing.width)); + expect(label.bottom, lessThanOrEqualTo(routing.height)); + expect( + _distanceToRoute(label, routing.routeFor(label.edgeId)!), + lessThanOrEqualTo(const LinearGraphMetrics().labelGap), + reason: 'label ${label.edgeId} stays on its own route', + ); + } + }); +} diff --git a/app/test/features/graph/widgets/graph_label_clearance_test.dart b/app/test/features/graph/widgets/graph_label_clearance_test.dart new file mode 100644 index 00000000..74f7a6f6 --- /dev/null +++ b/app/test/features/graph/widgets/graph_label_clearance_test.dart @@ -0,0 +1,164 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/layout/linear_label_placement.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_canvas.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; + +import '../domain/graph_fixtures.dart'; + +const String _longKey = 'implementer-with-an-unusually-long-stage-label'; + +/// The browser probe's definition (tool/graph_canvas_probe.dart): a long +/// wrapping stage, a fallback error, a retry self-loop and blocked/error +/// routes to the terminals. +JsonMap _probeGraph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': _longKey, 'retry': 'build'}, + }, + { + 'key': _longKey, + 'type': 'model', + 'edges': {'success': 'audit', 'blocked': '#failure'}, + }, + { + 'key': 'audit', + 'type': 'model', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +/// A run that took plan -> build, retried build, then went on to the long +/// stage, so taken labels carry order badges (`1`, `2`, `3`). +JsonMap _probeRun() => { + 'id': 7, + 'steps': [ + step(sequence: 1, stage: 'plan', outcome: 'success', target: 'build'), + step(sequence: 2, stage: 'build', outcome: 'retry', target: 'build'), + step(sequence: 3, stage: 'build', outcome: 'success', target: _longKey), + step( + sequence: 4, + stage: _longKey, + status: 'running', + startedAt: '2026-10-21T10:00:00Z', + ), + ], + 'current_stage': _longKey, + 'executing': true, +}; + +Widget _host(Widget child, double scale, double width) => MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox(width: width, height: 700, child: child), + ), + ), + ), +); + +/// Asserts no placed label comes within the clearance of any placed node or +/// other label, using the on-screen rectangles of the canvas children. +void _expectLabelsClear(WidgetTester tester, Finder canvas) { + final scale = tester + .widget(find.byType(InteractiveViewer)) + .transformationController! + .value + .getMaxScaleOnAxis(); + final placed = tester.widgetList( + find.descendant(of: canvas, matching: find.byType(Positioned)), + ); + final nodes = []; + final labels = []; + for (final positioned in placed) { + final rect = tester.getRect(find.byWidget(positioned.child).first); + // Nodes are placed with their measured box, labels by origin only; the + // edge layer fills the whole canvas and is neither. + if (positioned.width != null) { + nodes.add(rect); + } else if (positioned.right == null && positioned.bottom == null) { + labels.add(rect); + } + } + expect(nodes, isNotEmpty); + expect(labels, isNotEmpty); + // Slightly under the graph-space clearance, for float rounding. + final margin = (edgeLabelClearance - 0.01) * scale; + for (final label in labels) { + final grown = label.inflate(margin); + for (final node in nodes) { + expect( + grown.overlaps(node), + isFalse, + reason: 'label $label overlaps node $node', + ); + } + for (final other in labels) { + if (other == label) continue; + expect( + grown.overlaps(other), + isFalse, + reason: 'label $label overlaps label $other', + ); + } + } +} + +void main() { + for (final scale in const [1.0, 2.0]) { + for (final width in const [560.0, 1200.0]) { + testWidgets('definition labels clear nodes at ${scale}x, $width wide', ( + tester, + ) async { + await tester.pumpWidget( + _host( + DefinitionGraphView(graph: _probeGraph(), onSelected: (_) {}), + scale, + width, + ), + ); + await tester.pump(); + await tester.pump(); + _expectLabelsClear(tester, find.byType(DefinitionGraphCanvas)); + expect(tester.takeException(), isNull); + }); + + testWidgets('run labels with order badges clear nodes at ${scale}x, ' + '$width wide', (tester) async { + await tester.pumpWidget( + _host( + RunGraphView( + graph: _probeGraph(), + run: _probeRun(), + onStageSelected: (_) {}, + now: () => DateTime.utc(2026, 10, 21, 10, 2), + ), + scale, + width, + ), + ); + await tester.pump(); + await tester.pump(); + expect(find.byType(RunRouteLabel), findsWidgets); + _expectLabelsClear(tester, find.byType(RunGraphCanvas)); + expect(tester.takeException(), isNull); + }); + } + } +}