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

fan FableLoom scene threads into orthogonal lanes and stack the graph on small screens (#4799)

[._.]/ Adam Eivy075b875b0c52
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsx
index 14736159e9..c10faecc38 100644
--- a/client/src/components/fableloom/LoomCanvas.jsx
+++ b/client/src/components/fableloom/LoomCanvas.jsx
@@ -2,18 +2,25 @@
* FableLoom canvas — the visual editor for one episode's scene graph.
*
* 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.
+ * placement, orientation, and orthogonal routing come from `layoutLoomGraph`.
+ * The canvas measures itself for card wrapping. Flow direction comes from
+ * the parent when it knows the page breakpoint (editor rail beside vs
+ * under); otherwise `pickLoomOrientation` keys off canvas width.
+ * Click (or tap) selects a scene (selection lives in the URL — the parent
+ * navigates); mouse-drag repositions a card and persists `pos` on release.
+ * Touch never drags — it would fight scrolling, and desktop `pos` is the
+ * wrong coordinate space for the stacked layout. Selecting a scene dims
+ * every edge that doesn't touch it, and on the stacked layout a path strip
+ * lists the inbound/outbound intents so a dense graph stays traversable
+ * without tracing overlapping strokes.
*/
-import { useMemo, useRef } from 'react';
-import { Play, Flag } from 'lucide-react';
-import { layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_NODE_W, LOOM_NODE_H } from '../../lib/loomLayout';
+import { useEffect, useId, useMemo, useRef } from 'react';
+import { Flag, Play } from 'lucide-react';
+import useContainerWidth from '../../hooks/useContainerWidth';
+import {
+ layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_ORIENTATION,
+} from '../../lib/loomLayout';
const DRAG_THRESHOLD_PX = 4;
@@ -22,20 +29,47 @@ const truncate = (text, max) => {
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
};
-export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMoveNode }) {
+const startOfPath = (d) => {
+ const match = /^M\s+(-?[\d.]+)\s+(-?[\d.]+)/.exec(d || '');
+ return match ? { x: Number(match[1]), y: Number(match[2]) } : null;
+};
+
+export default function LoomCanvas({
+ episode, selectedNodeId, onSelectNode, onMoveNode,
+ viewportWidth: viewportWidthProp, orientation: orientationProp,
+}) {
// An in-flight drag lives entirely outside React state: the dragged <g>'s
// transform is mutated directly per pointermove, and the position commits
// once on release. Routing it through setState re-rendered every node card
// (each with a foreignObject subtree) ~60×/s. Edges catch up on release.
const dragRef = useRef(null);
+ const [measureRef, measuredWidth] = useContainerWidth();
+ const viewportWidth = viewportWidthProp ?? measuredWidth;
+ const markerId = useId().replace(/:/g, '');
- const layout = useMemo(() => layoutLoomGraph(episode), [episode]);
- const { positions, edges } = layout;
+ const layout = useMemo(
+ () => layoutLoomGraph(episode, { viewportWidth, orientation: orientationProp }),
+ [episode, viewportWidth, orientationProp],
+ );
+ const { positions, edges, nodeW, nodeH, orientation } = layout;
+ const stacked = orientation === LOOM_ORIENTATION.TB;
const nodes = episode?.nodes || [];
+ const byId = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
+
+ useEffect(() => {
+ if (!selectedNodeId || !measureRef.current) return undefined;
+ const el = measureRef.current.querySelector(`[data-node-id="${selectedNodeId}"]`);
+ el?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
+ return undefined;
+ }, [selectedNodeId, measureRef, layout.width, layout.height]);
const handlePointerDown = (event, node) => {
if (event.button !== 0) return;
+ // Touch/pen: tap-to-select only. Capturing the pointer would steal the
+ // scroll gesture, and a stacked layout's coordinates must not persist as
+ // desktop `pos`.
+ if (event.pointerType !== 'mouse' || stacked) return;
event.currentTarget.setPointerCapture(event.pointerId);
const start = positions[node.id] || { x: 0, y: 0 };
dragRef.current = {
@@ -68,39 +102,110 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
dragRef.current = null;
if (!drag) return;
if (drag.moved) {
+ drag.el.dataset.loomDragged = '1';
onMoveNode?.(drag.id, { x: Math.round(drag.x), y: Math.round(drag.y) });
- } else {
- onSelectNode?.(drag.id);
}
};
+ const handleNodeActivate = (event, nodeId) => {
+ // A completed mouse-drag fires click on the card too — ignore that one so
+ // repositioning doesn't also select (and so we don't persist stacked-layout
+ // coordinates as desktop `pos` via a follow-up navigate).
+ if (event?.currentTarget?.dataset?.loomDragged === '1') {
+ delete event.currentTarget.dataset.loomDragged;
+ return;
+ }
+ onSelectNode?.(nodeId);
+ };
+
if (!nodes.length) return null;
const { width, height } = layout;
+ const titleMax = Math.max(12, Math.floor((nodeW - 20) / 7.2));
+ const accentMarker = `loom-arrow-accent-${markerId}`;
+ const mutedMarker = `loom-arrow-${markerId}`;
+
+ const showStrip = stacked && selectedNodeId && byId.has(selectedNodeId);
return (
- <div className="overflow-auto h-full w-full" data-testid="loom-canvas">
- <svg width={width} height={height} className="block select-none touch-none">
+ <div className="relative h-full w-full">
+ <div
+ ref={measureRef}
+ className={`overflow-auto h-full w-full overscroll-contain ${showStrip ? 'pb-28' : ''}`}
+ data-testid="loom-canvas"
+ data-orientation={orientation}
+ >
+ <svg
+ width={width}
+ height={height}
+ className="block select-none"
+ aria-label="Episode scene graph"
+ >
+ <defs>
+ <marker id={mutedMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
+ <path d="M0,1 L8,4 L0,7 Z" className="fill-port-border" />
+ </marker>
+ <marker id={accentMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
+ <path d="M0,1 L8,4 L0,7 Z" className="fill-port-accent" />
+ </marker>
+ </defs>
<g>
{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.
+ const start = startOfPath(edge.d);
return (
- <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'} />
+ <g key={edge.id} className={!selectedNodeId ? 'opacity-80' : connected ? 'opacity-100' : 'opacity-20'}>
+ <path
+ d={edge.d}
+ fill="none"
+ strokeWidth={connected ? 2.25 : 1.5}
+ markerEnd={`url(#${outgoing || (!selectedNodeId && connected) ? accentMarker : mutedMarker})`}
+ className={outgoing ? 'stroke-port-accent' : 'stroke-port-border'}
+ />
+ {/* Invisible fat stroke so a label-less jog is still easy to hover/tap. */}
+ <path
+ d={edge.d}
+ fill="none"
+ stroke="transparent"
+ strokeWidth={16}
+ className="cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectNode?.(edge.targetId);
+ }}
+ />
{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">
+ <text
+ x={edge.labelX}
+ y={edge.labelY}
+ textAnchor="middle"
+ role="button"
+ tabIndex={0}
+ aria-label={`Path: ${edge.intent}`}
+ style={{ paintOrder: 'stroke' }}
+ strokeWidth={4}
+ strokeLinejoin="round"
+ className="fill-port-text-muted stroke-port-bg text-[10px] cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectNode?.(edge.targetId);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelectNode?.(edge.targetId);
+ }
+ }}
+ >
{truncate(edge.intent, LOOM_EDGE_LABEL_MAX)}
</text>
)}
+ {outgoing && start && (
+ <circle cx={start.x} cy={start.y} r={3} className="fill-port-accent" />
+ )}
</g>
);
})}
@@ -114,14 +219,17 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
return (
<g
key={node.id}
+ data-node-id={node.id}
transform={`translate(${pos.x}, ${pos.y})`}
- className="cursor-pointer"
+ className={stacked ? 'cursor-pointer' : 'cursor-grab'}
role="button"
tabIndex={0}
aria-label={`Scene: ${node.title || 'Untitled'}`}
+ aria-current={selected ? 'true' : undefined}
onPointerDown={(e) => handlePointerDown(e, node)}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
+ onClick={(e) => handleNodeActivate(e, node.id)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
@@ -130,10 +238,10 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
}}
>
<rect
- width={LOOM_NODE_W}
- height={LOOM_NODE_H}
+ width={nodeW}
+ height={nodeH}
rx={10}
- strokeWidth={selected ? 2 : 1}
+ strokeWidth={selected ? 2.5 : 1}
className={`${node.isEnding ? 'fill-port-success/10' : 'fill-port-card'} ${
selected ? 'stroke-port-accent' : 'stroke-port-border'
}`}
@@ -141,19 +249,24 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
{node.image && (
<image
href={`/data/images/${node.image}`}
- x={8} y={26} width={54} height={LOOM_NODE_H - 34}
+ x={8} y={26} width={54} height={nodeH - 34}
preserveAspectRatio="xMidYMid slice"
/>
)}
<text x={10} y={17} className="fill-port-text text-[11px] font-semibold pointer-events-none">
- {truncate(node.title || 'Untitled scene', 26)}
+ {truncate(node.title || 'Untitled scene', titleMax)}
</text>
- <foreignObject x={node.image ? 68 : 10} y={24} width={LOOM_NODE_W - (node.image ? 78 : 20)} height={LOOM_NODE_H - 48}>
+ <foreignObject
+ x={node.image ? 68 : 10}
+ y={24}
+ width={nodeW - (node.image ? 78 : 20)}
+ height={nodeH - 48}
+ >
<div className="text-[10px] leading-snug text-port-text-muted overflow-hidden h-full pointer-events-none">
- {truncate(node.prose, 110)}
+ {truncate(node.prose, stacked ? 80 : 110)}
</div>
</foreignObject>
- <g transform={`translate(10, ${LOOM_NODE_H - 16})`} className="pointer-events-none">
+ <g transform={`translate(10, ${nodeH - 16})`} className="pointer-events-none">
{isStart && (
<g>
<Play size={10} className="text-port-accent" x={0} y={-8} />
@@ -173,7 +286,74 @@ export default function LoomCanvas({ episode, selectedNodeId, onSelectNode, onMo
);
})}
</g>
- </svg>
+ </svg>
+ </div>
+ {showStrip && (
+ <PathStrip
+ episode={episode}
+ node={byId.get(selectedNodeId)}
+ byId={byId}
+ onSelectNode={onSelectNode}
+ />
+ )}
+ </div>
+ );
+}
+
+/**
+ * Compact inbound/outbound list for the stacked (phone) layout — tracing an
+ * orthogonal path with a finger is how the desktop graph became unreadable
+ * on small screens; tapping a named intent is the traversal that survives.
+ */
+function PathStrip({ episode, node, byId, onSelectNode }) {
+ const outgoing = (node.transitions || []).filter((t) => byId.has(t.targetNodeId));
+ const incoming = episode.nodes.flatMap((n) => (
+ (n.transitions || [])
+ .filter((t) => t.targetNodeId === node.id)
+ .map((t) => ({ from: n, tr: t }))
+ ));
+ return (
+ <div
+ className="absolute bottom-0 inset-x-0 border-t border-port-border bg-port-card/95 backdrop-blur-sm px-3 py-2 space-y-1.5"
+ data-testid="loom-path-strip"
+ >
+ <p className="text-[11px] font-semibold truncate">{node.title || 'Untitled scene'}</p>
+ {incoming.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 items-center">
+ <span className="text-[10px] text-port-text-muted shrink-0">From</span>
+ {incoming.map(({ from, tr }) => (
+ <button
+ key={`in-${from.id}-${tr.id}`}
+ type="button"
+ onClick={() => onSelectNode?.(from.id)}
+ className="text-[10px] px-2 py-0.5 rounded-full border border-port-border hover:border-port-accent max-w-full truncate"
+ >
+ {from.title || 'Untitled'}
+ {tr.intent ? ` · ${truncate(tr.intent, 22)}` : ''}
+ </button>
+ ))}
+ </div>
+ )}
+ {outgoing.length > 0 && (
+ <div className="flex flex-wrap gap-1.5 items-center">
+ <span className="text-[10px] text-port-text-muted shrink-0">To</span>
+ {outgoing.map((tr) => (
+ <button
+ key={tr.id}
+ type="button"
+ onClick={() => onSelectNode?.(tr.targetNodeId)}
+ className="text-[10px] px-2 py-0.5 rounded-full border border-port-accent/40 text-port-accent hover:border-port-accent max-w-full truncate"
+ >
+ {truncate(tr.intent || 'continue', 22)}
+ {' → '}
+ {byId.get(tr.targetNodeId)?.title || 'Untitled'}
+ </button>
+ ))}
+ </div>
+ )}
+ {incoming.length === 0 && outgoing.length === 0 && (
+ <p className="text-[10px] text-port-text-muted">No paths in or out of this scene.</p>
+ )}
</div>
);
}
diff --git a/client/src/components/fableloom/LoomCanvas.test.jsx b/client/src/components/fableloom/LoomCanvas.test.jsx
index 45ca40199e..9b03ed1a18 100644
--- a/client/src/components/fableloom/LoomCanvas.test.jsx
+++ b/client/src/components/fableloom/LoomCanvas.test.jsx
@@ -46,4 +46,41 @@ describe('LoomCanvas', () => {
);
expect(container.firstChild).toBeNull();
});
+
+ it('selects the target scene from an edge intent label', () => {
+ const onSelectNode = vi.fn();
+ render(<LoomCanvas episode={episode()} selectedNodeId={null} onSelectNode={onSelectNode} />);
+ fireEvent.click(screen.getByLabelText('Path: enter the gate'));
+ expect(onSelectNode).toHaveBeenCalledWith('n2');
+ });
+
+ it('keeps left-to-right flow when the page pins orientation on a narrow canvas', () => {
+ render(
+ <LoomCanvas
+ episode={episode()}
+ selectedNodeId="n1"
+ onSelectNode={() => {}}
+ viewportWidth={390}
+ orientation="lr"
+ />,
+ );
+ expect(screen.getByTestId('loom-canvas')).toHaveAttribute('data-orientation', 'lr');
+ expect(screen.queryByTestId('loom-path-strip')).not.toBeInTheDocument();
+ });
+
+ it('stacks the graph and shows a path strip on a narrow canvas', () => {
+ const onSelectNode = vi.fn();
+ render(
+ <LoomCanvas
+ episode={episode()}
+ selectedNodeId="n1"
+ onSelectNode={onSelectNode}
+ viewportWidth={390}
+ />,
+ );
+ expect(screen.getByTestId('loom-canvas')).toHaveAttribute('data-orientation', 'tb');
+ expect(screen.getByTestId('loom-path-strip')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /enter the gate → Inside/i }));
+ expect(onSelectNode).toHaveBeenCalledWith('n2');
+ });
});
diff --git a/client/src/hooks/useContainerWidth.js b/client/src/hooks/useContainerWidth.js
index f0c6efd7f0..0bfa54f222 100644
--- a/client/src/hooks/useContainerWidth.js
+++ b/client/src/hooks/useContainerWidth.js
@@ -8,7 +8,7 @@ export default function useContainerWidth() {
const ref = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
- if (!ref.current) return undefined;
+ if (!ref.current || typeof ResizeObserver === 'undefined') return undefined;
const ro = new ResizeObserver((entries) => {
const w = entries[0]?.contentRect?.width;
if (w) setWidth(Math.floor(w));
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3b98930b37..8072469578 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 + 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. |
+| `loomLayout.js` | FableLoom canvas layout — `layoutLoomGraph(episode, { viewportWidth, orientation })` (BFS + barycenter-ordered positions, persisted `pos` overrides on left-to-right only, orthogonal port-fanned edges, canvas extents), `pickLoomOrientation` (stacks top-to-bottom under `LOOM_STACK_WIDTH` when orientation is not pinned), `loomGraphLayers`, `routeLoomEdges` (forward edges in packed gap lanes; backward/skip edges around the card band), `placeEdgeLabels` (de-collides intent labels), `loomEdgePath(from, to, { laneY, self, orientation })`, `LOOM_NODE_W`/`LOOM_NODE_H`/`LOOM_EDGE_LABEL_MAX`/`LOOM_ORIENTATION`/`LOOM_STACK_WIDTH`. 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 ce0924497f..e9b1bc2e46 100644
--- a/client/src/lib/loomLayout.js
+++ b/client/src/lib/loomLayout.js
@@ -2,44 +2,56 @@
* FableLoom graph layout — pure helpers that place an episode's scene nodes on
* the editor canvas and route its transition edges.
*
- * Default positions come from BFS layering (columns = depth from the opening
- * scene, rows = order within a layer; unreachable nodes trail in extra
- * 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
+ * Default positions come from BFS layering (depth from the opening scene, then
+ * a barycenter pass so forward edges cross as little as possible). Unreachable
+ * nodes trail in extra layers so the author can see them — this 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.
+ * (which omits them; the server's analysis stays 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`.
+ * A node the author dragged carries a persisted `pos` that wins on the
+ * left-to-right desktop layout. Narrow viewports flip the flow top-to-bottom
+ * and IGNORE `pos`: those coordinates are in the desktop space and would pile
+ * cards off-screen. Touch on that layout taps to select; it does not drag.
+ *
+ * Edge routing is orthogonal (stub → lane → stub) with per-node port fanning,
+ * because a branching narrative is a CYCLIC graph and drawing every edge as a
+ * right-edge → left-edge cubic made parallel intents occupy the same curve.
+ * Backward / same-layer edges drop into packed return lanes on the unused
+ * side of the card band; skip-layer edges go around the other side so they
+ * don't sweep through cards in between. Labels sit on the first stub, then
+ * de-collide — see `routeLoomEdges`.
*/
export const LOOM_NODE_W = 200;
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.
+export const LOOM_ORIENTATION = Object.freeze({ LR: 'lr', TB: 'tb' });
+/** Below this canvas width the graph stacks top-to-bottom. Matches the
+ * editor-rail `lg` breakpoint: beside the canvas we keep left-to-right
+ * (pan is fine); once the rail wraps under, a vertical scroll is the
+ * readable mobile/tablet layout. */
+export const LOOM_STACK_WIDTH = 1024;
+
+const MARGIN = 24;
+// Gap along the reading direction: enough for a 24-char label plus a vertical
+// (or horizontal, in tb) lane. Fan-out adds LANE_GAP per extra parallel edge.
+const BASE_FLOW_GAP = 148;
+const RANK_GAP = 48;
+const LANE_OFFSET = 36;
+const LANE_GAP = 18;
+const LANE_PAD = 12;
+const STUB = 20;
+const PORT_INSET = 16;
+const SIDE_GUTTER = 52;
const LABEL_CHAR_W = 5.2;
const LABEL_ROW_H = 12;
-const LABEL_MAX_NUDGE_ROWS = 6;
+const LABEL_MAX_NUDGE_ROWS = 8;
+const MIN_NODE_W = 168;
const asArray = (v) => (Array.isArray(v) ? v : []);
+const isFinitePos = (pos) => pos && Number.isFinite(pos.x) && Number.isFinite(pos.y);
/** BFS layers from the start node, ordered to reduce edge crossings. */
export function loomGraphLayers(episode) {
@@ -102,53 +114,200 @@ function orderLayersByBarycenter(layers, byId) {
return layers;
}
+/**
+ * Pick a flow direction from the canvas width. Width 0 means "not measured
+ * yet" and stays left-to-right so SSR/tests match the desktop path. Layer
+ * count is accepted so callers can pass it without a signature fork; it
+ * does not change the result — a wide desktop canvas pans a long episode,
+ * it does not flip the author's left-to-right map.
+ */
+export function pickLoomOrientation(viewportWidth, _layerCount = 1) {
+ if (!viewportWidth) return LOOM_ORIENTATION.LR;
+ return viewportWidth < LOOM_STACK_WIDTH ? LOOM_ORIENTATION.TB : LOOM_ORIENTATION.LR;
+}
+
+function nodeMetrics(orientation, viewportWidth) {
+ if (orientation === LOOM_ORIENTATION.TB && viewportWidth > 0) {
+ const available = Math.max(MIN_NODE_W, viewportWidth - SIDE_GUTTER * 2 - MARGIN * 2);
+ return { nodeW: Math.min(LOOM_NODE_W, available), nodeH: LOOM_NODE_H };
+ }
+ return { nodeW: LOOM_NODE_W, nodeH: LOOM_NODE_H };
+}
+
+function maxFanout(nodes) {
+ let max = 1;
+ const incoming = new Map();
+ for (const node of asArray(nodes)) {
+ const outs = asArray(node.transitions).length;
+ if (outs > max) max = outs;
+ for (const tr of asArray(node.transitions)) {
+ incoming.set(tr?.targetNodeId, (incoming.get(tr?.targetNodeId) || 0) + 1);
+ }
+ }
+ for (const count of incoming.values()) {
+ if (count > max) max = count;
+ }
+ return max;
+}
+
+function flowGapFor(nodes) {
+ return BASE_FLOW_GAP + Math.max(0, maxFanout(nodes) - 2) * LANE_GAP;
+}
+
/**
* 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.
+ * `{ positions, edges, width, height, nodeW, nodeH, orientation }` —
+ * `positions` maps nodeId → `{ x, y }` (top-left corners), `edges` carries a
+ * ready-to-draw orthogonal path plus a de-collided label anchor. Persisted
+ * `node.pos` overrides the computed slot on left-to-right layouts only.
+ *
+ * `options.orientation` pins flow direction (`lr`/`tb`). When omitted,
+ * `pickLoomOrientation(viewportWidth)` decides. `viewportWidth` (the
+ * canvas CSS width) still drives how many cards fit in a stacked layer
+ * row — not the page breakpoint; the editor passes orientation from the
+ * page so a laptop with the rail beside the canvas stays left-to-right.
*/
-export function layoutLoomGraph(episode) {
+export function layoutLoomGraph(episode, options = {}) {
const nodes = asArray(episode?.nodes);
- const posById = new Map(nodes.map((n) => [n.id, n.pos]));
const layers = loomGraphLayers(episode);
- const positions = {};
- layers.forEach((layer, col) => {
- layer.forEach((id, row) => {
- const custom = posById.get(id);
- positions[id] = custom && Number.isFinite(custom.x) && Number.isFinite(custom.y)
- ? { x: custom.x, y: custom.y }
- : { x: MARGIN + col * (LOOM_NODE_W + COL_GAP), y: MARGIN + row * (LOOM_NODE_H + ROW_GAP) };
- });
+ const orientation = options.orientation
+ || pickLoomOrientation(options.viewportWidth, layers.length);
+ const { nodeW, nodeH } = nodeMetrics(orientation, options.viewportWidth);
+ const flowGap = flowGapFor(nodes);
+ const posById = new Map(nodes.map((n) => [n.id, n.pos]));
+
+ const place = (originX, originY) => placeNodes(layers, {
+ originX,
+ originY,
+ nodeW,
+ nodeH,
+ orientation,
+ viewportWidth: options.viewportWidth,
+ flowGap,
+ rankGap: RANK_GAP,
+ posById,
});
+ const depthById = new Map();
+ layers.forEach((layer, depth) => layer.forEach((id) => depthById.set(id, depth)));
+ const routeFor = (pos) => {
+ const band = cardBand(pos, nodeW, nodeH, orientation);
+ return routeLoomEdges(nodes, pos, band.max, {
+ orientation, nodeW, nodeH, bandMin: band.min, depthById,
+ });
+ };
+
+ const baseX = MARGIN + (orientation === LOOM_ORIENTATION.TB ? SIDE_GUTTER : 0);
+ let extraX = 0;
+ let extraY = 0;
+ let positions = place(baseX, MARGIN);
+ let edges = routeFor(positions);
+
+ // Skip/back lanes (and their labels) can run past the origin. Shift the
+ // whole graph rather than clipping them — the SVG root clips at 0,0 and
+ // the scroller can't recover a negative path. A second pass can still
+ // leave a label hanging past x=0, so we inset until the routed extents
+ // clear `MARGIN` or we hit the cap.
+ for (let i = 0; i < 3; i += 1) {
+ const overflow = edgeOverflow(edges, MARGIN);
+ if (!overflow.dx && !overflow.dy) break;
+ extraX += overflow.dx;
+ extraY += overflow.dy;
+ positions = place(baseX + extraX, MARGIN + extraY);
+ edges = routeFor(positions);
+ }
+
let width = 0;
- let cardBottom = 0;
+ let height = 0;
for (const { x, y } of Object.values(positions)) {
- width = Math.max(width, x + LOOM_NODE_W + MARGIN);
- cardBottom = Math.max(cardBottom, y + LOOM_NODE_H);
+ width = Math.max(width, x + nodeW + MARGIN);
+ height = Math.max(height, y + nodeH + MARGIN);
}
- const edges = routeLoomEdges(nodes, positions, cardBottom);
- // BOTH extents come from the edges too: a self-loop bows past the card's
- // right side and its label sits further right still, and the SVG root clips
- // at these numbers — the scrolling wrapper can't recover what the viewBox cut.
- let height = cardBottom + MARGIN;
for (const edge of edges) {
- height = Math.max(height, edge.maxY + MARGIN);
width = Math.max(width, edge.maxX + MARGIN);
+ height = Math.max(height, edge.maxY + MARGIN);
+ }
+ if (options.viewportWidth) {
+ width = Math.max(width, options.viewportWidth);
+ }
+ return {
+ positions,
+ edges,
+ width: Math.max(width, 400),
+ height: Math.max(height, 240),
+ nodeW,
+ nodeH,
+ orientation,
+ };
+}
+
+function placeNodes(layers, {
+ originX, originY, nodeW, nodeH, orientation, viewportWidth, flowGap, rankGap, posById,
+}) {
+ const positions = {};
+ const isLR = orientation === LOOM_ORIENTATION.LR;
+ if (isLR) {
+ layers.forEach((layer, col) => {
+ layer.forEach((id, row) => {
+ const custom = posById.get(id);
+ positions[id] = isFinitePos(custom)
+ ? { x: custom.x, y: custom.y }
+ : { x: originX + col * (nodeW + flowGap), y: originY + row * (nodeH + rankGap) };
+ });
+ });
+ return positions;
}
- return { positions, edges, width: Math.max(width, 400), height: Math.max(height, 240) };
+ // Top-to-bottom: wrap a layer onto as many cards as fit in the canvas so a
+ // 4-way branch doesn't force horizontal pan on a phone.
+ const inner = Math.max(nodeW, (viewportWidth || (nodeW + originX * 2)) - originX * 2);
+ const perRow = Math.max(1, Math.floor((inner + rankGap) / (nodeW + rankGap)));
+ let y = originY;
+ for (const layer of layers) {
+ for (let i = 0; i < layer.length; i += perRow) {
+ const row = layer.slice(i, i + perRow);
+ const rowW = row.length * nodeW + (row.length - 1) * rankGap;
+ const startX = originX + Math.max(0, (inner - rowW) / 2);
+ row.forEach((id, ci) => {
+ positions[id] = { x: startX + ci * (nodeW + rankGap), y };
+ });
+ const lastInLayer = i + perRow >= layer.length;
+ y += nodeH + (lastInLayer ? flowGap : rankGap);
+ }
+ }
+ return positions;
+}
+
+function cardBand(positions, nodeW, nodeH, orientation) {
+ let min = Infinity;
+ let max = 0;
+ for (const { x, y } of Object.values(positions)) {
+ if (orientation === LOOM_ORIENTATION.LR) {
+ min = Math.min(min, y);
+ max = Math.max(max, y + nodeH);
+ } else {
+ min = Math.min(min, x);
+ max = Math.max(max, x + nodeW);
+ }
+ }
+ return { min: Number.isFinite(min) ? min : 0, max };
+}
+
+function edgeOverflow(edges, margin) {
+ let minX = margin;
+ let minY = margin;
+ for (const edge of edges) {
+ if (Number.isFinite(edge.minX)) minX = Math.min(minX, edge.minX);
+ if (Number.isFinite(edge.minY)) minY = Math.min(minY, edge.minY);
+ }
+ return {
+ dx: minX < margin ? margin - minX : 0,
+ dy: minY < margin ? margin - minY : 0,
+ };
}
/**
- * 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`.
+ * Lowest lane whose occupied range doesn't overlap `[lo, hi]`, marking it
+ * occupied. Callers MUST assign in increasing `lo` — the tracker is only the
+ * rightmost/bottommost end, which is a correct free/busy test in that order.
*/
function assignLane(laneEnds, lo, hi) {
for (let i = 0; ; i += 1) {
@@ -159,13 +318,42 @@ function assignLane(laneEnds, lo, hi) {
}
}
+function fanPorts(count, start, end) {
+ if (count <= 0) return [];
+ if (count === 1) return [(start + end) / 2];
+ const span = end - start;
+ const step = span / (count + 1);
+ return Array.from({ length: count }, (_, i) => start + step * (i + 1));
+}
+
+function cardsBetween(fromId, toId, positions, nodeW, nodeH, isLR) {
+ const from = positions[fromId];
+ const to = positions[toId];
+ const a0 = isLR ? from.x + nodeW : from.y + nodeH;
+ const b0 = isLR ? to.x : to.y;
+ if (b0 <= a0) return false;
+ return Object.entries(positions).some(([id, pos]) => {
+ if (id === fromId || id === toId) return false;
+ const mid = isLR ? pos.x + nodeW / 2 : pos.y + nodeH / 2;
+ return mid > a0 && mid < b0;
+ });
+}
+
/**
- * 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.
+ * Route every transition whose endpoints are both placed. Forward edges take
+ * an orthogonal stub/lane/stub through the gap, with distinct ports so two
+ * intents leaving the same scene don't occupy one curve. Self-edges loop off
+ * the outgoing side; backward, same-layer, and skip-layer edges go around the
+ * card band in packed lanes. Labels de-collide afterwards across the set.
*/
-export function routeLoomEdges(nodes, positions, cardBottom) {
+export function routeLoomEdges(nodes, positions, cardExtent, options = {}) {
+ const orientation = options.orientation || LOOM_ORIENTATION.LR;
+ const nodeW = options.nodeW || LOOM_NODE_W;
+ const nodeH = options.nodeH || LOOM_NODE_H;
+ const isLR = orientation === LOOM_ORIENTATION.LR;
+ const bandMin = Number.isFinite(options.bandMin) ? options.bandMin : MARGIN;
+ const depthById = options.depthById instanceof Map ? options.depthById : null;
+
const routes = [];
for (const node of asArray(nodes)) {
const from = positions[node.id];
@@ -174,6 +362,21 @@ export function routeLoomEdges(nodes, positions, cardBottom) {
const to = positions[tr?.targetNodeId];
if (!to) continue;
const self = tr.targetNodeId === node.id;
+ const fromD = depthById?.get(node.id);
+ const toD = depthById?.get(tr.targetNodeId);
+ const byDepth = Number.isInteger(fromD) && Number.isInteger(toD);
+ // Depth is the source of truth for skip vs forward: a wrapped sibling
+ // in the stacked layout sits between two cards in Y without being
+ // between them in the story, and cardsBetween would send every other
+ // edge around the gutter. Position is the fallback when a caller
+ // (tests) didn't pass a layer map.
+ const throughCard = cardsBetween(node.id, tr.targetNodeId, positions, nodeW, nodeH, isLR);
+ const skip = !self && (byDepth
+ ? toD > fromD + 1 || throughCard
+ : throughCard);
+ const back = !self && (byDepth
+ ? toD <= fromD
+ : (isLR ? to.x <= from.x : to.y <= from.y));
routes.push({
id: tr.id,
sourceId: node.id,
@@ -182,28 +385,154 @@ export function routeLoomEdges(nodes, positions, cardBottom) {
from,
to,
self,
- laneY: null,
+ skip,
+ back,
+ around: !self && (back || skip),
});
}
}
- // 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;
- }
+ assignPorts(routes, nodeW, nodeH, isLR);
+ assignAroundLanes(routes, cardExtent, bandMin, nodeW, nodeH, isLR);
+ assignForwardLanes(routes, nodeW, nodeH, isLR);
- return placeEdgeLabels(routes.map(({ id, sourceId, targetId, intent, from, to, self, laneY }) => ({
- id, sourceId, targetId, intent, ...loomEdgePath(from, to, { laneY, self }),
+ return placeEdgeLabels(routes.map((route) => ({
+ id: route.id,
+ sourceId: route.sourceId,
+ targetId: route.targetId,
+ intent: route.intent,
+ ...loomEdgePath(route.from, route.to, {
+ self: route.self,
+ around: route.around,
+ back: route.back,
+ lane: route.lane,
+ fromPort: route.fromPort,
+ toPort: route.toPort,
+ orientation,
+ nodeW,
+ nodeH,
+ }),
})));
}
+function assignPorts(routes, nodeW, nodeH, isLR) {
+ const groups = new Map();
+ const key = (nodeId, side) => `${nodeId}:${side}`;
+ const add = (nodeId, side, route, field) => {
+ const k = key(nodeId, side);
+ const list = groups.get(k) || [];
+ list.push({ route, field });
+ groups.set(k, list);
+ };
+ for (const route of routes) {
+ if (route.self) continue;
+ if (route.around) {
+ const side = route.back ? 'back' : 'skip';
+ add(route.sourceId, `${side}Out`, route, 'fromPort');
+ add(route.targetId, `${side}In`, route, 'toPort');
+ } else {
+ add(route.sourceId, 'out', route, 'fromPort');
+ add(route.targetId, 'in', route, 'toPort');
+ }
+ }
+ for (const [k, list] of groups) {
+ const side = k.split(':')[1];
+ const around = side.startsWith('back') || side.startsWith('skip');
+ // Sort by the OTHER endpoint's cross-axis so fanned stubs don't cross.
+ list.sort((a, b) => {
+ const aPos = a.field === 'fromPort' ? a.route.to : a.route.from;
+ const bPos = b.field === 'fromPort' ? b.route.to : b.route.from;
+ const aCross = isLR ? aPos.y : aPos.x;
+ const bCross = isLR ? bPos.y : bPos.x;
+ return aCross - bCross || String(a.route.id).localeCompare(String(b.route.id));
+ });
+ const nodePos = list[0].field === 'fromPort' ? list[0].route.from : list[0].route.to;
+ let start;
+ let end;
+ if (around) {
+ // Around-band edges leave/enter along the unused side of the card
+ // (top/bottom in lr, left/right in tb) so they don't fight the forward ports.
+ start = (isLR ? nodePos.x : nodePos.y) + PORT_INSET;
+ end = (isLR ? nodePos.x + nodeW : nodePos.y + nodeH) - PORT_INSET;
+ } else {
+ start = (isLR ? nodePos.y : nodePos.x) + PORT_INSET;
+ end = (isLR ? nodePos.y + nodeH : nodePos.x + nodeW) - PORT_INSET;
+ }
+ const ports = fanPorts(list.length, start, end);
+ list.forEach((item, i) => {
+ item.route[item.field] = ports[i];
+ });
+ }
+}
+
+function assignAroundLanes(routes, cardExtent, bandMin, nodeW, nodeH, isLR) {
+ const around = routes.filter((r) => r.around).sort((a, b) => {
+ const aLo = isLR
+ ? Math.min(a.from.x, a.to.x) + nodeW / 2
+ : Math.min(a.from.y, a.to.y) + nodeH / 2;
+ const bLo = isLR
+ ? Math.min(b.from.x, b.to.x) + nodeW / 2
+ : Math.min(b.from.y, b.to.y) + nodeH / 2;
+ return aLo - bLo;
+ });
+ const backEnds = [];
+ const skipEnds = [];
+ for (const route of around) {
+ const lo = (isLR
+ ? Math.min(route.from.x, route.to.x)
+ : Math.min(route.from.y, route.to.y)) - LANE_PAD;
+ const hi = (isLR
+ ? Math.max(route.from.x + nodeW, route.to.x + nodeW)
+ : Math.max(route.from.y + nodeH, route.to.y + nodeH)) + LANE_PAD;
+ if (route.back) {
+ route.lane = cardExtent + LANE_OFFSET + assignLane(backEnds, lo, hi) * LANE_GAP;
+ } else {
+ // Skip-layer: the other side of the band (above in lr, left in tb).
+ route.lane = bandMin - LANE_OFFSET - assignLane(skipEnds, lo, hi) * LANE_GAP;
+ }
+ }
+}
+
+function assignForwardLanes(routes, nodeW, nodeH, isLR) {
+ const forward = routes.filter((r) => !r.self && !r.around);
+ const corridors = new Map();
+ for (const route of forward) {
+ const along0 = isLR ? route.from.x + nodeW : route.from.y + nodeH;
+ const along1 = isLR ? route.to.x : route.to.y;
+ const key = `${Math.round(along0 / 8)}:${Math.round(along1 / 8)}`;
+ const list = corridors.get(key) || [];
+ list.push(route);
+ corridors.set(key, list);
+ }
+ for (const list of corridors.values()) {
+ list.sort((a, b) => {
+ const aLo = Math.min(a.fromPort, a.toPort);
+ const bLo = Math.min(b.fromPort, b.toPort);
+ return aLo - bLo || String(a.id).localeCompare(String(b.id));
+ });
+ const laneEnds = [];
+ const along0 = isLR ? list[0].from.x + nodeW : list[0].from.y + nodeH;
+ const along1 = isLR ? list[0].to.x : list[0].to.y;
+ const gap = along1 - along0;
+ for (const route of list) {
+ const lo = Math.min(route.fromPort, route.toPort) - LANE_PAD;
+ const hi = Math.max(route.fromPort, route.toPort) + LANE_PAD;
+ route.laneIndex = assignLane(laneEnds, lo, hi);
+ }
+ const laneCount = laneEnds.length || 1;
+ const usable = Math.max(STUB, gap - STUB * 2);
+ const step = usable / (laneCount + 1);
+ for (const route of list) {
+ const raw = along0 + STUB + step * (route.laneIndex + 1);
+ const fromAlong = isLR ? route.from.x + nodeW : route.from.y + nodeH;
+ const toAlong = isLR ? route.to.x : route.to.y;
+ const lo = Math.min(fromAlong, toAlong) + 8;
+ const hi = Math.max(fromAlong, toAlong) - 8;
+ route.lane = hi <= lo ? (fromAlong + toAlong) / 2 : Math.min(hi, Math.max(lo, raw));
+ }
+ }
+}
+
/**
* 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
@@ -225,60 +554,161 @@ export function placeEdgeLabels(edges) {
}
edge.labelY = y;
edge.maxY = Math.max(edge.maxY, y);
- edge.maxX = Math.max(edge.maxX, edge.labelX + half);
+ edge.maxX = Math.max(edge.maxX ?? 0, edge.labelX + half);
+ edge.minY = Math.min(edge.minY ?? y, y - LABEL_ROW_H);
+ edge.minX = Math.min(edge.minX ?? edge.labelX, edge.labelX - half);
placed.push({ x: edge.labelX, y, half });
}
return edges;
}
/**
- * Path between two placed nodes, plus the label anchor and the deepest y the
+ * Path between two placed nodes, plus the label anchor and the extents 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.
+ * - forward: orthogonal stub → packed lane → stub, ports already fanned.
+ * - around (backward / same-layer / skip): U on the unused side of the band.
+ * - self: a small loop off the outgoing side.
*/
export function loomEdgePath(from, to, options = {}) {
- const { laneY = null, self = false } = options;
+ const {
+ lane = null,
+ laneY = null,
+ laneX = null,
+ self = false,
+ around = false,
+ back = false,
+ fromPort = null,
+ toPort = null,
+ orientation = LOOM_ORIENTATION.LR,
+ nodeW = LOOM_NODE_W,
+ nodeH = LOOM_NODE_H,
+ } = options;
+ const isLR = orientation === LOOM_ORIENTATION.LR;
+ const resolvedLane = Number.isFinite(lane) ? lane
+ : (Number.isFinite(laneY) ? laneY : laneX);
+ const sameRank = isLR ? to.x === from.x : to.y === from.y;
+ const goingBack = isLR ? to.x <= from.x : to.y <= from.y;
+
if (self) {
- const x = from.x + LOOM_NODE_W;
- const y = from.y + LOOM_NODE_H / 2;
+ if (isLR) {
+ const x = from.x + nodeW;
+ const y = from.y + nodeH / 2;
+ return {
+ d: `M ${x} ${y - 24} C ${x + 64} ${y - 44}, ${x + 64} ${y + 44}, ${x} ${y + 24}`,
+ labelX: x + 46,
+ labelY: y,
+ maxX: x + 64,
+ maxY: from.y + nodeH,
+ minX: from.x,
+ minY: from.y,
+ };
+ }
+ const x = from.x + nodeW / 2;
+ const y = from.y + nodeH;
return {
- d: `M ${x} ${y - 24} C ${x + 64} ${y - 44}, ${x + 64} ${y + 44}, ${x} ${y + 24}`,
- labelX: x + 46,
- labelY: y,
- maxX: x + 64,
- maxY: from.y + LOOM_NODE_H,
+ d: `M ${x - 24} ${y} C ${x - 44} ${y + 64}, ${x + 44} ${y + 64}, ${x + 24} ${y}`,
+ labelX: x,
+ labelY: y + 46,
+ maxX: from.x + nodeW,
+ maxY: y + 64,
+ minX: from.x,
+ minY: from.y,
};
}
- 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);
+
+ if (around || goingBack || sameRank) {
+ return aroundPath(from, to, {
+ lane: resolvedLane, fromPort, toPort, isLR, nodeW, nodeH,
+ // Skip-layer is `around && !back`; a same-column / backward edge
+ // without the flag still uses the return side (existing tests pass
+ // `{ laneY }` with no `around`).
+ back: around ? back : true,
+ });
+ }
+
+ return forwardPath(from, to, {
+ lane: resolvedLane, fromPort, toPort, isLR, nodeW, nodeH,
+ });
+}
+
+function aroundPath(from, to, { lane, fromPort, toPort, isLR, nodeW, nodeH, back }) {
+ if (isLR) {
+ const x1 = fromPort ?? from.x + nodeW / 2;
+ const x2 = toPort ?? to.x + nodeW / 2;
+ const y1 = back ? from.y + nodeH : from.y;
+ const y2 = back ? to.y + nodeH : to.y;
+ const laneY = Number.isFinite(lane) ? lane
+ : (back ? Math.max(y1, y2) + LANE_OFFSET : Math.min(y1, y2) - LANE_OFFSET);
return {
- d: `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`,
+ d: `M ${x1} ${y1} V ${laneY} H ${x2} V ${y2}`,
labelX: (x1 + x2) / 2,
- labelY: (y1 + y2) / 2,
- maxX: Math.max(x1, x2),
- maxY: Math.max(y1, y2),
+ labelY: laneY + (back ? -6 : 14),
+ maxX: Math.max(x1, x2, from.x + nodeW, to.x + nodeW),
+ maxY: Math.max(y1, y2, laneY),
+ minX: Math.min(x1, x2, from.x, to.x),
+ minY: Math.min(from.y, to.y, laneY, y1, y2),
+ };
+ }
+ const y1 = fromPort ?? from.y + nodeH / 2;
+ const y2 = toPort ?? to.y + nodeH / 2;
+ const x1 = back ? from.x + nodeW : from.x;
+ const x2 = back ? to.x + nodeW : to.x;
+ const laneX = Number.isFinite(lane) ? lane
+ : (back ? Math.max(x1, x2) + LANE_OFFSET : Math.min(x1, x2) - LANE_OFFSET);
+ return {
+ d: `M ${x1} ${y1} H ${laneX} V ${y2} H ${x2}`,
+ // Label sits on the card side of the lane so a left-gutter skip doesn't
+ // paint past x=0 (the SVG clips there, and the overflow pass can't
+ // recover a label that extends further left than the path).
+ labelX: laneX + (back ? -8 : 8),
+ labelY: (y1 + y2) / 2,
+ maxX: Math.max(x1, x2, laneX, from.x + nodeW, to.x + nodeW),
+ maxY: Math.max(y1, y2, from.y + nodeH, to.y + nodeH),
+ minX: Math.min(from.x, to.x, laneX, x1, x2),
+ minY: Math.min(y1, y2, from.y, to.y),
+ };
+}
+
+function forwardPath(from, to, { lane, fromPort, toPort, isLR, nodeW, nodeH }) {
+ if (isLR) {
+ const x1 = from.x + nodeW;
+ const y1 = fromPort ?? from.y + nodeH / 2;
+ const x2 = to.x;
+ const y2 = toPort ?? to.y + nodeH / 2;
+ const laneX = Number.isFinite(lane) ? lane : (x1 + x2) / 2;
+ const straight = Math.abs(y1 - y2) < 1;
+ const d = straight
+ ? `M ${x1} ${y1} H ${x2}`
+ : `M ${x1} ${y1} H ${laneX} V ${y2} H ${x2}`;
+ const firstH = Math.abs(laneX - x1);
+ const labelOnStub = !straight && firstH >= 28;
+ return {
+ d,
+ labelX: labelOnStub ? (x1 + laneX) / 2 : (x1 + x2) / 2,
+ labelY: (labelOnStub ? y1 : (y1 + y2) / 2) - 6,
+ maxX: Math.max(x1, x2, laneX),
+ maxY: Math.max(y1, y2, from.y + nodeH, to.y + nodeH),
+ minX: Math.min(from.x, to.x, laneX),
+ minY: Math.min(y1, y2, from.y, to.y) - 8,
};
}
- 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;
+ const x1 = fromPort ?? from.x + nodeW / 2;
+ const y1 = from.y + nodeH;
+ const x2 = toPort ?? to.x + nodeW / 2;
+ const y2 = to.y;
+ const laneY = Number.isFinite(lane) ? lane : (y1 + y2) / 2;
+ const straight = Math.abs(x1 - x2) < 1;
+ const d = straight
+ ? `M ${x1} ${y1} V ${y2}`
+ : `M ${x1} ${y1} V ${laneY} H ${x2} V ${y2}`;
return {
- d: `M ${x1} ${y1} C ${x1} ${lane}, ${x2} ${lane}, ${x2} ${y2}`,
- labelX: (x1 + x2) / 2,
- // Bottom of the cubic at t=0.5, where the run is flattest.
- labelY: (y1 + y2 + 6 * lane) / 8,
- maxX: Math.max(x1, x2),
- maxY: lane,
+ d,
+ labelX: straight ? x1 + 10 : (x1 + x2) / 2,
+ labelY: straight ? (y1 + y2) / 2 : laneY - 6,
+ maxX: Math.max(x1, x2, from.x + nodeW, to.x + nodeW),
+ maxY: Math.max(y1, y2, laneY),
+ minX: Math.min(x1, x2, from.x, to.x),
+ minY: Math.min(from.y, to.y, laneY),
};
}
diff --git a/client/src/lib/loomLayout.test.js b/client/src/lib/loomLayout.test.js
index 6f69433136..b6088a56f9 100644
--- a/client/src/lib/loomLayout.test.js
+++ b/client/src/lib/loomLayout.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
- layoutLoomGraph, loomEdgePath, loomGraphLayers, placeEdgeLabels, routeLoomEdges,
- LOOM_NODE_H, LOOM_NODE_W,
+ layoutLoomGraph, loomEdgePath, loomGraphLayers, pickLoomOrientation, placeEdgeLabels, routeLoomEdges,
+ LOOM_NODE_H, LOOM_NODE_W, LOOM_ORIENTATION, LOOM_STACK_WIDTH,
} from './loomLayout.js';
const tr = (id, targetNodeId) => ({ id, targetNodeId, intent: 'go' });
@@ -176,12 +176,42 @@ describe('placeEdgeLabels', () => {
});
});
+describe('pickLoomOrientation', () => {
+ it('stays left-to-right when the canvas has not been measured', () => {
+ expect(pickLoomOrientation(0, 5)).toBe(LOOM_ORIENTATION.LR);
+ });
+
+ it('stacks top-to-bottom on a narrow canvas even for a short graph', () => {
+ expect(pickLoomOrientation(LOOM_STACK_WIDTH - 1, 2)).toBe(LOOM_ORIENTATION.TB);
+ });
+
+ it('stacks when the editor rail has wrapped under the canvas', () => {
+ expect(pickLoomOrientation(800, 8)).toBe(LOOM_ORIENTATION.TB);
+ });
+
+ it('keeps a short graph left-to-right on a wide canvas', () => {
+ expect(pickLoomOrientation(1400, 3)).toBe(LOOM_ORIENTATION.LR);
+ });
+});
+
+describe('explicit orientation', () => {
+ it('stays left-to-right when the page pins lr even if the canvas is narrow', () => {
+ const { orientation, positions } = layoutLoomGraph(episode(), {
+ viewportWidth: 800,
+ orientation: LOOM_ORIENTATION.LR,
+ });
+ expect(orientation).toBe(LOOM_ORIENTATION.LR);
+ expect(positions.n1.x).toBeLessThan(positions.n2.x);
+ });
+});
+
describe('loomEdgePath', () => {
- it('produces a cubic path from right edge to left edge with a label midpoint', () => {
+ it('produces an orthogonal path from right edge to left edge', () => {
const { d, labelX, labelY } = loomEdgePath({ x: 0, y: 0 }, { x: 300, y: 100 });
expect(d.startsWith(`M ${LOOM_NODE_W} `)).toBe(true);
- expect(d).toContain('C ');
- expect(labelX).toBe((LOOM_NODE_W + 300) / 2);
+ expect(d).toMatch(/[HV]/);
+ expect(d).not.toContain('C ');
+ expect(labelX).toBeGreaterThan(LOOM_NODE_W);
expect(labelY).toBeGreaterThan(0);
});
@@ -191,3 +221,76 @@ describe('loomEdgePath', () => {
expect(maxY).toBe(500);
});
});
+
+const pathStart = (d) => {
+ const match = /^M\s+(-?[\d.]+)\s+(-?[\d.]+)/.exec(d);
+ return { x: Number(match[1]), y: Number(match[2]) };
+};
+
+describe('port fanning and skip routing', () => {
+ it('fans two outgoing intents off distinct ports so they do not share a curve', () => {
+ const { edges, positions } = layoutLoomGraph({
+ startNodeId: 'n1',
+ nodes: [
+ { id: 'n1', transitions: [tr('t1', 'n2'), tr('t2', 'n3')] },
+ { id: 'n2', transitions: [] },
+ { id: 'n3', transitions: [] },
+ ],
+ });
+ const a = pathStart(edges.find((e) => e.id === 't1').d);
+ const b = pathStart(edges.find((e) => e.id === 't2').d);
+ expect(a.x).toBe(positions.n1.x + LOOM_NODE_W);
+ expect(b.x).toBe(positions.n1.x + LOOM_NODE_W);
+ expect(a.y).not.toBe(b.y);
+ expect(new Set(edges.map((e) => e.d)).size).toBe(edges.length);
+ });
+
+ it('routes a skip-layer edge around the card band instead of through the middle column', () => {
+ const ep = {
+ startNodeId: 'n1',
+ nodes: [
+ { id: 'n1', transitions: [tr('t-adj', 'n2'), tr('t-skip', 'n3')] },
+ { id: 'n2', transitions: [tr('t2', 'n3')] },
+ { id: 'n3', isEnding: true, transitions: [] },
+ ],
+ };
+ const { edges, positions } = layoutLoomGraph(ep);
+ const skip = edges.find((e) => e.id === 't-skip');
+ const mid = positions.n2;
+ // The skip run sits above the intervening card, not through its interior,
+ // and the canvas origin still contains it (the SVG clips at 0,0).
+ expect(skip.minY).toBeLessThan(mid.y);
+ expect(skip.minY).toBeGreaterThanOrEqual(0);
+ expect(skip.d).toContain('V ');
+ expect(skip.d).toContain('H ');
+ });
+
+ it('stacks layers top-to-bottom on a narrow viewport and ignores desktop pos', () => {
+ const ep = episode();
+ ep.nodes[0].pos = { x: 900, y: 10 };
+ const { positions, orientation, width, edges } = layoutLoomGraph(ep, { viewportWidth: 390 });
+ expect(orientation).toBe(LOOM_ORIENTATION.TB);
+ expect(positions.n1.y).toBeLessThan(positions.n2.y);
+ expect(positions.n1.x).toBeLessThan(400);
+ expect(width).toBeGreaterThanOrEqual(390);
+ for (const edge of edges) {
+ expect(edge.minX).toBeGreaterThanOrEqual(0);
+ expect(edge.minY).toBeGreaterThanOrEqual(0);
+ }
+ });
+
+ it('keeps a diamond of forward edges on unique orthogonal paths', () => {
+ const { edges } = layoutLoomGraph({
+ startNodeId: 'a',
+ nodes: [
+ { id: 'a', transitions: [tr('t1', 'b'), tr('t2', 'c')] },
+ { id: 'b', transitions: [tr('t3', 'd')] },
+ { id: 'c', transitions: [tr('t4', 'd')] },
+ { id: 'd', isEnding: true, transitions: [] },
+ ],
+ });
+ expect(new Set(edges.map((e) => e.d)).size).toBe(4);
+ const labels = edges.map((e) => `${e.labelX},${e.labelY}`);
+ expect(new Set(labels).size).toBe(labels.length);
+ });
+});
diff --git a/client/src/pages/FableLoomStory.jsx b/client/src/pages/FableLoomStory.jsx
index d9f0998c03..df7d013058 100644
--- a/client/src/pages/FableLoomStory.jsx
+++ b/client/src/pages/FableLoomStory.jsx
@@ -3,8 +3,11 @@
*
* URL is the source of truth: /fableloom/:loomId/:episodeId/:nodeId? — the
* selected episode and scene are route params, the play drawer rides ?play=1.
- * Left: the scene-graph canvas. Right rail: the selected scene's editor, or
- * the structure/review panel when nothing is selected.
+ * Left: the scene-graph canvas (stacks top-to-bottom under the `lg` rail
+ * breakpoint). Right rail: the selected scene's editor, or the
+ * structure/review panel when nothing is selected. On small screens the
+ * rail sits under the canvas and is height-capped so the graph stays the
+ * thing you scroll.
*/
import { useCallback, useEffect, useState } from 'react';
@@ -18,12 +21,14 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import TabPills from '../components/ui/TabPills';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { useConfirmDelete } from '../hooks/useConfirmDelete';
+import useContainerWidth from '../hooks/useContainerWidth';
import LoomCanvas from '../components/fableloom/LoomCanvas';
import LoomNodeEditor from '../components/fableloom/LoomNodeEditor';
import LoomPlayPanel from '../components/fableloom/LoomPlayPanel';
import LoomSettingsDrawer from '../components/fableloom/LoomSettingsDrawer';
import LoomValidationPanel from '../components/fableloom/LoomValidationPanel';
import { fieldClass, labelClass } from '../components/fableloom/fieldStyles';
+import { LOOM_ORIENTATION, LOOM_STACK_WIDTH } from '../lib/loomLayout';
import {
addLoomEpisode, addLoomNode, deleteLoomEpisode, getLoom, getPipelineSeries,
updateLoomEpisode, updateLoomNode, weaveLoomEpisode,
@@ -42,6 +47,13 @@ export default function FableLoomStory() {
const [setupOpen, setSetupOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const playOpen = searchParams.get('play') === '1';
+ // Orientation keys off the PAGE, not the canvas. The canvas is the leftover
+ // after the 380px rail on `lg+`, so measuring it would stack a laptop graph
+ // while the rail is still beside it.
+ const [pageRef, pageWidth] = useContainerWidth();
+ const graphOrientation = pageWidth > 0
+ ? (pageWidth < LOOM_STACK_WIDTH ? LOOM_ORIENTATION.TB : LOOM_ORIENTATION.LR)
+ : undefined;
useEffect(() => {
setNotFound(false);
@@ -152,7 +164,7 @@ export default function FableLoomStory() {
}
return (
- <div className="h-full flex flex-col">
+ <div ref={pageRef} className="h-full flex flex-col">
<header className="border-b border-port-border px-4 py-2.5 space-y-2">
<div className="flex items-center gap-3 flex-wrap">
<Link to="/fableloom" className="text-port-text-muted hover:text-port-text" aria-label="Back to FableLoom">
@@ -248,13 +260,14 @@ export default function FableLoomStory() {
</div>
) : (
<div className="flex-1 min-h-0 flex flex-col lg:flex-row">
- <section className="flex-1 min-h-[45vh] lg:min-h-0 relative">
+ <section className="flex-1 min-h-[55vh] lg:min-h-0 min-w-0 relative">
{episode.nodes.length ? (
<LoomCanvas
episode={episode}
selectedNodeId={nodeId || null}
onSelectNode={selectNode}
onMoveNode={handleMoveNode}
+ orientation={graphOrientation}
/>
) : (
<div className="h-full grid place-items-center p-8 text-center">
@@ -282,7 +295,7 @@ export default function FableLoomStory() {
</div>
)}
</section>
- <aside className="lg:w-[380px] lg:shrink-0 border-t lg:border-t-0 lg:border-l border-port-border overflow-y-auto">
+ <aside className="lg:w-[380px] lg:shrink-0 max-h-[45vh] lg:max-h-none border-t lg:border-t-0 lg:border-l border-port-border overflow-y-auto">
{node ? (
<LoomNodeEditor
key={node.id}
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 1d3e41a632..8b45f9f5f4 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -23,10 +23,13 @@ answers in-world without leaving the scene when nothing matches.
- **`/fableloom`** — index: create/delete looms, link a universe (canon +
style for AI) and optionally a pipeline series.
- **`/fableloom/:loomId/:episodeId/:nodeId?`** — the visual editor: an SVG
- scene-graph canvas (BFS-layered; drag to reposition, positions persist),
- a scene editor rail (prose, endings, intent paths, scene image), and a
- structure/review rail when nothing is selected. `?play=1` opens the reader
- drawer.
+ scene-graph canvas (BFS-layered; orthogonal port-fanned edges; drag to
+ reposition on desktop, positions persist). Below the editor-rail
+ breakpoint the graph flips top-to-bottom (and ignores persisted `pos`) so
+ it scrolls instead of pan-clipping. A scene editor rail (prose, endings,
+ intent paths, scene image) sits beside the canvas on large screens and
+ below it on small ones, with a path strip for inbound/outbound intents
+ when the graph is stacked. `?play=1` opens the reader drawer.
- **Play drawer** — the reader chat. Sessions are client-side state
(restart is free; nothing persists server-side).
- **Story settings drawer** — scene format (plus the rewrite pass), and the