Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

route FableLoom's backward graph edges under the cards instead of across them

[._.]/ Adam Eivy6cd09c880193
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsx
index b865ad458c..14736159e9 100644
--- a/client/src/components/fableloom/LoomCanvas.jsx
+++ b/client/src/components/fableloom/LoomCanvas.jsx
@@ -1,16 +1,19 @@
/**
* FableLoom canvas — the visual editor for one episode's scene graph.
*
- * Renders scene nodes as SVG cards (BFS-layered by `layoutLoomGraph`,
- * author-dragged positions win) with intent-labeled transition edges. Click
- * selects a scene (selection lives in the URL — the parent navigates); drag
- * repositions it and persists `pos` on release. The wrapper owns scrolling in
- * both axes so a wide graph pans instead of clipping.
+ * Renders scene nodes as SVG cards with intent-labeled transition edges —
+ * both the placement and the edge routing come from `layoutLoomGraph`, which
+ * layers the graph, sends backward edges through return lanes under the cards,
+ * and de-collides the labels. Click selects a scene (selection lives in the URL
+ * — the parent navigates); drag repositions it and persists `pos` on release.
+ * Selecting a scene dims every edge that doesn't touch it, so one path stays
+ * readable in a dense graph. The wrapper owns scrolling in both axes so a wide
+ * graph pans instead of clipping.
*/
import { useMemo, useRef } from 'react';
import { Play, Flag } from 'lucide-react';
-import { layoutLoomGraph, loomEdgePath, LOOM_NODE_W, LOOM_NODE_H } from '../../lib/loomLayout';
+import { layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_NODE_W, LOOM_NODE_H } from '../../lib/loomLayout';
const DRAG_THRESHOLD_PX = 4;
@@ -27,7 +30,7 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
const dragRef = useRef(null);
const layout = useMemo(() => layoutLoomGraph(episode), [episode]);
- const { positions } = layout;
+ const { positions, edges } = layout;
const nodes = episode?.nodes || [];
@@ -79,25 +82,28 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
<div className="overflow-auto h-full w-full" data-testid="loom-canvas">
<svg width={width} height={height} className="block select-none touch-none">
<g>
- {nodes.flatMap((node) => (node.transitions || []).map((tr) => {
- const from = positions[node.id];
- const to = positions[tr.targetNodeId];
- if (!from || !to) return null;
- const { d, labelX, labelY } = loomEdgePath(from, to);
- const active = node.id === selectedNodeId;
+ {edges.map((edge) => {
+ // With a scene selected, its own edges come forward and the rest
+ // recede — the only way to read one path through a dense graph.
+ const connected = edge.sourceId === selectedNodeId || edge.targetId === selectedNodeId;
+ const outgoing = edge.sourceId === selectedNodeId;
+ // Labels paint their stroke FIRST, which draws each one its own
+ // background out of the page color — a path running under a label
+ // then doesn't strike through the text.
return (
- <g key={tr.id} className={active ? 'opacity-100' : 'opacity-70'}>
- <path d={d} fill="none" strokeWidth={active ? 2 : 1.5}
- className={active ? 'stroke-port-accent' : 'stroke-port-border'} />
- {tr.intent && (
- <text x={labelX} y={labelY - 6} textAnchor="middle"
- className="fill-port-text-muted text-[10px] pointer-events-none">
- {truncate(tr.intent, 28)}
+ <g key={edge.id} className={!selectedNodeId ? 'opacity-70' : connected ? 'opacity-100' : 'opacity-25'}>
+ <path d={edge.d} fill="none" strokeWidth={connected ? 2 : 1.5}
+ className={outgoing ? 'stroke-port-accent' : 'stroke-port-border'} />
+ {edge.intent && (
+ <text x={edge.labelX} y={edge.labelY - 6} textAnchor="middle"
+ style={{ paintOrder: 'stroke' }} strokeWidth={3} strokeLinejoin="round"
+ className="fill-port-text-muted stroke-port-bg text-[10px] pointer-events-none">
+ {truncate(edge.intent, LOOM_EDGE_LABEL_MAX)}
</text>
)}
</g>
);
- }))}
+ })}
</g>
<g>
{nodes.map((node) => {
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index fe5fa87c02..a20ede6221 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -120,7 +120,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `kanbanColumns.js` | `bucketTickets` / `ticketInColumn` / `columnConfig` / `FALLBACK_COLUMNS` — pure column logic for the Jira Kanban board (`components/KanbanBoard.jsx`). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique `id` (Jira `name` is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category). |
| `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. |
| `letteringDensity.js` | `analyzeComicLettering` / `panelLetteringMetrics` / `countWords` / `overflowSeverity` / `DEFAULT_LETTERING_THRESHOLDS` — comic lettering-density accounting over parsed comic pages, powering the comic-script stage's inline over-stuffed-panel warnings (#1313). Byte-for-byte mirror of `server/lib/editorial/letteringDensity.js` (the server `comic.lettering-density` check is authoritative). Pure/DOM-free. |
-| `loomLayout.js` | FableLoom canvas layout — `layoutLoomGraph(episode)` (BFS-layered default positions, persisted `pos` overrides, canvas extents), `loomGraphLayers`, `loomEdgePath(from, to)` (cubic edge + label midpoint), `LOOM_NODE_W`/`LOOM_NODE_H`. A view-layer layering (shows unreachable nodes in trailing columns), deliberately NOT a mirror of the server's analysis-oriented `computeGraphLayers`. Pure/DOM-free. |
+| `loomLayout.js` | FableLoom canvas layout — `layoutLoomGraph(episode)` (BFS + barycenter-ordered positions, persisted `pos` overrides, routed edges, canvas extents), `loomGraphLayers`, `routeLoomEdges` (backward edges packed into return lanes under the cards), `placeEdgeLabels` (de-collides intent labels), `loomEdgePath(from, to, { laneY, self })`, `LOOM_NODE_W`/`LOOM_NODE_H`/`LOOM_EDGE_LABEL_MAX`. A view-layer layering (shows unreachable nodes in trailing columns), deliberately NOT a mirror of the server's analysis-oriented `computeGraphLayers`. Pure/DOM-free. |
| `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. |
| `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |
| `manuscriptFormat.js` | `formatManuscript(text, stageId)` / `REFLOW_STAGES` — normalize a manuscript section's text for the editor's "Format" button: undo PDF-paste artifacts (stylized drop-cap split onto its own line, hyphen-split words, trailing whitespace, runaway blank lines) for every stage, and additionally reflow soft-wrapped lines back into paragraphs for `prose` only (scripts keep their structural line breaks). Pure/DOM-free. |
diff --git a/client/src/lib/loomLayout.js b/client/src/lib/loomLayout.js
index 592040127f..82978a3dee 100644
--- a/client/src/lib/loomLayout.js
+++ b/client/src/lib/loomLayout.js
@@ -4,11 +4,20 @@
*
* Default positions come from BFS layering (columns = depth from the opening
* scene, rows = order within a layer; unreachable nodes trail in extra
- * columns). A node the author dragged carries a persisted `pos` override that
- * always wins. Layering here is a VIEW concern, deliberately not a mirror of
- * the server's `computeGraphLayers` (which omits unreachable nodes — the
- * canvas must show them so the author can fix them); the server's analysis
- * remains authoritative for reachability/depth stats.
+ * columns), then a barycenter pass reorders each layer toward its parents so
+ * forward edges cross as little as possible. A node the author dragged carries
+ * a persisted `pos` override that always wins. Layering here is a VIEW
+ * concern, deliberately not a mirror of the server's `computeGraphLayers`
+ * (which omits unreachable nodes — the canvas must show them so the author can
+ * fix them); the server's analysis remains authoritative for
+ * reachability/depth stats.
+ *
+ * Edge routing is direction-aware, because a branching narrative is a CYCLIC
+ * graph: "go back to the cell" edges point left, and drawing those the same
+ * right-edge → left-edge way as a forward edge sweeps a giant S across every
+ * card between them. Backward (and same-column) edges instead drop into a
+ * packed return lane below the card band, and every label is nudged out of its
+ * neighbours' way — see `routeLoomEdges`.
*/
export const LOOM_NODE_W = 200;
@@ -16,10 +25,23 @@ export const LOOM_NODE_H = 112;
const COL_GAP = 96;
const ROW_GAP = 40;
const MARGIN = 24;
+// Return lanes for backward edges: the first sits this far under the deepest
+// card, each further lane LANE_GAP below it. Lanes are packed (see
+// `assignLane`), so a graph with many short back-edges stays shallow.
+const LANE_OFFSET = 32;
+const LANE_GAP = 22;
+const LANE_PAD = 10;
+/** Longest intent text drawn on an edge before it is ellipsized. */
+export const LOOM_EDGE_LABEL_MAX = 24;
+// Label collision geometry. The canvas draws labels at 10px, whose average
+// advance is ~5.2px — enough to bucket overlaps without measuring text.
+const LABEL_CHAR_W = 5.2;
+const LABEL_ROW_H = 12;
+const LABEL_MAX_NUDGE_ROWS = 6;
const asArray = (v) => (Array.isArray(v) ? v : []);
-/** BFS layers from the start node (client mirror of computeGraphLayers). */
+/** BFS layers from the start node, ordered to reduce edge crossings. */
export function loomGraphLayers(episode) {
const nodes = asArray(episode?.nodes);
const byId = new Map(nodes.map((n) => [n.id, n]));
@@ -47,13 +69,45 @@ export function loomGraphLayers(episode) {
for (let i = 0; i < orphans.length; i += 4) {
layers.push(orphans.slice(i, i + 4));
}
+ return orderLayersByBarycenter(layers, byId);
+}
+
+/**
+ * Reorder each layer by the mean row of its parents in the layer before it
+ * (the standard barycenter heuristic). Nodes with no parent in the previous
+ * layer keep their BFS slot, and equal barycenters keep BFS order, so the
+ * result is deterministic. One downward pass: enough to untangle the common
+ * "two parents fan into shared children" shape without the cost (or the
+ * position churn) of iterating to a fixed point.
+ */
+function orderLayersByBarycenter(layers, byId) {
+ for (let col = 1; col < layers.length; col += 1) {
+ const sums = new Map();
+ for (const [row, parentId] of layers[col - 1].entries()) {
+ for (const tr of asArray(byId.get(parentId)?.transitions)) {
+ const entry = sums.get(tr?.targetNodeId) || { total: 0, count: 0 };
+ entry.total += row;
+ entry.count += 1;
+ sums.set(tr?.targetNodeId, entry);
+ }
+ }
+ layers[col] = layers[col]
+ .map((id, row) => {
+ const entry = sums.get(id);
+ return { id, row, key: entry ? entry.total / entry.count : row };
+ })
+ .sort((a, b) => a.key - b.key || a.row - b.row)
+ .map((e) => e.id);
+ }
return layers;
}
/**
- * Position every node. Returns `{ positions, width, height }` where
- * `positions` maps nodeId → `{ x, y }` (top-left corners). Persisted
- * `node.pos` overrides the computed slot; the canvas size covers both.
+ * Position every node and route every transition. Returns
+ * `{ positions, edges, width, height }` — `positions` maps nodeId →
+ * `{ x, y }` (top-left corners), `edges` carries a ready-to-draw path plus a
+ * de-collided label anchor. Persisted `node.pos` overrides the computed slot;
+ * the canvas size covers the cards AND the return lanes below them.
*/
export function layoutLoomGraph(episode) {
const nodes = asArray(episode?.nodes);
@@ -69,28 +123,154 @@ export function layoutLoomGraph(episode) {
});
});
let width = 0;
- let height = 0;
+ let cardBottom = 0;
for (const { x, y } of Object.values(positions)) {
width = Math.max(width, x + LOOM_NODE_W + MARGIN);
- height = Math.max(height, y + LOOM_NODE_H + MARGIN);
+ cardBottom = Math.max(cardBottom, y + LOOM_NODE_H);
+ }
+ const edges = routeLoomEdges(nodes, positions, cardBottom);
+ let height = cardBottom + MARGIN;
+ for (const edge of edges) {
+ height = Math.max(height, edge.maxY + MARGIN);
+ }
+ return { positions, edges, width: Math.max(width, 400), height: Math.max(height, 240) };
+}
+
+/**
+ * Lowest return lane whose horizontal runs don't overlap `[lo, hi]`, marking
+ * it occupied. Packing keeps a graph full of short back-edges from stacking
+ * one lane per edge (which would push the canvas hundreds of pixels deep)
+ * while never letting two lane runs sit on top of each other.
+ *
+ * `laneEnds[i]` is the rightmost x lane `i` is occupied to. That single number
+ * is enough because callers assign in left-to-right order of `lo`, so a lane
+ * is free for this run exactly when its previous run ended before `lo`.
+ */
+function assignLane(laneEnds, lo, hi) {
+ for (let i = 0; ; i += 1) {
+ if (laneEnds[i] === undefined || laneEnds[i] < lo) {
+ laneEnds[i] = hi;
+ return i;
+ }
+ }
+}
+
+/**
+ * Route every transition whose endpoints are both placed. Forward edges keep
+ * the right → left cubic; self-edges loop off the right side; backward and
+ * same-column edges dive under the cards into a packed return lane. Labels are
+ * de-collided afterwards, across the whole edge set.
+ */
+export function routeLoomEdges(nodes, positions, cardBottom) {
+ const routes = [];
+ for (const node of asArray(nodes)) {
+ const from = positions[node.id];
+ if (!from) continue;
+ for (const tr of asArray(node?.transitions)) {
+ const to = positions[tr?.targetNodeId];
+ if (!to) continue;
+ const self = tr.targetNodeId === node.id;
+ routes.push({
+ id: tr.id,
+ sourceId: node.id,
+ targetId: tr.targetNodeId,
+ intent: tr.intent || '',
+ from,
+ to,
+ self,
+ laneY: null,
+ });
+ }
}
- return { positions, width: Math.max(width, 400), height: Math.max(height, 240) };
+
+ // Lanes are packed left to right, so the sort has to come BEFORE assignment:
+ // `assignLane` tracks only each lane's rightmost end, which is a correct
+ // free/busy test only when runs arrive in increasing `lo`.
+ const laneBase = cardBottom + LANE_OFFSET;
+ const laneEnds = [];
+ const runStart = (route) => Math.min(route.from.x, route.to.x) + LOOM_NODE_W / 2 - LANE_PAD;
+ const returning = routes.filter((r) => !r.self && r.to.x <= r.from.x).sort((a, b) => runStart(a) - runStart(b));
+ for (const route of returning) {
+ const hi = Math.max(route.from.x, route.to.x) + LOOM_NODE_W / 2 + LANE_PAD;
+ route.laneY = laneBase + assignLane(laneEnds, runStart(route), hi) * LANE_GAP;
+ }
+
+ return placeEdgeLabels(routes.map(({ id, sourceId, targetId, intent, from, to, self, laneY }) => ({
+ id, sourceId, targetId, intent, ...loomEdgePath(from, to, { laneY, self }),
+ })));
}
/**
- * Cubic path from a source node's right edge to a target node's left edge,
- * with the label midpoint. A self-or-backward edge bows harder so it stays
- * readable when the target sits left of (or on top of) the source.
+ * Push overlapping labels down a row at a time until each clears the ones
+ * already placed. Sorted by anchor so the result doesn't depend on transition
+ * order, and capped so a hopelessly crowded cluster stops sliding down the
+ * canvas rather than trailing off it.
*/
-export function loomEdgePath(from, to) {
- const x1 = from.x + LOOM_NODE_W;
- const y1 = from.y + LOOM_NODE_H / 2;
- const x2 = to.x;
- const y2 = to.y + LOOM_NODE_H / 2;
- const dx = Math.max(48, Math.abs(x2 - x1) / 2);
+export function placeEdgeLabels(edges) {
+ const placed = [];
+ const halfWidth = (text) => (Math.min(text.length, LOOM_EDGE_LABEL_MAX) * LABEL_CHAR_W) / 2;
+ for (const edge of [...edges].sort((a, b) => a.labelY - b.labelY || a.labelX - b.labelX)) {
+ if (!edge.intent) continue;
+ const half = halfWidth(edge.intent);
+ let y = edge.labelY;
+ for (let row = 0; row < LABEL_MAX_NUDGE_ROWS; row += 1) {
+ const clash = placed.some((p) => Math.abs(p.y - y) < LABEL_ROW_H
+ && Math.abs(p.x - edge.labelX) < p.half + half);
+ if (!clash) break;
+ y += LABEL_ROW_H;
+ }
+ edge.labelY = y;
+ edge.maxY = Math.max(edge.maxY, y);
+ placed.push({ x: edge.labelX, y, half });
+ }
+ return edges;
+}
+
+/**
+ * Path between two placed nodes, plus the label anchor and the deepest y the
+ * route reaches (so the canvas can size itself around a return lane).
+ *
+ * - forward (`to` is right of `from`): cubic from the right edge to the left edge.
+ * - backward / same column: a U from the source's bottom edge down to
+ * `laneY` and back up into the target's bottom edge — it stays out of the
+ * card band instead of sweeping across it.
+ * - self: a small loop off the right side.
+ */
+export function loomEdgePath(from, to, options = {}) {
+ const { laneY = null, self = false } = options;
+ if (self) {
+ const x = from.x + LOOM_NODE_W;
+ const y = from.y + LOOM_NODE_H / 2;
+ return {
+ d: `M ${x} ${y - 24} C ${x + 64} ${y - 44}, ${x + 64} ${y + 44}, ${x} ${y + 24}`,
+ labelX: x + 46,
+ labelY: y,
+ maxY: from.y + LOOM_NODE_H,
+ };
+ }
+ if (to.x > from.x) {
+ const x1 = from.x + LOOM_NODE_W;
+ const y1 = from.y + LOOM_NODE_H / 2;
+ const x2 = to.x;
+ const y2 = to.y + LOOM_NODE_H / 2;
+ const dx = Math.max(48, (x2 - x1) / 2);
+ return {
+ d: `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`,
+ labelX: (x1 + x2) / 2,
+ labelY: (y1 + y2) / 2,
+ maxY: Math.max(y1, y2),
+ };
+ }
+ const x1 = from.x + LOOM_NODE_W / 2;
+ const y1 = from.y + LOOM_NODE_H;
+ const x2 = to.x + LOOM_NODE_W / 2;
+ const y2 = to.y + LOOM_NODE_H;
+ const lane = Number.isFinite(laneY) ? laneY : Math.max(y1, y2) + LANE_OFFSET;
return {
- d: `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`,
+ d: `M ${x1} ${y1} C ${x1} ${lane}, ${x2} ${lane}, ${x2} ${y2}`,
labelX: (x1 + x2) / 2,
- labelY: (y1 + y2) / 2,
+ // Bottom of the cubic at t=0.5, where the run is flattest.
+ labelY: (y1 + y2 + 6 * lane) / 8,
+ maxY: lane,
};
}
diff --git a/client/src/lib/loomLayout.test.js b/client/src/lib/loomLayout.test.js
index 907b756a40..a2e40eaeea 100644
--- a/client/src/lib/loomLayout.test.js
+++ b/client/src/lib/loomLayout.test.js
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
- layoutLoomGraph, loomEdgePath, loomGraphLayers, LOOM_NODE_W,
+ layoutLoomGraph, loomEdgePath, loomGraphLayers, placeEdgeLabels, routeLoomEdges,
+ LOOM_NODE_H, LOOM_NODE_W,
} from './loomLayout.js';
const tr = (id, targetNodeId) => ({ id, targetNodeId, intent: 'go' });
@@ -31,6 +32,23 @@ describe('loomGraphLayers', () => {
const layers = loomGraphLayers({ startNodeId: 'gone', nodes: [{ id: 'a' }, { id: 'b' }] });
expect(layers).toEqual([['a', 'b']]);
});
+
+ it('reorders a layer toward its parents so forward edges stop crossing', () => {
+ // a → x, b → y discovered as [y, x]: barycenter pulls x above y to match
+ // the parent order, which is the crossing-free arrangement.
+ const layers = loomGraphLayers({
+ startNodeId: 'root',
+ nodes: [
+ { id: 'root', transitions: [tr('t1', 'a'), tr('t2', 'b')] },
+ { id: 'a', transitions: [tr('t3', 'x')] },
+ { id: 'b', transitions: [tr('t4', 'y')] },
+ { id: 'y', transitions: [] },
+ { id: 'x', transitions: [] },
+ ],
+ });
+ expect(layers[1]).toEqual(['a', 'b']);
+ expect(layers[2]).toEqual(['x', 'y']);
+ });
});
describe('layoutLoomGraph', () => {
@@ -46,11 +64,99 @@ describe('layoutLoomGraph', () => {
});
it('handles an empty episode without NaN extents', () => {
- const { positions, width, height } = layoutLoomGraph({ nodes: [] });
+ const { positions, edges, width, height } = layoutLoomGraph({ nodes: [] });
expect(positions).toEqual({});
+ expect(edges).toEqual([]);
expect(width).toBeGreaterThan(0);
expect(height).toBeGreaterThan(0);
});
+
+ it('routes an edge per transition and grows the canvas to cover return lanes', () => {
+ const ep = episode();
+ // A loop back to the opening scene — the shape the old right-to-left
+ // routing swept across every card in between.
+ ep.nodes[1].transitions.push(tr('t9', 'n1'));
+ const { edges, height, positions } = layoutLoomGraph(ep);
+ expect(edges.map((e) => e.id)).toEqual(['t1', 't2', 't3', 't9']);
+ const back = edges.find((e) => e.id === 't9');
+ // Leaves and enters through the BOTTOM edges, dipping below both cards.
+ expect(back.d.startsWith(`M ${positions.n2.x + LOOM_NODE_W / 2} ${positions.n2.y + LOOM_NODE_H}`)).toBe(true);
+ expect(back.maxY).toBeGreaterThan(positions.n1.y + LOOM_NODE_H);
+ expect(height).toBeGreaterThan(back.maxY);
+ });
+
+ it('drops a transition whose target no longer exists', () => {
+ const ep = episode();
+ ep.nodes[1].transitions.push(tr('t-dangling', 'gone'));
+ const { edges } = layoutLoomGraph(ep);
+ expect(edges.some((e) => e.id === 't-dangling')).toBe(false);
+ });
+});
+
+describe('routeLoomEdges', () => {
+ it('packs non-overlapping back edges into the same lane', () => {
+ const positions = {
+ a: { x: 0, y: 0 }, b: { x: 300, y: 0 }, c: { x: 900, y: 0 }, d: { x: 1200, y: 0 },
+ };
+ const nodes = [
+ { id: 'b', transitions: [{ id: 'e1', targetNodeId: 'a', intent: '' }] },
+ { id: 'd', transitions: [{ id: 'e2', targetNodeId: 'c', intent: '' }] },
+ // Spans both of the runs above, so it cannot share their lane.
+ { id: 'd2', transitions: [{ id: 'e3', targetNodeId: 'a', intent: '' }] },
+ ];
+ positions.d2 = { x: 1200, y: 0 };
+ const [e1, e2, e3] = routeLoomEdges(nodes, positions, LOOM_NODE_H);
+ expect(e2.maxY).toBe(e1.maxY);
+ expect(e3.maxY).toBeGreaterThan(e1.maxY);
+ });
+
+ it('packs the same way whichever order the transitions were authored in', () => {
+ const positions = { a: { x: 0, y: 0 }, b: { x: 300, y: 0 }, c: { x: 900, y: 0 }, d: { x: 1200, y: 0 } };
+ const near = { id: 'b', transitions: [{ id: 'e1', targetNodeId: 'a', intent: '' }] };
+ const far = { id: 'd', transitions: [{ id: 'e2', targetNodeId: 'c', intent: '' }] };
+ const depths = (nodes) => Object.fromEntries(
+ routeLoomEdges(nodes, positions, LOOM_NODE_H).map((e) => [e.id, e.maxY]),
+ );
+ expect(depths([near, far])).toEqual(depths([far, near]));
+ });
+
+ it('loops a self-transition off the right side instead of routing under', () => {
+ const positions = { a: { x: 0, y: 0 } };
+ const [edge] = routeLoomEdges(
+ [{ id: 'a', transitions: [{ id: 'e1', targetNodeId: 'a', intent: 'wait' }] }],
+ positions,
+ LOOM_NODE_H,
+ );
+ expect(edge.labelX).toBeGreaterThan(LOOM_NODE_W);
+ expect(edge.maxY).toBe(LOOM_NODE_H);
+ });
+});
+
+describe('placeEdgeLabels', () => {
+ it('nudges overlapping labels apart and leaves separated ones alone', () => {
+ const edges = [
+ { intent: 'take the left hallway', labelX: 100, labelY: 50, maxY: 50 },
+ { intent: 'take the right hallway', labelX: 100, labelY: 50, maxY: 50 },
+ { intent: 'far away', labelX: 900, labelY: 50, maxY: 50 },
+ ];
+ const [a, b, c] = placeEdgeLabels(edges);
+ expect(a.labelY).toBe(50);
+ expect(b.labelY).toBeGreaterThan(a.labelY);
+ expect(c.labelY).toBe(50);
+ // The nudge has to grow the routed extent too, or the label lands under
+ // the canvas floor and clips.
+ expect(b.maxY).toBe(b.labelY);
+ });
+
+ it('ignores unlabeled edges', () => {
+ const edges = [
+ { intent: '', labelX: 100, labelY: 50, maxY: 50 },
+ { intent: 'labeled', labelX: 100, labelY: 50, maxY: 50 },
+ ];
+ const [blank, labeled] = placeEdgeLabels(edges);
+ expect(blank.labelY).toBe(50);
+ expect(labeled.labelY).toBe(50);
+ });
});
describe('loomEdgePath', () => {
@@ -61,4 +167,10 @@ describe('loomEdgePath', () => {
expect(labelX).toBe((LOOM_NODE_W + 300) / 2);
expect(labelY).toBeGreaterThan(0);
});
+
+ it('sends a same-column edge under the cards rather than across them', () => {
+ const { d, maxY } = loomEdgePath({ x: 300, y: 0 }, { x: 300, y: 300 }, { laneY: 500 });
+ expect(d.startsWith(`M ${300 + LOOM_NODE_W / 2} ${LOOM_NODE_H}`)).toBe(true);
+ expect(maxY).toBe(500);
+ });
});