@spellkave/world-map 0.0.0-stage → 0.1.0

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,268 @@
1
+ /**
2
+ * Outdoor world layout: ADR-0029 composition + H3 hex footprints.
3
+ *
4
+ * - Root outdoor graph anchors at origin_cell_res10 (centroid).
5
+ * - Nested outdoor graphs project into the parent frame at the portal nest point.
6
+ * - Indoor graphs are not drawn as floorplans — only outdoor portal nodes remain.
7
+ * - Hex outlines from authored cell_res10 (terrain substrate later fills these).
8
+ *
9
+ * Same methodology for spellkave_map_graph / CLI / fixture proofs (not web-only).
10
+ */
11
+
12
+ import { cellToBoundary, isValidCell } from "h3-js";
13
+
14
+ import { cellRes10ToHex, latLngToPlane, placeWorld, worldOffsetToPlane } from "../coords.ts";
15
+ import type { EdgeRow, GraphRow, NodeRow } from "../rows.ts";
16
+
17
+ import type { SpatialGraphEdge, SpatialGraphMeta, SpatialGraphNode } from "./types.ts";
18
+
19
+ export { cellRes10ToHex };
20
+
21
+ export interface H3HexFootprint {
22
+ /** H3 res10 hex index. */
23
+ hex: string;
24
+ /** Closed ring in layout plane (same coords as nodes). */
25
+ ring: Array<{ x: number; y: number }>;
26
+ /** Fill class for terrain/ownership (CSS h3-cell--*). */
27
+ fillKind?: "root" | "settlement" | "wilderness" | "default";
28
+ }
29
+
30
+ export interface H3WorldLayoutResult {
31
+ nodes: SpatialGraphNode[];
32
+ edges: SpatialGraphEdge[];
33
+ graphs: Array<{ graphId: string; offsetX: number; offsetY: number }>;
34
+ hexes: H3HexFootprint[];
35
+ /** True when composition projection produced the layout. */
36
+ usedComposition: boolean;
37
+ }
38
+
39
+ /**
40
+ * Layout outdoor world via root H3 anchor + nested metric composition.
41
+ * Implemented on top of @spellkave/world-map placeWorld (ADR-0123 D-1).
42
+ * Indoor nodes omitted (portal presence is on outdoor endpoints).
43
+ */
44
+ export function layoutOutdoorWorldByComposition(
45
+ nodes: readonly SpatialGraphNode[],
46
+ edges: readonly SpatialGraphEdge[],
47
+ graphs: readonly SpatialGraphMeta[],
48
+ ): H3WorldLayoutResult | null {
49
+ const outdoor = nodes.filter((n) => n.substrateId === "outdoor");
50
+ if (outdoor.length < 2) return null;
51
+
52
+ const gmeta = new Map(graphs.map((g) => [g.graphId, g]));
53
+ const outdoorGraphIds = new Set(outdoor.map((n) => n.graphId));
54
+
55
+ const graphRows: GraphRow[] = graphs
56
+ .filter((g) => outdoorGraphIds.has(g.graphId))
57
+ .map((g) => ({
58
+ place_graph_id: g.graphId,
59
+ parent_graph_id:
60
+ g.parentGraphId && outdoorGraphIds.has(g.parentGraphId.trim())
61
+ ? g.parentGraphId.trim()
62
+ : "",
63
+ anchor_node_id: g.anchorNodeId ?? outdoor.find((n) => n.graphId === g.graphId)?.id ?? "",
64
+ substrate_id: g.substrateId ?? "outdoor",
65
+ bearing: g.bearing ?? 0,
66
+ metres_per_unit: g.metresPerUnit && g.metresPerUnit > 0 ? g.metresPerUnit : 1,
67
+ origin_cell_res10: g.originCellRes10Hex ?? 0,
68
+ origin_cell_res7: 0,
69
+ origin_cell_res4: 0,
70
+ display_name: g.displayName ?? "",
71
+ description: "",
72
+ bundle_id: "",
73
+ blueprint_id: "",
74
+ is_ephemeral_instance: false,
75
+ }));
76
+
77
+ const nodeRows: NodeRow[] = outdoor.map((n) => ({
78
+ node_id: n.id,
79
+ place_graph_id: n.graphId,
80
+ bundle_id: "",
81
+ local_id: "",
82
+ substrate_id: n.substrateId ?? "outdoor",
83
+ display_name: n.label,
84
+ description: "",
85
+ cell_res10: n.cellRes10Hex ?? 0,
86
+ cell_res7: 0,
87
+ cell_res4: 0,
88
+ pos_present: true,
89
+ pos_x: n.x,
90
+ pos_y: n.y,
91
+ pose_elevation_present: n.elevationPresent,
92
+ pose_elevation: n.elevation,
93
+ extent_shape_id: n.extent?.shapeId ?? "",
94
+ extent_params_json: n.extent?.params ? JSON.stringify(n.extent.params) : "",
95
+ is_ephemeral: false,
96
+ }));
97
+
98
+ const edgeRows: EdgeRow[] = edges.map((e, i) => ({
99
+ edge_key: `${e.from}->${e.to}`,
100
+ bundle_id: "",
101
+ place_graph_id: e.graphId,
102
+ from_node_id: e.from,
103
+ to_node_id: e.to,
104
+ pose_dt_elevation_present: false,
105
+ pose_dt_elevation: 0,
106
+ substrate_crossing: false,
107
+ cell_anchor_present: false,
108
+ cell_anchor: 0,
109
+ cell_anchor_u: 0,
110
+ cell_anchor_v: 0,
111
+ from_anchor_side: "",
112
+ from_anchor_offset: 0,
113
+ to_anchor_side: "",
114
+ to_anchor_offset: 0,
115
+ description: "",
116
+ inherit_movement_default: true,
117
+ }));
118
+
119
+ const { placed, origin } = placeWorld(graphRows, nodeRows, edgeRows);
120
+ if (origin === null || placed.size < 2) return null;
121
+
122
+ const placedNodes: SpatialGraphNode[] = [];
123
+ for (const n of outdoor) {
124
+ const p = placed.get(n.id);
125
+ if (!p) continue;
126
+ const plane = worldOffsetToPlane({ east_m: p.east_m, north_m: p.north_m }, 0, 0);
127
+ placedNodes.push({ ...n, x: plane.x, y: plane.y });
128
+ }
129
+
130
+ const nodeIds = new Set(placedNodes.map((n) => n.id));
131
+ // Portal entrances: outdoor node linked to a non-outdoor endpoint.
132
+ const portalEntrances = new Set<string>();
133
+ for (const e of edges) {
134
+ if (nodeIds.has(e.from) && !nodeIds.has(e.to)) portalEntrances.add(e.from);
135
+ if (nodeIds.has(e.to) && !nodeIds.has(e.from)) portalEntrances.add(e.to);
136
+ }
137
+ for (let i = 0; i < placedNodes.length; i++) {
138
+ const n = placedNodes[i];
139
+ if (n === undefined) continue;
140
+ const short = n.label.length <= 14 ? n.label : `${n.label.slice(0, 12)}…`;
141
+ placedNodes[i] = {
142
+ ...n,
143
+ shortLabel: short,
144
+ portalEntrance: portalEntrances.has(n.id),
145
+ };
146
+ }
147
+ // Edges among outdoor placed nodes (includes outdoor↔outdoor portals).
148
+ const placedEdges = edges.filter((e) => nodeIds.has(e.from) && nodeIds.has(e.to));
149
+
150
+ // Hex footprints: unique outdoor cells (authored) + root origin.
151
+ const hexSet = new Set<string>();
152
+ hexSet.add(origin.hex);
153
+ for (const n of outdoor) {
154
+ if (n.cellRes10Hex && isValidCell(n.cellRes10Hex)) hexSet.add(n.cellRes10Hex);
155
+ }
156
+
157
+ const outdoorGraphIdsList = [...outdoorGraphIds];
158
+ const nestGraphIds = new Set(
159
+ outdoorGraphIdsList.filter((id) => {
160
+ const p = gmeta.get(id)?.parentGraphId?.trim() ?? "";
161
+ return p !== "" && outdoorGraphIds.has(p);
162
+ }),
163
+ );
164
+ const rootId = [...outdoorGraphIdsList]
165
+ .filter((id) => {
166
+ const p = gmeta.get(id)?.parentGraphId?.trim() ?? "";
167
+ return (
168
+ (p === "" || !outdoorGraphIds.has(p)) &&
169
+ cellRes10ToHex(gmeta.get(id)?.originCellRes10Hex) !== null
170
+ );
171
+ })
172
+ .sort((a, b) => a.localeCompare(b))[0];
173
+
174
+ const cellsOf = (pred: (n: SpatialGraphNode) => boolean) => {
175
+ const s = new Set<string>();
176
+ for (const n of outdoor) {
177
+ if (!pred(n) || !n.cellRes10Hex || !isValidCell(n.cellRes10Hex)) continue;
178
+ s.add(n.cellRes10Hex);
179
+ }
180
+ return s;
181
+ };
182
+ const settlementCells = cellsOf((n) => nestGraphIds.has(n.graphId));
183
+ const rootCells = rootId ? cellsOf((n) => n.graphId === rootId) : new Set<string>();
184
+
185
+ const hexes: H3HexFootprint[] = [];
186
+ for (const hex of [...hexSet].sort()) {
187
+ const boundary = cellToBoundary(hex); // [[lat,lng], ...]
188
+ const ring = boundary.map(([lat, lng]) => {
189
+ const p = latLngToPlane(lat, lng, origin.lat, origin.lon);
190
+ return worldOffsetToPlane({ east_m: p.x, north_m: -p.y }, 0, 0);
191
+ });
192
+ // Close ring
193
+ if (ring.length > 0) ring.push({ ...ring[0]! });
194
+ let fillKind: H3HexFootprint["fillKind"] = "default";
195
+ if (hex === origin.hex) fillKind = "root";
196
+ else if (settlementCells.has(hex)) fillKind = "settlement";
197
+ else if (rootCells.has(hex)) fillKind = "wilderness";
198
+ hexes.push({ hex, ring, fillKind });
199
+ }
200
+
201
+ const placedGraphIds = new Set([...placed.values()].map((p) => p.node.place_graph_id));
202
+ const graphOffsets = [...placedGraphIds].map((graphId) => ({
203
+ graphId,
204
+ offsetX: 0,
205
+ offsetY: 0,
206
+ }));
207
+
208
+ return {
209
+ nodes: placedNodes,
210
+ edges: placedEdges,
211
+ graphs: graphOffsets,
212
+ hexes,
213
+ usedComposition: true,
214
+ };
215
+ }
216
+
217
+ /** @deprecated kept for tests — prefer layoutOutdoorWorldByComposition */
218
+ export function layoutNodesByH3(
219
+ nodes: readonly SpatialGraphNode[],
220
+ cellByNodeId: ReadonlyMap<string, string | null>,
221
+ metresPerUnitByGraphId: ReadonlyMap<string, number>,
222
+ ): SpatialGraphNode[] | null {
223
+ const enriched = nodes.map((n) => ({
224
+ ...n,
225
+ cellRes10Hex: cellByNodeId.get(n.id) ?? n.cellRes10Hex ?? null,
226
+ }));
227
+ const graphs: SpatialGraphMeta[] = [...new Set(nodes.map((n) => n.graphId))].map((graphId) => ({
228
+ graphId,
229
+ metresPerUnit: metresPerUnitByGraphId.get(graphId) ?? 1,
230
+ substrateId: "outdoor",
231
+ displayName: null,
232
+ parentGraphId: "",
233
+ originCellRes10Hex: null,
234
+ bearing: 0,
235
+ anchorNodeId: null,
236
+ }));
237
+ // Fake root origin from first cell
238
+ const first = [...cellByNodeId.values()].find((h) => h && isValidCell(h));
239
+ if (!first) return null;
240
+ graphs[0] = { ...graphs[0]!, originCellRes10Hex: first };
241
+ const r = layoutOutdoorWorldByComposition(enriched, [], graphs);
242
+ return r?.nodes ?? null;
243
+ }
244
+
245
+ export function shouldUseH3WorldLayout(
246
+ graphScoped: boolean,
247
+ nodes: readonly SpatialGraphNode[],
248
+ _cellByNodeId: ReadonlyMap<string, string | null>,
249
+ graphs?: readonly SpatialGraphMeta[],
250
+ ): boolean {
251
+ if (graphScoped) return false;
252
+ const outdoor = nodes.filter((n) => n.substrateId === "outdoor" || n.substrateId === null);
253
+ if (outdoor.length < 2) return false;
254
+ if (graphs) {
255
+ const hasRootOrigin = graphs.some(
256
+ (g) =>
257
+ (g.substrateId === "outdoor" || g.substrateId === null) &&
258
+ g.originCellRes10Hex &&
259
+ isValidCell(g.originCellRes10Hex),
260
+ );
261
+ if (hasRootOrigin) return true;
262
+ }
263
+ let withCell = 0;
264
+ for (const n of outdoor) {
265
+ if (n.cellRes10Hex && isValidCell(n.cellRes10Hex)) withCell += 1;
266
+ }
267
+ return withCell >= 2 && withCell / outdoor.length >= 0.5;
268
+ }
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Browser-safe spatial-graph products: layout, SVG, ASCII, braille, inventory.
3
+ * Node-only raster pieces live in `@spellkave/world-map/node`; terminal/pi-tui helpers in `@spellkave/world-map/node/terminal`.
4
+ */
5
+
6
+ export {
7
+ composeProjection,
8
+ latLngToPlane,
9
+ METRES_PER_DEG_LAT,
10
+ type ProjectionParams,
11
+ projectLocalPosition,
12
+ type WorldOffset,
13
+ worldOffsetToLatLng,
14
+ worldOffsetToPlane,
15
+ } from "../coords.ts";
16
+ export {
17
+ type AnchorComposeParams,
18
+ composeChildLocalToParentFrame,
19
+ isEphemeralInstanceGraph,
20
+ localBoundsCenter,
21
+ metresPerParentLocalUnit,
22
+ type Point2D,
23
+ resolveGraphAncestorChain,
24
+ } from "./compose.ts";
25
+ export {
26
+ cellRes10ToHex,
27
+ layoutOutdoorWorldByComposition,
28
+ shouldUseH3WorldLayout,
29
+ } from "./h3-layout.ts";
30
+ export {
31
+ countMapPlaces,
32
+ isTacticalGridCell,
33
+ renderSpatialGraphTextInventory,
34
+ } from "./inventory.ts";
35
+ export { layoutSpatialGraph, mapBounds } from "./layout.ts";
36
+ export { buildSpatialGraphModel, pickDefaultSlice } from "./model.ts";
37
+ export { type RenderAsciiOptions, renderSpatialGraphAscii } from "./render-ascii.ts";
38
+ export { type RenderBrailleOptions, renderSpatialGraphBraille } from "./render-braille.ts";
39
+ export { renderSpatialGraphSvg, svgEdgePairs, svgNodeIds } from "./render-svg.ts";
40
+ export {
41
+ chooseScaleBar,
42
+ formatMetresLabel,
43
+ type ScaleBarSpec,
44
+ sharedMetresPerGraphUnit,
45
+ } from "./scale.ts";
46
+ export type {
47
+ RenderSvgOptions,
48
+ SpatialGraphActorCluster,
49
+ SpatialGraphBackdrop,
50
+ SpatialGraphEdge,
51
+ SpatialGraphLayout,
52
+ SpatialGraphMeta,
53
+ SpatialGraphModel,
54
+ SpatialGraphNode,
55
+ SpatialGraphToolRows,
56
+ SpatialLod,
57
+ SpatialSliceMode,
58
+ SpatialViewOptions,
59
+ } from "./types.ts";
60
+
61
+ import { renderSpatialGraphTextInventory } from "./inventory.ts";
62
+ import { layoutSpatialGraph } from "./layout.ts";
63
+ import { buildSpatialGraphModel, pickDefaultSlice } from "./model.ts";
64
+ import { type RenderAsciiOptions, renderSpatialGraphAscii } from "./render-ascii.ts";
65
+ import { type RenderBrailleOptions, renderSpatialGraphBraille } from "./render-braille.ts";
66
+ import { renderSpatialGraphSvg } from "./render-svg.ts";
67
+ import type {
68
+ RenderSvgOptions,
69
+ SpatialGraphModel,
70
+ SpatialGraphToolRows,
71
+ SpatialViewOptions,
72
+ } from "./types.ts";
73
+
74
+ /** Which terminal map to put in the primary text body. */
75
+ export type SpatialTerminalMode = "utf8" | "ascii" | "braille";
76
+
77
+ /**
78
+ * A single computable artifact off the shared model+layout. `buildSpatialGraphView`
79
+ * used to render all four unconditionally on every call regardless of what a
80
+ * caller actually wanted — the direct cost behind bead sk-due (18 unread SVG
81
+ * payloads bloating the elven-mini story JSONL 286 KB -> 380 KB). `renderOnly`
82
+ * below is the opt-in fix; `inventory`/`model`/`hasLayout` are not artifacts in
83
+ * this sense — they are the cheap part and stay unconditional.
84
+ */
85
+ export type SpatialArtifact = "svg" | "utf8" | "ascii" | "braille";
86
+
87
+ export interface SpatialGraphView {
88
+ model: SpatialGraphModel;
89
+ svg: string | null;
90
+ /**
91
+ * Primary terminal map for the tool text body (selected mode).
92
+ * Kept as `ascii` for back-compat with details.ascii consumers.
93
+ */
94
+ ascii: string | null;
95
+ /** UTF-8 box-drawing map (junction-aware). */
96
+ utf8: string | null;
97
+ /** Dense braille map via termdot. */
98
+ braille: string | null;
99
+ inventory: string;
100
+ hasLayout: boolean;
101
+ }
102
+
103
+ export type BuildSpatialGraphViewOptions = SpatialViewOptions &
104
+ RenderSvgOptions &
105
+ RenderAsciiOptions &
106
+ RenderBrailleOptions & {
107
+ /** Primary terminal product (default utf8). Selects which computed text
108
+ * variant becomes `view.ascii` — has no effect on WHICH variants get
109
+ * rendered; that's `renderOnly` below. */
110
+ terminal?: SpatialTerminalMode;
111
+ /**
112
+ * Restrict which of svg/utf8/ascii/braille actually get rendered — omit
113
+ * to keep the historical "compute everything" default every non-tool
114
+ * caller (renders.ts, spellkave-cli's map.ts, author-spatial-map-proofs.ts)
115
+ * still relies on for byte-identical fixtures (none of them pass this).
116
+ * The two tool call sites (spellkave_map, spellkave_map_graph) are the
117
+ * only callers that pass it, deriving it 1:1 from their own
118
+ * `output_type` param via `spatialRenderPlanForOutputType` below (bead
119
+ * sk-due). An artifact not in `renderOnly` comes back `null`, never computed.
120
+ */
121
+ renderOnly?: readonly SpatialArtifact[];
122
+ };
123
+
124
+ /** One-shot: tool rows → model + SVG + terminal maps (or inventory-only when empty). */
125
+ export function buildSpatialGraphView(
126
+ rows: SpatialGraphToolRows,
127
+ options: BuildSpatialGraphViewOptions = {},
128
+ ): SpatialGraphView {
129
+ const {
130
+ graphId,
131
+ slice,
132
+ z,
133
+ zTolerance,
134
+ lod,
135
+ sheetAlign,
136
+ preferH3World,
137
+ composeParent,
138
+ hideOccupancy: hideOccupancyOpt,
139
+ sliceCaption: sliceCaptionOpt,
140
+ width: termWidth,
141
+ height: termHeight,
142
+ unicode: asciiUnicode,
143
+ chrome: termChrome,
144
+ color: termColor,
145
+ terminal = "utf8",
146
+ renderOnly,
147
+ ...svgOptions
148
+ } = options;
149
+ const viewOpts: SpatialViewOptions = {
150
+ graphId,
151
+ slice,
152
+ z,
153
+ zTolerance,
154
+ lod,
155
+ sheetAlign,
156
+ preferH3World,
157
+ composeParent,
158
+ };
159
+ const model = buildSpatialGraphModel(rows, viewOpts);
160
+ const inventory = renderSpatialGraphTextInventory(model);
161
+ if (model.nodes.length === 0) {
162
+ return {
163
+ model,
164
+ svg: null,
165
+ ascii: null,
166
+ utf8: null,
167
+ braille: null,
168
+ inventory,
169
+ hasLayout: false,
170
+ };
171
+ }
172
+ const sliceMode = pickDefaultSlice(model.nodes, viewOpts);
173
+ const layout = layoutSpatialGraph(model, { ...viewOpts, sliceMode });
174
+ if (layout.nodes.length === 0) {
175
+ return {
176
+ model,
177
+ svg: null,
178
+ ascii: null,
179
+ utf8: null,
180
+ braille: null,
181
+ inventory,
182
+ hasLayout: false,
183
+ };
184
+ }
185
+ const hideOccupancy = hideOccupancyOpt ?? lod === "structure";
186
+ const want = (artifact: SpatialArtifact): boolean =>
187
+ renderOnly === undefined || renderOnly.includes(artifact);
188
+ const svg = want("svg")
189
+ ? renderSpatialGraphSvg(model, layout, {
190
+ ...svgOptions,
191
+ hideOccupancy,
192
+ sliceCaption: sliceCaptionOpt ?? model.sliceLabel,
193
+ })
194
+ : null;
195
+ const utf8 = want("utf8")
196
+ ? renderSpatialGraphAscii(model, layout, {
197
+ width: termWidth,
198
+ height: termHeight,
199
+ unicode: asciiUnicode !== false,
200
+ chrome: termChrome,
201
+ color: termColor,
202
+ hideOccupancy,
203
+ })
204
+ : null;
205
+ const asciiOnly = want("ascii")
206
+ ? renderSpatialGraphAscii(model, layout, {
207
+ width: termWidth,
208
+ height: termHeight,
209
+ unicode: false,
210
+ chrome: termChrome,
211
+ color: false,
212
+ hideOccupancy,
213
+ })
214
+ : null;
215
+ const braille = want("braille")
216
+ ? renderSpatialGraphBraille(model, layout, {
217
+ width: termWidth,
218
+ height: termHeight,
219
+ chrome: termChrome,
220
+ hideOccupancy,
221
+ })
222
+ : null;
223
+ const primary = terminal === "ascii" ? asciiOnly : terminal === "braille" ? braille : utf8;
224
+ return {
225
+ model,
226
+ svg,
227
+ ascii: primary,
228
+ utf8,
229
+ braille,
230
+ inventory,
231
+ hasLayout: true,
232
+ };
233
+ }
234
+
235
+ /** The 6-value `output_type` shape shared by `spellkave_map` and
236
+ * `spellkave_map_graph` (bead sk-due — one flat enum, the canonical
237
+ * `--format` shape, replacing the old `terminal` param that only picked the
238
+ * TEXT variant while the engine rendered everything regardless). */
239
+ export type MapOutputType = "utf8" | "ascii" | "braille" | "inventory" | "svg" | "jpg";
240
+
241
+ /**
242
+ * Derive the engine's `renderOnly`/`terminal` knobs from a map tool's own
243
+ * `output_type` — the ONE place this mapping is written, so the two tools'
244
+ * output_type semantics can never drift apart. `jpg` needs no artifact from
245
+ * THIS call: its backdrop-composed raster source comes from a second,
246
+ * dedicated `buildSpatialGraphView` call the jpg branch makes itself (sheet-
247
+ * aligned, with backdrops) — see `spellkave_map`/`spellkave_map_graph`'s own
248
+ * jpg branch. `inventory` renders nothing at all — `renderSpatialGraphTextInventory`
249
+ * output is unconditional regardless of `renderOnly`.
250
+ */
251
+ export function spatialRenderPlanForOutputType(outputType: MapOutputType): {
252
+ renderOnly: readonly SpatialArtifact[];
253
+ terminal: SpatialTerminalMode;
254
+ } {
255
+ switch (outputType) {
256
+ case "utf8":
257
+ return { renderOnly: ["utf8"], terminal: "utf8" };
258
+ case "ascii":
259
+ return { renderOnly: ["ascii"], terminal: "ascii" };
260
+ case "braille":
261
+ return { renderOnly: ["braille"], terminal: "braille" };
262
+ case "svg":
263
+ return { renderOnly: ["svg"], terminal: "utf8" };
264
+ case "inventory":
265
+ case "jpg":
266
+ return { renderOnly: [], terminal: "utf8" };
267
+ }
268
+ }
269
+
270
+ /** Browser SVG product: model + laid-out SVG (or null when empty). */
271
+ export interface SpatialGraphSvgView {
272
+ model: SpatialGraphModel;
273
+ svg: string | null;
274
+ hasLayout: boolean;
275
+ }
276
+
277
+ export type BuildSpatialGraphSvgViewOptions = SpatialViewOptions & RenderSvgOptions;
278
+
279
+ /**
280
+ * One-shot browser path: tool rows → model → layout → SVG.
281
+ * Same SVG bytes as `buildSpatialGraphView(..., { renderOnly: ["svg"] }).svg`
282
+ * for identical inputs (asserted by browser-entry tests).
283
+ */
284
+ export function buildSpatialGraphSvgView(
285
+ rows: SpatialGraphToolRows,
286
+ options: BuildSpatialGraphSvgViewOptions = {},
287
+ ): SpatialGraphSvgView {
288
+ const {
289
+ graphId,
290
+ slice,
291
+ z,
292
+ zTolerance,
293
+ lod,
294
+ sheetAlign,
295
+ preferH3World,
296
+ composeParent,
297
+ hideOccupancy: hideOccupancyOpt,
298
+ sliceCaption: sliceCaptionOpt,
299
+ ...svgOptions
300
+ } = options;
301
+ const viewOpts: SpatialViewOptions = {
302
+ graphId,
303
+ slice,
304
+ z,
305
+ zTolerance,
306
+ lod,
307
+ sheetAlign,
308
+ preferH3World,
309
+ composeParent,
310
+ };
311
+ const model = buildSpatialGraphModel(rows, viewOpts);
312
+ if (model.nodes.length === 0) {
313
+ return { model, svg: null, hasLayout: false };
314
+ }
315
+ const sliceMode = pickDefaultSlice(model.nodes, viewOpts);
316
+ const layout = layoutSpatialGraph(model, { ...viewOpts, sliceMode });
317
+ if (layout.nodes.length === 0) {
318
+ return { model, svg: null, hasLayout: false };
319
+ }
320
+ const hideOccupancy = hideOccupancyOpt ?? lod === "structure";
321
+ const svg = renderSpatialGraphSvg(model, layout, {
322
+ ...svgOptions,
323
+ hideOccupancy,
324
+ sliceCaption: sliceCaptionOpt ?? model.sliceLabel,
325
+ });
326
+ return { model, svg, hasLayout: true };
327
+ }