feat(app): add deterministic content-sized graph node layout

Pure-Dart SCC ranking and column placement over the landed graph
identities. Every extent and gap is caller supplied; missing
measurements are rejected rather than defaulted.

Focused tests cover linear, diamond, cycle, self-loop, disconnected,
terminal, expanded-text and invalid-input cases.
This commit is contained in:
2026-10-21 16:25:17 +01:00
parent 2227faad40
commit c1f140bc78
8 changed files with 1104 additions and 0 deletions
@@ -0,0 +1,142 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import 'graph_ranks.dart';
import 'layout_models.dart';
/// Places definition nodes in topological columns.
///
/// Nodes keep definition order inside a rank, each column is as wide as its
/// widest measured node, and columns are top-aligned. A node is centred in its
/// column, so heterogeneous widths and text-expanded heights stay separated by
/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap]
/// between ranks. Nothing is clipped to a fixed box: the supplied measured
/// width and height are used verbatim and the returned bounds include them.
///
/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose
/// source or target is not one of [nodes] are ignored, so an unknown target can
/// never invent a node. A measurement is required for every node; a missing one
/// is an error rather than a made-up size. Extra measurement entries are
/// ignored because they cannot become nodes.
GraphLayout layoutGraphNodes({
required List<GraphNode> nodes,
required List<GraphEdge> edges,
required Map<String, NodeExtent> extents,
required GraphLayoutConfig config,
}) {
_validateNodeKeys(nodes);
final ranks = assignGraphRanks(nodes, edges);
final measured = <String, NodeExtent>{};
final missing = <String>[];
for (final node in nodes) {
final extent = extents[node.key];
if (extent == null) {
missing.add(node.key);
} else {
measured[node.key] = extent;
}
}
if (missing.isNotEmpty) {
throw ArgumentError.value(
missing,
'extents',
'missing measured extents for graph nodes',
);
}
final columns = List<List<GraphNode>>.generate(
ranks.rankCount,
(_) => <GraphNode>[],
);
for (final node in nodes) {
columns[ranks.rankOf[node.key]!].add(node);
}
final columnWidths = <double>[
for (final column in columns)
column.fold<double>(
0,
(width, node) => math.max(width, measured[node.key]!.width),
),
];
final columnHeights = <double>[
for (final column in columns)
_columnHeight(column, measured, config.rowGap),
];
final columnX = <double>[];
var nextX = config.padding;
for (var rank = 0; rank < columns.length; rank += 1) {
columnX.add(nextX);
nextX += columnWidths[rank];
if (rank + 1 < columns.length) nextX += config.columnGap;
}
final boxes = <GraphNodeBox>[];
for (var rank = 0; rank < columns.length; rank += 1) {
var nextY = config.padding;
for (final node in columns[rank]) {
final extent = measured[node.key]!;
boxes.add(
GraphNodeBox(
key: node.key,
terminal: node.terminal,
stageIndex: node.stageIndex,
rank: rank,
x: columnX[rank] + (columnWidths[rank] - extent.width) / 2,
y: nextY,
width: extent.width,
height: extent.height,
),
);
nextY += extent.height + config.rowGap;
}
}
final width =
config.padding * 2 +
columnWidths.fold<double>(0, (sum, column) => sum + column) +
config.columnGap * math.max(0, columns.length - 1);
final height =
config.padding * 2 +
columnHeights.fold<double>(
0,
(tallest, column) => math.max(tallest, column),
);
return GraphLayout(
nodes: boxes,
width: width,
height: height,
rankCount: ranks.rankCount,
ranks: ranks.rankOf,
);
}
void _validateNodeKeys(List<GraphNode> nodes) {
final seen = <String>{};
for (final node in nodes) {
if (node.key.isEmpty) {
throw ArgumentError.value(
node.key,
'nodes',
'node key must not be empty',
);
}
if (!seen.add(node.key)) {
throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key');
}
}
}
double _columnHeight(
List<GraphNode> column,
Map<String, NodeExtent> measured,
double rowGap,
) {
if (column.isEmpty) return 0;
var height = 0.0;
for (final node in column) {
height += measured[node.key]!.height;
}
return height + rowGap * (column.length - 1);
}
@@ -0,0 +1,191 @@
import 'dart:collection';
import 'dart:math' as math;
import '../domain/graph_definition.dart';
/// Deterministic 0-based ranks for a graph definition's nodes.
///
/// Ranks come from the condensation DAG: every strongly connected component
/// shares one rank, and a component sits one past its deepest predecessor
/// (longest path). Self loops and cycles therefore stay finite, a cycle's
/// members do not drift apart, and disconnected nodes stay at rank 0. Edges
/// whose endpoints are not definition nodes are ignored: an unknown target
/// never invents a node.
class GraphRanks {
GraphRanks({
required Map<String, int> rankOf,
required this.rankCount,
required List<List<String>> components,
}) : rankOf = Map.unmodifiable(rankOf),
components = List.unmodifiable(<List<String>>[
for (final component in components) List.unmodifiable(component),
]);
/// Every definition key's rank, in definition order.
final Map<String, int> rankOf;
/// Number of distinct ranks, 0 for an empty node set.
final int rankCount;
/// Strongly connected components as keys, each sorted by definition order and
/// the list sorted by its first member.
final List<List<String>> components;
}
/// One DFS frame for the iterative Tarjan walk.
class _Frame {
_Frame(this.node);
final int node;
int nextChild = 0;
}
/// Assigns ranks to exactly the supplied [nodes].
///
/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are
/// harmless. The walk is iterative, so a deep chain cannot overflow the call
/// stack, and the work is linear in nodes plus edges.
GraphRanks assignGraphRanks(List<GraphNode> nodes, List<GraphEdge> edges) {
final indexOf = <String, int>{};
for (var index = 0; index < nodes.length; index += 1) {
indexOf[nodes[index].key] = index;
}
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
final seenPairs = <int>{};
for (final edge in edges) {
final source = indexOf[edge.source];
final target = indexOf[edge.target];
if (source == null || target == null) continue;
if (!seenPairs.add(source * nodes.length + target)) continue;
adjacency[source].add(target);
}
final components = _components(adjacency);
final componentOf = List<int>.filled(nodes.length, -1);
for (var component = 0; component < components.length; component += 1) {
for (final node in components[component]) {
componentOf[node] = component;
}
}
// Condensation edges and their indegrees.
final successors = List<Set<int>>.generate(components.length, (_) => <int>{});
final indegree = List<int>.filled(components.length, 0);
for (var source = 0; source < adjacency.length; source += 1) {
final from = componentOf[source];
for (final target in adjacency[source]) {
final to = componentOf[target];
if (from == to) continue;
if (successors[from].add(to)) indegree[to] += 1;
}
}
// Longest-path ranks over the condensation. Queue order only has to be a
// topological order; the resulting rank per component is unique.
final ranks = List<int>.filled(components.length, 0);
final ready = ListQueue<int>();
for (var component = 0; component < components.length; component += 1) {
if (indegree[component] == 0) ready.add(component);
}
var settled = 0;
while (ready.isNotEmpty) {
final component = ready.removeFirst();
settled += 1;
for (final next in successors[component]) {
ranks[next] = math.max(ranks[next], ranks[component] + 1);
indegree[next] -= 1;
if (indegree[next] == 0) ready.add(next);
}
}
if (settled != components.length) {
// The condensation cannot contain a cycle by construction; stop rather than
// return a silently truncated layout.
throw StateError('graph condensation was not acyclic');
}
final componentKeys = <List<String>>[
for (final component in components)
<String>[for (final node in component) nodes[node].key],
];
final componentOrder = <int>[
for (var component = 0; component < components.length; component += 1)
component,
]..sort((a, b) => components[a].first.compareTo(components[b].first));
final rankOf = <String, int>{};
var rankCount = 0;
for (var index = 0; index < nodes.length; index += 1) {
final rank = ranks[componentOf[index]];
rankOf[nodes[index].key] = rank;
if (rank + 1 > rankCount) rankCount = rank + 1;
}
return GraphRanks(
rankOf: rankOf,
rankCount: rankCount,
components: <List<String>>[
for (final component in componentOrder) componentKeys[component],
],
);
}
/// Tarjan's strongly connected components, emitted sinks first.
///
/// Iterative rather than recursive so a long chain cannot exhaust the stack.
/// Members are sorted by definition index, which keeps every output stable.
List<List<int>> _components(List<List<int>> adjacency) {
final discovery = List<int>.filled(adjacency.length, -1);
final low = List<int>.filled(adjacency.length, 0);
final onStack = List<bool>.filled(adjacency.length, false);
final stack = <int>[];
final components = <List<int>>[];
var nextDiscovery = 0;
for (var root = 0; root < adjacency.length; root += 1) {
if (discovery[root] != -1) continue;
discovery[root] = low[root] = nextDiscovery;
nextDiscovery += 1;
stack.add(root);
onStack[root] = true;
final callStack = <_Frame>[_Frame(root)];
while (callStack.isNotEmpty) {
final frame = callStack.last;
final node = frame.node;
if (frame.nextChild < adjacency[node].length) {
final child = adjacency[node][frame.nextChild];
frame.nextChild += 1;
if (discovery[child] == -1) {
discovery[child] = low[child] = nextDiscovery;
nextDiscovery += 1;
stack.add(child);
onStack[child] = true;
callStack.add(_Frame(child));
} else if (onStack[child]) {
low[node] = math.min(low[node], discovery[child]);
}
continue;
}
callStack.removeLast();
if (callStack.isNotEmpty) {
final parent = callStack.last.node;
low[parent] = math.min(low[parent], low[node]);
}
if (low[node] == discovery[node]) {
final component = <int>[];
while (stack.isNotEmpty) {
final member = stack.removeLast();
onStack[member] = false;
component.add(member);
if (member == node) break;
}
component.sort();
components.add(component);
}
}
}
return components;
}
@@ -0,0 +1,129 @@
/// Pure geometry for a workflow graph's node layout.
///
/// Every size and gap is supplied by the caller. The native renderer measures
/// each node after text layout (including the platform's text scaling), so this
/// library never assumes a node width, font, palette or device class.
///
/// No Flutter imports: rectangles are plain numbers so the same result can be
/// built into widgets, a canvas or a test fixture.
library;
void _requireFiniteNonNegative(String name, double value) {
if (!value.isFinite || value < 0) {
throw ArgumentError.value(value, name, 'must be finite and non-negative');
}
}
/// One caller-measured node extent, in logical pixels.
///
/// A width or height may be zero for an empty label; the layout still keeps the
/// node separate from its neighbours through the configured gaps.
class NodeExtent {
NodeExtent({required this.width, required this.height}) {
_requireFiniteNonNegative('width', width);
_requireFiniteNonNegative('height', height);
}
final double width;
final double height;
}
/// The gaps a caller reserves around measured nodes.
///
/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a
/// rank, and [padding] is the outer margin included in [GraphLayout] bounds.
class GraphLayoutConfig {
GraphLayoutConfig({
required this.columnGap,
required this.rowGap,
this.padding = 0,
}) {
_requireFiniteNonNegative('columnGap', columnGap);
_requireFiniteNonNegative('rowGap', rowGap);
_requireFiniteNonNegative('padding', padding);
}
final double columnGap;
final double rowGap;
final double padding;
}
/// One placed node.
///
/// [key], [terminal] and [stageIndex] are the definition node's own identity,
/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in
/// graph space and [rank] is its 0-based topological column.
class GraphNodeBox {
const GraphNodeBox({
required this.key,
required this.terminal,
required this.stageIndex,
required this.rank,
required this.x,
required this.y,
required this.width,
required this.height,
});
final String key;
final bool terminal;
final int? stageIndex;
final int rank;
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 GraphNodeBox &&
other.key == key &&
other.terminal == terminal &&
other.stageIndex == stageIndex &&
other.rank == rank &&
other.x == x &&
other.y == y &&
other.width == width &&
other.height == height;
@override
int get hashCode =>
Object.hash(key, terminal, stageIndex, rank, x, y, width, height);
}
/// An immutable node layout: every placed box plus the total graph bounds.
///
/// [nodes] is ordered by rank first and definition order inside a rank; use
/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the
/// caller's padding; every box's [right] and [bottom] stay inside them.
/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the
/// number of columns (0 for an empty node set).
class GraphLayout {
GraphLayout({
required List<GraphNodeBox> nodes,
required this.width,
required this.height,
required this.rankCount,
required Map<String, int> ranks,
}) : nodes = List.unmodifiable(nodes),
ranks = Map.unmodifiable(ranks);
final List<GraphNodeBox> nodes;
final Map<String, int> ranks;
final double width;
final double height;
final int rankCount;
bool get isEmpty => nodes.isEmpty;
/// The placed box for [key], or null when the definition has no such node.
GraphNodeBox? nodeFor(String key) {
for (final node in nodes) {
if (node.key == key) return node;
}
return null;
}
}