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
@@ -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<GraphNode> nodes,
required List<GraphEdge> edges,
required Map<String, NodeExtent> extents,
required Map<int, LabelExtent> 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<int>) _layoutPass({
required List<GraphNode> nodes,
required List<GraphEdge> edges,
required Map<String, NodeExtent> extents,
required Map<int, LabelExtent> 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 <int>{},
);
}
@@ -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 = <int, double>{};
@@ -277,7 +324,6 @@ class LinearGraphMetrics {
edge.outcome == 'error' && edge.target == failureEnd;
final routes = <EdgeRoute>[];
final labels = <EdgeLabelBox>[];
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<RoutePoint> _collapse(List<RoutePoint> 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<RoutePoint> 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 {
@@ -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<EdgeLabelBox> 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<int> 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<EdgeRoute> routes,
required Map<int, LabelExtent> extents,
required List<GraphNodeBox> nodes,
required double labelGap,
double clearance = edgeLabelClearance,
}) {
final labels = <EdgeLabelBox>[];
final misfits = <int>{};
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<EdgeRoute> 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<GraphNodeBox> nodes,
List<EdgeLabelBox> 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<EdgeRoute> 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 = <double>[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;
}
@@ -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<int> 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<String, String?> 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),
),
),
],
),
@@ -76,7 +76,7 @@ class RunGraphView extends StatefulWidget {
class _RunGraphViewState extends State<RunGraphView> {
final Map<String, Size> _nodeSizes = {};
final Map<String, Size> _labelSizes = {};
final Map<int, Size> _labelSizes = {};
final Map<String, String?> _measuredStatuses = {};
final GraphViewportController _viewport = GraphViewportController();
TextScaler? _scaler;
@@ -99,7 +99,7 @@ class _RunGraphViewState extends State<RunGraphView> {
}
}
void _record(Map<String, Size> sizes, String key, Size size) {
void _record<K>(Map<K, Size> sizes, K key, Size size) {
if (sizes[key] == size) return;
sizes[key] = size;
if (_rebuildScheduled) return;
@@ -122,7 +122,7 @@ class _RunGraphViewState extends State<RunGraphView> {
}
final labelExtents = <int, LabelExtent>{};
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<RunGraphView> {
maxNodeWidth: constraints.maxWidth,
labelStyle: style.labelStyle,
recordedStatuses: statuses,
state: state,
onNodeSize: (key, size) => _record(_nodeSizes, key, size),
onLabelSize: (key, size) => _record(_labelSizes, key, size),
),