merge(app): land measured graph edge routing and label geometry
This commit is contained in:
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# P2c — deterministic orthogonal edge and label routing
|
||||
|
||||
## What changed
|
||||
|
||||
New app-only, pure-Dart files. No existing file, server, web client, legacy
|
||||
client, shell, `main.dart`, pubspec, domain, layout, other feature or platform
|
||||
source was edited.
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | --- | --- |
|
||||
| `lib/features/graph/routing/route_models.dart` | 261 | public route, port, label, diagnostic and bounds types |
|
||||
| `lib/features/graph/routing/routing_inputs.dart` | 64 | measured label extents and caller clearances |
|
||||
| `lib/features/graph/routing/route_geometry.dart` | 175 | axis track allocator and column-gap bands |
|
||||
| `lib/features/graph/routing/corridor_plan.dart` | 105 | vertical corridor allocation per column gap |
|
||||
| `lib/features/graph/routing/edge_route_planner.dart` | 265 | forward/back/same-rank/self-loop polyline planning |
|
||||
| `lib/features/graph/routing/edge_label_placement.dart` | 175 | measured label boxes clear of nodes and other labels |
|
||||
| `lib/features/graph/routing/graph_edge_routing.dart` | 135 | validation, skipped diagnostics, labels, total bounds |
|
||||
| `test/features/graph/routing/routing_fixtures.dart` | 143 | chain/diamond/parallel/cycle/self-loop/disconnected fixtures |
|
||||
| `test/features/graph/routing/routing_assertions.dart` | 215 | orthogonality, borders, node interiors, corridors, labels, bounds |
|
||||
| `test/features/graph/routing/graph_edge_routing_test.dart` | 191 | chain, diamond, parallel, cycle, loop, disconnected, expanded text, unknown targets |
|
||||
| `test/features/graph/routing/graph_routing_geometry_test.dart` | 161 | wide labels, tight gaps, 3-stage SCC, backward layout, loop + forwards |
|
||||
| `test/features/graph/routing/graph_routing_validation_test.dart` | 222 | empty input, missing measurements, duplicate ids, invalid config, determinism/immutability |
|
||||
|
||||
No painting, widgets, styling, shell wiring or font/CSS/device constants were
|
||||
added.
|
||||
|
||||
## Public API
|
||||
|
||||
```dart
|
||||
GraphRouting routeGraphEdges({
|
||||
required GraphLayout layout,
|
||||
required List<GraphEdge> edges,
|
||||
required Map<int, LabelExtent> labelExtents,
|
||||
required RoutingConfig config,
|
||||
});
|
||||
```
|
||||
|
||||
`RoutingConfig` takes `nodeClearance`, `laneSpacing`, `corridorSpacing`,
|
||||
`portSpacing`, `labelGap` and optional `boundsPadding`. `LabelExtent` is the
|
||||
caller's measured label width/height. The node boxes and ranks are the landed
|
||||
`GraphLayout` values; the router never moves or resizes a node.
|
||||
|
||||
`GraphRouting` exposes unmodifiable `routes`, `labels`, `skipped`, `width` and
|
||||
`height`, plus `routeFor(id)` / `labelFor(id)`. Each `EdgeRoute` keeps the
|
||||
definition `id`, `source`, `outcome`, `target`, `label` and `fallback` flag, and
|
||||
returns `sourcePort`, `targetPort`, a `RouteKind` and an orthogonal `points`
|
||||
list. Each `EdgeLabelBox` carries the measured box for its edge id.
|
||||
|
||||
## Deterministic guarantees (and what is not claimed)
|
||||
|
||||
- **Identity:** routed edges copy the definition identity unchanged; skipped
|
||||
edges keep it in `RouteDiagnostic` with `unknownSource`/`unknownTarget`. No
|
||||
node, route or visit is invented for an empty, missing or unknown target.
|
||||
- **Order and stability:** routes, labels and diagnostics are ordered by edge id
|
||||
regardless of input order. Equal input produces equal, immutable results.
|
||||
- **Orthogonality and ports:** every consecutive point pair shares one
|
||||
coordinate. Endpoints are exactly on the source/target border with the
|
||||
recorded side: forward routes leave right and enter left; same-rank, backward
|
||||
and self-loop routes leave/enter the right side.
|
||||
- **Node avoidance:** a forward one-rank route is a straight horizontal run only
|
||||
when the boxes share a port band and leave room for label-aware track spacing.
|
||||
Every other route drops into a unique horizontal lane below the node grid,
|
||||
travels vertically only inside column gaps (or the free space right of the
|
||||
last column), and returns to a port through its own stub. Vertical corridors
|
||||
and lanes never enter a node column, and every horizontal stub stays on a row
|
||||
that is clear of unrelated node boxes.
|
||||
- **Distinguishable runs:** vertical tracks are spread across each gap, one
|
||||
slot per corridor request; horizontal stubs and straight routes share one
|
||||
interval-aware allocator; every wrapping route owns its own lane. Two edges
|
||||
cannot share a collinear run in the tested fixtures.
|
||||
- **Labels:** each routed edge needs a measured `LabelExtent`; a missing one is
|
||||
an `ArgumentError`. The box is placed at a deterministic route run, clear of
|
||||
node interiors and earlier labels. If a run is too narrow (for example a wide
|
||||
label between close columns), the label moves to a free shelf below the
|
||||
drawing and the returned bounds grow instead of covering a node.
|
||||
- **Bounds:** `width`/`height` include the landed node layout, all route points
|
||||
and all label boxes, plus `boundsPadding`. A self loop or an edge into the
|
||||
right-free gap expands the box; nothing is clipped.
|
||||
- **Not claimed:** perfect general crossing minimization or minimal bend
|
||||
counts. Corridors and lanes are deterministic and locally separated, not a
|
||||
globally optimal routing.
|
||||
|
||||
## Checks actually run
|
||||
|
||||
```
|
||||
flutter pub get
|
||||
dart format lib/features/graph/routing test/features/graph/routing # 0 changed
|
||||
flutter test test/features/graph/routing # 20 passed
|
||||
flutter analyze # No issues found!
|
||||
flutter test # 193 passed
|
||||
```
|
||||
|
||||
Focused coverage includes chain, diamond fan-out/fan-in, three outcomes to one
|
||||
target, a two-stage and a three-stage SCC, a self loop alone and beside forward
|
||||
routes, disconnected stages, heterogeneous widths, 2.6x expanded text, tight
|
||||
gaps, wide labels, a caller-supplied backward rank, missing/empty/unknown
|
||||
targets, immutability, stable ordering and finite bounds.
|
||||
|
||||
## Honest limits
|
||||
|
||||
- **No rendering.** This is a nonvisual geometry slice: no painter, widgets,
|
||||
native controls, screenshots or browser behavior. Rendered parity belongs to
|
||||
the next renderer task.
|
||||
- **Layout is an input.** The router does not widen columns for labels or move
|
||||
nodes. Very wide labels may sit on the free shelf below the drawing; callers
|
||||
that want labels beside an edge should reserve enough column gap when laying
|
||||
out nodes. A zero-width column gap leaves no space for distinct vertical
|
||||
corridors, so callers should supply a positive gap (the landed layout keeps
|
||||
whatever gap it is given).
|
||||
- **No general crossing optimum.** Only deterministic corridor/lane separation
|
||||
is guaranteed, as described above.
|
||||
- **No server or device.** Tests use local fixtures only; no run, pipeline,
|
||||
schedule, service, emulator, ADB, Android/iOS build or live chat was touched.
|
||||
- **Mobile unverified.** Only web-targeted Flutter test/analyze ran.
|
||||
- **Uncommitted candidate.** Per this stage's instruction the slice is left in
|
||||
the worktree; no commit, push or deployment was made.
|
||||
@@ -0,0 +1,191 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
import '../layout/layout_fixtures.dart' as layout;
|
||||
import 'routing_assertions.dart';
|
||||
import 'routing_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
test('chain routes keep identities and use straight forward runs', () {
|
||||
final graph = chainGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges);
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.skipped, isEmpty);
|
||||
expect(
|
||||
routing.routes.map((route) => route.id),
|
||||
edges.map((edge) => edge.id),
|
||||
);
|
||||
for (var index = 0; index < edges.length; index += 1) {
|
||||
final edge = edges[index];
|
||||
final route = routing.routes[index];
|
||||
expect(route.source, edge.source);
|
||||
expect(route.outcome, edge.outcome);
|
||||
expect(route.target, edge.target);
|
||||
expect(route.label, edge.label);
|
||||
expect(route.fallback, edge.fallback);
|
||||
expect(route.kind, RouteKind.forward);
|
||||
expect(route.straight, isTrue);
|
||||
expect(route.points.length, 2);
|
||||
expect(route.sourcePort.side, RoutePortSide.right);
|
||||
expect(route.targetPort.side, RoutePortSide.left);
|
||||
}
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('diamond fan-out and fan-in avoid every node interior', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.skipped, isEmpty);
|
||||
expect(routing.routes.length, graphEdges(graph).length);
|
||||
final fromA = routing.routes.where((route) => route.source == 'a');
|
||||
expect(fromA.length, 3);
|
||||
expect(
|
||||
fromA.where((route) => route.straight).length,
|
||||
greaterThanOrEqualTo(1),
|
||||
);
|
||||
final longForward = fromA.singleWhere(
|
||||
(route) => route.target == failureEnd,
|
||||
);
|
||||
expect(longForward.kind, RouteKind.forward);
|
||||
expect(longForward.straight, isFalse);
|
||||
expect(longForward.points.length, greaterThan(4));
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('parallel outcomes to one target get separate corridors and labels', () {
|
||||
final graph = parallelOutcomesGraph();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
final parallel = routing.routes
|
||||
.where((route) => route.source == 'a' && route.target == 'b')
|
||||
.toList();
|
||||
expect(parallel.length, 3);
|
||||
final ports = <String>{
|
||||
for (final route in parallel)
|
||||
'${route.sourcePort.point.y}/${route.targetPort.point.y}',
|
||||
};
|
||||
expect(ports.length, 3, reason: 'each outcome has its own port pair');
|
||||
final labelBoxes = <EdgeLabelBox>[
|
||||
for (final route in parallel) routing.labelFor(route.id)!,
|
||||
];
|
||||
expect(labelBoxes.map((box) => box.y).toSet().length, greaterThan(1));
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('a same-rank cycle uses distinct lanes around both members', () {
|
||||
final graph = cycleGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
final sameRank = routing.routes
|
||||
.where((route) => route.kind == RouteKind.sameRank)
|
||||
.toList();
|
||||
expect(sameRank.length, 2);
|
||||
expect(sameRank.map((route) => route.target).toSet(), <String>{'a', 'b'});
|
||||
for (final route in sameRank) {
|
||||
expect(route.straight, isFalse);
|
||||
expect(route.sourcePort.side, RoutePortSide.right);
|
||||
expect(route.targetPort.side, RoutePortSide.right);
|
||||
expect(
|
||||
route.points.map((point) => point.y).toSet().length,
|
||||
greaterThan(2),
|
||||
);
|
||||
}
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('a self loop expands bounds and keeps both ports on its border', () {
|
||||
final graph = selfLoopOnlyGraph();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
final route = routing.routes.single;
|
||||
expect(route.kind, RouteKind.selfLoop);
|
||||
expect(route.straight, isFalse);
|
||||
expect(route.points.length, greaterThanOrEqualTo(4));
|
||||
expect(route.sourcePort.side, RoutePortSide.right);
|
||||
expect(route.targetPort.side, RoutePortSide.right);
|
||||
expect(route.sourcePort.point.y, isNot(route.targetPort.point.y));
|
||||
expect(routing.width, greaterThan(layoutBox.width));
|
||||
expect(routing.height, greaterThan(layoutBox.height));
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('disconnected stages route only their declared edges', () {
|
||||
final graph = disconnectedGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.skipped, isEmpty);
|
||||
expect(routing.routes.length, 2);
|
||||
expect(routing.routes.map((route) => route.source).toSet(), <String>{
|
||||
'a',
|
||||
'b',
|
||||
});
|
||||
expect(layoutBox.nodeFor('c'), isNotNull);
|
||||
expect(routing.routes.any((route) => route.source == 'c'), isFalse);
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('heterogeneous and expanded text sizes stay valid and grow bounds', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final baseLayout = layoutFor(graph, extents: layout.heterogeneousExtents());
|
||||
final expandedExtents = layout.scaledExtents(
|
||||
layout.heterogeneousExtents(),
|
||||
2.6,
|
||||
);
|
||||
final expandedLayout = layoutFor(graph, extents: expandedExtents);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = fixedLabels(edges);
|
||||
|
||||
final base = routeFor(
|
||||
graph,
|
||||
extents: layout.heterogeneousExtents(),
|
||||
labels: labels,
|
||||
);
|
||||
final expanded = routeFor(graph, extents: expandedExtents, labels: labels);
|
||||
|
||||
expectValidRouting(base, baseLayout, extents: labels);
|
||||
expectValidRouting(expanded, expandedLayout, extents: labels);
|
||||
expect(expanded.width, greaterThan(base.width));
|
||||
expect(expanded.height, greaterThan(base.height));
|
||||
});
|
||||
|
||||
test('unknown and missing targets are skipped with their identity', () {
|
||||
final graph = incompleteGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges);
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.skipped.length, 2);
|
||||
final skipped = routing.skipped.toList();
|
||||
expect(skipped.map((item) => item.reason), <RouteSkipReason>[
|
||||
RouteSkipReason.unknownTarget,
|
||||
RouteSkipReason.unknownTarget,
|
||||
]);
|
||||
expect(skipped.map((item) => item.id), <int>[1, 2]);
|
||||
expect(skipped[0].source, 'a');
|
||||
expect(skipped[0].outcome, 'blocked');
|
||||
expect(skipped[0].target, '');
|
||||
expect(skipped[1].target, 'ghost');
|
||||
expect(routing.routes.map((route) => route.id), <int>[3, 4]);
|
||||
expect(routing.routeFor(1), isNull);
|
||||
expect(routing.routeFor(2), isNull);
|
||||
expect(layoutBox.nodeFor('ghost'), isNull);
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
import 'routing_assertions.dart';
|
||||
import 'routing_fixtures.dart';
|
||||
import '../layout/layout_fixtures.dart' as layout;
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'wide measured labels move outside the drawing instead of covering it',
|
||||
() {
|
||||
final graph = chainGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = fixedLabels(edges, width: 400, height: 40);
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.labels.length, edges.length);
|
||||
for (final label in routing.labels) {
|
||||
expect(label.y, greaterThanOrEqualTo(layoutBox.height));
|
||||
expect(label.right, lessThanOrEqualTo(routing.width));
|
||||
expect(label.bottom, lessThanOrEqualTo(routing.height));
|
||||
}
|
||||
expect(routing.height, greaterThan(layoutBox.height));
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
},
|
||||
);
|
||||
|
||||
test('tight gaps and expanded extents keep the same guarantees', () {
|
||||
for (final gap in <double>[8, 24, 80]) {
|
||||
for (final scale in <double>[1, 2.6]) {
|
||||
final extents = layout.scaledExtents(
|
||||
layout.heterogeneousExtents(),
|
||||
scale,
|
||||
);
|
||||
final layoutBox = layoutFor(
|
||||
diamondGraphFixture(),
|
||||
extents: extents,
|
||||
config: routingLayoutConfig(columnGap: gap, rowGap: 16),
|
||||
);
|
||||
final edges = graphEdges(diamondGraphFixture());
|
||||
final labels = labelsFor(edges);
|
||||
final routing = routeFor(
|
||||
diamondGraphFixture(),
|
||||
extents: extents,
|
||||
labels: labels,
|
||||
layoutConfig: routingLayoutConfig(columnGap: gap, rowGap: 16),
|
||||
);
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('a three-stage cycle keeps every same-rank corridor distinct', () {
|
||||
final graph = cycleThreeGraph();
|
||||
final layoutBox = layoutFor(
|
||||
graph,
|
||||
config: routingLayoutConfig(columnGap: 8),
|
||||
);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges);
|
||||
final routing = routeFor(
|
||||
graph,
|
||||
labels: labels,
|
||||
layoutConfig: routingLayoutConfig(columnGap: 8),
|
||||
);
|
||||
|
||||
expect(routing.routes.length, 3);
|
||||
expect(
|
||||
routing.routes.every((route) => route.kind == RouteKind.sameRank),
|
||||
isTrue,
|
||||
);
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('a caller-supplied backward rank routes around the target column', () {
|
||||
final layoutBox = GraphLayout(
|
||||
nodes: <GraphNodeBox>[
|
||||
const GraphNodeBox(
|
||||
key: 'a',
|
||||
terminal: false,
|
||||
stageIndex: 0,
|
||||
rank: 1,
|
||||
x: 208,
|
||||
y: 8,
|
||||
width: 120,
|
||||
height: 60,
|
||||
),
|
||||
const GraphNodeBox(
|
||||
key: 'b',
|
||||
terminal: false,
|
||||
stageIndex: 1,
|
||||
rank: 0,
|
||||
x: 8,
|
||||
y: 8,
|
||||
width: 120,
|
||||
height: 60,
|
||||
),
|
||||
],
|
||||
ranks: <String, int>{'a': 1, 'b': 0},
|
||||
rankCount: 2,
|
||||
width: 336,
|
||||
height: 76,
|
||||
);
|
||||
final edge = GraphEdge(
|
||||
id: 1,
|
||||
source: 'a',
|
||||
outcome: 'success',
|
||||
target: 'b',
|
||||
label: 'success',
|
||||
fallback: false,
|
||||
knownTarget: true,
|
||||
);
|
||||
final labels = <int, LabelExtent>{1: LabelExtent(width: 52, height: 18)};
|
||||
final routing = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: <GraphEdge>[edge],
|
||||
labelExtents: labels,
|
||||
config: routingConfig(),
|
||||
);
|
||||
|
||||
final route = routing.routes.single;
|
||||
expect(route.kind, RouteKind.back);
|
||||
expect(route.sourcePort.side, RoutePortSide.right);
|
||||
expect(route.targetPort.side, RoutePortSide.right);
|
||||
expect(route.straight, isFalse);
|
||||
expect(route.points.length, greaterThan(4));
|
||||
expect(routing.width, greaterThan(layoutBox.width));
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
|
||||
test('a self loop and forward routes share one valid layout', () {
|
||||
final graph = selfLoopGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final labels = labelsFor(graphEdges(graph));
|
||||
final routing = routeFor(graph, labels: labels);
|
||||
|
||||
expect(routing.routes.length, 4);
|
||||
expect(routing.routes.map((route) => route.kind).toSet(), <RouteKind>{
|
||||
RouteKind.forward,
|
||||
RouteKind.selfLoop,
|
||||
});
|
||||
final loop = routing.routes.singleWhere(
|
||||
(route) => route.kind == RouteKind.selfLoop,
|
||||
);
|
||||
expect(loop.source, 'a');
|
||||
expect(loop.target, 'a');
|
||||
expect(loop.sourcePort.point.y, isNot(loop.targetPort.point.y));
|
||||
expect(
|
||||
routing.routes
|
||||
.where((route) => route.target == successEnd)
|
||||
.every((route) => route.targetPort.side == RoutePortSide.left),
|
||||
isTrue,
|
||||
);
|
||||
expectValidRouting(routing, layoutBox, extents: labels);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
import 'routing_fixtures.dart';
|
||||
|
||||
GraphEdge _edge({
|
||||
int id = 1,
|
||||
String source = 'a',
|
||||
String target = 'b',
|
||||
String outcome = 'success',
|
||||
bool knownTarget = true,
|
||||
}) {
|
||||
return GraphEdge(
|
||||
id: id,
|
||||
source: source,
|
||||
outcome: outcome,
|
||||
target: target,
|
||||
label: outcome,
|
||||
fallback: false,
|
||||
knownTarget: knownTarget,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('an empty graph has empty routes and the layout bounds', () {
|
||||
final layoutBox = layoutFor(<String, dynamic>{'stages': <dynamic>[]});
|
||||
final routing = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: const <GraphEdge>[],
|
||||
labelExtents: const <int, LabelExtent>{},
|
||||
config: routingConfig(),
|
||||
);
|
||||
|
||||
expect(routing.isEmpty, isTrue);
|
||||
expect(routing.routes, isEmpty);
|
||||
expect(routing.labels, isEmpty);
|
||||
expect(routing.skipped, isEmpty);
|
||||
expect(routing.width, layoutBox.width + routingConfig().boundsPadding);
|
||||
expect(routing.height, layoutBox.height + routingConfig().boundsPadding);
|
||||
});
|
||||
|
||||
test('unknown endpoints become diagnostics, never invented nodes', () {
|
||||
final layoutBox = layoutFor(chainGraphFixture());
|
||||
final edges = <GraphEdge>[
|
||||
_edge(id: 1, source: 'missing', target: 's0'),
|
||||
_edge(id: 2, source: 's0', target: 'ghost'),
|
||||
_edge(id: 3, source: 's0', target: '', knownTarget: false),
|
||||
];
|
||||
final routing = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: const <int, LabelExtent>{},
|
||||
config: routingConfig(),
|
||||
);
|
||||
|
||||
expect(routing.routes, isEmpty);
|
||||
expect(routing.skipped.map((item) => item.reason), <RouteSkipReason>[
|
||||
RouteSkipReason.unknownSource,
|
||||
RouteSkipReason.unknownTarget,
|
||||
RouteSkipReason.unknownTarget,
|
||||
]);
|
||||
expect(routing.skipped.map((item) => item.id), <int>[1, 2, 3]);
|
||||
expect(layoutBox.nodeFor('missing'), isNull);
|
||||
expect(layoutBox.nodeFor('ghost'), isNull);
|
||||
});
|
||||
|
||||
test('routed edges require measured label extents', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges)..remove(edges.first.id);
|
||||
|
||||
expect(
|
||||
() => routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: labels,
|
||||
config: routingConfig(),
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('extra label extents are ignored and duplicate ids are rejected', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges)..[999] = LabelExtent(width: 10, height: 10);
|
||||
final routing = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: labels,
|
||||
config: routingConfig(),
|
||||
);
|
||||
expect(routing.routes.length, edges.length);
|
||||
expect(routing.labelFor(999), isNull);
|
||||
|
||||
expect(
|
||||
() => routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: <GraphEdge>[edges.first, edges.first],
|
||||
labelExtents: labelsFor(edges),
|
||||
config: routingConfig(),
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid configuration and label extents are rejected', () {
|
||||
expect(
|
||||
() => RoutingConfig(
|
||||
nodeClearance: -1,
|
||||
laneSpacing: 10,
|
||||
corridorSpacing: 10,
|
||||
portSpacing: 8,
|
||||
labelGap: 2,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => RoutingConfig(
|
||||
nodeClearance: 2,
|
||||
laneSpacing: 0,
|
||||
corridorSpacing: 10,
|
||||
portSpacing: 8,
|
||||
labelGap: 2,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => RoutingConfig(
|
||||
nodeClearance: 2,
|
||||
laneSpacing: 10,
|
||||
corridorSpacing: double.nan,
|
||||
portSpacing: 8,
|
||||
labelGap: 2,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
() => LabelExtent(width: double.infinity, height: 10),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(() => LabelExtent(width: 10, height: -1), throwsArgumentError);
|
||||
});
|
||||
|
||||
test('the same input produces equal immutable results', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges);
|
||||
final config = routingConfig();
|
||||
|
||||
final first = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: labels,
|
||||
config: config,
|
||||
);
|
||||
final second = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: labels,
|
||||
config: config,
|
||||
);
|
||||
|
||||
expect(first.routes, second.routes);
|
||||
expect(first.labels, second.labels);
|
||||
expect(first.skipped, second.skipped);
|
||||
expect(first.width, second.width);
|
||||
expect(first.height, second.height);
|
||||
expect(() => first.routes.add(first.routes.first), throwsUnsupportedError);
|
||||
expect(
|
||||
() => first.routes.first.points.add(const RoutePoint(0, 0)),
|
||||
throwsUnsupportedError,
|
||||
);
|
||||
expect(() => first.labels.add(first.labels.first), throwsUnsupportedError);
|
||||
expect(
|
||||
() => first.skipped.add(
|
||||
const RouteDiagnostic(
|
||||
id: 1,
|
||||
source: 'a',
|
||||
outcome: 'success',
|
||||
target: 'b',
|
||||
reason: RouteSkipReason.unknownTarget,
|
||||
message: '',
|
||||
),
|
||||
),
|
||||
throwsUnsupportedError,
|
||||
);
|
||||
});
|
||||
|
||||
test('edges are routed in definition id order regardless of input order', () {
|
||||
final graph = diamondGraphFixture();
|
||||
final layoutBox = layoutFor(graph);
|
||||
final edges = graphEdges(graph);
|
||||
final labels = labelsFor(edges);
|
||||
final forward = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges,
|
||||
labelExtents: labels,
|
||||
config: routingConfig(),
|
||||
);
|
||||
final reversed = routeGraphEdges(
|
||||
layout: layoutBox,
|
||||
edges: edges.reversed.toList(),
|
||||
labelExtents: labels,
|
||||
config: routingConfig(),
|
||||
);
|
||||
|
||||
expect(reversed.routes, forward.routes);
|
||||
expect(reversed.labels, forward.labels);
|
||||
expect(reversed.width, forward.width);
|
||||
expect(reversed.height, forward.height);
|
||||
expect(
|
||||
forward.routes.map((route) => route.id),
|
||||
edges.map((edge) => edge.id),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
const double _epsilon = 1e-9;
|
||||
|
||||
/// Checks the routing guarantees every fixture must satisfy.
|
||||
void expectValidRouting(
|
||||
GraphRouting routing,
|
||||
GraphLayout layout, {
|
||||
Map<int, LabelExtent>? extents,
|
||||
}) {
|
||||
expect(routing.width.isFinite, isTrue);
|
||||
expect(routing.height.isFinite, isTrue);
|
||||
expect(routing.width, greaterThan(0));
|
||||
expect(routing.height, greaterThan(0));
|
||||
|
||||
for (final route in routing.routes) {
|
||||
_expectRoute(route, layout, routing.width, routing.height);
|
||||
_expectNoNodeInterior(route, layout);
|
||||
}
|
||||
expectDistinctCorridors(routing.routes);
|
||||
|
||||
final byId = <int, EdgeLabelBox>{
|
||||
for (final label in routing.labels) label.edgeId: label,
|
||||
};
|
||||
expect(byId.length, routing.labels.length, reason: 'one label per edge');
|
||||
for (final route in routing.routes) {
|
||||
final label = byId[route.id];
|
||||
expect(label, isNotNull, reason: 'edge ${route.id} has a label');
|
||||
final extent = extents?[route.id];
|
||||
if (extent != null) {
|
||||
expect(label!.width, extent.width);
|
||||
expect(label.height, extent.height);
|
||||
}
|
||||
expect(label!.x, greaterThanOrEqualTo(-_epsilon));
|
||||
expect(label.y, greaterThanOrEqualTo(-_epsilon));
|
||||
expect(label.right, lessThanOrEqualTo(routing.width + _epsilon));
|
||||
expect(label.bottom, lessThanOrEqualTo(routing.height + _epsilon));
|
||||
for (final node in layout.nodes) {
|
||||
expect(
|
||||
_overlaps(
|
||||
label.x,
|
||||
label.y,
|
||||
label.width,
|
||||
label.height,
|
||||
node.x,
|
||||
node.y,
|
||||
node.width,
|
||||
node.height,
|
||||
),
|
||||
isFalse,
|
||||
reason: 'label for edge ${route.id} overlaps node ${node.key}',
|
||||
);
|
||||
}
|
||||
}
|
||||
for (var first = 0; first < routing.labels.length; first += 1) {
|
||||
for (var second = first + 1; second < routing.labels.length; second += 1) {
|
||||
final a = routing.labels[first];
|
||||
final b = routing.labels[second];
|
||||
expect(
|
||||
_overlaps(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height),
|
||||
isFalse,
|
||||
reason: 'labels for edges ${a.edgeId} and ${b.edgeId} overlap',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (final skipped in routing.skipped) {
|
||||
expect(routing.routeFor(skipped.id), isNull);
|
||||
expect(routing.labelFor(skipped.id), isNull);
|
||||
}
|
||||
}
|
||||
|
||||
void expectDistinctCorridors(List<EdgeRoute> routes) {
|
||||
for (var first = 0; first < routes.length; first += 1) {
|
||||
for (var second = first + 1; second < routes.length; second += 1) {
|
||||
final a = routes[first];
|
||||
final b = routes[second];
|
||||
for (var ai = 1; ai < a.points.length; ai += 1) {
|
||||
final a0 = a.points[ai - 1];
|
||||
final a1 = a.points[ai];
|
||||
for (var bi = 1; bi < b.points.length; bi += 1) {
|
||||
final b0 = b.points[bi - 1];
|
||||
final b1 = b.points[bi];
|
||||
if (a0.x == a1.x && b0.x == b1.x && a0.x == b0.x) {
|
||||
final aLo = math.min(a0.y, a1.y);
|
||||
final aHi = math.max(a0.y, a1.y);
|
||||
final bLo = math.min(b0.y, b1.y);
|
||||
final bHi = math.max(b0.y, b1.y);
|
||||
expect(
|
||||
aLo < bHi - _epsilon && bLo < aHi - _epsilon,
|
||||
isFalse,
|
||||
reason: 'edges ${a.id} and ${b.id} share a vertical corridor',
|
||||
);
|
||||
}
|
||||
if (a0.y == a1.y && b0.y == b1.y && a0.y == b0.y) {
|
||||
final aLo = math.min(a0.x, a1.x);
|
||||
final aHi = math.max(a0.x, a1.x);
|
||||
final bLo = math.min(b0.x, b1.x);
|
||||
final bHi = math.max(b0.x, b1.x);
|
||||
expect(
|
||||
aLo < bHi - _epsilon && bLo < aHi - _epsilon,
|
||||
isFalse,
|
||||
reason: 'edges ${a.id} and ${b.id} share a horizontal run',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _expectRoute(
|
||||
EdgeRoute route,
|
||||
GraphLayout layout,
|
||||
double width,
|
||||
double height,
|
||||
) {
|
||||
expect(route.points.length, greaterThanOrEqualTo(2));
|
||||
expect(route.points.first, route.sourcePort.point);
|
||||
expect(route.points.last, route.targetPort.point);
|
||||
for (var index = 0; index < route.points.length; index += 1) {
|
||||
final point = route.points[index];
|
||||
expect(point.x.isFinite, isTrue);
|
||||
expect(point.y.isFinite, isTrue);
|
||||
expect(point.x, greaterThanOrEqualTo(-_epsilon));
|
||||
expect(point.y, greaterThanOrEqualTo(-_epsilon));
|
||||
expect(point.x, lessThanOrEqualTo(width + _epsilon));
|
||||
expect(point.y, lessThanOrEqualTo(height + _epsilon));
|
||||
if (index > 0) {
|
||||
final previous = route.points[index - 1];
|
||||
expect(
|
||||
previous.x == point.x || previous.y == point.y,
|
||||
isTrue,
|
||||
reason: 'edge ${route.id} segment ${index - 1} is not orthogonal',
|
||||
);
|
||||
expect(previous, isNot(point), reason: 'zero-length segment');
|
||||
}
|
||||
}
|
||||
_expectPort(route.sourcePort, layout.nodeFor(route.source)!);
|
||||
_expectPort(route.targetPort, layout.nodeFor(route.target)!);
|
||||
}
|
||||
|
||||
void _expectPort(RoutePort port, GraphNodeBox box) {
|
||||
switch (port.side) {
|
||||
case RoutePortSide.right:
|
||||
expect(port.point.x, closeTo(box.right, _epsilon));
|
||||
expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon));
|
||||
expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon));
|
||||
case RoutePortSide.left:
|
||||
expect(port.point.x, closeTo(box.x, _epsilon));
|
||||
expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon));
|
||||
expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon));
|
||||
case RoutePortSide.top:
|
||||
expect(port.point.y, closeTo(box.y, _epsilon));
|
||||
expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon));
|
||||
expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon));
|
||||
case RoutePortSide.bottom:
|
||||
expect(port.point.y, closeTo(box.bottom, _epsilon));
|
||||
expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon));
|
||||
expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon));
|
||||
}
|
||||
}
|
||||
|
||||
void _expectNoNodeInterior(EdgeRoute route, GraphLayout layout) {
|
||||
for (var index = 1; index < route.points.length; index += 1) {
|
||||
final a = route.points[index - 1];
|
||||
final b = route.points[index];
|
||||
for (final node in layout.nodes) {
|
||||
if (a.y == b.y) {
|
||||
final left = math.min(a.x, b.x);
|
||||
final right = math.max(a.x, b.x);
|
||||
final crosses =
|
||||
a.y > node.y + _epsilon &&
|
||||
a.y < node.bottom - _epsilon &&
|
||||
right > node.x + _epsilon &&
|
||||
left < node.right - _epsilon;
|
||||
expect(
|
||||
crosses,
|
||||
isFalse,
|
||||
reason: 'edge ${route.id} crosses node ${node.key} horizontally',
|
||||
);
|
||||
} else {
|
||||
final top = math.min(a.y, b.y);
|
||||
final bottom = math.max(a.y, b.y);
|
||||
final crosses =
|
||||
a.x > node.x + _epsilon &&
|
||||
a.x < node.right - _epsilon &&
|
||||
bottom > node.y + _epsilon &&
|
||||
top < node.bottom - _epsilon;
|
||||
expect(
|
||||
crosses,
|
||||
isFalse,
|
||||
reason: 'edge ${route.id} crosses node ${node.key} vertically',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _overlaps(
|
||||
double ax,
|
||||
double ay,
|
||||
double aw,
|
||||
double ah,
|
||||
double bx,
|
||||
double by,
|
||||
double bw,
|
||||
double bh,
|
||||
) {
|
||||
return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by;
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart';
|
||||
import 'package:pipelines_app/features/graph/layout/layout_models.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart';
|
||||
import 'package:pipelines_app/features/graph/routing/route_models.dart';
|
||||
|
||||
import '../layout/layout_fixtures.dart' as layout;
|
||||
import '../domain/graph_fixtures.dart' as domain;
|
||||
|
||||
/// Definitions, measured extents and configs shared by the routing tests.
|
||||
|
||||
GraphLayoutConfig routingLayoutConfig({
|
||||
double columnGap = 80,
|
||||
double rowGap = 16,
|
||||
double padding = 8,
|
||||
}) {
|
||||
return GraphLayoutConfig(
|
||||
columnGap: columnGap,
|
||||
rowGap: rowGap,
|
||||
padding: padding,
|
||||
);
|
||||
}
|
||||
|
||||
RoutingConfig routingConfig({
|
||||
double nodeClearance = 8,
|
||||
double laneSpacing = 28,
|
||||
double corridorSpacing = 20,
|
||||
double portSpacing = 12,
|
||||
double labelGap = 4,
|
||||
double boundsPadding = 4,
|
||||
}) {
|
||||
return RoutingConfig(
|
||||
nodeClearance: nodeClearance,
|
||||
laneSpacing: laneSpacing,
|
||||
corridorSpacing: corridorSpacing,
|
||||
portSpacing: portSpacing,
|
||||
labelGap: labelGap,
|
||||
boundsPadding: boundsPadding,
|
||||
);
|
||||
}
|
||||
|
||||
GraphLayout layoutFor(
|
||||
Map<String, dynamic> graph, {
|
||||
Map<String, NodeExtent>? extents,
|
||||
GraphLayoutConfig? config,
|
||||
}) {
|
||||
final nodes = graphNodes(graph);
|
||||
return layoutGraphNodes(
|
||||
nodes: nodes,
|
||||
edges: graphEdges(graph),
|
||||
extents: extents ?? layout.uniformExtents(nodes),
|
||||
config: config ?? routingLayoutConfig(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Measured label boxes sized from their text, as a renderer would supply them.
|
||||
Map<int, LabelExtent> labelsFor(
|
||||
Iterable<GraphEdge> edges, {
|
||||
double charWidth = 7,
|
||||
double padding = 12,
|
||||
double height = 18,
|
||||
}) {
|
||||
return <int, LabelExtent>{
|
||||
for (final edge in edges)
|
||||
edge.id: LabelExtent(
|
||||
width: edge.label.length * charWidth + padding,
|
||||
height: height,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/// One box per edge at an explicit size, used for wide-label checks.
|
||||
Map<int, LabelExtent> fixedLabels(
|
||||
Iterable<GraphEdge> edges, {
|
||||
double width = 52,
|
||||
double height = 18,
|
||||
}) {
|
||||
return <int, LabelExtent>{
|
||||
for (final edge in edges)
|
||||
edge.id: LabelExtent(width: width, height: height),
|
||||
};
|
||||
}
|
||||
|
||||
GraphRouting routeFor(
|
||||
Map<String, dynamic> graph, {
|
||||
Map<String, NodeExtent>? extents,
|
||||
Map<int, LabelExtent>? labels,
|
||||
GraphLayoutConfig? layoutConfig,
|
||||
RoutingConfig? config,
|
||||
}) {
|
||||
final layout = layoutFor(graph, extents: extents, config: layoutConfig);
|
||||
final edges = graphEdges(graph);
|
||||
return routeGraphEdges(
|
||||
layout: layout,
|
||||
edges: edges,
|
||||
labelExtents: labels ?? labelsFor(edges),
|
||||
config: config ?? routingConfig(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Three outcomes from `a` to the same target `b`, then `b` to Success.
|
||||
Map<String, dynamic> parallelOutcomesGraph() => <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
domain.stage(
|
||||
'a',
|
||||
edges: <String, String?>{
|
||||
'success': 'b',
|
||||
'approved': 'b',
|
||||
'rejected': 'b',
|
||||
},
|
||||
),
|
||||
domain.stage('b', edges: <String, String?>{'success': '#success'}),
|
||||
],
|
||||
};
|
||||
|
||||
/// A single stage that retries itself and has no terminal pair.
|
||||
Map<String, dynamic> selfLoopOnlyGraph() => <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
domain.stage('a', edges: <String, String?>{'retry': 'a'}),
|
||||
],
|
||||
};
|
||||
|
||||
Map<String, dynamic> chainGraphFixture() => layout.chainGraph(4);
|
||||
|
||||
Map<String, dynamic> diamondGraphFixture() => layout.diamondGraphFixture();
|
||||
|
||||
Map<String, dynamic> cycleGraphFixture() => layout.cycleGraph();
|
||||
|
||||
Map<String, dynamic> selfLoopGraphFixture() => layout.selfLoopGraphFixture();
|
||||
|
||||
Map<String, dynamic> disconnectedGraphFixture() => layout.disconnectedGraph();
|
||||
|
||||
Map<String, dynamic> incompleteGraphFixture() =>
|
||||
layout.incompleteGraphFixture();
|
||||
|
||||
/// Three stages in one strongly connected component with no terminals.
|
||||
Map<String, dynamic> cycleThreeGraph() => <String, dynamic>{
|
||||
'stages': <dynamic>[
|
||||
domain.stage('a', edges: <String, String?>{'success': 'b'}),
|
||||
domain.stage('b', edges: <String, String?>{'success': 'c'}),
|
||||
domain.stage('c', edges: <String, String?>{'success': 'a'}),
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user