intent-prompt-graph 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/layout.ts ADDED
@@ -0,0 +1,350 @@
1
+ import type { GraphEdge, GraphNode, NodeKind } from "../src/model";
2
+
3
+ export interface Point {
4
+ x: number;
5
+ y: number;
6
+ }
7
+
8
+ export interface EdgeGeometry {
9
+ d: string;
10
+ /** Centre of the label: always inside a gap between cards, next to the target node. */
11
+ lx: number;
12
+ ly: number;
13
+ /** True for a same-column edge, whose label sits in the row gap instead of the column gap. */
14
+ vertical: boolean;
15
+ }
16
+
17
+ /** A node list and the edges between those nodes. */
18
+ export interface GraphSlice {
19
+ nodes: readonly GraphNode[];
20
+ edges: readonly GraphEdge[];
21
+ }
22
+
23
+ export interface TimelineRow {
24
+ node: GraphNode;
25
+ /** 0 for a spine row, 1 for a branch row indented under a spine row. */
26
+ depth: 0 | 1;
27
+ /** Spine node a branch row hangs under; unset for spine rows and for branch rows with no spine ancestor. */
28
+ parentId?: string;
29
+ /** Edge that leads into this node; its label is shown on the row. */
30
+ edge?: GraphEdge;
31
+ }
32
+
33
+ /** Fixed card footprint used by the layered DAG layout engine. */
34
+ export const NODE_W = 248;
35
+ export const NODE_H = 128;
36
+ export const COL_GAP = 120;
37
+ export const ROW_GAP = 42;
38
+
39
+ const SPINE_KIND: Record<NodeKind, boolean> = {
40
+ goal: true,
41
+ decision: true,
42
+ chosen: true,
43
+ loop: true,
44
+ rejected: false,
45
+ option: false,
46
+ side: false,
47
+ };
48
+
49
+ /**
50
+ * Tells whether a node kind belongs to the main spine of the session (as opposed to a branch off it).
51
+ *
52
+ * Args:
53
+ * kind (NodeKind): Node kind to test.
54
+ *
55
+ * Returns:
56
+ * boolean: True for goal, decision, chosen and loop; false for rejected, option and side.
57
+ */
58
+ export function isSpineKind(kind: NodeKind): boolean {
59
+ return SPINE_KIND[kind];
60
+ }
61
+
62
+ const KIND_PRIORITY: Record<NodeKind, number> = {
63
+ goal: 0,
64
+ chosen: 1,
65
+ decision: 2,
66
+ loop: 3,
67
+ option: 4,
68
+ rejected: 5,
69
+ side: 6,
70
+ };
71
+
72
+ /**
73
+ * Computes collision-free top-left (x, y) coordinates for every node in a Decision & Path Graph.
74
+ * Columns follow time along the spine: a spine node is never placed left of a spine node that
75
+ * happened before it. A node sits one column right of its parent (same column for a side question);
76
+ * a node with no earlier parent starts after the latest spine node instead of restarting at the far
77
+ * left. Rejected, unchosen option, and side-question branches stay beside the node they branch from
78
+ * and stack below the spine in their column.
79
+ *
80
+ * Args:
81
+ * nodes (readonly GraphNode[]): Graph nodes to place.
82
+ * edges (readonly GraphEdge[]): Directed edges between nodes.
83
+ *
84
+ * Returns:
85
+ * Map<string, Point>: Map of node id to top-left canvas position in px.
86
+ */
87
+ export function layoutGraph(nodes: readonly GraphNode[], edges: readonly GraphEdge[]): Map<string, Point> {
88
+ const pos = new Map<string, Point>();
89
+ if (nodes.length === 0) return pos;
90
+
91
+ const orderIndex = new Map(nodes.map((n, i) => [n.id, i] as const));
92
+ const incoming = new Map<string, GraphEdge[]>();
93
+ for (const e of edges) {
94
+ if (!orderIndex.has(e.from) || !orderIndex.has(e.to) || e.from === e.to) continue;
95
+ const list = incoming.get(e.to) ?? [];
96
+ list.push(e);
97
+ incoming.set(e.to, list);
98
+ }
99
+
100
+ // Walk the nodes oldest first. Only parents already placed constrain a node, so an edge that
101
+ // points back in time (or closes a cycle) cannot pull anything left.
102
+ const byTime = [...nodes].sort((a, b) => a.at - b.at || (orderIndex.get(a.id) ?? 0) - (orderIndex.get(b.id) ?? 0));
103
+ const layer = new Map<string, number>();
104
+ let spineMax = 0;
105
+ for (const n of byTime) {
106
+ let col = -1;
107
+ for (const e of incoming.get(n.id) ?? []) {
108
+ const fromL = layer.get(e.from);
109
+ if (fromL === undefined) continue;
110
+ col = Math.max(col, e.kind === "side" ? fromL : fromL + 1);
111
+ }
112
+ const spine = isSpineKind(n.kind);
113
+ if (col < 0) col = layer.size === 0 ? 0 : spine ? spineMax + 1 : spineMax;
114
+ else if (spine) col = Math.max(col, spineMax);
115
+ layer.set(n.id, col);
116
+ if (spine) spineMax = col;
117
+ }
118
+
119
+ // Group nodes into columns and sort each column so the main spine stays on row 0.
120
+ const columns = new Map<number, GraphNode[]>();
121
+ for (const n of nodes) {
122
+ const col = layer.get(n.id) ?? 0;
123
+ const list = columns.get(col) ?? [];
124
+ list.push(n);
125
+ columns.set(col, list);
126
+ }
127
+
128
+ for (const [col, list] of columns) {
129
+ list.sort((a, b) => {
130
+ const pDiff = KIND_PRIORITY[a.kind] - KIND_PRIORITY[b.kind];
131
+ if (pDiff !== 0) return pDiff;
132
+ return (orderIndex.get(a.id) ?? 0) - (orderIndex.get(b.id) ?? 0);
133
+ });
134
+ const x = col * (NODE_W + COL_GAP);
135
+ list.forEach((n, row) => {
136
+ pos.set(n.id, { x, y: row * (NODE_H + ROW_GAP) });
137
+ });
138
+ }
139
+
140
+ return pos;
141
+ }
142
+
143
+ function cubic(a: number, b: number, c: number, d: number, t: number): number {
144
+ const u = 1 - t;
145
+ return u * u * u * a + 3 * u * u * t * b + 3 * u * t * t * c + t * t * t * d;
146
+ }
147
+
148
+ /**
149
+ * Computes a smooth cubic-Bezier SVG path between two node positions and where its label goes.
150
+ * The label is placed in the gap just before the target node, so no card can cover it: the column
151
+ * gap for edges between columns, the row gap for edges inside one column.
152
+ *
153
+ * Args:
154
+ * from (Point): Top-left position of the source node.
155
+ * to (Point): Top-left position of the target node.
156
+ *
157
+ * Returns:
158
+ * EdgeGeometry: SVG path `d` string, label centre `(lx, ly)` and whether the edge is vertical.
159
+ */
160
+ export function edgePath(from: Point, to: Point): EdgeGeometry {
161
+ if (Math.abs(from.x - to.x) < 40) {
162
+ const down = from.y <= to.y;
163
+ const sy = down ? from.y + NODE_H : from.y;
164
+ const ey = down ? to.y : to.y + NODE_H;
165
+ const cx = from.x + NODE_W / 2;
166
+ const midY = (sy + ey) / 2;
167
+ return {
168
+ d: `M ${cx} ${sy} C ${cx} ${midY}, ${cx} ${midY}, ${cx} ${ey}`,
169
+ lx: cx,
170
+ ly: down ? ey - ROW_GAP / 2 : ey + ROW_GAP / 2,
171
+ vertical: true,
172
+ };
173
+ }
174
+
175
+ const forward = to.x >= from.x;
176
+ const x1 = forward ? from.x + NODE_W : from.x;
177
+ const y1 = from.y + NODE_H / 2;
178
+ const x2 = forward ? to.x : to.x + NODE_W;
179
+ const y2 = to.y + NODE_H / 2;
180
+ const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
181
+ const c1x = forward ? x1 + dx : x1 - dx;
182
+ const c2x = forward ? x2 - dx : x2 + dx;
183
+
184
+ // Adjacent columns: the curve's midpoint is the gap's centre. Longer edges cross other columns,
185
+ // so find the curve point that lies in the middle of the last gap instead.
186
+ let t = 0.5;
187
+ if (Math.abs(x2 - x1) > COL_GAP) {
188
+ const target = forward ? x2 - COL_GAP / 2 : x2 + COL_GAP / 2;
189
+ let lo = 0;
190
+ let hi = 1;
191
+ for (let i = 0; i < 20; i++) {
192
+ t = (lo + hi) / 2;
193
+ if (cubic(x1, c1x, c2x, x2, t) < target === forward) lo = t;
194
+ else hi = t;
195
+ }
196
+ }
197
+ return {
198
+ d: `M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`,
199
+ lx: cubic(x1, c1x, c2x, x2, t),
200
+ ly: cubic(y1, y1, y2, y2, t),
201
+ vertical: false,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Removes nodes from a graph and keeps the rest connected. Edges between surviving nodes are kept
207
+ * as they are. Where a path ran through removed nodes, one bridging edge joins the surviving node
208
+ * before it to the surviving node after it, carrying the kind and label of the path's last edge.
209
+ *
210
+ * Args:
211
+ * nodes (readonly GraphNode[]): All graph nodes.
212
+ * edges (readonly GraphEdge[]): All graph edges.
213
+ * keep ((node: GraphNode) => boolean): Returns true for nodes that survive.
214
+ *
215
+ * Returns:
216
+ * GraphSlice: Surviving nodes in their original order, and the kept plus bridging edges.
217
+ */
218
+ export function pruneGraph(
219
+ nodes: readonly GraphNode[],
220
+ edges: readonly GraphEdge[],
221
+ keep: (node: GraphNode) => boolean,
222
+ ): GraphSlice {
223
+ const kept = nodes.filter(keep);
224
+ const keptIds = new Set(kept.map((n) => n.id));
225
+ const outgoing = new Map<string, GraphEdge[]>(nodes.map((n) => [n.id, []]));
226
+ const linked = new Map<string, Set<string>>(kept.map((n) => [n.id, new Set()]));
227
+ const out: GraphEdge[] = [];
228
+
229
+ for (const e of edges) {
230
+ const list = outgoing.get(e.from);
231
+ if (!list || !outgoing.has(e.to) || e.from === e.to) continue;
232
+ list.push(e);
233
+ if (keptIds.has(e.from) && keptIds.has(e.to)) {
234
+ out.push(e);
235
+ linked.get(e.from)?.add(e.to);
236
+ }
237
+ }
238
+ if (kept.length === nodes.length) return { nodes: kept, edges: out };
239
+
240
+ for (const src of kept) {
241
+ const targets = linked.get(src.id) ?? new Set<string>();
242
+ const seen = new Set<string>();
243
+ const removed = (outgoing.get(src.id) ?? []).filter((e) => !keptIds.has(e.to)).map((e) => e.to);
244
+ for (let via = removed.pop(); via !== undefined; via = removed.pop()) {
245
+ if (seen.has(via)) continue;
246
+ seen.add(via);
247
+ for (const e of outgoing.get(via) ?? []) {
248
+ if (!keptIds.has(e.to)) {
249
+ removed.push(e.to);
250
+ } else if (e.to !== src.id && !targets.has(e.to)) {
251
+ targets.add(e.to);
252
+ out.push({ ...e, id: `${src.id}~${e.to}`, from: src.id });
253
+ }
254
+ }
255
+ }
256
+ }
257
+ return { nodes: kept, edges: out };
258
+ }
259
+
260
+ /** Topological order of `subset`; ties and cycles are broken by the order of `subset` itself. */
261
+ function runOrder(subset: readonly GraphNode[], outgoing: ReadonlyMap<string, GraphEdge[]>): GraphNode[] {
262
+ const waiting = new Map<string, number>(subset.map((n) => [n.id, 0]));
263
+ for (const n of subset) {
264
+ for (const e of outgoing.get(n.id) ?? []) {
265
+ const count = waiting.get(e.to);
266
+ if (count !== undefined) waiting.set(e.to, count + 1);
267
+ }
268
+ }
269
+ const left = [...subset];
270
+ const order: GraphNode[] = [];
271
+ while (left.length > 0) {
272
+ const ready = left.findIndex((n) => waiting.get(n.id) === 0);
273
+ const [next] = left.splice(Math.max(0, ready), 1);
274
+ if (!next) break;
275
+ order.push(next);
276
+ waiting.delete(next.id);
277
+ for (const e of outgoing.get(next.id) ?? []) {
278
+ const count = waiting.get(e.to);
279
+ if (count !== undefined) waiting.set(e.to, count - 1);
280
+ }
281
+ }
282
+ return order;
283
+ }
284
+
285
+ /**
286
+ * Orders a graph as a top-to-bottom timeline. Spine nodes (goal, decision, chosen, loop) come in the
287
+ * order the edges run, starting at the goal; where the edges leave the order open, the order of
288
+ * `nodes` decides. Each rejected, option or side node becomes a branch row directly under the
289
+ * nearest spine node it descends from. Nodes that cannot be reached from a goal are appended after
290
+ * the reachable ones in the same way, and branch nodes with no spine ancestor come last.
291
+ *
292
+ * Args:
293
+ * nodes (readonly GraphNode[]): Graph nodes; every one appears in the result exactly once.
294
+ * edges (readonly GraphEdge[]): Directed edges between nodes.
295
+ *
296
+ * Returns:
297
+ * TimelineRow[]: Rows in display order.
298
+ */
299
+ export function timelineRows(nodes: readonly GraphNode[], edges: readonly GraphEdge[]): TimelineRow[] {
300
+ const byId = new Map(nodes.map((n) => [n.id, n] as const));
301
+ const outgoing = new Map<string, GraphEdge[]>(nodes.map((n) => [n.id, []]));
302
+ const incoming = new Map<string, GraphEdge>();
303
+ for (const e of edges) {
304
+ const list = outgoing.get(e.from);
305
+ if (!list || !byId.has(e.to) || e.from === e.to) continue;
306
+ list.push(e);
307
+ if (!incoming.has(e.to)) incoming.set(e.to, e);
308
+ }
309
+
310
+ const reachable = new Set<string>();
311
+ const frontier = nodes.filter((n) => n.kind === "goal").map((n) => n.id);
312
+ for (let id = frontier.pop(); id !== undefined; id = frontier.pop()) {
313
+ if (reachable.has(id)) continue;
314
+ reachable.add(id);
315
+ for (const e of outgoing.get(id) ?? []) frontier.push(e.to);
316
+ }
317
+ const order = [
318
+ ...runOrder(nodes.filter((n) => reachable.has(n.id)), outgoing),
319
+ ...runOrder(nodes.filter((n) => !reachable.has(n.id)), outgoing),
320
+ ];
321
+
322
+ const spineAncestor = (id: string): string | undefined => {
323
+ const seen = new Set([id]);
324
+ for (let up = incoming.get(id)?.from; up !== undefined && !seen.has(up); up = incoming.get(up)?.from) {
325
+ const parent = byId.get(up);
326
+ if (parent && isSpineKind(parent.kind)) return up;
327
+ seen.add(up);
328
+ }
329
+ return undefined;
330
+ };
331
+
332
+ const branches = new Map<string, TimelineRow[]>();
333
+ const loose: TimelineRow[] = [];
334
+ for (const node of order) {
335
+ if (isSpineKind(node.kind)) continue;
336
+ const parentId = spineAncestor(node.id);
337
+ const row: TimelineRow = { node, depth: 1, parentId, edge: incoming.get(node.id) };
338
+ const siblings = parentId === undefined ? loose : branches.get(parentId);
339
+ if (siblings) siblings.push(row);
340
+ else if (parentId !== undefined) branches.set(parentId, [row]);
341
+ }
342
+
343
+ const rows: TimelineRow[] = [];
344
+ for (const node of order) {
345
+ if (!isSpineKind(node.kind)) continue;
346
+ rows.push({ node, depth: 0, edge: incoming.get(node.id) }, ...(branches.get(node.id) ?? []));
347
+ }
348
+ rows.push(...loose);
349
+ return rows;
350
+ }