Keep graph edge labels clear of nodes and other labels

The linear layout used by the definition and run graphs placed each
outcome label at the middle of its widest run with no collision check,
and the run graph measured only the label text while rendering an order
badge in front of it, so taken labels ran into the next node.

Labels now try positions along their own route (horizontal runs above
and below, sliding along, then vertical runs) and take the first whose
box stays 4px clear of every node and earlier label, preferring spots
off other wires. If a label finds no spot, the layout widens its column
gaps and lanes and runs again; a last-resort shelf below the drawing
never overlaps. The run graph measures the exact badge+label widget it
renders, keyed by edge id.
This commit is contained in:
2026-10-31 16:36:48 +00:00
parent 4235cd858f
commit fb1935a62d
6 changed files with 794 additions and 111 deletions
@@ -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<EdgeLabelBox> labels, List<GraphNodeBox> 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',
);
}
});
}
@@ -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() => <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'plan',
'type': 'model',
'edges': <String, String?>{'success': 'build', 'error': '#'},
'fallback_error': true,
},
<String, dynamic>{
'key': 'build',
'type': 'model',
'edges': <String, String?>{'success': _longKey, 'retry': 'build'},
},
<String, dynamic>{
'key': _longKey,
'type': 'model',
'edges': <String, String?>{'success': 'audit', 'blocked': '#failure'},
},
<String, dynamic>{
'key': 'audit',
'type': 'model',
'edges': <String, String?>{'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() => <String, dynamic>{
'id': 7,
'steps': <dynamic>[
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<InteractiveViewer>(find.byType(InteractiveViewer))
.transformationController!
.value
.getMaxScaleOnAxis();
final placed = tester.widgetList<Positioned>(
find.descendant(of: canvas, matching: find.byType(Positioned)),
);
final nodes = <Rect>[];
final labels = <Rect>[];
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);
});
}
}
}