@bendyline/squisq-react 2.12.8 → 2.12.10

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,1074 @@
1
+ // src/graph/DiagramViewer.tsx
2
+ import {
3
+ forwardRef,
4
+ memo,
5
+ useCallback,
6
+ useEffect,
7
+ useId,
8
+ useImperativeHandle,
9
+ useLayoutEffect,
10
+ useMemo,
11
+ useRef,
12
+ useState
13
+ } from "react";
14
+ import { polylinePath } from "@bendyline/squisq-graph";
15
+
16
+ // src/graph/spatialIndex.ts
17
+ var GridIndex = class {
18
+ constructor(boxes, cellSize) {
19
+ this.cells = /* @__PURE__ */ new Map();
20
+ this.round = 0;
21
+ this.boxes = boxes;
22
+ this.cellSize = Math.max(1, cellSize);
23
+ this.stamp = new Uint32Array(boxes.length);
24
+ boxes.forEach((b, i) => {
25
+ const [c0, r0, c1, r1] = this.span(b.x, b.y, b.x + b.width, b.y + b.height);
26
+ for (let r = r0; r <= r1; r++) {
27
+ for (let c = c0; c <= c1; c++) {
28
+ const key = this.key(c, r);
29
+ const list = this.cells.get(key);
30
+ if (list) list.push(i);
31
+ else this.cells.set(key, [i]);
32
+ }
33
+ }
34
+ });
35
+ }
36
+ /** Indices of every box overlapping the rectangle, in ascending order. */
37
+ query(x0, y0, x1, y1) {
38
+ if (++this.round === 4294967295) {
39
+ this.stamp = new Uint32Array(this.boxes.length);
40
+ this.round = 1;
41
+ }
42
+ const out = [];
43
+ const [c0, r0, c1, r1] = this.span(x0, y0, x1, y1);
44
+ for (let r = r0; r <= r1; r++) {
45
+ for (let c = c0; c <= c1; c++) {
46
+ for (const i of this.cells.get(this.key(c, r)) ?? []) {
47
+ if (this.stamp[i] === this.round) continue;
48
+ this.stamp[i] = this.round;
49
+ const b = this.boxes[i];
50
+ if (b.x <= x1 && b.x + b.width >= x0 && b.y <= y1 && b.y + b.height >= y0) out.push(i);
51
+ }
52
+ }
53
+ }
54
+ return out.sort((a, b) => a - b);
55
+ }
56
+ span(x0, y0, x1, y1) {
57
+ const s = this.cellSize;
58
+ return [Math.floor(x0 / s), Math.floor(y0 / s), Math.floor(x1 / s), Math.floor(y1 / s)];
59
+ }
60
+ key(c, r) {
61
+ return (c + 1048576) * 2097152 + (r + 1048576);
62
+ }
63
+ };
64
+
65
+ // src/graph/styles.ts
66
+ var TONES = {
67
+ accent: "#2563eb",
68
+ positive: "#15803d",
69
+ notice: "#a16207",
70
+ warning: "#c2410c",
71
+ danger: "#dc2626",
72
+ muted: "#94a3b8"
73
+ };
74
+ var toneRules = Object.entries(TONES).map(
75
+ ([tone, color]) => `.squisq-graph-view .gv-node[data-tone="${tone}"]>.gv-box{stroke:var(--squisq-graph-tone-${tone},${color})}.squisq-graph-view .gv-edge[data-tone="${tone}"]>.gv-line{stroke:var(--squisq-graph-tone-${tone},${color})}.squisq-graph-view .gv-arrow-${tone}{fill:var(--squisq-graph-tone-${tone},${color})}`
76
+ ).join("");
77
+ var GRAPH_TONE_NAMES = ["neutral", ...Object.keys(TONES)];
78
+ var GRAPH_VIEW_CSS = ".squisq-graph-view{position:relative;overflow:hidden;outline:none;touch-action:none;user-select:none;-webkit-user-select:none;background:var(--squisq-graph-bg,transparent);font-family:inherit}.squisq-graph-view:focus-visible{box-shadow:inset 0 0 0 2px var(--squisq-graph-focus,#2563eb)}.squisq-graph-view>svg{display:block;width:100%;height:100%;cursor:grab}.squisq-graph-view[data-panning]>svg{cursor:grabbing}.squisq-graph-view .gv-frame{fill:var(--squisq-graph-container-bg,rgba(100,116,139,.07));stroke:var(--squisq-graph-container-border,rgba(100,116,139,.4));stroke-width:1px;vector-effect:non-scaling-stroke}.squisq-graph-view .gv-container-label{font-size:12px;font-weight:600;fill:var(--squisq-graph-muted,#475569)}.squisq-graph-view .gv-box{fill:var(--squisq-graph-node-bg,#fff);stroke:var(--squisq-graph-node-border,#94a3b8);stroke-width:1px;vector-effect:non-scaling-stroke}.squisq-graph-view .gv-node[data-collapsed]>.gv-box{stroke-dasharray:none;stroke-width:1.5px}.squisq-graph-view .gv-stack{fill:var(--squisq-graph-node-bg,#fff);stroke:var(--squisq-graph-node-border,#94a3b8);stroke-width:1px;vector-effect:non-scaling-stroke}.squisq-graph-view .gv-node{cursor:pointer}.squisq-graph-view .gv-label{font-size:12px;fill:var(--squisq-graph-text,#1f2937);pointer-events:none}.squisq-graph-view .gv-detail{font-size:10px;fill:var(--squisq-graph-muted,#64748b);pointer-events:none}.squisq-graph-view .gv-badge>rect{fill:var(--squisq-graph-badge-bg,rgba(100,116,139,.15))}.squisq-graph-view .gv-badge>text{font-size:10px;font-weight:600;fill:var(--squisq-graph-text,#1f2937)}.squisq-graph-view .gv-toggle{cursor:pointer}.squisq-graph-view .gv-toggle>path{fill:none;stroke:var(--squisq-graph-muted,#64748b);stroke-width:1.5px;vector-effect:non-scaling-stroke}.squisq-graph-view .gv-toggle>rect{fill:transparent}.squisq-graph-view .gv-line{fill:none;stroke:var(--squisq-graph-edge,#64748b);stroke-opacity:.85;vector-effect:non-scaling-stroke}.squisq-graph-view .gv-edge[data-dashed]>.gv-line{stroke-dasharray:5 4}.squisq-graph-view .gv-hit{fill:none;stroke:transparent;stroke-width:10px;vector-effect:non-scaling-stroke;pointer-events:stroke;cursor:pointer}.squisq-graph-view .gv-arrow-neutral{fill:var(--squisq-graph-edge,#64748b)}" + toneRules + ".squisq-graph-view .gv-node,.squisq-graph-view .gv-edge{transition:opacity 120ms}.squisq-graph-view[data-dim] .gv-node,.squisq-graph-view[data-dim] .gv-edge{opacity:.15}.squisq-graph-view.gv-lod-0 .gv-label,.squisq-graph-view.gv-lod-0 .gv-detail,.squisq-graph-view.gv-lod-0 .gv-badge,.squisq-graph-view.gv-lod-0 .gv-container-label,.squisq-graph-view.gv-lod-0 .gv-toggle{display:none}.squisq-graph-view.gv-lod-1 .gv-detail,.squisq-graph-view.gv-lod-1 .gv-badge{display:none}.squisq-graph-view .gv-controls{position:absolute;right:8px;bottom:8px;display:flex;align-items:center;gap:2px;padding:2px;border-radius:6px;background:var(--squisq-graph-controls-bg,rgba(255,255,255,.92));border:1px solid var(--squisq-graph-container-border,rgba(100,116,139,.4))}.squisq-graph-view .gv-controls>button{min-width:28px;height:26px;padding:0 6px;border:0;border-radius:4px;background:transparent;color:var(--squisq-graph-text,#1f2937);font:inherit;font-size:13px;cursor:pointer}.squisq-graph-view .gv-controls>button:hover{background:var(--squisq-graph-badge-bg,rgba(100,116,139,.15))}.squisq-graph-view .gv-controls>output{min-width:40px;text-align:center;font-size:12px;color:var(--squisq-graph-muted,#64748b)}.squisq-graph-view .gv-live{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}@media (prefers-reduced-motion:reduce){.squisq-graph-view .gv-node,.squisq-graph-view .gv-edge{transition:none}}";
79
+
80
+ // src/graph/textMetrics.ts
81
+ var NARROW = new Set("iIl|.,:;'!`1tfjr ()[]");
82
+ var WIDE = new Set("mwMW@%");
83
+ function estimateTextWidth(text, fontSize = 12) {
84
+ let em = 0;
85
+ for (const ch of text) {
86
+ if (NARROW.has(ch)) em += 0.3;
87
+ else if (WIDE.has(ch)) em += 0.85;
88
+ else if (ch >= "A" && ch <= "Z") em += 0.66;
89
+ else if (ch >= "0" && ch <= "9") em += 0.56;
90
+ else if (ch.charCodeAt(0) > 11903) em += 1;
91
+ else em += 0.54;
92
+ }
93
+ return em * fontSize;
94
+ }
95
+ function truncateToWidth(text, maxWidth, fontSize = 12) {
96
+ if (estimateTextWidth(text, fontSize) <= maxWidth) return text;
97
+ const chars = Array.from(text);
98
+ const ellipsis = estimateTextWidth("\u2026", fontSize);
99
+ let width = 0;
100
+ let cut = 0;
101
+ for (; cut < chars.length; cut++) {
102
+ const w = estimateTextWidth(chars[cut], fontSize);
103
+ if (width + w + ellipsis > maxWidth) break;
104
+ width += w;
105
+ }
106
+ return cut === 0 ? "\u2026" : `${chars.slice(0, cut).join("").trimEnd()}\u2026`;
107
+ }
108
+ var GRAPH_NODE_METRICS = {
109
+ labelSize: 12,
110
+ detailSize: 10,
111
+ badgeSize: 10,
112
+ paddingX: 10,
113
+ /** Height of a node with a label only, and with a label plus a detail line. */
114
+ height: 28,
115
+ heightWithDetail: 40,
116
+ /** Width of a badge per character beyond its padding, and the room for a toggle chevron. */
117
+ badgePadding: 10,
118
+ toggleWidth: 16
119
+ };
120
+ function graphNodeSize(node, options = {}) {
121
+ const m = GRAPH_NODE_METRICS;
122
+ const text = Math.max(
123
+ estimateTextWidth(node.label, m.labelSize),
124
+ node.detail ? estimateTextWidth(node.detail, m.detailSize) : 0
125
+ );
126
+ const badge = node.badge ? estimateTextWidth(node.badge, m.badgeSize) + m.badgePadding + 6 : 0;
127
+ const toggle = node.expandable ? m.toggleWidth : 0;
128
+ const width = Math.ceil(m.paddingX * 2 + text + badge + toggle);
129
+ return {
130
+ width: Math.min(options.maxWidth ?? 280, Math.max(options.minWidth ?? 64, width)),
131
+ height: node.detail ? m.heightWithDetail : m.height
132
+ };
133
+ }
134
+
135
+ // src/graph/viewTransform.ts
136
+ var MIN_VIEW_SCALE = 0.02;
137
+ var MAX_VIEW_SCALE = 8;
138
+ function clampScale(scale) {
139
+ return Math.min(MAX_VIEW_SCALE, Math.max(MIN_VIEW_SCALE, scale));
140
+ }
141
+ function zoomAt(t, factor, fx, fy) {
142
+ const scale = clampScale(t.scale * factor);
143
+ const k = scale / t.scale;
144
+ return { tx: fx - (fx - t.tx) * k, ty: fy - (fy - t.ty) * k, scale };
145
+ }
146
+ function fitTransform(box, size, padding = 24, maxScale = 1.5) {
147
+ const availW = Math.max(1, size.width - padding * 2);
148
+ const availH = Math.max(1, size.height - padding * 2);
149
+ const scale = box.width <= 0 || box.height <= 0 ? clampScale(maxScale) : clampScale(Math.min(maxScale, availW / box.width, availH / box.height));
150
+ return {
151
+ tx: (size.width - box.width * scale) / 2 - box.x * scale,
152
+ ty: (size.height - box.height * scale) / 2 - box.y * scale,
153
+ scale
154
+ };
155
+ }
156
+ function visibleRect(t, size) {
157
+ return {
158
+ x0: -t.tx / t.scale,
159
+ y0: -t.ty / t.scale,
160
+ x1: (size.width - t.tx) / t.scale,
161
+ y1: (size.height - t.ty) / t.scale
162
+ };
163
+ }
164
+ function revealTransform(t, box, size, margin = 24) {
165
+ const left = box.x * t.scale + t.tx;
166
+ const top = box.y * t.scale + t.ty;
167
+ const right = left + box.width * t.scale;
168
+ const bottom = top + box.height * t.scale;
169
+ const shift = (lo, hi, extent) => {
170
+ if (hi - lo > extent - margin * 2) return extent / 2 - (lo + hi) / 2;
171
+ if (lo < margin) return margin - lo;
172
+ if (hi > extent - margin) return extent - margin - hi;
173
+ return 0;
174
+ };
175
+ return {
176
+ tx: t.tx + shift(left, right, size.width),
177
+ ty: t.ty + shift(top, bottom, size.height),
178
+ scale: t.scale
179
+ };
180
+ }
181
+
182
+ // src/graph/constants.ts
183
+ var GRAPH_VIEW_CULL_AT = 600;
184
+ var graphViewRenderCounts = { containers: 0, edges: 0, nodes: 0 };
185
+
186
+ // src/graph/DiagramViewer.tsx
187
+ import { jsx, jsxs } from "react/jsx-runtime";
188
+ var LOD_LABELS = 0.4;
189
+ var LOD_DETAILS = 0.75;
190
+ var DRAG_SLOP = 3;
191
+ var ANCHOR_TTL_MS = 1e4;
192
+ var DEFAULT_SIZE = { width: 800, height: 600 };
193
+ function buildModel(layout, nodes, edges, cornerRadius) {
194
+ const nodeById = new Map(nodes?.map((n) => [n.id, n]));
195
+ const edgeById = new Map(edges?.map((e) => [e.id, e]));
196
+ const indexOf = /* @__PURE__ */ new Map();
197
+ layout.nodes.forEach((n, i) => {
198
+ if (!indexOf.has(n.id)) indexOf.set(n.id, i);
199
+ });
200
+ const edgeIndexOf = /* @__PURE__ */ new Map();
201
+ layout.edges.forEach((e, i) => {
202
+ if (!edgeIndexOf.has(e.id)) edgeIndexOf.set(e.id, i);
203
+ });
204
+ const m = GRAPH_NODE_METRICS;
205
+ const nodeView = layout.nodes.map((n) => nodeById.get(n.id));
206
+ const nodeText = layout.nodes.map((n, i) => {
207
+ const view = nodeView[i];
208
+ const label = view?.label ?? n.id;
209
+ const badgeWidth = view?.badge ? estimateTextWidth(view.badge, m.badgeSize) + m.badgePadding : 0;
210
+ const toggle = view?.expandable ? m.toggleWidth : 0;
211
+ if (n.container) {
212
+ return {
213
+ label: truncateToWidth(label, n.width - m.paddingX * 2 - toggle - badgeWidth, m.labelSize),
214
+ badge: view?.badge,
215
+ badgeWidth
216
+ };
217
+ }
218
+ const room = n.width - m.paddingX * 2 - toggle - (badgeWidth ? badgeWidth + 6 : 0);
219
+ return {
220
+ label: truncateToWidth(label, room, m.labelSize),
221
+ detail: view?.detail ? truncateToWidth(view.detail, room, m.detailSize) : void 0,
222
+ badge: view?.badge,
223
+ badgeWidth
224
+ };
225
+ });
226
+ const edgeView = layout.edges.map((e) => edgeById.get(e.id));
227
+ const edgePath = layout.edges.map((e) => polylinePath(e.points, { radius: cornerRadius }));
228
+ const edgeWidth = edgeView.map((v) => {
229
+ const w = v?.weight ?? 1;
230
+ return Math.min(6, Math.max(1, 1 + 1.25 * Math.log2(Math.max(1, w))));
231
+ });
232
+ const edgeTone = edgeView.map((v) => v?.tone ?? "neutral");
233
+ const incident = layout.nodes.map(() => []);
234
+ const successors = layout.nodes.map(() => []);
235
+ const predecessors = layout.nodes.map(() => []);
236
+ layout.edges.forEach((e, k) => {
237
+ const s = indexOf.get(e.source);
238
+ const t = indexOf.get(e.target);
239
+ if (s === void 0 || t === void 0) return;
240
+ incident[s].push(k);
241
+ incident[t].push(k);
242
+ if (!successors[s].includes(t)) successors[s].push(t);
243
+ if (!predecessors[t].includes(s)) predecessors[t].push(s);
244
+ });
245
+ const containers = [];
246
+ const leaves = [];
247
+ layout.nodes.forEach((n, i) => (n.container ? containers : leaves).push(i));
248
+ containers.sort(
249
+ (a, b) => layout.nodes[b].width * layout.nodes[b].height - layout.nodes[a].width * layout.nodes[a].height || a - b
250
+ );
251
+ const edgeBoxes = layout.edges.map((e) => {
252
+ let x0 = Infinity;
253
+ let y0 = Infinity;
254
+ let x1 = -Infinity;
255
+ let y1 = -Infinity;
256
+ for (const p of e.points) {
257
+ x0 = Math.min(x0, p.x);
258
+ y0 = Math.min(y0, p.y);
259
+ x1 = Math.max(x1, p.x);
260
+ y1 = Math.max(y1, p.y);
261
+ }
262
+ return Number.isFinite(x0) ? { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } : { x: 0, y: 0, width: 0, height: 0 };
263
+ });
264
+ const cell = Math.max(
265
+ 128,
266
+ Math.sqrt(layout.width * layout.height / Math.max(1, layout.nodes.length)) * 4
267
+ );
268
+ const tones = [.../* @__PURE__ */ new Set(["neutral", ...edgeTone])];
269
+ return {
270
+ layout,
271
+ nodeView,
272
+ edgeView,
273
+ nodeText,
274
+ edgePath,
275
+ edgeWidth,
276
+ edgeTone,
277
+ indexOf,
278
+ edgeIndexOf,
279
+ incident,
280
+ successors,
281
+ predecessors,
282
+ containers,
283
+ leaves,
284
+ nodeIndex: new GridIndex(layout.nodes, cell),
285
+ edgeIndex: new GridIndex(edgeBoxes, cell),
286
+ tones
287
+ };
288
+ }
289
+ function drawingBox(layout) {
290
+ return { x: 0, y: 0, width: layout.width, height: layout.height };
291
+ }
292
+ function joinClass(...names) {
293
+ return names.filter(Boolean).join(" ");
294
+ }
295
+ var ContainersLayer = memo(function ContainersLayer2({ model, visible }) {
296
+ graphViewRenderCounts.containers++;
297
+ const m = GRAPH_NODE_METRICS;
298
+ return /* @__PURE__ */ jsx("g", { className: "gv-containers", children: model.containers.map((i) => {
299
+ if (visible && !visible.has(i)) return null;
300
+ const n = model.layout.nodes[i];
301
+ const view = model.nodeView[i];
302
+ const text = model.nodeText[i];
303
+ const toggle = view?.expandable ? m.toggleWidth : 0;
304
+ return /* @__PURE__ */ jsxs(
305
+ "g",
306
+ {
307
+ className: joinClass("gv-container", view?.className),
308
+ "data-i": i,
309
+ transform: `translate(${n.x} ${n.y})`,
310
+ children: [
311
+ /* @__PURE__ */ jsx("title", { children: view?.title ?? view?.label ?? n.id }),
312
+ /* @__PURE__ */ jsx(
313
+ "rect",
314
+ {
315
+ className: "gv-frame",
316
+ width: n.width,
317
+ height: n.height,
318
+ rx: 6,
319
+ style: view?.fill ? { fill: view.fill } : void 0
320
+ }
321
+ ),
322
+ toggle > 0 && /* @__PURE__ */ jsx(Toggle, { x: m.paddingX - 2, y: 14, open: view?.expanded !== false }),
323
+ /* @__PURE__ */ jsx("text", { className: "gv-container-label", x: m.paddingX + toggle, y: 18, children: text.label }),
324
+ text.badge && /* @__PURE__ */ jsx(
325
+ Badge,
326
+ {
327
+ x: n.width - m.paddingX - text.badgeWidth,
328
+ y: 7,
329
+ width: text.badgeWidth,
330
+ text: text.badge
331
+ }
332
+ )
333
+ ]
334
+ },
335
+ i
336
+ );
337
+ }) });
338
+ });
339
+ var NodesLayer = memo(function NodesLayer2({ model, visible }) {
340
+ graphViewRenderCounts.nodes++;
341
+ const m = GRAPH_NODE_METRICS;
342
+ return /* @__PURE__ */ jsx("g", { className: "gv-nodes", children: model.leaves.map((i) => {
343
+ if (visible && !visible.has(i)) return null;
344
+ const n = model.layout.nodes[i];
345
+ const view = model.nodeView[i];
346
+ const text = model.nodeText[i];
347
+ const toggle = view?.expandable ? m.toggleWidth : 0;
348
+ const collapsed = !!view?.expandable && !view.expanded;
349
+ const tone = view?.tone && view.tone !== "neutral" ? view.tone : void 0;
350
+ const labelY = text.detail ? n.height / 2 - 2 : n.height / 2 + 4;
351
+ return /* @__PURE__ */ jsxs(
352
+ "g",
353
+ {
354
+ className: joinClass("gv-node", view?.className),
355
+ "data-i": i,
356
+ "data-tone": tone,
357
+ "data-collapsed": collapsed ? "" : void 0,
358
+ transform: `translate(${n.x} ${n.y})`,
359
+ children: [
360
+ /* @__PURE__ */ jsx("title", { children: view?.title ?? view?.label ?? n.id }),
361
+ collapsed && /* @__PURE__ */ jsx("rect", { className: "gv-stack", x: 3, y: -3, width: n.width, height: n.height, rx: 4 }),
362
+ /* @__PURE__ */ jsx(
363
+ "rect",
364
+ {
365
+ className: "gv-box",
366
+ width: n.width,
367
+ height: n.height,
368
+ rx: 4,
369
+ style: view?.fill ? { fill: view.fill } : void 0
370
+ }
371
+ ),
372
+ toggle > 0 && /* @__PURE__ */ jsx(Toggle, { x: m.paddingX - 4, y: n.height / 2, open: !collapsed }),
373
+ /* @__PURE__ */ jsx("text", { className: "gv-label", x: m.paddingX + toggle, y: labelY, children: text.label }),
374
+ text.detail && /* @__PURE__ */ jsx("text", { className: "gv-detail", x: m.paddingX + toggle, y: n.height / 2 + 11, children: text.detail }),
375
+ text.badge && /* @__PURE__ */ jsx(
376
+ Badge,
377
+ {
378
+ x: n.width - m.paddingX - text.badgeWidth,
379
+ y: n.height / 2 - 8,
380
+ width: text.badgeWidth,
381
+ text: text.badge
382
+ }
383
+ )
384
+ ]
385
+ },
386
+ i
387
+ );
388
+ }) });
389
+ });
390
+ var EdgesLayer = memo(function EdgesLayer2({ model, visible, scope, clickable }) {
391
+ graphViewRenderCounts.edges++;
392
+ return /* @__PURE__ */ jsx("g", { className: "gv-edges", children: model.layout.edges.map((e, k) => {
393
+ if (visible && !visible.has(k)) return null;
394
+ const view = model.edgeView[k];
395
+ const tone = model.edgeTone[k];
396
+ const marker = `url(#${scope}-arrow-${tone})`;
397
+ return /* @__PURE__ */ jsxs(
398
+ "g",
399
+ {
400
+ className: joinClass("gv-edge", view?.className),
401
+ "data-e": k,
402
+ "data-tone": tone !== "neutral" ? tone : void 0,
403
+ "data-dashed": view?.dashed ? "" : void 0,
404
+ children: [
405
+ view?.title && /* @__PURE__ */ jsx("title", { children: view.title }),
406
+ /* @__PURE__ */ jsx(
407
+ "path",
408
+ {
409
+ className: "gv-line",
410
+ d: model.edgePath[k],
411
+ style: { strokeWidth: model.edgeWidth[k] },
412
+ markerEnd: marker,
413
+ markerStart: view?.bidirectional ? marker : void 0
414
+ }
415
+ ),
416
+ clickable && /* @__PURE__ */ jsx("path", { className: "gv-hit", d: model.edgePath[k] })
417
+ ]
418
+ },
419
+ k
420
+ );
421
+ }) });
422
+ });
423
+ function Toggle({ x, y, open }) {
424
+ return /* @__PURE__ */ jsxs("g", { className: "gv-toggle", "data-toggle": "", transform: `translate(${x} ${y})`, children: [
425
+ /* @__PURE__ */ jsx("rect", { x: -4, y: -8, width: 16, height: 16 }),
426
+ /* @__PURE__ */ jsx("path", { d: open ? "M0 -2 L4 2 L8 -2" : "M2 -4 L6 0 L2 4" })
427
+ ] });
428
+ }
429
+ function Badge({ x, y, width, text }) {
430
+ return /* @__PURE__ */ jsxs("g", { className: "gv-badge", transform: `translate(${x} ${y})`, children: [
431
+ /* @__PURE__ */ jsx("rect", { width, height: 16, rx: 3 }),
432
+ /* @__PURE__ */ jsx("text", { x: width / 2, y: 11.5, textAnchor: "middle", children: text })
433
+ ] });
434
+ }
435
+ function hitTest(target) {
436
+ const el = target instanceof Element ? target : null;
437
+ const toggle = !!el?.closest("[data-toggle]");
438
+ const node = el?.closest("[data-i]");
439
+ if (node) return { kind: "node", i: Number(node.getAttribute("data-i")), toggle };
440
+ const edge = el?.closest("[data-e]");
441
+ if (edge) return { kind: "edge", k: Number(edge.getAttribute("data-e")) };
442
+ return { kind: "none" };
443
+ }
444
+ function cullKeyFor(t, size) {
445
+ const v = visibleRect(t, size);
446
+ const w = v.x1 - v.x0;
447
+ const h = v.y1 - v.y0;
448
+ const tile = 2 ** Math.ceil(Math.log2(Math.max(w, h, 1) / 2));
449
+ return [
450
+ tile,
451
+ Math.floor((v.x0 - w / 2) / tile),
452
+ Math.floor((v.y0 - h / 2) / tile),
453
+ Math.ceil((v.x1 + w / 2) / tile),
454
+ Math.ceil((v.y1 + h / 2) / tile)
455
+ ].join(":");
456
+ }
457
+ var DiagramViewer = forwardRef(
458
+ function DiagramViewer2(props, ref) {
459
+ const {
460
+ layout,
461
+ nodes,
462
+ edges,
463
+ selectedIds,
464
+ onSelectionChange,
465
+ onNodeActivate,
466
+ onContainerToggle,
467
+ onEdgeClick,
468
+ onHoverChange,
469
+ highlightIds,
470
+ hoverNeighbors = true,
471
+ wheel = "zoom",
472
+ cornerRadius = 6,
473
+ fitPadding = 24,
474
+ maxFitScale = 1.5,
475
+ controls = true,
476
+ ariaLabel,
477
+ describeNode,
478
+ initialSize,
479
+ className,
480
+ style
481
+ } = props;
482
+ const scope = `gv${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
483
+ const model = useMemo(
484
+ () => buildModel(layout, nodes, edges, cornerRadius),
485
+ [layout, nodes, edges, cornerRadius]
486
+ );
487
+ const rootRef = useRef(null);
488
+ const [size, setSize] = useState(initialSize ?? DEFAULT_SIZE);
489
+ const sizeRef = useRef(size);
490
+ sizeRef.current = size;
491
+ const [transform, setTransformState] = useState(
492
+ () => fitTransform(drawingBox(layout), initialSize ?? DEFAULT_SIZE, fitPadding, maxFitScale)
493
+ );
494
+ const transformRef = useRef(transform);
495
+ const setTransform = useCallback((t2) => {
496
+ transformRef.current = t2;
497
+ setTransformState(t2);
498
+ }, []);
499
+ const userMoved = useRef(false);
500
+ const anchor = useRef(null);
501
+ const [hover, setHover] = useState(null);
502
+ const [panning, setPanning] = useState(false);
503
+ const [announcement, setAnnouncement] = useState("");
504
+ const [ownSelection, setOwnSelection] = useState([]);
505
+ const selection = selectedIds ?? ownSelection;
506
+ const followIndex = useRef(0);
507
+ useLayoutEffect(() => {
508
+ const el = rootRef.current;
509
+ if (!el) return;
510
+ const measure = () => {
511
+ const r = el.getBoundingClientRect();
512
+ if (r.width <= 0 || r.height <= 0) return;
513
+ setSize(
514
+ (prev) => prev.width === r.width && prev.height === r.height ? prev : { width: r.width, height: r.height }
515
+ );
516
+ };
517
+ measure();
518
+ if (typeof ResizeObserver === "undefined") return;
519
+ const observer = new ResizeObserver(measure);
520
+ observer.observe(el);
521
+ return () => observer.disconnect();
522
+ }, []);
523
+ useLayoutEffect(() => {
524
+ const held = anchor.current;
525
+ anchor.current = null;
526
+ if (held && Date.now() - held.at < ANCHOR_TTL_MS) {
527
+ const i = model.indexOf.get(held.id);
528
+ if (i !== void 0) {
529
+ const n = model.layout.nodes[i];
530
+ const t2 = transformRef.current;
531
+ userMoved.current = true;
532
+ setTransform({ tx: held.x - n.x * t2.scale, ty: held.y - n.y * t2.scale, scale: t2.scale });
533
+ return;
534
+ }
535
+ }
536
+ if (userMoved.current) return;
537
+ setTransform(fitTransform(drawingBox(model.layout), size, fitPadding, maxFitScale));
538
+ }, [model, size, fitPadding, maxFitScale, setTransform]);
539
+ useEffect(() => {
540
+ setHover((h) => h !== null && h >= model.layout.nodes.length ? null : h);
541
+ }, [model]);
542
+ const moveView = useCallback(
543
+ (t2) => {
544
+ userMoved.current = true;
545
+ setTransform(t2);
546
+ },
547
+ [setTransform]
548
+ );
549
+ const fit = useCallback(() => {
550
+ userMoved.current = false;
551
+ setTransform(
552
+ fitTransform(drawingBox(model.layout), sizeRef.current, fitPadding, maxFitScale)
553
+ );
554
+ }, [model, fitPadding, maxFitScale, setTransform]);
555
+ const boxOf = useCallback(
556
+ (ids) => {
557
+ let x0 = Infinity;
558
+ let y0 = Infinity;
559
+ let x1 = -Infinity;
560
+ let y1 = -Infinity;
561
+ for (const id of ids) {
562
+ const i = model.indexOf.get(id);
563
+ if (i === void 0) continue;
564
+ const n = model.layout.nodes[i];
565
+ x0 = Math.min(x0, n.x);
566
+ y0 = Math.min(y0, n.y);
567
+ x1 = Math.max(x1, n.x + n.width);
568
+ y1 = Math.max(y1, n.y + n.height);
569
+ }
570
+ return Number.isFinite(x0) ? { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } : null;
571
+ },
572
+ [model]
573
+ );
574
+ const reveal = useCallback(
575
+ (id) => {
576
+ const box = boxOf([id]);
577
+ if (!box) return;
578
+ const t2 = transformRef.current;
579
+ const next = revealTransform(t2, box, sizeRef.current, fitPadding);
580
+ if (next.tx !== t2.tx || next.ty !== t2.ty) moveView(next);
581
+ },
582
+ [boxOf, moveView, fitPadding]
583
+ );
584
+ const keepInPlace = useCallback(
585
+ (id) => {
586
+ const i = model.indexOf.get(id);
587
+ if (i === void 0) return;
588
+ const n = model.layout.nodes[i];
589
+ const t2 = transformRef.current;
590
+ anchor.current = { id, x: n.x * t2.scale + t2.tx, y: n.y * t2.scale + t2.ty, at: Date.now() };
591
+ },
592
+ [model]
593
+ );
594
+ const zoomBy = useCallback(
595
+ (factor) => {
596
+ const s = sizeRef.current;
597
+ moveView(zoomAt(transformRef.current, factor, s.width / 2, s.height / 2));
598
+ },
599
+ [moveView]
600
+ );
601
+ useImperativeHandle(
602
+ ref,
603
+ () => ({
604
+ fit,
605
+ focus: (ids) => {
606
+ const box = boxOf(ids);
607
+ if (box)
608
+ moveView(fitTransform(box, sizeRef.current, fitPadding * 2, Math.max(1, maxFitScale)));
609
+ },
610
+ reveal,
611
+ keepInPlace,
612
+ zoomBy
613
+ }),
614
+ [fit, boxOf, moveView, fitPadding, maxFitScale, reveal, keepInPlace, zoomBy]
615
+ );
616
+ const select = useCallback(
617
+ (ids) => {
618
+ if (!selectedIds) setOwnSelection(ids);
619
+ onSelectionChange?.(ids);
620
+ },
621
+ [selectedIds, onSelectionChange]
622
+ );
623
+ const announce = useCallback(
624
+ (i) => {
625
+ const id = model.layout.nodes[i].id;
626
+ setAnnouncement(describeNode?.(id) ?? model.nodeView[i]?.label ?? id);
627
+ },
628
+ [model, describeNode]
629
+ );
630
+ useEffect(() => {
631
+ const el = rootRef.current;
632
+ if (!el) return;
633
+ const onWheel = (e) => {
634
+ if (wheel === "scroll-unless-modifier" && !(e.ctrlKey || e.metaKey)) return;
635
+ e.preventDefault();
636
+ const r = el.getBoundingClientRect();
637
+ const step = e.deltaMode === 1 ? 0.05 : e.deltaMode === 2 ? 1 : 15e-4;
638
+ moveView(
639
+ zoomAt(
640
+ transformRef.current,
641
+ Math.exp(-e.deltaY * step),
642
+ e.clientX - r.left,
643
+ e.clientY - r.top
644
+ )
645
+ );
646
+ };
647
+ el.addEventListener("wheel", onWheel, { passive: false });
648
+ return () => el.removeEventListener("wheel", onWheel);
649
+ }, [wheel, moveView]);
650
+ const drag = useRef(null);
651
+ const onPointerDown = (e) => {
652
+ if (e.button > 0) return;
653
+ rootRef.current?.focus({ preventScroll: true });
654
+ const t2 = transformRef.current;
655
+ drag.current = {
656
+ pointer: e.pointerId,
657
+ x: e.clientX,
658
+ y: e.clientY,
659
+ tx: t2.tx,
660
+ ty: t2.ty,
661
+ moved: false,
662
+ hit: hitTest(e.target),
663
+ additive: e.shiftKey || e.metaKey || e.ctrlKey
664
+ };
665
+ };
666
+ const onPointerMove = (e) => {
667
+ const d = drag.current;
668
+ if (!d || d.pointer !== e.pointerId) return;
669
+ const dx = e.clientX - d.x;
670
+ const dy = e.clientY - d.y;
671
+ if (!d.moved && Math.hypot(dx, dy) < DRAG_SLOP) return;
672
+ if (!d.moved) {
673
+ d.moved = true;
674
+ setPanning(true);
675
+ setHover(null);
676
+ try {
677
+ e.currentTarget.setPointerCapture(e.pointerId);
678
+ } catch {
679
+ }
680
+ }
681
+ moveView({ tx: d.tx + dx, ty: d.ty + dy, scale: transformRef.current.scale });
682
+ };
683
+ const onPointerUp = (e) => {
684
+ const d = drag.current;
685
+ if (!d || d.pointer !== e.pointerId) return;
686
+ drag.current = null;
687
+ setPanning(false);
688
+ if (d.moved) return;
689
+ const hit = d.hit;
690
+ if (hit.kind === "node") {
691
+ const id = model.layout.nodes[hit.i]?.id;
692
+ if (id === void 0) return;
693
+ const view = model.nodeView[hit.i];
694
+ if (hit.toggle && view?.expandable) {
695
+ keepInPlace(id);
696
+ onContainerToggle?.(id, !view.expanded);
697
+ return;
698
+ }
699
+ if (d.additive) {
700
+ select(selection.includes(id) ? selection.filter((s) => s !== id) : [...selection, id]);
701
+ } else {
702
+ select([id]);
703
+ }
704
+ announce(hit.i);
705
+ } else if (hit.kind === "edge") {
706
+ const id = model.layout.edges[hit.k]?.id;
707
+ if (id !== void 0) onEdgeClick?.(id);
708
+ } else if (selection.length > 0) {
709
+ select([]);
710
+ }
711
+ };
712
+ const onDoubleClick = (e) => {
713
+ const hit = hitTest(e.target);
714
+ if (hit.kind !== "node" || hit.toggle) return;
715
+ const n = model.layout.nodes[hit.i];
716
+ if (n && !n.container) onNodeActivate?.(n.id);
717
+ };
718
+ const onPointerOver = (e) => {
719
+ if (drag.current?.moved) return;
720
+ const hit = hitTest(e.target);
721
+ const next = hit.kind === "node" && !model.layout.nodes[hit.i]?.container ? hit.i : null;
722
+ if (next === hover) return;
723
+ setHover(next);
724
+ onHoverChange?.(next === null ? null : model.layout.nodes[next].id);
725
+ };
726
+ const onPointerLeave = () => {
727
+ if (hover === null) return;
728
+ setHover(null);
729
+ onHoverChange?.(null);
730
+ };
731
+ const selectedIndex = () => {
732
+ const id = selection[selection.length - 1];
733
+ const i = id === void 0 ? void 0 : model.indexOf.get(id);
734
+ return i === void 0 ? null : i;
735
+ };
736
+ const center = (i) => {
737
+ const n = model.layout.nodes[i];
738
+ return { x: n.x + n.width / 2, y: n.y + n.height / 2 };
739
+ };
740
+ const pickInDirection = (dx, dy) => {
741
+ const from = selectedIndex();
742
+ const origin = from !== null ? center(from) : (() => {
743
+ const v = visibleRect(transformRef.current, sizeRef.current);
744
+ return { x: (v.x0 + v.x1) / 2, y: (v.y0 + v.y1) / 2 };
745
+ })();
746
+ let best = null;
747
+ let bestScore = Infinity;
748
+ for (const i of model.leaves) {
749
+ if (i === from) continue;
750
+ const c = center(i);
751
+ const along = (c.x - origin.x) * dx + (c.y - origin.y) * dy;
752
+ const across = Math.abs((c.x - origin.x) * dy - (c.y - origin.y) * dx);
753
+ if (from !== null && along <= 0) continue;
754
+ const score = from === null ? Math.hypot(c.x - origin.x, c.y - origin.y) : along + across * 2;
755
+ if (score < bestScore) {
756
+ bestScore = score;
757
+ best = i;
758
+ }
759
+ }
760
+ return best;
761
+ };
762
+ const choose = (i) => {
763
+ const id = model.layout.nodes[i].id;
764
+ select([id]);
765
+ announce(i);
766
+ reveal(id);
767
+ };
768
+ const onKeyDown = (e) => {
769
+ if (e.target !== e.currentTarget) return;
770
+ const arrows = {
771
+ ArrowLeft: [-1, 0],
772
+ ArrowRight: [1, 0],
773
+ ArrowUp: [0, -1],
774
+ ArrowDown: [0, 1]
775
+ };
776
+ const arrow = arrows[e.key];
777
+ if (arrow) {
778
+ e.preventDefault();
779
+ const next = pickInDirection(arrow[0], arrow[1]);
780
+ if (next !== null) choose(next);
781
+ return;
782
+ }
783
+ const current = selectedIndex();
784
+ switch (e.key) {
785
+ case "]":
786
+ case "[": {
787
+ if (current === null) return;
788
+ const list = e.key === "]" ? model.successors[current] : model.predecessors[current];
789
+ if (list.length === 0) return;
790
+ e.preventDefault();
791
+ choose(list[followIndex.current++ % list.length]);
792
+ return;
793
+ }
794
+ case "Enter":
795
+ if (current !== null && !model.layout.nodes[current].container) {
796
+ e.preventDefault();
797
+ onNodeActivate?.(model.layout.nodes[current].id);
798
+ }
799
+ return;
800
+ case " ": {
801
+ const view = current === null ? void 0 : model.nodeView[current];
802
+ if (current !== null && view?.expandable) {
803
+ e.preventDefault();
804
+ keepInPlace(model.layout.nodes[current].id);
805
+ onContainerToggle?.(model.layout.nodes[current].id, !view.expanded);
806
+ }
807
+ return;
808
+ }
809
+ case "Escape":
810
+ if (selection.length > 0) {
811
+ e.preventDefault();
812
+ select([]);
813
+ }
814
+ return;
815
+ case "f":
816
+ case "0":
817
+ e.preventDefault();
818
+ fit();
819
+ return;
820
+ case "+":
821
+ case "=":
822
+ e.preventDefault();
823
+ zoomBy(1.25);
824
+ return;
825
+ case "-":
826
+ e.preventDefault();
827
+ zoomBy(0.8);
828
+ return;
829
+ default:
830
+ followIndex.current = 0;
831
+ }
832
+ };
833
+ const emphasis = useMemo(() => {
834
+ if (hover !== null && hoverNeighbors) {
835
+ const nodesOn = /* @__PURE__ */ new Set([hover]);
836
+ const edgesOn = /* @__PURE__ */ new Set();
837
+ for (const k of model.incident[hover] ?? []) {
838
+ edgesOn.add(k);
839
+ const e = model.layout.edges[k];
840
+ nodesOn.add(model.indexOf.get(e.source));
841
+ nodesOn.add(model.indexOf.get(e.target));
842
+ }
843
+ return { nodes: nodesOn, edges: edgesOn };
844
+ }
845
+ if (highlightIds && highlightIds.length > 0) {
846
+ const nodesOn = /* @__PURE__ */ new Set();
847
+ for (const id of highlightIds) {
848
+ const i = model.indexOf.get(id);
849
+ if (i !== void 0) nodesOn.add(i);
850
+ }
851
+ const edgesOn = /* @__PURE__ */ new Set();
852
+ model.layout.edges.forEach((e, k) => {
853
+ if (nodesOn.has(model.indexOf.get(e.source)) && nodesOn.has(model.indexOf.get(e.target)))
854
+ edgesOn.add(k);
855
+ });
856
+ return { nodes: nodesOn, edges: edgesOn };
857
+ }
858
+ return null;
859
+ }, [hover, hoverNeighbors, highlightIds, model]);
860
+ const dynamicCss = useMemo(() => {
861
+ let css = "";
862
+ const chosen = selection.map((id) => model.indexOf.get(id)).filter((i) => i !== void 0);
863
+ if (chosen.length > 0) {
864
+ const list = chosen.map((i) => `[data-i="${i}"]`).join(",");
865
+ css += `.${scope} :is(${list})>:is(.gv-box,.gv-frame){stroke:var(--squisq-graph-selected,var(--squisq-graph-tone-accent,#2563eb));stroke-width:2.5px}`;
866
+ }
867
+ if (emphasis && (emphasis.nodes.size > 0 || emphasis.edges.size > 0)) {
868
+ const list = [
869
+ ...[...emphasis.nodes].map((i) => `[data-i="${i}"]`),
870
+ ...[...emphasis.edges].map((k) => `[data-e="${k}"]`)
871
+ ].join(",");
872
+ css += `.${scope}[data-dim] :is(${list}){opacity:1}`;
873
+ }
874
+ return css;
875
+ }, [selection, emphasis, model, scope]);
876
+ const culling = model.layout.nodes.length > GRAPH_VIEW_CULL_AT;
877
+ const cullKey = culling ? cullKeyFor(transform, size) : "";
878
+ const visible = useMemo(() => {
879
+ if (!culling) return null;
880
+ const [tile, qx0, qy0, qx1, qy1] = cullKey.split(":").map(Number);
881
+ const x0 = qx0 * tile;
882
+ const y0 = qy0 * tile;
883
+ const x1 = qx1 * tile;
884
+ const y1 = qy1 * tile;
885
+ return {
886
+ nodes: new Set(model.nodeIndex.query(x0, y0, x1, y1)),
887
+ edges: new Set(model.edgeIndex.query(x0, y0, x1, y1))
888
+ };
889
+ }, [culling, cullKey, model]);
890
+ const lod = transform.scale < LOD_LABELS ? 0 : transform.scale < LOD_DETAILS ? 1 : 2;
891
+ const t = transform;
892
+ return /* @__PURE__ */ jsxs(
893
+ "div",
894
+ {
895
+ ref: rootRef,
896
+ className: joinClass("squisq-graph-view", scope, `gv-lod-${lod}`, className),
897
+ style,
898
+ tabIndex: 0,
899
+ role: "group",
900
+ "aria-roledescription": "diagram",
901
+ "aria-label": ariaLabel,
902
+ "data-dim": emphasis ? "" : void 0,
903
+ "data-panning": panning ? "" : void 0,
904
+ onKeyDown,
905
+ children: [
906
+ /* @__PURE__ */ jsx("style", { children: GRAPH_VIEW_CSS }),
907
+ /* @__PURE__ */ jsx("style", { children: dynamicCss }),
908
+ /* @__PURE__ */ jsxs(
909
+ "svg",
910
+ {
911
+ "aria-hidden": "true",
912
+ onPointerDown,
913
+ onPointerMove,
914
+ onPointerUp,
915
+ onPointerCancel: onPointerUp,
916
+ onPointerOver,
917
+ onPointerLeave,
918
+ onDoubleClick,
919
+ children: [
920
+ /* @__PURE__ */ jsx("defs", { children: model.tones.map((tone) => /* @__PURE__ */ jsx(
921
+ "marker",
922
+ {
923
+ id: `${scope}-arrow-${tone}`,
924
+ viewBox: "0 0 10 10",
925
+ refX: 9,
926
+ refY: 5,
927
+ markerWidth: 7,
928
+ markerHeight: 7,
929
+ markerUnits: "userSpaceOnUse",
930
+ orient: "auto-start-reverse",
931
+ children: /* @__PURE__ */ jsx("path", { className: `gv-arrow-${tone}`, d: "M0,0 L10,5 L0,10 z" })
932
+ },
933
+ tone
934
+ )) }),
935
+ /* @__PURE__ */ jsxs("g", { className: "gv-world", transform: `translate(${t.tx} ${t.ty}) scale(${t.scale})`, children: [
936
+ /* @__PURE__ */ jsx(ContainersLayer, { model, visible: visible?.nodes ?? null }),
937
+ /* @__PURE__ */ jsx(
938
+ EdgesLayer,
939
+ {
940
+ model,
941
+ visible: visible?.edges ?? null,
942
+ scope,
943
+ clickable: !!onEdgeClick
944
+ }
945
+ ),
946
+ /* @__PURE__ */ jsx(NodesLayer, { model, visible: visible?.nodes ?? null })
947
+ ] })
948
+ ]
949
+ }
950
+ ),
951
+ controls && /* @__PURE__ */ jsxs(
952
+ "div",
953
+ {
954
+ className: "gv-controls",
955
+ role: "toolbar",
956
+ "aria-label": "Zoom",
957
+ onPointerDown: (e) => e.stopPropagation(),
958
+ children: [
959
+ /* @__PURE__ */ jsx(
960
+ "button",
961
+ {
962
+ type: "button",
963
+ "aria-label": "Zoom out",
964
+ title: "Zoom out",
965
+ onClick: () => zoomBy(0.8),
966
+ children: "\u2212"
967
+ }
968
+ ),
969
+ /* @__PURE__ */ jsxs("output", { "aria-label": "Zoom level", children: [
970
+ Math.round(t.scale * 100),
971
+ "%"
972
+ ] }),
973
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": "Zoom in", title: "Zoom in", onClick: () => zoomBy(1.25), children: "+" }),
974
+ /* @__PURE__ */ jsx(
975
+ "button",
976
+ {
977
+ type: "button",
978
+ "aria-label": "Fit diagram",
979
+ title: "Fit the whole diagram",
980
+ onClick: fit,
981
+ children: "Fit"
982
+ }
983
+ )
984
+ ]
985
+ }
986
+ ),
987
+ /* @__PURE__ */ jsx("div", { className: "gv-live", "aria-live": "polite", children: announcement })
988
+ ]
989
+ }
990
+ );
991
+ }
992
+ );
993
+
994
+ // src/graph/useGraphLayout.ts
995
+ import { useEffect as useEffect2, useMemo as useMemo2, useState as useState2 } from "react";
996
+ import {
997
+ createInlineLayoutEngine,
998
+ graphSignature
999
+ } from "@bendyline/squisq-graph";
1000
+ var CACHE_LIMIT = 12;
1001
+ var cache = /* @__PURE__ */ new Map();
1002
+ var inlineEngine = null;
1003
+ function remember(signature, layout) {
1004
+ cache.delete(signature);
1005
+ cache.set(signature, layout);
1006
+ while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
1007
+ }
1008
+ function clearGraphLayoutCache() {
1009
+ cache.clear();
1010
+ }
1011
+ function useGraphLayout(graph, options, config = {}) {
1012
+ const signature = useMemo2(
1013
+ () => graph ? graphSignature(graph, options) : null,
1014
+ [graph, options]
1015
+ );
1016
+ const cached = signature ? cache.get(signature) : void 0;
1017
+ const [settled, setSettled] = useState2({ signature: null, layout: null, error: null });
1018
+ const [slow, setSlow] = useState2(false);
1019
+ const { engine, slowAfterMs = 150 } = config;
1020
+ useEffect2(() => {
1021
+ if (!graph || !signature) return;
1022
+ const hit = cache.get(signature);
1023
+ if (hit) {
1024
+ remember(signature, hit);
1025
+ setSettled({ signature, layout: hit, error: null });
1026
+ return;
1027
+ }
1028
+ const controller = new AbortController();
1029
+ const timer = setTimeout(() => setSlow(true), slowAfterMs);
1030
+ const runner = engine ?? (inlineEngine ?? (inlineEngine = createInlineLayoutEngine()));
1031
+ runner.layout(graph, options, { signal: controller.signal }).then(
1032
+ (layout) => {
1033
+ remember(signature, layout);
1034
+ if (!controller.signal.aborted) setSettled({ signature, layout, error: null });
1035
+ },
1036
+ (err) => {
1037
+ if (controller.signal.aborted) return;
1038
+ const error = err instanceof Error ? err : new Error(String(err));
1039
+ setSettled((prev) => ({ signature, layout: prev.layout, error }));
1040
+ }
1041
+ ).finally(() => {
1042
+ clearTimeout(timer);
1043
+ if (!controller.signal.aborted) setSlow(false);
1044
+ });
1045
+ return () => {
1046
+ controller.abort();
1047
+ clearTimeout(timer);
1048
+ setSlow(false);
1049
+ };
1050
+ }, [signature, engine, slowAfterMs]);
1051
+ const pending = signature !== null && !cached && settled.signature !== signature;
1052
+ return {
1053
+ layout: cached ?? settled.layout,
1054
+ pending,
1055
+ slow: pending && slow,
1056
+ error: !pending && settled.signature === signature ? settled.error : null,
1057
+ signature
1058
+ };
1059
+ }
1060
+ export {
1061
+ DiagramViewer,
1062
+ GRAPH_NODE_METRICS,
1063
+ GRAPH_TONE_NAMES,
1064
+ GRAPH_VIEW_CULL_AT,
1065
+ clearGraphLayoutCache,
1066
+ estimateTextWidth,
1067
+ fitTransform,
1068
+ graphNodeSize,
1069
+ revealTransform,
1070
+ truncateToWidth,
1071
+ useGraphLayout,
1072
+ visibleRect,
1073
+ zoomAt
1074
+ };