@spellkave/world-map 0.0.0-bootstrap

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.
@@ -0,0 +1,168 @@
1
+ import type { SpatialGraphModel } from "./types.ts";
2
+
3
+ /** Tactical-grid cell ids minted as `…/c_<x>_<y>` (session grids, ADR-0052). */
4
+ const TACTICAL_GRID_CELL_ID = /\/c_-?\d+_-?\d+$/;
5
+
6
+ /** A grid cell is not a listed place: composed cells are unlabeled, and
7
+ * bare-grid (compose_parent=false) cells keep their labels but still share
8
+ * the same `c_x_y` identity. */
9
+ export function isTacticalGridCell(node: SpatialGraphModel["nodes"][number]): boolean {
10
+ return node.unlabeled === true || TACTICAL_GRID_CELL_ID.test(node.id);
11
+ }
12
+
13
+ /** How many understandable places the map list should report: named rooms /
14
+ * outdoor nodes, or one row per grid layer when the slice is cells only.
15
+ * Never one row per cell (sk-zz8). */
16
+ export function countMapPlaces(model: SpatialGraphModel): number {
17
+ const named = model.nodes.filter((n) => !isTacticalGridCell(n)).length;
18
+ if (named > 0) return named;
19
+ return groupByGraph(model.nodes.filter(isTacticalGridCell)).size;
20
+ }
21
+
22
+ /** Agent-facing text inventory: coords, elevation, adjacency, occupancy, floors. */
23
+ export function renderSpatialGraphTextInventory(model: SpatialGraphModel): string {
24
+ if (model.nodes.length === 0) {
25
+ return "Spatial graph: empty (no positioned place_nodes for this slice/filter).";
26
+ }
27
+ const lines: string[] = [];
28
+ const gridNodes = model.nodes.filter(isTacticalGridCell);
29
+ const visibleNodes = model.nodes.filter((n) => !isTacticalGridCell(n));
30
+ const gridNodeIds = new Set(gridNodes.map((n) => n.id));
31
+ const visibleEdges = model.edges.filter(
32
+ (e) => !(gridNodeIds.has(e.from) && gridNodeIds.has(e.to)),
33
+ );
34
+ const adj = adjacency(visibleNodes, visibleEdges);
35
+ const connectionCount = new Set(
36
+ visibleEdges.map((e) => [e.from, e.to].sort((a, b) => a.localeCompare(b)).join("—")),
37
+ ).size;
38
+ lines.push(
39
+ `Spatial inventory: ${visibleNodes.length} named places` +
40
+ (gridNodes.length > 0 ? `; ${gridNodes.length}-cell grid` : "") +
41
+ `; ${connectionCount} named connections; slice=${model.sliceLabel}`,
42
+ );
43
+ const scales = [...new Set(model.graphs.map((g) => g.metresPerUnit))];
44
+ if (scales.length === 1 && scales[0] !== undefined) {
45
+ const s = scales[0];
46
+ lines.push(`1 graph unit = ${s === 1 ? "1 m" : `${s} m`} (place_graph.metres_per_unit)`);
47
+ if (model.nodes.length >= 2) {
48
+ const xs = model.nodes.map((n) => n.x);
49
+ const ys = model.nodes.map((n) => n.y);
50
+ const dx = Math.max(...xs) - Math.min(...xs);
51
+ const dy = Math.max(...ys) - Math.min(...ys);
52
+ if (dx > 0) lines.push(`Δx ${dx * s} m (bbox)`);
53
+ if (dy > 0) lines.push(`Δy ${dy * s} m (bbox)`);
54
+ }
55
+ }
56
+ if (model.floors.length > 0) {
57
+ lines.push(`Floors (elevation): ${model.floors.map((z) => formatZ(z)).join(", ")}`);
58
+ }
59
+
60
+ const occ = new Map(model.actorClusters.map((c) => [c.placeNodeId, c.count]));
61
+
62
+ lines.push("NODES (id | name | x,y,z | occupants | adjacent)");
63
+ const sorted = [...visibleNodes].sort((a, b) => a.id.localeCompare(b.id));
64
+ for (const n of sorted) {
65
+ const count = occ.get(n.id) ?? 0;
66
+ const zBit = n.elevationPresent || n.elevation !== 0 ? formatZ(n.elevation) : "0";
67
+ const neighbours = adj.get(n.id) ?? [];
68
+ lines.push(
69
+ ` ${n.id} "${n.label}" (${n.x}, ${n.y}, z=${zBit})` +
70
+ (count > 0 ? ` actors=${count}` : "") +
71
+ ` adjacent=[${neighbours.join(", ")}]`,
72
+ );
73
+ }
74
+ for (const [graphId, cells] of groupByGraph(gridNodes)) {
75
+ const graph = model.graphs.find((g) => g.graphId === graphId);
76
+ const width = new Set(cells.map((n) => n.x)).size;
77
+ const height = new Set(cells.map((n) => n.y)).size;
78
+ const cellSize = graph?.metresPerUnit ?? 1;
79
+ lines.push(
80
+ ` GRID ${graphId} ${width}x${height} cells cell=${formatZ(cellSize)} m` +
81
+ ` anchor=${graph?.anchorNodeId || "?"}`,
82
+ );
83
+ const drillDown = visibleNodes.length === 0;
84
+ for (const cell of cells.sort((a, b) => a.id.localeCompare(b.id))) {
85
+ const count = occ.get(cell.id) ?? 0;
86
+ // A composed tactical grid is centred in its anchor's own extent, so
87
+ // repeating that tautological overlap on every cell adds no signal.
88
+ // Other visible place extents remain useful map-local landmarks.
89
+ const overlaps = visibleNodes.filter(
90
+ (node) => node.id !== graph?.anchorNodeId && containsPoint(node, cell.x, cell.y),
91
+ );
92
+ const notable = model.notableScopes.filter((scope) => containsPoint(scope, cell.x, cell.y));
93
+ // Composed listing collapses empty cells under the GRID row. A bare
94
+ // grid (no named parent) is the drill-down: list every cell id.
95
+ if (count > 0 || overlaps.length > 0 || notable.length > 0 || drillDown) {
96
+ lines.push(
97
+ ` ${cell.id}` +
98
+ (count > 0 ? ` actors=${count}` : "") +
99
+ (overlaps.length > 0 ? ` overlaps=[${overlaps.map((n) => n.id).join(", ")}]` : "") +
100
+ (notable.length > 0
101
+ ? ` notable=[${notable.map((n) => `${n.nicheId}@${n.anchorNodeId}`).join(", ")}]`
102
+ : ""),
103
+ );
104
+ }
105
+ }
106
+ }
107
+ return lines.join("\n");
108
+ }
109
+
110
+ /** Mirrors the kernel's planar extent-overlap test for the two extent shapes
111
+ * projected by the map model. This is the strongest map-local notable-cell
112
+ * signal available: attachment rows are intentionally not part of the
113
+ * player-scoped topology projection, while inherited local attachments use
114
+ * this same containing extent as their spatial scope. */
115
+ function containsPoint(
116
+ node: SpatialGraphModel["nodes"][number] | SpatialGraphModel["notableScopes"][number],
117
+ x: number,
118
+ y: number,
119
+ ): boolean {
120
+ const extent = node.extent;
121
+ if (extent === undefined || extent.widthUnits <= 0 || extent.heightUnits <= 0) return false;
122
+ const dx = Math.abs(x - node.x);
123
+ const dy = Math.abs(y - node.y);
124
+ const rx = extent.widthUnits / 2;
125
+ const ry = extent.heightUnits / 2;
126
+ if (extent.shapeId === "core/area/sphere") {
127
+ return (dx * dx) / (rx * rx) + (dy * dy) / (ry * ry) <= 1;
128
+ }
129
+ if (extent.shapeId === "core/area/cube") return dx <= rx && dy <= ry;
130
+ return false;
131
+ }
132
+
133
+ function formatZ(z: number): string {
134
+ if (Number.isInteger(z)) return String(z);
135
+ return z.toFixed(2).replace(/\.?0+$/, "");
136
+ }
137
+
138
+ function adjacency(
139
+ nodes: readonly SpatialGraphModel["nodes"][number][],
140
+ edges: readonly SpatialGraphModel["edges"][number][],
141
+ ): Map<string, string[]> {
142
+ const m = new Map<string, string[]>();
143
+ for (const n of nodes) m.set(n.id, []);
144
+ for (const e of edges) {
145
+ if (!m.has(e.from) || !m.has(e.to)) continue;
146
+ m.get(e.from)!.push(e.to);
147
+ m.get(e.to)!.push(e.from);
148
+ }
149
+ for (const [k, v] of m) {
150
+ m.set(
151
+ k,
152
+ [...new Set(v)].sort((a, b) => a.localeCompare(b)),
153
+ );
154
+ }
155
+ return m;
156
+ }
157
+
158
+ function groupByGraph(
159
+ nodes: readonly SpatialGraphModel["nodes"][number][],
160
+ ): Map<string, SpatialGraphModel["nodes"]> {
161
+ const groups = new Map<string, SpatialGraphModel["nodes"]>();
162
+ for (const node of nodes) {
163
+ const group = groups.get(node.graphId) ?? [];
164
+ group.push(node);
165
+ groups.set(node.graphId, group);
166
+ }
167
+ return groups;
168
+ }
@@ -0,0 +1,431 @@
1
+ import { layoutOutdoorWorldByComposition, shouldUseH3WorldLayout } from "./h3-layout.ts";
2
+ import { pickDefaultSlice } from "./model.ts";
3
+ import type {
4
+ SpatialGraphEdge,
5
+ SpatialGraphLayout,
6
+ SpatialGraphModel,
7
+ SpatialGraphNode,
8
+ SpatialSliceMode,
9
+ SpatialViewOptions,
10
+ } from "./types.ts";
11
+
12
+ type GraphOffset = { graphId: string; offsetX: number; offsetY: number };
13
+
14
+ /**
15
+ * Deterministic layout from already-materialized node positions,
16
+ * multi-floor side-by-side panels, or topology-only adjacency placement.
17
+ * Does NOT implement ADR-0029's coordinate projection kernel.
18
+ */
19
+ export function layoutSpatialGraph(
20
+ model: SpatialGraphModel,
21
+ options: SpatialViewOptions & { sliceMode?: SpatialSliceMode } = {},
22
+ ): SpatialGraphLayout {
23
+ const graphId = options.graphId?.trim();
24
+ const sliceMode = options.sliceMode ?? options.slice ?? pickDefaultSlice(model.nodes, options);
25
+
26
+ if (sliceMode === "topology_only") {
27
+ return layoutTopology(model, graphId);
28
+ }
29
+ if (sliceMode === "all_floors_offset") {
30
+ return layoutAllFloorsOffset(model, graphId);
31
+ }
32
+ if (sliceMode === "h3_world") {
33
+ return layoutH3World(model, graphId) ?? layoutMetric(model, graphId, options);
34
+ }
35
+
36
+ // Unfiltered outdoor compose: ADR-0029 composition + H3 footprints when root has origin.
37
+ const graphScoped = graphId !== undefined && graphId.length > 0;
38
+ if (
39
+ options.preferH3World !== false &&
40
+ shouldUseH3WorldLayout(
41
+ graphScoped,
42
+ model.nodes,
43
+ new Map(model.nodes.map((n) => [n.id, n.cellRes10Hex ?? null])),
44
+ model.graphs,
45
+ )
46
+ ) {
47
+ const h3 = layoutH3World(model, graphId);
48
+ if (h3 !== null) return h3;
49
+ }
50
+
51
+ // metric + elevation_band: single plane from node x/y
52
+ return layoutMetric(model, graphId, options);
53
+ }
54
+
55
+ function layoutH3World(
56
+ model: SpatialGraphModel,
57
+ graphId: string | undefined,
58
+ ): SpatialGraphLayout | null {
59
+ // Single-graph filter: fall back to metric (sheet view).
60
+ if (graphId !== undefined && graphId.length > 0) return null;
61
+ const result = layoutOutdoorWorldByComposition(model.nodes, model.edges, model.graphs);
62
+ if (result === null) return null;
63
+ return {
64
+ nodes: result.nodes,
65
+ edges: result.edges,
66
+ graphs: result.graphs,
67
+ hexes: result.hexes,
68
+ };
69
+ }
70
+
71
+ function layoutMetric(
72
+ model: SpatialGraphModel,
73
+ graphId: string | undefined,
74
+ options: SpatialViewOptions = {},
75
+ ): SpatialGraphLayout {
76
+ // `model.nodes` is already the authority on which graph(s) are drawn —
77
+ // for an ordinary single-graph call that is exactly `[graphId]` (model.ts
78
+ // filtered to only that graph's nodes, as before); for sk-pej D-2's
79
+ // composed session-grid call, model.ts has already folded the child
80
+ // (grid) graph's nodes into the parent's local frame and included both
81
+ // graphIds. Deriving `selected` from the node set itself (rather than
82
+ // trusting the single `graphId` string) picks up whichever graph(s)
83
+ // model.ts actually included, with no separate "composed" branch here —
84
+ // byte-identical to the old `[graphId]` for every non-composed call.
85
+ const selected = [...new Set(model.nodes.map((node) => node.graphId))];
86
+ const selectedSet = new Set(selected);
87
+ const nodesByGraph = new Map<string, SpatialGraphNode[]>();
88
+ for (const node of model.nodes) {
89
+ if (!selectedSet.has(node.graphId)) continue;
90
+ const group = nodesByGraph.get(node.graphId) ?? [];
91
+ group.push(node);
92
+ nodesByGraph.set(node.graphId, group);
93
+ }
94
+ const graphOffsets =
95
+ graphId === undefined || graphId.length === 0
96
+ ? composeGraphOffsets(nodesByGraph, model.edges)
97
+ : combinedBoundsOffsets(nodesByGraph);
98
+ const nodes = model.nodes
99
+ .filter((node) => selectedSet.has(node.graphId))
100
+ .flatMap((node) => {
101
+ const offset = graphOffsets.get(node.graphId);
102
+ if (offset === undefined) return [];
103
+ return [{ ...node, x: node.x + offset.offsetX, y: node.y + offset.offsetY }];
104
+ });
105
+ const graphs = [...graphOffsets.values()].filter((offset) => selectedSet.has(offset.graphId));
106
+ // Indoor/tactical plans: flip Y so larger authored y reads "up" on the page.
107
+ // sheetAlign keeps image-cell coords (y-down) for backdrop-aligned product views.
108
+ const indoorish =
109
+ !options.sheetAlign &&
110
+ nodes.some((n) => n.substrateId === "indoor" || n.substrateId === "tactical");
111
+ const oriented = indoorish ? flipYInPlace(nodes) : nodes;
112
+ const nodeIds = new Set(oriented.map((node) => node.id));
113
+ const edges = model.edges.filter((edge) => nodeIds.has(edge.from) && nodeIds.has(edge.to));
114
+ return { nodes: oriented, edges, graphs };
115
+ }
116
+
117
+ function flipYInPlace(nodes: SpatialGraphNode[]): SpatialGraphNode[] {
118
+ if (nodes.length === 0) return nodes;
119
+ const b = mapBounds(nodes);
120
+ return nodes.map((n) => ({ ...n, y: b.maxY - (n.y - b.minY) }));
121
+ }
122
+
123
+ /**
124
+ * Place each elevation in a **uniform** panel, stacked top→bottom (highest z first).
125
+ * Y is flipped inside each panel (architectural: +y up on the page).
126
+ * Cross-floor edges are marked for dashed "stairs" rendering.
127
+ */
128
+ function layoutAllFloorsOffset(
129
+ model: SpatialGraphModel,
130
+ graphId: string | undefined,
131
+ ): SpatialGraphLayout {
132
+ const selected =
133
+ graphId === undefined || graphId.length === 0
134
+ ? model.nodes
135
+ : model.nodes.filter((n) => n.graphId === graphId);
136
+ const byFloor = new Map<number, SpatialGraphNode[]>();
137
+ for (const node of selected) {
138
+ const z = Math.round(node.elevation * 1000) / 1000;
139
+ const group = byFloor.get(z) ?? [];
140
+ group.push(node);
141
+ byFloor.set(z, group);
142
+ }
143
+ const floors = [...byFloor.keys()].sort((a, b) => b - a); // highest elevation at top
144
+
145
+ // Uniform content box = max span of any floor (so a 1-node cellar isn't a stamp).
146
+ let contentW = 1;
147
+ let contentH = 1;
148
+ for (const z of floors) {
149
+ const b = mapBounds(byFloor.get(z) ?? []);
150
+ contentW = Math.max(contentW, b.maxX - b.minX, 1);
151
+ contentH = Math.max(contentH, b.maxY - b.minY, 1);
152
+ }
153
+ const pad = 1.5;
154
+ const panelW = contentW + pad * 2;
155
+ const panelH = contentH + pad * 2 + 1.2; // title strip
156
+ const gap = 2.5;
157
+
158
+ const laid: SpatialGraphNode[] = [];
159
+ const panels: NonNullable<SpatialGraphLayout["floorPanels"]> = [];
160
+ const elevById = new Map<string, number>();
161
+ let cursorY = 0;
162
+ for (const z of floors) {
163
+ const floorNodes = byFloor.get(z) ?? [];
164
+ const bounds = mapBounds(floorNodes);
165
+ const spanX = bounds.maxX - bounds.minX;
166
+ const spanY = bounds.maxY - bounds.minY;
167
+ const ox = pad + (contentW - spanX) / 2 - bounds.minX;
168
+ const oyBase = cursorY + pad + 1.0;
169
+ const placed = floorNodes.map((n) => {
170
+ const localY = n.y - bounds.minY;
171
+ const flippedY = spanY - localY;
172
+ elevById.set(n.id, z);
173
+ return {
174
+ ...n,
175
+ x: n.x + ox,
176
+ y: oyBase + flippedY + (contentH - spanY) / 2,
177
+ };
178
+ });
179
+ laid.push(...placed);
180
+ panels.push({
181
+ elevation: z,
182
+ title: floorTitle(z),
183
+ minX: 0,
184
+ minY: cursorY,
185
+ maxX: panelW,
186
+ maxY: cursorY + panelH,
187
+ });
188
+ cursorY += panelH + gap;
189
+ }
190
+
191
+ const nodeIds = new Set(laid.map((n) => n.id));
192
+ const edges = model.edges.filter((e) => nodeIds.has(e.from) && nodeIds.has(e.to));
193
+ const crossFloorEdgeKeys: string[] = [];
194
+ for (const e of edges) {
195
+ const za = elevById.get(e.from);
196
+ const zb = elevById.get(e.to);
197
+ if (za !== undefined && zb !== undefined && za !== zb) {
198
+ crossFloorEdgeKeys.push(edgeKey(e.from, e.to));
199
+ }
200
+ }
201
+ const graphs =
202
+ graphId === undefined || graphId.length === 0
203
+ ? [...new Set(laid.map((n) => n.graphId))].map((id) => ({
204
+ graphId: id,
205
+ offsetX: 0,
206
+ offsetY: 0,
207
+ }))
208
+ : [{ graphId, offsetX: 0, offsetY: 0 }];
209
+ return { nodes: laid, edges, graphs, floorPanels: panels, crossFloorEdgeKeys };
210
+ }
211
+
212
+ function floorTitle(z: number): string {
213
+ if (Math.abs(z) < 1e-9) return "Ground floor (z=0)";
214
+ if (z < 0) return `Below (z=${fmtZ(z)})`;
215
+ return `Upper (z=${fmtZ(z)})`;
216
+ }
217
+
218
+ function fmtZ(z: number): string {
219
+ return Number.isInteger(z) ? String(z) : z.toFixed(1);
220
+ }
221
+
222
+ function edgeKey(a: string, b: string): string {
223
+ return a < b ? `${a}|${b}` : `${b}|${a}`;
224
+ }
225
+
226
+ /**
227
+ * Deterministic adjacency layout: BFS levels left→right, siblings top→bottom.
228
+ * Ignores authored x/y (topology_only).
229
+ */
230
+ function layoutTopology(model: SpatialGraphModel, graphId: string | undefined): SpatialGraphLayout {
231
+ const selected =
232
+ graphId === undefined || graphId.length === 0
233
+ ? model.nodes
234
+ : model.nodes.filter((n) => n.graphId === graphId);
235
+ if (selected.length === 0) {
236
+ return { nodes: [], edges: [], graphs: [] };
237
+ }
238
+ const ids = selected.map((n) => n.id).sort((a, b) => a.localeCompare(b));
239
+ const idSet = new Set(ids);
240
+ const adj = new Map<string, string[]>();
241
+ for (const id of ids) adj.set(id, []);
242
+ for (const edge of model.edges) {
243
+ if (!idSet.has(edge.from) || !idSet.has(edge.to)) continue;
244
+ adj.get(edge.from)!.push(edge.to);
245
+ adj.get(edge.to)!.push(edge.from);
246
+ }
247
+ for (const [k, v] of adj)
248
+ adj.set(
249
+ k,
250
+ [...new Set(v)].sort((a, b) => a.localeCompare(b)),
251
+ );
252
+
253
+ // Prefer graph anchor / model.root so entrance leads left→right.
254
+ const root = model.root !== null && idSet.has(model.root) ? model.root : ids[0]!;
255
+ const level = new Map<string, number>();
256
+ const order = new Map<string, number>();
257
+ const queue = [root];
258
+ level.set(root, 0);
259
+ order.set(root, 0);
260
+ let qi = 0;
261
+ const perLevelCount = new Map<number, number>([[0, 1]]);
262
+ while (qi < queue.length) {
263
+ const cur = queue[qi++]!;
264
+ const L = level.get(cur)!;
265
+ for (const next of adj.get(cur) ?? []) {
266
+ if (level.has(next)) continue;
267
+ const nL = L + 1;
268
+ const idx = perLevelCount.get(nL) ?? 0;
269
+ perLevelCount.set(nL, idx + 1);
270
+ level.set(next, nL);
271
+ order.set(next, idx);
272
+ queue.push(next);
273
+ }
274
+ }
275
+ // Disconnected components
276
+ for (const id of ids) {
277
+ if (level.has(id)) continue;
278
+ const nL = Math.max(0, ...level.values()) + 2;
279
+ const idx = perLevelCount.get(nL) ?? 0;
280
+ perLevelCount.set(nL, idx + 1);
281
+ level.set(id, nL);
282
+ order.set(id, idx);
283
+ }
284
+
285
+ const xGap = 6;
286
+ const yGap = 4;
287
+ const byId = new Map(selected.map((n) => [n.id, n] as const));
288
+ const laid = ids.map((id) => {
289
+ const n = byId.get(id)!;
290
+ const L = level.get(id) ?? 0;
291
+ const o = order.get(id) ?? 0;
292
+ const levelSize = perLevelCount.get(L) ?? 1;
293
+ const y = (o - (levelSize - 1) / 2) * yGap;
294
+ return { ...n, x: L * xGap, y };
295
+ });
296
+ const nodeIds = new Set(laid.map((n) => n.id));
297
+ const edges = model.edges.filter((e) => nodeIds.has(e.from) && nodeIds.has(e.to));
298
+ const graphs = [
299
+ {
300
+ graphId: graphId ?? selected[0]!.graphId,
301
+ offsetX: 0,
302
+ offsetY: 0,
303
+ },
304
+ ];
305
+ // Normalize to origin
306
+ const b = mapBounds(laid);
307
+ const nodes = laid.map((n) => ({ ...n, x: n.x - b.minX, y: n.y - b.minY }));
308
+ return { nodes, edges, graphs };
309
+ }
310
+
311
+ /**
312
+ * ONE bounds-normalising offset computed over ALL graphs' nodes together,
313
+ * applied identically to every graph key present. For the pre-existing
314
+ * single-graph call (`nodesByGraph.size === 1`) this is byte-identical to
315
+ * the old per-graph-independent `singleGraphOffsets` it replaces — bounds
316
+ * over "the one graph's nodes" either way. For sk-pej D-2's composed
317
+ * session-grid call (`nodesByGraph.size === 2`: parent + grid, the grid's
318
+ * nodes already expressed in the parent's own local frame by model.ts),
319
+ * computing ONE shared offset — rather than each graph's own independent
320
+ * bounds-normalise — is what keeps the grid and its parent's own nodes (and,
321
+ * via `layout.graphs` sharing this same offset, the parent's backdrop image)
322
+ * moving together as a rigid body instead of each being re-centred on its
323
+ * own bounds and drifting apart.
324
+ */
325
+ function combinedBoundsOffsets(
326
+ nodesByGraph: Map<string, SpatialGraphNode[]>,
327
+ ): Map<string, GraphOffset> {
328
+ const bounds = mapBounds([...nodesByGraph.values()].flat());
329
+ const offsets = new Map<string, GraphOffset>();
330
+ for (const graphId of nodesByGraph.keys()) {
331
+ offsets.set(graphId, { graphId, offsetX: -bounds.minX, offsetY: -bounds.minY });
332
+ }
333
+ return offsets;
334
+ }
335
+
336
+ function composeGraphOffsets(
337
+ nodesByGraph: Map<string, SpatialGraphNode[]>,
338
+ edges: readonly SpatialGraphEdge[],
339
+ ): Map<string, GraphOffset> {
340
+ const offsets = new Map<string, GraphOffset>();
341
+ const nodeById = new Map(
342
+ [...nodesByGraph.values()].flat().map((node) => [node.id, node] as const),
343
+ );
344
+ const sortedGraphIds = [...nodesByGraph.keys()].sort((a, b) =>
345
+ graphSortKey(a).localeCompare(graphSortKey(b)),
346
+ );
347
+ let cursorX = 0;
348
+ for (const id of sortedGraphIds) {
349
+ if (offsets.has(id)) continue;
350
+ const bounds = mapBounds(nodesByGraph.get(id) ?? []);
351
+ offsets.set(id, { graphId: id, offsetX: cursorX - bounds.minX, offsetY: -bounds.minY });
352
+ propagateGraphOffsets(offsets, nodeById, edges);
353
+ const placedBounds = transformedBounds(offsets, nodesByGraph);
354
+ cursorX = placedBounds.maxX + 18;
355
+ }
356
+ return offsets;
357
+ }
358
+
359
+ function propagateGraphOffsets(
360
+ offsets: Map<string, GraphOffset>,
361
+ nodeById: Map<string, SpatialGraphNode>,
362
+ edges: readonly SpatialGraphEdge[],
363
+ ): void {
364
+ let changed = true;
365
+ while (changed) {
366
+ changed = false;
367
+ for (const edge of edges) {
368
+ const from = nodeById.get(edge.from);
369
+ const to = nodeById.get(edge.to);
370
+ if (from === undefined || to === undefined) continue;
371
+ const fromOff = offsets.get(from.graphId);
372
+ const toOff = offsets.get(to.graphId);
373
+ if (fromOff !== undefined && toOff === undefined) {
374
+ offsets.set(to.graphId, {
375
+ graphId: to.graphId,
376
+ offsetX: fromOff.offsetX + from.x - to.x,
377
+ offsetY: fromOff.offsetY + from.y - to.y,
378
+ });
379
+ changed = true;
380
+ } else if (toOff !== undefined && fromOff === undefined) {
381
+ offsets.set(from.graphId, {
382
+ graphId: from.graphId,
383
+ offsetX: toOff.offsetX + to.x - from.x,
384
+ offsetY: toOff.offsetY + to.y - from.y,
385
+ });
386
+ changed = true;
387
+ }
388
+ }
389
+ }
390
+ }
391
+
392
+ function transformedBounds(
393
+ offsets: Map<string, GraphOffset>,
394
+ nodesByGraph: Map<string, SpatialGraphNode[]>,
395
+ ): { minX: number; minY: number; maxX: number; maxY: number } {
396
+ const pts: SpatialGraphNode[] = [];
397
+ for (const [graphId, nodes] of nodesByGraph) {
398
+ const off = offsets.get(graphId);
399
+ if (off === undefined) continue;
400
+ for (const n of nodes) {
401
+ pts.push({ ...n, x: n.x + off.offsetX, y: n.y + off.offsetY });
402
+ }
403
+ }
404
+ return mapBounds(pts);
405
+ }
406
+
407
+ function graphSortKey(graphId: string): string {
408
+ return graphId;
409
+ }
410
+
411
+ export function mapBounds(nodes: readonly { x: number; y: number }[]): {
412
+ minX: number;
413
+ minY: number;
414
+ maxX: number;
415
+ maxY: number;
416
+ } {
417
+ if (nodes.length === 0) {
418
+ return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
419
+ }
420
+ let minX = nodes[0]!.x;
421
+ let minY = nodes[0]!.y;
422
+ let maxX = nodes[0]!.x;
423
+ let maxY = nodes[0]!.y;
424
+ for (const n of nodes) {
425
+ minX = Math.min(minX, n.x);
426
+ minY = Math.min(minY, n.y);
427
+ maxX = Math.max(maxX, n.x);
428
+ maxY = Math.max(maxY, n.y);
429
+ }
430
+ return { minX, minY, maxX, maxY };
431
+ }