@stacksjs/components 0.2.855 → 0.2.857

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.
Files changed (100) hide show
  1. package/dist/ContextMenu-43g3w5tp.stx +188 -0
  2. package/dist/DataGrid-7rt7v865.stx +376 -0
  3. package/dist/GraphView-0t3t9mec.stx +320 -0
  4. package/dist/JsonTree-satc4010.stx +317 -0
  5. package/dist/PreviewFrame-erbgvzj8.stx +257 -0
  6. package/dist/SplitPane-7sqfdwqa.stx +159 -0
  7. package/dist/component-api/component-api.js +36 -0
  8. package/dist/context-menu/context-menu.js +575 -0
  9. package/dist/data-grid/data-grid.js +1244 -0
  10. package/dist/graph-view/graph-view.js +1408 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.js +22 -20
  13. package/dist/json-tree/json-tree.js +1121 -0
  14. package/dist/preview-frame/preview-frame.js +356 -0
  15. package/dist/split-pane/split-pane.js +364 -0
  16. package/dist/ui/context-menu/ContextMenu.d.ts +14 -0
  17. package/dist/ui/context-menu/context-menu.d.ts +8 -0
  18. package/dist/ui/context-menu/core.d.ts +74 -0
  19. package/dist/ui/context-menu/index.d.ts +11 -0
  20. package/dist/ui/context-menu/view.d.ts +36 -0
  21. package/dist/ui/data-grid/DataGrid.d.ts +30 -0
  22. package/dist/ui/data-grid/core.d.ts +141 -0
  23. package/dist/ui/data-grid/data-grid.d.ts +9 -0
  24. package/dist/ui/data-grid/index.d.ts +20 -0
  25. package/dist/ui/data-grid/view.d.ts +56 -0
  26. package/dist/ui/graph-view/GraphView.d.ts +21 -0
  27. package/dist/ui/graph-view/core/edges.d.ts +34 -0
  28. package/dist/ui/graph-view/core/force.d.ts +10 -0
  29. package/dist/ui/graph-view/core/graph.d.ts +83 -0
  30. package/dist/ui/graph-view/core/index.d.ts +5 -0
  31. package/dist/ui/graph-view/core/layered.d.ts +24 -0
  32. package/dist/ui/graph-view/core/viewport.d.ts +34 -0
  33. package/dist/ui/graph-view/graph-view.d.ts +9 -0
  34. package/dist/ui/graph-view/index.d.ts +21 -0
  35. package/dist/ui/graph-view/view.d.ts +51 -0
  36. package/dist/ui/json-tree/JsonTree.d.ts +18 -0
  37. package/dist/ui/json-tree/core.d.ts +108 -0
  38. package/dist/ui/json-tree/index.d.ts +18 -0
  39. package/dist/ui/json-tree/json-tree.d.ts +10 -0
  40. package/dist/ui/json-tree/tinker.d.ts +84 -0
  41. package/dist/ui/json-tree/view.d.ts +59 -0
  42. package/dist/ui/preview-frame/PreviewFrame.d.ts +44 -0
  43. package/dist/ui/preview-frame/core.d.ts +81 -0
  44. package/dist/ui/preview-frame/index.d.ts +19 -0
  45. package/dist/ui/preview-frame/preview-frame.d.ts +8 -0
  46. package/dist/ui/preview-frame/view.d.ts +37 -0
  47. package/dist/ui/split-pane/SplitPane.d.ts +18 -0
  48. package/dist/ui/split-pane/core.d.ts +58 -0
  49. package/dist/ui/split-pane/index.d.ts +15 -0
  50. package/dist/ui/split-pane/split-pane.d.ts +8 -0
  51. package/dist/ui/split-pane/view.d.ts +27 -0
  52. package/dist/ui/virtual-table/index.d.ts +6 -0
  53. package/dist/utils/component-api.d.ts +4 -0
  54. package/package.json +38 -3
  55. package/src/index.ts +8 -0
  56. package/src/ui/code-editor/README.md +2 -1
  57. package/src/ui/context-menu/ContextMenu.stx +188 -0
  58. package/src/ui/context-menu/README.md +117 -0
  59. package/src/ui/context-menu/context-menu.ts +8 -0
  60. package/src/ui/context-menu/core.ts +250 -0
  61. package/src/ui/context-menu/index.ts +16 -0
  62. package/src/ui/context-menu/view.ts +540 -0
  63. package/src/ui/data-grid/DataGrid.stx +376 -0
  64. package/src/ui/data-grid/README.md +204 -0
  65. package/src/ui/data-grid/core.ts +813 -0
  66. package/src/ui/data-grid/data-grid.ts +9 -0
  67. package/src/ui/data-grid/index.ts +34 -0
  68. package/src/ui/data-grid/view.ts +806 -0
  69. package/src/ui/graph-view/GraphView.stx +320 -0
  70. package/src/ui/graph-view/README.md +210 -0
  71. package/src/ui/graph-view/core/edges.ts +180 -0
  72. package/src/ui/graph-view/core/force.ts +237 -0
  73. package/src/ui/graph-view/core/graph.ts +277 -0
  74. package/src/ui/graph-view/core/index.ts +5 -0
  75. package/src/ui/graph-view/core/layered.ts +256 -0
  76. package/src/ui/graph-view/core/viewport.ts +141 -0
  77. package/src/ui/graph-view/graph-view.ts +9 -0
  78. package/src/ui/graph-view/index.ts +35 -0
  79. package/src/ui/graph-view/view.ts +809 -0
  80. package/src/ui/json-tree/JsonTree.stx +317 -0
  81. package/src/ui/json-tree/README.md +193 -0
  82. package/src/ui/json-tree/core.ts +588 -0
  83. package/src/ui/json-tree/index.ts +28 -0
  84. package/src/ui/json-tree/json-tree.ts +10 -0
  85. package/src/ui/json-tree/tinker.ts +349 -0
  86. package/src/ui/json-tree/view.ts +665 -0
  87. package/src/ui/preview-frame/PreviewFrame.stx +257 -0
  88. package/src/ui/preview-frame/README.md +107 -0
  89. package/src/ui/preview-frame/core.ts +195 -0
  90. package/src/ui/preview-frame/index.ts +31 -0
  91. package/src/ui/preview-frame/preview-frame.ts +8 -0
  92. package/src/ui/preview-frame/view.ts +336 -0
  93. package/src/ui/split-pane/README.md +87 -0
  94. package/src/ui/split-pane/SplitPane.stx +159 -0
  95. package/src/ui/split-pane/core.ts +200 -0
  96. package/src/ui/split-pane/index.ts +24 -0
  97. package/src/ui/split-pane/split-pane.ts +8 -0
  98. package/src/ui/split-pane/view.ts +305 -0
  99. package/src/ui/virtual-table/index.ts +6 -0
  100. package/src/utils/component-api.ts +72 -0
@@ -0,0 +1,1408 @@
1
+ // src/ui/graph-view/core/edges.ts
2
+ var round = (value) => Math.round(value * 100) / 100;
3
+ var at = (point) => `${round(point.x)} ${round(point.y)}`;
4
+ function clipToRect(centre, size, towards) {
5
+ const dx = towards.x - centre.x;
6
+ const dy = towards.y - centre.y;
7
+ if (dx === 0 && dy === 0)
8
+ return { x: centre.x, y: centre.y };
9
+ const scaleX = dx === 0 ? Number.POSITIVE_INFINITY : size.width / 2 / Math.abs(dx);
10
+ const scaleY = dy === 0 ? Number.POSITIVE_INFINITY : size.height / 2 / Math.abs(dy);
11
+ const scale = Math.min(scaleX, scaleY);
12
+ return { x: centre.x + dx * scale, y: centre.y + dy * scale };
13
+ }
14
+ function pullBack(end, from, inset) {
15
+ const dx = end.x - from.x;
16
+ const dy = end.y - from.y;
17
+ const length = Math.sqrt(dx * dx + dy * dy);
18
+ if (inset <= 0 || length <= inset)
19
+ return end;
20
+ return { x: end.x - dx / length * inset, y: end.y - dy / length * inset };
21
+ }
22
+ function selfLoopShape(centre, size, offset = 0) {
23
+ const reach = 26 + Math.abs(offset);
24
+ const start = { x: centre.x + size.width / 4, y: centre.y - size.height / 2 };
25
+ const end = { x: centre.x + size.width / 2, y: centre.y - size.height / 4 };
26
+ const one = { x: start.x, y: start.y - reach };
27
+ const two = { x: end.x + reach, y: end.y };
28
+ return {
29
+ d: `M ${at(start)} C ${at(one)}, ${at(two)}, ${at(end)}`,
30
+ start,
31
+ end,
32
+ label: cubicAt(start, one, two, end, 0.5),
33
+ angle: Math.atan2(end.y - two.y, end.x - two.x)
34
+ };
35
+ }
36
+ function cubicAt(a, b, c, d, t) {
37
+ const u = 1 - t;
38
+ return {
39
+ x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,
40
+ y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y
41
+ };
42
+ }
43
+ function edgeShape(ends, options = {}) {
44
+ const { source, sourceSize, target, targetSize } = ends;
45
+ const offset = options.offset ?? 0;
46
+ const inset = options.inset ?? 0;
47
+ if (source.x === target.x && source.y === target.y)
48
+ return selfLoopShape(source, sourceSize, offset);
49
+ if (options.curve === "bezier") {
50
+ const horizontal = options.direction !== "TB";
51
+ const sign = (horizontal ? target.x - source.x : target.y - source.y) >= 0 ? 1 : -1;
52
+ const start = horizontal ? { x: source.x + sign * sourceSize.width / 2, y: source.y } : { x: source.x, y: source.y + sign * sourceSize.height / 2 };
53
+ const tip = horizontal ? { x: target.x - sign * targetSize.width / 2, y: target.y } : { x: target.x, y: target.y - sign * targetSize.height / 2 };
54
+ const span = Math.abs(horizontal ? tip.x - start.x : tip.y - start.y);
55
+ const handle = Math.max(span / 2, 24) * sign;
56
+ const end = horizontal ? { x: tip.x - sign * inset, y: tip.y } : { x: tip.x, y: tip.y - sign * inset };
57
+ const one = horizontal ? { x: start.x + handle, y: start.y + offset } : { x: start.x + offset, y: start.y + handle };
58
+ const two = horizontal ? { x: end.x - handle, y: end.y + offset } : { x: end.x + offset, y: end.y - handle };
59
+ return {
60
+ d: `M ${at(start)} C ${at(one)}, ${at(two)}, ${at(end)}`,
61
+ start,
62
+ end,
63
+ label: cubicAt(start, one, two, end, 0.5),
64
+ angle: Math.atan2(end.y - two.y, end.x - two.x)
65
+ };
66
+ }
67
+ const start = clipToRect(source, sourceSize, target);
68
+ const tip = clipToRect(target, targetSize, source);
69
+ if (offset === 0) {
70
+ const end = pullBack(tip, start, inset);
71
+ return {
72
+ d: `M ${at(start)} L ${at(end)}`,
73
+ start,
74
+ end,
75
+ label: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 },
76
+ angle: Math.atan2(end.y - start.y, end.x - start.x)
77
+ };
78
+ }
79
+ const flip = source.x < target.x || source.x === target.x && source.y < target.y ? 1 : -1;
80
+ const dx = (target.x - source.x) * flip;
81
+ const dy = (target.y - source.y) * flip;
82
+ const length = Math.sqrt(dx * dx + dy * dy) || 1;
83
+ const control = { x: (start.x + tip.x) / 2 + -dy / length * offset * 2, y: (start.y + tip.y) / 2 + dx / length * offset * 2 };
84
+ const end = pullBack(tip, control, inset);
85
+ return {
86
+ d: `M ${at(start)} Q ${at(control)}, ${at(end)}`,
87
+ start,
88
+ end,
89
+ label: { x: 0.25 * start.x + 0.5 * control.x + 0.25 * end.x, y: 0.25 * start.y + 0.5 * control.y + 0.25 * end.y },
90
+ angle: Math.atan2(end.y - control.y, end.x - control.x)
91
+ };
92
+ }
93
+ function parallelOffsets(edges, spacing = 14) {
94
+ const groups = new Map;
95
+ for (const edge of edges) {
96
+ const key = edge.source < edge.target ? `${edge.source}\x00${edge.target}` : `${edge.target}\x00${edge.source}`;
97
+ const group = groups.get(key);
98
+ if (group)
99
+ group.push(edge);
100
+ else
101
+ groups.set(key, [edge]);
102
+ }
103
+ const offsets = new Map;
104
+ for (const group of groups.values()) {
105
+ if (group.length < 2)
106
+ continue;
107
+ group.forEach((edge, position) => {
108
+ const shift = (position - (group.length - 1) / 2) * spacing;
109
+ offsets.set(edge.id, edge.source === edge.target ? position * spacing : shift);
110
+ });
111
+ }
112
+ return offsets;
113
+ }
114
+
115
+ // src/ui/graph-view/core/graph.ts
116
+ var defaultNodeMetrics = {
117
+ charWidth: 7,
118
+ paddingX: 12,
119
+ minWidth: 48,
120
+ maxWidth: 220,
121
+ height: 32,
122
+ detailHeight: 14
123
+ };
124
+ function labelOf(node) {
125
+ return node.label == null || node.label === "" ? node.id : String(node.label);
126
+ }
127
+ function edgeIdOf(edge) {
128
+ return edge.id != null && edge.id !== "" ? String(edge.id) : `${edge.source}->${edge.target}${edge.label ? `:${edge.label}` : ""}`;
129
+ }
130
+ function nodeSize(node, metrics = defaultNodeMetrics) {
131
+ const longest = Math.max(labelOf(node).length, node.detail ? node.detail.length * 0.85 : 0);
132
+ const mark = node.expandable === true ? metrics.charWidth + 4 : 0;
133
+ const width = Math.min(metrics.maxWidth, Math.max(metrics.minWidth, Math.ceil(longest * metrics.charWidth) + metrics.paddingX * 2 + mark));
134
+ return { width, height: metrics.height + (node.detail ? metrics.detailHeight : 0) };
135
+ }
136
+ function maxLabelLength(metrics = defaultNodeMetrics) {
137
+ return Math.floor((metrics.maxWidth - metrics.paddingX * 2) / metrics.charWidth);
138
+ }
139
+ function fitLabel(text, limit) {
140
+ return text.length <= limit ? text : `${text.slice(0, Math.max(1, limit - 1))}…`;
141
+ }
142
+
143
+ class GraphModel {
144
+ metrics;
145
+ nodeMap = new Map;
146
+ edgeMap = new Map;
147
+ incident = new Map;
148
+ sizes = new Map;
149
+ constructor(nodes = [], edges = [], metrics = defaultNodeMetrics) {
150
+ this.metrics = metrics;
151
+ this.merge(nodes, edges);
152
+ }
153
+ get nodes() {
154
+ return [...this.nodeMap.values()];
155
+ }
156
+ get edges() {
157
+ return [...this.edgeMap.values()];
158
+ }
159
+ get nodeCount() {
160
+ return this.nodeMap.size;
161
+ }
162
+ get edgeCount() {
163
+ return this.edgeMap.size;
164
+ }
165
+ has(id) {
166
+ return this.nodeMap.has(id);
167
+ }
168
+ node(id) {
169
+ return this.nodeMap.get(id);
170
+ }
171
+ edge(id) {
172
+ return this.edgeMap.get(id);
173
+ }
174
+ addNode(node) {
175
+ if (!node || node.id == null || node.id === "")
176
+ return false;
177
+ const id = String(node.id);
178
+ if (this.nodeMap.has(id))
179
+ return false;
180
+ const kept = { ...node, id };
181
+ this.nodeMap.set(id, kept);
182
+ this.incident.set(id, new Set);
183
+ this.sizes.set(id, nodeSize(kept, this.metrics));
184
+ return true;
185
+ }
186
+ addEdge(edge) {
187
+ if (!edge)
188
+ return false;
189
+ const source = String(edge.source);
190
+ const target = String(edge.target);
191
+ if (!this.nodeMap.has(source) || !this.nodeMap.has(target))
192
+ return false;
193
+ const id = edgeIdOf({ ...edge, source, target });
194
+ if (this.edgeMap.has(id))
195
+ return false;
196
+ this.edgeMap.set(id, { ...edge, id, source, target });
197
+ this.incident.get(source).add(id);
198
+ this.incident.get(target).add(id);
199
+ return true;
200
+ }
201
+ updateNode(id, patch) {
202
+ const node = this.nodeMap.get(id);
203
+ if (!node)
204
+ return false;
205
+ const next = { ...node, ...patch, id };
206
+ this.nodeMap.set(id, next);
207
+ this.sizes.set(id, nodeSize(next, this.metrics));
208
+ return true;
209
+ }
210
+ removeNode(id) {
211
+ if (!this.nodeMap.has(id))
212
+ return false;
213
+ for (const edgeId of [...this.incident.get(id)])
214
+ this.removeEdge(edgeId);
215
+ this.nodeMap.delete(id);
216
+ this.incident.delete(id);
217
+ this.sizes.delete(id);
218
+ return true;
219
+ }
220
+ removeEdge(id) {
221
+ const edge = this.edgeMap.get(id);
222
+ if (!edge)
223
+ return false;
224
+ this.edgeMap.delete(id);
225
+ this.incident.get(edge.source)?.delete(id);
226
+ this.incident.get(edge.target)?.delete(id);
227
+ return true;
228
+ }
229
+ merge(nodes = [], edges = []) {
230
+ const added = { nodes: [], edges: [] };
231
+ for (const node of nodes) {
232
+ if (this.addNode(node))
233
+ added.nodes.push(String(node.id));
234
+ }
235
+ for (const edge of edges) {
236
+ if (this.addEdge(edge))
237
+ added.edges.push(edgeIdOf({ ...edge, source: String(edge.source), target: String(edge.target) }));
238
+ }
239
+ return added;
240
+ }
241
+ edgesOf(id) {
242
+ const ids = this.incident.get(id);
243
+ return ids ? [...ids].map((edgeId) => this.edgeMap.get(edgeId)) : [];
244
+ }
245
+ neighbours(id) {
246
+ const seen = new Set;
247
+ for (const edge of this.edgesOf(id)) {
248
+ const other = edge.source === id ? edge.target : edge.source;
249
+ if (other !== id)
250
+ seen.add(other);
251
+ }
252
+ return [...seen];
253
+ }
254
+ degree(id) {
255
+ return this.neighbours(id).length;
256
+ }
257
+ size(id) {
258
+ return this.sizes.get(id) ?? { width: this.metrics.minWidth, height: this.metrics.height };
259
+ }
260
+ bounds(positions) {
261
+ let left = Number.POSITIVE_INFINITY;
262
+ let top = Number.POSITIVE_INFINITY;
263
+ let right = Number.NEGATIVE_INFINITY;
264
+ let bottom = Number.NEGATIVE_INFINITY;
265
+ for (const [id, point] of positions) {
266
+ if (!this.nodeMap.has(id))
267
+ continue;
268
+ const size = this.size(id);
269
+ left = Math.min(left, point.x - size.width / 2);
270
+ right = Math.max(right, point.x + size.width / 2);
271
+ top = Math.min(top, point.y - size.height / 2);
272
+ bottom = Math.max(bottom, point.y + size.height / 2);
273
+ }
274
+ return Number.isFinite(left) ? { x: left, y: top, width: right - left, height: bottom - top } : null;
275
+ }
276
+ }
277
+ function seededRandom(seed) {
278
+ let state = seed >>> 0 || 1;
279
+ return () => {
280
+ state = state + 1831565813 >>> 0;
281
+ let t = state;
282
+ t = Math.imul(t ^ t >>> 15, t | 1);
283
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
284
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
285
+ };
286
+ }
287
+
288
+ // src/ui/graph-view/core/force.ts
289
+ var REPULSION = 0.15;
290
+ var GRAVITY = 0.06;
291
+ function forceLayout(graph, options = {}) {
292
+ const nodes = graph.nodes;
293
+ const count = nodes.length;
294
+ const result = new Map;
295
+ if (count === 0)
296
+ return result;
297
+ const distance = options.linkDistance ?? 90;
298
+ const padding = options.padding ?? 16;
299
+ const random = seededRandom(options.seed ?? 1);
300
+ const given = options.positions ?? null;
301
+ const pinned = new Set(options.pinned ?? []);
302
+ const index = new Map(nodes.map((node, position) => [node.id, position]));
303
+ const x = new Float64Array(count);
304
+ const y = new Float64Array(count);
305
+ const halfWidth = new Float64Array(count);
306
+ const halfHeight = new Float64Array(count);
307
+ const fixed = new Uint8Array(count);
308
+ const placed = new Uint8Array(count);
309
+ const mobility = new Float64Array(count).fill(1);
310
+ let known = 0;
311
+ nodes.forEach((node, position) => {
312
+ const size = graph.size(node.id);
313
+ halfWidth[position] = size.width / 2;
314
+ halfHeight[position] = size.height / 2;
315
+ const at = given?.get(node.id);
316
+ if (at && Number.isFinite(at.x) && Number.isFinite(at.y)) {
317
+ x[position] = at.x;
318
+ y[position] = at.y;
319
+ placed[position] = 1;
320
+ fixed[position] = pinned.has(node.id) ? 1 : 0;
321
+ mobility[position] = 0;
322
+ known++;
323
+ }
324
+ });
325
+ const radius = distance * Math.sqrt(count) * 0.6;
326
+ nodes.forEach((node, position) => {
327
+ if (placed[position])
328
+ return;
329
+ const anchor = graph.neighbours(node.id).map((id) => index.get(id)).find((other) => placed[other]);
330
+ const angle = random() * Math.PI * 2;
331
+ if (anchor !== undefined) {
332
+ x[position] = x[anchor] + Math.cos(angle) * distance * 0.5;
333
+ y[position] = y[anchor] + Math.sin(angle) * distance * 0.5;
334
+ } else {
335
+ const reach = Math.sqrt(random()) * radius;
336
+ x[position] = Math.cos(angle) * reach;
337
+ y[position] = Math.sin(angle) * reach;
338
+ }
339
+ });
340
+ const settled = Uint8Array.from(placed);
341
+ const warm = known > 0;
342
+ const iterations = Math.max(0, options.iterations ?? (warm ? 80 : 300));
343
+ const links = [];
344
+ const seen = new Set;
345
+ for (const edge of graph.edges) {
346
+ const a = index.get(edge.source);
347
+ const b = index.get(edge.target);
348
+ if (a === b)
349
+ continue;
350
+ const key = a < b ? a * count + b : b * count + a;
351
+ if (!seen.has(key)) {
352
+ seen.add(key);
353
+ links.push(a, b);
354
+ }
355
+ }
356
+ const dx = new Float64Array(count);
357
+ const dy = new Float64Array(count);
358
+ const k = distance;
359
+ const start = warm ? k * 0.5 : k * 1.5;
360
+ for (let pass = 0;pass < iterations; pass++) {
361
+ const temperature = start * (1 - pass / iterations);
362
+ dx.fill(0);
363
+ dy.fill(0);
364
+ for (let a = 0;a < count; a++) {
365
+ for (let b = a + 1;b < count; b++) {
366
+ if (settled[a] && settled[b])
367
+ continue;
368
+ let ox = x[a] - x[b];
369
+ let oy = y[a] - y[b];
370
+ let length = Math.sqrt(ox * ox + oy * oy);
371
+ if (length < 0.01) {
372
+ const angle = (a * 31 + b * 17) % 360 * Math.PI / 180;
373
+ ox = Math.cos(angle) * 0.01;
374
+ oy = Math.sin(angle) * 0.01;
375
+ length = 0.01;
376
+ }
377
+ const reach = Math.max(1, length - (halfWidth[a] + halfWidth[b]) * 0.5);
378
+ const push = k * k * REPULSION / reach / length;
379
+ dx[a] += ox * push;
380
+ dy[a] += oy * push;
381
+ dx[b] -= ox * push;
382
+ dy[b] -= oy * push;
383
+ }
384
+ }
385
+ for (let link = 0;link < links.length; link += 2) {
386
+ const a = links[link];
387
+ const b = links[link + 1];
388
+ if (settled[a] && settled[b])
389
+ continue;
390
+ const ox = x[a] - x[b];
391
+ const oy = y[a] - y[b];
392
+ const length = Math.sqrt(ox * ox + oy * oy) || 0.01;
393
+ const rest = (halfWidth[a] + halfWidth[b]) * 0.5;
394
+ const stretch = Math.max(0, length - rest);
395
+ const pull = stretch * stretch / k / length;
396
+ dx[a] -= ox * pull;
397
+ dy[a] -= oy * pull;
398
+ dx[b] += ox * pull;
399
+ dy[b] += oy * pull;
400
+ }
401
+ for (let node = 0;node < count; node++) {
402
+ if (fixed[node])
403
+ continue;
404
+ if (!settled[node]) {
405
+ dx[node] -= x[node] * GRAVITY;
406
+ dy[node] -= y[node] * GRAVITY;
407
+ }
408
+ const length = Math.sqrt(dx[node] * dx[node] + dy[node] * dy[node]);
409
+ if (length > 0) {
410
+ const step = Math.min(length, temperature) / length * mobility[node];
411
+ x[node] += dx[node] * step;
412
+ y[node] += dy[node] * step;
413
+ }
414
+ }
415
+ }
416
+ separate(x, y, halfWidth, halfHeight, fixed, padding);
417
+ nodes.forEach((node, position) => {
418
+ result.set(node.id, { x: Math.round(x[position] * 100) / 100, y: Math.round(y[position] * 100) / 100 });
419
+ });
420
+ return result;
421
+ }
422
+ function separate(x, y, halfWidth, halfHeight, fixed, padding) {
423
+ const count = x.length;
424
+ for (let pass = 0;pass < 40; pass++) {
425
+ let moved = false;
426
+ for (let a = 0;a < count; a++) {
427
+ for (let b = a + 1;b < count; b++) {
428
+ const overlapX = halfWidth[a] + halfWidth[b] + padding - Math.abs(x[a] - x[b]);
429
+ if (overlapX <= 0)
430
+ continue;
431
+ const overlapY = halfHeight[a] + halfHeight[b] + padding - Math.abs(y[a] - y[b]);
432
+ if (overlapY <= 0)
433
+ continue;
434
+ if (fixed[a] && fixed[b])
435
+ continue;
436
+ moved = true;
437
+ const shareA = fixed[a] ? 0 : fixed[b] ? 1 : 0.5;
438
+ const shareB = 1 - shareA;
439
+ if (overlapX < overlapY) {
440
+ const sign = x[a] < x[b] || x[a] === x[b] && a < b ? -1 : 1;
441
+ x[a] += sign * overlapX * shareA;
442
+ x[b] -= sign * overlapX * shareB;
443
+ } else {
444
+ const sign = y[a] < y[b] || y[a] === y[b] && a < b ? -1 : 1;
445
+ y[a] += sign * overlapY * shareA;
446
+ y[b] -= sign * overlapY * shareB;
447
+ }
448
+ }
449
+ }
450
+ if (!moved)
451
+ break;
452
+ }
453
+ }
454
+
455
+ // src/ui/graph-view/core/layered.ts
456
+ function connectedComponents(graph) {
457
+ const seen = new Set;
458
+ const parts = [];
459
+ for (const node of graph.nodes) {
460
+ if (seen.has(node.id))
461
+ continue;
462
+ const part = [];
463
+ const queue = [node.id];
464
+ seen.add(node.id);
465
+ while (queue.length) {
466
+ const id = queue.shift();
467
+ part.push(id);
468
+ for (const next of graph.neighbours(id)) {
469
+ if (!seen.has(next)) {
470
+ seen.add(next);
471
+ queue.push(next);
472
+ }
473
+ }
474
+ }
475
+ parts.push(part);
476
+ }
477
+ const order = new Map(graph.nodes.map((node, index) => [node.id, index]));
478
+ for (const part of parts)
479
+ part.sort((a, b) => order.get(a) - order.get(b));
480
+ return parts;
481
+ }
482
+ function findBackEdges(graph) {
483
+ const out = new Map;
484
+ for (const node of graph.nodes)
485
+ out.set(node.id, []);
486
+ for (const edge of graph.edges) {
487
+ if (edge.source !== edge.target)
488
+ out.get(edge.source).push({ id: edge.id, to: edge.target });
489
+ }
490
+ const reversed = new Set;
491
+ const state = new Map;
492
+ for (const root of graph.nodes) {
493
+ if (state.has(root.id))
494
+ continue;
495
+ const stack = [{ id: root.id, next: 0 }];
496
+ state.set(root.id, 1);
497
+ while (stack.length) {
498
+ const frame = stack[stack.length - 1];
499
+ const edges = out.get(frame.id);
500
+ if (frame.next >= edges.length) {
501
+ state.set(frame.id, 2);
502
+ stack.pop();
503
+ continue;
504
+ }
505
+ const edge = edges[frame.next++];
506
+ const seen = state.get(edge.to);
507
+ if (seen === 1)
508
+ reversed.add(edge.id);
509
+ else if (seen === undefined) {
510
+ state.set(edge.to, 1);
511
+ stack.push({ id: edge.to, next: 0 });
512
+ }
513
+ }
514
+ }
515
+ return reversed;
516
+ }
517
+ function crossings(links, place) {
518
+ const pairs = links.map((link) => [place.get(link.from), place.get(link.to)]).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
519
+ let count = 0;
520
+ for (let i = 0;i < pairs.length; i++) {
521
+ for (let j = i + 1;j < pairs.length; j++) {
522
+ if (pairs[i][0] < pairs[j][0] && pairs[i][1] > pairs[j][1])
523
+ count++;
524
+ }
525
+ }
526
+ return count;
527
+ }
528
+ function layeredLayout(graph, options = {}) {
529
+ const direction = options.direction === "TB" ? "TB" : "LR";
530
+ const nodeGap = options.nodeGap ?? 24;
531
+ const layerGap = options.layerGap ?? 80;
532
+ const componentGap = options.componentGap ?? 48;
533
+ const sweeps = options.sweeps ?? 4;
534
+ const horizontal = direction === "LR";
535
+ const reversed = findBackEdges(graph);
536
+ const links = [];
537
+ const seenLinks = new Set;
538
+ for (const edge of graph.edges) {
539
+ if (edge.source === edge.target)
540
+ continue;
541
+ const from = reversed.has(edge.id) ? edge.target : edge.source;
542
+ const to = reversed.has(edge.id) ? edge.source : edge.target;
543
+ const key = `${from}\x00${to}`;
544
+ if (!seenLinks.has(key)) {
545
+ seenLinks.add(key);
546
+ links.push({ from, to });
547
+ }
548
+ }
549
+ const forward = new Map;
550
+ const backward = new Map;
551
+ for (const node of graph.nodes) {
552
+ forward.set(node.id, []);
553
+ backward.set(node.id, []);
554
+ }
555
+ for (const link of links) {
556
+ forward.get(link.from).push(link.to);
557
+ backward.get(link.to).push(link.from);
558
+ }
559
+ const layerOf = new Map;
560
+ const waiting = new Map;
561
+ const ready = [];
562
+ for (const node of graph.nodes) {
563
+ waiting.set(node.id, backward.get(node.id).length);
564
+ if (backward.get(node.id).length === 0) {
565
+ ready.push(node.id);
566
+ layerOf.set(node.id, 0);
567
+ }
568
+ }
569
+ for (let cursor = 0;cursor < ready.length; cursor++) {
570
+ const id = ready[cursor];
571
+ for (const next of forward.get(id)) {
572
+ layerOf.set(next, Math.max(layerOf.get(next) ?? 0, layerOf.get(id) + 1));
573
+ const left = waiting.get(next) - 1;
574
+ waiting.set(next, left);
575
+ if (left === 0)
576
+ ready.push(next);
577
+ }
578
+ }
579
+ const positions = new Map;
580
+ const components = [];
581
+ let offset = 0;
582
+ for (const part of connectedComponents(graph)) {
583
+ const layers = [];
584
+ for (const id of part) {
585
+ const layer = layerOf.get(id) ?? 0;
586
+ while (layers.length <= layer)
587
+ layers.push([]);
588
+ layers[layer].push(id);
589
+ }
590
+ const inPart = new Set(part);
591
+ const adjacent = links.filter((link) => inPart.has(link.from) && layerOf.get(link.to) - layerOf.get(link.from) === 1);
592
+ const place = new Map;
593
+ const index = () => {
594
+ for (const layer of layers)
595
+ layer.forEach((id, position) => place.set(id, layer.length > 1 ? position / (layer.length - 1) : 0.5));
596
+ };
597
+ const reorder = (layer, others) => {
598
+ const weight = new Map;
599
+ layer.forEach((id, position) => {
600
+ const around = others.get(id);
601
+ const here = layer.length > 1 ? position / (layer.length - 1) : 0.5;
602
+ weight.set(id, around.length ? around.reduce((sum, other) => sum + place.get(other), 0) / around.length : here);
603
+ });
604
+ const before = new Map(layer.map((id, position) => [id, position]));
605
+ layer.sort((a, b) => weight.get(a) - weight.get(b) || before.get(a) - before.get(b));
606
+ layer.forEach((id, position) => place.set(id, layer.length > 1 ? position / (layer.length - 1) : 0.5));
607
+ };
608
+ index();
609
+ let best = layers.map((layer) => [...layer]);
610
+ let fewest = crossings(adjacent, place);
611
+ for (let sweep = 0;sweep < sweeps && fewest > 0; sweep++) {
612
+ for (let layer = 1;layer < layers.length; layer++)
613
+ reorder(layers[layer], backward);
614
+ for (let layer = layers.length - 2;layer >= 0; layer--)
615
+ reorder(layers[layer], forward);
616
+ const count = crossings(adjacent, place);
617
+ if (count < fewest) {
618
+ fewest = count;
619
+ best = layers.map((layer) => [...layer]);
620
+ }
621
+ }
622
+ const along = (id) => horizontal ? graph.size(id).width : graph.size(id).height;
623
+ const across = (id) => horizontal ? graph.size(id).height : graph.size(id).width;
624
+ const extents = best.map((layer) => layer.reduce((sum, id) => sum + across(id), 0) + nodeGap * Math.max(0, layer.length - 1));
625
+ const widest = Math.max(0, ...extents);
626
+ let flow = 0;
627
+ best.forEach((layer, layerIndex) => {
628
+ const thickness = Math.max(0, ...layer.map(along));
629
+ let cursor = offset + (widest - extents[layerIndex]) / 2;
630
+ for (const id of layer) {
631
+ const centre = cursor + across(id) / 2;
632
+ positions.set(id, horizontal ? { x: flow + thickness / 2, y: centre } : { x: centre, y: flow + thickness / 2 });
633
+ cursor += across(id) + nodeGap;
634
+ }
635
+ flow += thickness + layerGap;
636
+ });
637
+ components.push(best);
638
+ offset += widest + componentGap;
639
+ }
640
+ return { positions, layerOf, reversed, components, bounds: graph.bounds(positions) };
641
+ }
642
+
643
+ // src/ui/graph-view/core/viewport.ts
644
+ var identityViewport = { x: 0, y: 0, k: 1 };
645
+ function clampZoom(k, min, max) {
646
+ return Math.min(Math.max(k, min), max);
647
+ }
648
+ function toScreen(view, point) {
649
+ return { x: point.x * view.k + view.x, y: point.y * view.k + view.y };
650
+ }
651
+ function toGraph(view, point) {
652
+ return { x: (point.x - view.x) / view.k, y: (point.y - view.y) / view.k };
653
+ }
654
+ function pan(view, dx, dy) {
655
+ return { x: view.x + dx, y: view.y + dy, k: view.k };
656
+ }
657
+ function zoomAt(view, point, factor, min = 0.1, max = 4) {
658
+ const k = clampZoom(view.k * factor, min, max);
659
+ const ratio = k / view.k;
660
+ return { x: point.x - (point.x - view.x) * ratio, y: point.y - (point.y - view.y) * ratio, k };
661
+ }
662
+ function fit(bounds, size, padding = 24, min = 0.1, max = 1) {
663
+ if (!bounds || size.width <= 0 || size.height <= 0)
664
+ return { ...identityViewport };
665
+ const roomX = Math.max(1, size.width - padding * 2);
666
+ const roomY = Math.max(1, size.height - padding * 2);
667
+ const k = clampZoom(Math.min(roomX / Math.max(1, bounds.width), roomY / Math.max(1, bounds.height)), min, max);
668
+ return {
669
+ x: size.width / 2 - (bounds.x + bounds.width / 2) * k,
670
+ y: size.height / 2 - (bounds.y + bounds.height / 2) * k,
671
+ k
672
+ };
673
+ }
674
+ function centreOn(view, point, size) {
675
+ return { x: size.width / 2 - point.x * view.k, y: size.height / 2 - point.y * view.k, k: view.k };
676
+ }
677
+ function reveal(view, box, size, margin = 16) {
678
+ const left = box.x * view.k + view.x;
679
+ const top = box.y * view.k + view.y;
680
+ const right = left + box.width * view.k;
681
+ const bottom = top + box.height * view.k;
682
+ let dx = 0;
683
+ let dy = 0;
684
+ if (left < margin)
685
+ dx = margin - left;
686
+ else if (right > size.width - margin)
687
+ dx = size.width - margin - right;
688
+ if (top < margin)
689
+ dy = margin - top;
690
+ else if (bottom > size.height - margin)
691
+ dy = size.height - margin - bottom;
692
+ return dx === 0 && dy === 0 ? view : pan(view, dx, dy);
693
+ }
694
+ function nearestInDirection(positions, from, heading) {
695
+ const origin = positions.get(from);
696
+ if (!origin)
697
+ return null;
698
+ const ux = heading === "left" ? -1 : heading === "right" ? 1 : 0;
699
+ const uy = heading === "up" ? -1 : heading === "down" ? 1 : 0;
700
+ let best = null;
701
+ let bestScore = Number.POSITIVE_INFINITY;
702
+ for (const [id, point] of positions) {
703
+ if (id === from)
704
+ continue;
705
+ const dx = point.x - origin.x;
706
+ const dy = point.y - origin.y;
707
+ const ahead = dx * ux + dy * uy;
708
+ if (ahead <= 0.5)
709
+ continue;
710
+ const aside = Math.abs(dx * uy) + Math.abs(dy * ux);
711
+ if (aside > ahead * 2)
712
+ continue;
713
+ const score = ahead + aside * 2;
714
+ if (score < bestScore) {
715
+ bestScore = score;
716
+ best = id;
717
+ }
718
+ }
719
+ return best;
720
+ }
721
+ function nearestTo(positions, point) {
722
+ let best = null;
723
+ let bestDistance = Number.POSITIVE_INFINITY;
724
+ for (const [id, at] of positions) {
725
+ const distance = (at.x - point.x) ** 2 + (at.y - point.y) ** 2;
726
+ if (distance < bestDistance) {
727
+ bestDistance = distance;
728
+ best = id;
729
+ }
730
+ }
731
+ return best;
732
+ }
733
+ function nodeAt(graph, positions, point) {
734
+ let hit = null;
735
+ for (const [id, at] of positions) {
736
+ const size = graph.size(id);
737
+ if (Math.abs(point.x - at.x) <= size.width / 2 && Math.abs(point.y - at.y) <= size.height / 2)
738
+ hit = id;
739
+ }
740
+ return hit;
741
+ }
742
+ // src/ui/graph-view/view.ts
743
+ var SVG = "http://www.w3.org/2000/svg";
744
+ var DRAG_THRESHOLD = 3;
745
+ var DOUBLE_CLICK = 350;
746
+ var MOVE_TIME = 240;
747
+ var LABEL_CHAR = 6.2;
748
+ function make(name, attributes = {}) {
749
+ const element = document.createElementNS(SVG, name);
750
+ for (const key in attributes)
751
+ element.setAttribute(key, String(attributes[key]));
752
+ return element;
753
+ }
754
+ var instances = 0;
755
+
756
+ class GraphCanvas {
757
+ root;
758
+ callbacks;
759
+ timings = { layout: 0, render: 0 };
760
+ model = new GraphModel;
761
+ positions = new Map;
762
+ shown = new Map;
763
+ pinned = new Set;
764
+ view = { x: 0, y: 0, k: 1 };
765
+ size = { width: 0, height: 0 };
766
+ layoutName;
767
+ direction;
768
+ selected = null;
769
+ autoFit = true;
770
+ animate;
771
+ minZoom;
772
+ maxZoom;
773
+ contextMenu;
774
+ prefix;
775
+ surface;
776
+ status;
777
+ svg;
778
+ stage;
779
+ edgeLayer;
780
+ nodeLayer;
781
+ labelLayer;
782
+ nodeEls = new Map;
783
+ edgeEls = new Map;
784
+ idOf = new WeakMap;
785
+ offsets = new Map;
786
+ serial = 0;
787
+ gesture = null;
788
+ pinch = null;
789
+ lastClick = { id: "", at: 0 };
790
+ lastExpand = 0;
791
+ frame = 0;
792
+ observer = null;
793
+ disposers = [];
794
+ constructor(root, options = {}, callbacks = {}) {
795
+ this.root = root;
796
+ this.callbacks = callbacks;
797
+ this.prefix = `${root.id || "graph"}-${++instances}`;
798
+ this.layoutName = options.layout === "force" ? "force" : "layered";
799
+ this.direction = options.direction === "TB" ? "TB" : "LR";
800
+ this.minZoom = options.minZoom ?? 0.1;
801
+ this.maxZoom = options.maxZoom ?? 4;
802
+ this.contextMenu = Boolean(options.contextMenu);
803
+ this.animate = options.animate !== false;
804
+ this.surface = root.querySelector('[data-gv="surface"]') ?? root;
805
+ this.status = root.querySelector('[data-gv="status"]');
806
+ if (options.label)
807
+ this.surface.setAttribute("aria-label", options.label);
808
+ this.svg = make("svg", { class: "stx-gv-svg", "aria-hidden": "false", focusable: "false" });
809
+ this.svg.__stx_inert_content = true;
810
+ const defs = make("defs");
811
+ for (const name of ["arrow", "arrow-active"]) {
812
+ const marker = make("marker", { id: `${this.prefix}-${name}`, viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: "auto-start-reverse", class: `stx-gv-${name}` });
813
+ marker.append(make("path", { d: "M 0 0 L 10 5 L 0 10 z" }));
814
+ defs.append(marker);
815
+ }
816
+ this.stage = make("g", { class: "stx-gv-stage" });
817
+ this.edgeLayer = make("g", { class: "stx-gv-edges" });
818
+ this.nodeLayer = make("g", { class: "stx-gv-nodes" });
819
+ this.labelLayer = make("g", { class: "stx-gv-edge-labels" });
820
+ this.stage.append(this.edgeLayer, this.nodeLayer, this.labelLayer);
821
+ this.svg.append(defs, this.stage);
822
+ this.surface.append(this.svg);
823
+ this.listen();
824
+ this.measure();
825
+ this.setGraph(options.nodes ?? [], options.edges ?? []);
826
+ if (options.selected)
827
+ this.select(options.selected, { silent: true });
828
+ if (typeof ResizeObserver !== "undefined") {
829
+ this.observer = new ResizeObserver(() => {
830
+ this.measure();
831
+ if (this.autoFit)
832
+ this.fit();
833
+ });
834
+ this.observer.observe(this.surface);
835
+ }
836
+ root.setAttribute("data-gv-ready", "");
837
+ }
838
+ graph() {
839
+ return this.model;
840
+ }
841
+ getViewport() {
842
+ return { ...this.view };
843
+ }
844
+ getLayout() {
845
+ return this.layoutName;
846
+ }
847
+ getSelected() {
848
+ return this.selected;
849
+ }
850
+ getPositions() {
851
+ return Object.fromEntries([...this.positions].map(([id, point]) => [id, { ...point }]));
852
+ }
853
+ setGraph(nodes, edges) {
854
+ this.stop();
855
+ this.model = new GraphModel(nodes ?? [], edges ?? []);
856
+ this.positions = new Map;
857
+ this.pinned.clear();
858
+ if (this.selected && !this.model.has(this.selected))
859
+ this.selected = null;
860
+ this.layout(false);
861
+ this.shown = new Map(this.positions);
862
+ this.render();
863
+ this.autoFit = true;
864
+ this.fit();
865
+ this.mark();
866
+ }
867
+ addNeighbours(id, nodes, edges) {
868
+ const added = this.model.merge(nodes ?? [], edges ?? []);
869
+ if (added.nodes.length === 0 && added.edges.length === 0)
870
+ return added;
871
+ const from = this.shown.get(id) ?? this.positions.get(id) ?? toGraph(this.view, { x: this.size.width / 2, y: this.size.height / 2 });
872
+ for (const node of added.nodes)
873
+ this.shown.set(node, { ...from });
874
+ this.layout(true);
875
+ this.sync();
876
+ this.moveToPlace();
877
+ this.mark();
878
+ if (added.nodes.length)
879
+ this.announce(`${added.nodes.length} ${added.nodes.length === 1 ? "node" : "nodes"} added${this.model.has(id) ? ` to ${labelOf(this.model.node(id))}` : ""}`);
880
+ return added;
881
+ }
882
+ updateNode(id, patch) {
883
+ if (!this.model.updateNode(id, patch))
884
+ return;
885
+ const old = this.nodeEls.get(id);
886
+ if (old) {
887
+ old.remove();
888
+ this.nodeEls.delete(id);
889
+ }
890
+ this.sync();
891
+ this.draw();
892
+ this.mark();
893
+ }
894
+ setLayout(name) {
895
+ const next = name === "force" ? "force" : "layered";
896
+ if (next === this.layoutName)
897
+ return;
898
+ this.layoutName = next;
899
+ this.relayout();
900
+ this.callbacks.onLayout?.({ layout: next });
901
+ }
902
+ setDirection(direction) {
903
+ const next = direction === "TB" ? "TB" : "LR";
904
+ if (next === this.direction)
905
+ return;
906
+ this.direction = next;
907
+ if (this.layoutName === "layered")
908
+ this.relayout();
909
+ }
910
+ select(id, options = {}) {
911
+ const next = id != null && this.model.has(id) ? id : null;
912
+ if (next === this.selected)
913
+ return;
914
+ this.selected = next;
915
+ this.mark();
916
+ if (next)
917
+ this.describe(next);
918
+ if (!options.silent)
919
+ this.callbacks.onSelect?.(this.selection());
920
+ }
921
+ focusNode(id) {
922
+ if (!this.model.has(id))
923
+ return;
924
+ this.select(id);
925
+ const at = this.positions.get(id);
926
+ if (at) {
927
+ this.autoFit = false;
928
+ this.setView(centreOn(this.view, at, this.size));
929
+ }
930
+ }
931
+ fit() {
932
+ this.measure();
933
+ this.setView(fit(this.model.bounds(this.positions), this.size, 32, this.minZoom, Math.min(1, this.maxZoom)));
934
+ this.autoFit = true;
935
+ }
936
+ zoomIn() {
937
+ this.zoomBy(1.25);
938
+ }
939
+ zoomOut() {
940
+ this.zoomBy(0.8);
941
+ }
942
+ zoomBy(factor, point) {
943
+ this.autoFit = false;
944
+ this.setView(zoomAt(this.view, point ?? { x: this.size.width / 2, y: this.size.height / 2 }, factor, this.minZoom, this.maxZoom));
945
+ }
946
+ panBy(dx, dy) {
947
+ this.autoFit = false;
948
+ this.setView(pan(this.view, dx, dy));
949
+ }
950
+ setZoomLimits(min, max) {
951
+ this.minZoom = min;
952
+ this.maxZoom = max;
953
+ }
954
+ destroy() {
955
+ this.stop();
956
+ this.observer?.disconnect();
957
+ for (const dispose of this.disposers)
958
+ dispose();
959
+ this.svg.remove();
960
+ this.root.removeAttribute("data-gv-ready");
961
+ }
962
+ selection() {
963
+ const node = this.selected ? this.model.node(this.selected) ?? null : null;
964
+ return { node, neighbours: node ? this.model.neighbours(node.id).map((id) => this.model.node(id)) : [] };
965
+ }
966
+ measure() {
967
+ const box = this.surface.getBoundingClientRect();
968
+ this.size = { width: box.width, height: box.height };
969
+ }
970
+ layout(warm) {
971
+ const started = performance.now();
972
+ if (this.layoutName === "layered") {
973
+ this.positions = layeredLayout(this.model, { direction: this.direction }).positions;
974
+ } else {
975
+ this.positions = forceLayout(this.model, {
976
+ positions: warm && this.positions.size ? this.positions : null,
977
+ pinned: warm ? this.pinned : null
978
+ });
979
+ }
980
+ this.timings.layout = performance.now() - started;
981
+ }
982
+ relayout() {
983
+ this.pinned.clear();
984
+ this.layout(false);
985
+ this.sync();
986
+ this.moveToPlace();
987
+ if (this.autoFit)
988
+ this.fit();
989
+ }
990
+ render() {
991
+ const started = performance.now();
992
+ this.sync();
993
+ this.draw();
994
+ this.timings.render = performance.now() - started;
995
+ }
996
+ sync() {
997
+ const limit = maxLabelLength(this.model.metrics);
998
+ for (const [id, element] of this.nodeEls) {
999
+ if (!this.model.has(id)) {
1000
+ element.remove();
1001
+ this.nodeEls.delete(id);
1002
+ }
1003
+ }
1004
+ for (const node of this.model.nodes) {
1005
+ let group = this.nodeEls.get(node.id);
1006
+ if (!group) {
1007
+ group = this.buildNode(node, limit);
1008
+ this.nodeEls.set(node.id, group);
1009
+ this.idOf.set(group, node.id);
1010
+ this.nodeLayer.append(group);
1011
+ }
1012
+ const degree = this.model.degree(node.id);
1013
+ group.setAttribute("aria-label", `${labelOf(node)}, ${degree} ${degree === 1 ? "connection" : "connections"}`);
1014
+ }
1015
+ for (const [id, parts] of this.edgeEls) {
1016
+ if (!this.model.edge(id)) {
1017
+ parts.group.remove();
1018
+ parts.label?.remove();
1019
+ this.edgeEls.delete(id);
1020
+ }
1021
+ }
1022
+ for (const edge of this.model.edges) {
1023
+ if (!this.edgeEls.has(edge.id))
1024
+ this.edgeEls.set(edge.id, this.buildEdge(edge));
1025
+ }
1026
+ this.offsets = parallelOffsets(this.model.edges);
1027
+ }
1028
+ buildNode(node, limit) {
1029
+ const size = this.model.size(node.id);
1030
+ const group = make("g", { class: "stx-gv-node", id: `${this.prefix}-node-${this.serial++}`, role: "group", "data-node": node.id });
1031
+ if (node.kind)
1032
+ group.setAttribute("data-kind", node.kind);
1033
+ if (node.expandable === true)
1034
+ group.setAttribute("data-expandable", "");
1035
+ const title = make("title");
1036
+ title.textContent = node.detail ? `${labelOf(node)}: ${node.detail}` : labelOf(node);
1037
+ const box = make("rect", { x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height, rx: 6, ry: 6 });
1038
+ const mark = node.expandable === true ? (this.model.metrics.charWidth + 4) / 2 : 0;
1039
+ const label = make("text", { class: "stx-gv-node-label", x: -mark, y: node.detail ? -6 : 0, "text-anchor": "middle", "dominant-baseline": "central" });
1040
+ label.textContent = fitLabel(labelOf(node), limit);
1041
+ group.append(title, box, label);
1042
+ if (node.detail) {
1043
+ const detail = make("text", { class: "stx-gv-node-detail", x: -mark, y: 9, "text-anchor": "middle", "dominant-baseline": "central" });
1044
+ detail.textContent = fitLabel(node.detail, Math.floor(limit / 0.85));
1045
+ group.append(detail);
1046
+ }
1047
+ if (node.expandable === true) {
1048
+ const plus = make("text", { class: "stx-gv-node-mark", x: size.width / 2 - 10, y: 0, "text-anchor": "middle", "dominant-baseline": "central", "aria-hidden": "true" });
1049
+ plus.textContent = "+";
1050
+ group.append(plus);
1051
+ }
1052
+ return group;
1053
+ }
1054
+ buildEdge(edge) {
1055
+ const group = make("g", { class: "stx-gv-edge", "data-edge": edge.id });
1056
+ const path = make("path", { fill: "none" });
1057
+ if (edge.directed !== false)
1058
+ path.setAttribute("marker-end", `url(#${this.prefix}-arrow)`);
1059
+ group.append(path);
1060
+ this.edgeLayer.append(group);
1061
+ let label = null;
1062
+ if (edge.label) {
1063
+ const text = fitLabel(String(edge.label), 32);
1064
+ const width = Math.ceil(text.length * LABEL_CHAR) + 8;
1065
+ label = make("g", { class: "stx-gv-edge-label", "data-edge": edge.id });
1066
+ const plate = make("rect", { x: -width / 2, y: -8, width, height: 16, rx: 3, ry: 3 });
1067
+ const words = make("text", { "text-anchor": "middle", "dominant-baseline": "central" });
1068
+ words.textContent = text;
1069
+ label.append(plate, words);
1070
+ this.labelLayer.append(label);
1071
+ }
1072
+ return { group, path, label };
1073
+ }
1074
+ draw() {
1075
+ for (const [id, group] of this.nodeEls) {
1076
+ const at = this.shown.get(id) ?? this.positions.get(id);
1077
+ if (at)
1078
+ group.setAttribute("transform", `translate(${at.x} ${at.y})`);
1079
+ }
1080
+ for (const edge of this.model.edges)
1081
+ this.drawEdge(edge);
1082
+ }
1083
+ shape(edge) {
1084
+ const source = this.shown.get(edge.source) ?? this.positions.get(edge.source);
1085
+ const target = this.shown.get(edge.target) ?? this.positions.get(edge.target);
1086
+ if (!source || !target)
1087
+ return null;
1088
+ return edgeShape({ source, sourceSize: this.model.size(edge.source), target, targetSize: this.model.size(edge.target) }, { curve: this.layoutName === "layered" ? "bezier" : "straight", direction: this.direction, offset: this.offsets.get(edge.id) ?? 0, inset: edge.directed !== false ? 1 : 0 });
1089
+ }
1090
+ drawEdge(edge) {
1091
+ const parts = this.edgeEls.get(edge.id);
1092
+ const shape = parts && this.shape(edge);
1093
+ if (!parts || !shape)
1094
+ return;
1095
+ parts.path.setAttribute("d", shape.d);
1096
+ parts.label?.setAttribute("transform", `translate(${Math.round(shape.label.x * 10) / 10} ${Math.round(shape.label.y * 10) / 10})`);
1097
+ }
1098
+ moveToPlace() {
1099
+ this.stop();
1100
+ const still = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
1101
+ if (!this.animate || still || typeof requestAnimationFrame !== "function") {
1102
+ this.shown = new Map(this.positions);
1103
+ this.draw();
1104
+ return;
1105
+ }
1106
+ const from = new Map;
1107
+ for (const [id, to] of this.positions)
1108
+ from.set(id, this.shown.get(id) ?? to);
1109
+ const started = performance.now();
1110
+ const step = (now) => {
1111
+ const t = Math.min(1, (now - started) / MOVE_TIME);
1112
+ const eased = 1 - (1 - t) ** 3;
1113
+ for (const [id, to] of this.positions) {
1114
+ const a = from.get(id);
1115
+ this.shown.set(id, { x: a.x + (to.x - a.x) * eased, y: a.y + (to.y - a.y) * eased });
1116
+ }
1117
+ this.draw();
1118
+ this.frame = t < 1 ? requestAnimationFrame(step) : 0;
1119
+ if (t >= 1)
1120
+ this.shown = new Map(this.positions);
1121
+ };
1122
+ this.frame = requestAnimationFrame(step);
1123
+ }
1124
+ stop() {
1125
+ if (this.frame)
1126
+ cancelAnimationFrame(this.frame);
1127
+ this.frame = 0;
1128
+ }
1129
+ setView(next) {
1130
+ this.view = next;
1131
+ this.stage.setAttribute("transform", `translate(${next.x} ${next.y}) scale(${next.k})`);
1132
+ this.callbacks.onViewport?.({ ...next });
1133
+ }
1134
+ mark() {
1135
+ const selected = this.selected;
1136
+ const near = new Set(selected ? this.model.neighbours(selected) : []);
1137
+ this.root.toggleAttribute("data-has-selection", Boolean(selected));
1138
+ for (const [id, group] of this.nodeEls) {
1139
+ group.toggleAttribute("data-selected", id === selected);
1140
+ group.toggleAttribute("data-neighbour", near.has(id));
1141
+ if (id === selected)
1142
+ group.setAttribute("aria-current", "true");
1143
+ else
1144
+ group.removeAttribute("aria-current");
1145
+ }
1146
+ for (const edge of this.model.edges) {
1147
+ const parts = this.edgeEls.get(edge.id);
1148
+ if (!parts)
1149
+ continue;
1150
+ const active = selected != null && (edge.source === selected || edge.target === selected);
1151
+ parts.group.toggleAttribute("data-active", active);
1152
+ parts.label?.toggleAttribute("data-active", active);
1153
+ if (edge.directed !== false)
1154
+ parts.path.setAttribute("marker-end", `url(#${this.prefix}-${active ? "arrow-active" : "arrow"})`);
1155
+ }
1156
+ const element = selected ? this.nodeEls.get(selected) : null;
1157
+ if (element)
1158
+ this.surface.setAttribute("aria-activedescendant", element.id);
1159
+ else
1160
+ this.surface.removeAttribute("aria-activedescendant");
1161
+ }
1162
+ describe(id) {
1163
+ const node = this.model.node(id);
1164
+ if (!node)
1165
+ return;
1166
+ const names = this.model.neighbours(id).map((other) => labelOf(this.model.node(other)));
1167
+ const shown = names.slice(0, 5).join(", ");
1168
+ const rest = names.length > 5 ? ` and ${names.length - 5} more` : "";
1169
+ this.announce(names.length === 0 ? `${labelOf(node)}, no connections` : `${labelOf(node)}, ${names.length} ${names.length === 1 ? "connection" : "connections"}: ${shown}${rest}`);
1170
+ }
1171
+ announce(text) {
1172
+ if (this.status)
1173
+ this.status.textContent = text;
1174
+ }
1175
+ expand(id, open = false) {
1176
+ const node = this.model.node(id);
1177
+ if (!node)
1178
+ return;
1179
+ this.lastExpand = performance.now();
1180
+ if (open || node.expandable === false)
1181
+ this.callbacks.onOpen?.({ node });
1182
+ else
1183
+ this.callbacks.onExpand?.({ node });
1184
+ }
1185
+ nodeUnder(target) {
1186
+ const element = target instanceof Element ? target.closest(".stx-gv-node") : null;
1187
+ return element ? this.idOf.get(element) ?? null : null;
1188
+ }
1189
+ local(event) {
1190
+ const box = this.surface.getBoundingClientRect();
1191
+ return { x: event.clientX - box.left, y: event.clientY - box.top };
1192
+ }
1193
+ listen() {
1194
+ const on = (type, handler, options) => {
1195
+ this.surface.addEventListener(type, handler, options);
1196
+ this.disposers.push(() => this.surface.removeEventListener(type, handler, options));
1197
+ };
1198
+ on("pointerdown", (event) => this.onPointerDown(event));
1199
+ on("pointermove", (event) => this.onPointerMove(event));
1200
+ on("pointerup", (event) => this.onPointerUp(event));
1201
+ on("pointercancel", () => this.endGesture());
1202
+ on("dblclick", (event) => {
1203
+ const id = this.nodeUnder(event.target);
1204
+ if (id && performance.now() - this.lastExpand > DOUBLE_CLICK)
1205
+ this.expand(id, event.metaKey || event.ctrlKey);
1206
+ });
1207
+ on("wheel", (event) => this.onWheel(event), { passive: false });
1208
+ on("keydown", (event) => this.onKeyDown(event));
1209
+ on("contextmenu", (event) => {
1210
+ if (this.contextMenu)
1211
+ event.preventDefault();
1212
+ const id = this.nodeUnder(event.target);
1213
+ if (id)
1214
+ this.select(id);
1215
+ this.callbacks.onContext?.({ node: id ? this.model.node(id) : null, x: event.clientX, y: event.clientY });
1216
+ });
1217
+ const gesture = (type, handler) => {
1218
+ this.surface.addEventListener(type, handler);
1219
+ this.disposers.push(() => this.surface.removeEventListener(type, handler));
1220
+ };
1221
+ gesture("gesturestart", (event) => {
1222
+ event.preventDefault();
1223
+ const point = this.local(event);
1224
+ this.pinch = { k: this.view.k, x: point.x, y: point.y };
1225
+ });
1226
+ gesture("gesturechange", (event) => {
1227
+ if (!this.pinch)
1228
+ return;
1229
+ event.preventDefault();
1230
+ this.zoomBy(this.pinch.k * event.scale / this.view.k, { x: this.pinch.x, y: this.pinch.y });
1231
+ });
1232
+ gesture("gestureend", () => {
1233
+ this.pinch = null;
1234
+ });
1235
+ }
1236
+ onPointerDown(event) {
1237
+ if (event.button !== 0)
1238
+ return;
1239
+ const node = this.nodeUnder(event.target);
1240
+ this.surface.focus({ preventScroll: true });
1241
+ try {
1242
+ this.surface.setPointerCapture(event.pointerId);
1243
+ } catch {}
1244
+ this.gesture = {
1245
+ pointer: event.pointerId,
1246
+ node,
1247
+ startX: event.clientX,
1248
+ startY: event.clientY,
1249
+ origin: node ? { ...this.positions.get(node) ?? { x: 0, y: 0 } } : { x: 0, y: 0 },
1250
+ view: { ...this.view },
1251
+ moved: false
1252
+ };
1253
+ }
1254
+ onPointerMove(event) {
1255
+ const gesture = this.gesture;
1256
+ if (!gesture || event.pointerId !== gesture.pointer)
1257
+ return;
1258
+ const dx = event.clientX - gesture.startX;
1259
+ const dy = event.clientY - gesture.startY;
1260
+ if (!gesture.moved) {
1261
+ if (Math.abs(dx) < DRAG_THRESHOLD && Math.abs(dy) < DRAG_THRESHOLD)
1262
+ return;
1263
+ gesture.moved = true;
1264
+ this.stop();
1265
+ this.shown = new Map(this.positions);
1266
+ this.root.setAttribute("data-dragging", gesture.node ? "node" : "pan");
1267
+ }
1268
+ if (gesture.node) {
1269
+ const at = { x: gesture.origin.x + dx / this.view.k, y: gesture.origin.y + dy / this.view.k };
1270
+ this.positions.set(gesture.node, at);
1271
+ this.shown.set(gesture.node, at);
1272
+ this.nodeEls.get(gesture.node)?.setAttribute("transform", `translate(${at.x} ${at.y})`);
1273
+ for (const edge of this.model.edgesOf(gesture.node))
1274
+ this.drawEdge(edge);
1275
+ } else {
1276
+ this.autoFit = false;
1277
+ this.setView(pan(gesture.view, dx, dy));
1278
+ }
1279
+ }
1280
+ onPointerUp(event) {
1281
+ const gesture = this.gesture;
1282
+ if (!gesture || event.pointerId !== gesture.pointer)
1283
+ return;
1284
+ this.endGesture();
1285
+ if (gesture.moved) {
1286
+ if (gesture.node) {
1287
+ this.pinned.add(gesture.node);
1288
+ this.autoFit = false;
1289
+ const at = this.positions.get(gesture.node);
1290
+ this.callbacks.onMove?.({ node: this.model.node(gesture.node), x: at.x, y: at.y });
1291
+ }
1292
+ return;
1293
+ }
1294
+ if (!gesture.node) {
1295
+ this.select(null);
1296
+ return;
1297
+ }
1298
+ const now = performance.now();
1299
+ const double = this.lastClick.id === gesture.node && now - this.lastClick.at < DOUBLE_CLICK;
1300
+ this.lastClick = double ? { id: "", at: 0 } : { id: gesture.node, at: now };
1301
+ this.select(gesture.node);
1302
+ if (double)
1303
+ this.expand(gesture.node, event.metaKey || event.ctrlKey);
1304
+ }
1305
+ endGesture() {
1306
+ const gesture = this.gesture;
1307
+ this.gesture = null;
1308
+ this.root.removeAttribute("data-dragging");
1309
+ if (gesture) {
1310
+ try {
1311
+ this.surface.releasePointerCapture(gesture.pointer);
1312
+ } catch {}
1313
+ }
1314
+ }
1315
+ onWheel(event) {
1316
+ event.preventDefault();
1317
+ if (event.ctrlKey || event.metaKey) {
1318
+ this.zoomBy(Math.exp(-event.deltaY * (event.deltaMode === 1 ? 0.05 : 0.01)), this.local(event));
1319
+ return;
1320
+ }
1321
+ const unit = event.deltaMode === 1 ? 16 : 1;
1322
+ this.panBy(-event.deltaX * unit, -event.deltaY * unit);
1323
+ }
1324
+ onKeyDown(event) {
1325
+ const headings = { ArrowLeft: "left", ArrowRight: "right", ArrowUp: "up", ArrowDown: "down" };
1326
+ const heading = headings[event.key];
1327
+ if (heading) {
1328
+ event.preventDefault();
1329
+ const next = this.selected ? nearestInDirection(this.positions, this.selected, heading) : nearestTo(this.positions, toGraph(this.view, { x: this.size.width / 2, y: this.size.height / 2 }));
1330
+ if (next) {
1331
+ this.select(next);
1332
+ this.bringIntoView(next);
1333
+ }
1334
+ return;
1335
+ }
1336
+ const mod = event.metaKey || event.ctrlKey;
1337
+ if (event.key === "Enter" || event.key === " ") {
1338
+ if (!this.selected)
1339
+ return;
1340
+ event.preventDefault();
1341
+ this.expand(this.selected, mod);
1342
+ } else if (mod || event.altKey) {} else if (event.key === "+" || event.key === "=") {
1343
+ event.preventDefault();
1344
+ this.zoomIn();
1345
+ } else if (event.key === "-" || event.key === "_") {
1346
+ event.preventDefault();
1347
+ this.zoomOut();
1348
+ } else if (event.key === "0") {
1349
+ event.preventDefault();
1350
+ this.fit();
1351
+ } else if (event.key === "f" || event.key === "F") {
1352
+ if (!this.selected)
1353
+ return;
1354
+ event.preventDefault();
1355
+ this.focusNode(this.selected);
1356
+ } else if (event.key === "o" || event.key === "O") {
1357
+ if (!this.selected)
1358
+ return;
1359
+ event.preventDefault();
1360
+ this.expand(this.selected, true);
1361
+ } else if (event.key === "Escape" && this.selected) {
1362
+ event.preventDefault();
1363
+ this.select(null);
1364
+ }
1365
+ }
1366
+ bringIntoView(id) {
1367
+ const at = this.positions.get(id);
1368
+ if (!at)
1369
+ return;
1370
+ const size = this.model.size(id);
1371
+ const next = reveal(this.view, { x: at.x - size.width / 2, y: at.y - size.height / 2, width: size.width, height: size.height }, this.size);
1372
+ if (next !== this.view) {
1373
+ this.autoFit = false;
1374
+ this.setView(next);
1375
+ }
1376
+ }
1377
+ }
1378
+ export {
1379
+ GraphCanvas,
1380
+ GraphModel,
1381
+ centreOn,
1382
+ clampZoom,
1383
+ clipToRect,
1384
+ connectedComponents,
1385
+ defaultNodeMetrics,
1386
+ edgeIdOf,
1387
+ edgeShape,
1388
+ findBackEdges,
1389
+ fit,
1390
+ fitLabel,
1391
+ forceLayout,
1392
+ identityViewport,
1393
+ labelOf,
1394
+ layeredLayout,
1395
+ maxLabelLength,
1396
+ nearestInDirection,
1397
+ nearestTo,
1398
+ nodeAt,
1399
+ nodeSize,
1400
+ pan,
1401
+ parallelOffsets,
1402
+ reveal,
1403
+ seededRandom,
1404
+ selfLoopShape,
1405
+ toGraph,
1406
+ toScreen,
1407
+ zoomAt
1408
+ };