@dxos/react-ui-graph 0.8.4-main.406dc2a → 0.8.4-main.4668b7de9b

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 (138) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +5 -7
  3. package/dist/lib/browser/chunk-EASNZZ7B.mjs +52 -0
  4. package/dist/lib/browser/chunk-EASNZZ7B.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +2731 -661
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +16 -16
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/node-esm/chunk-JSE2X4ML.mjs +54 -0
  11. package/dist/lib/node-esm/chunk-JSE2X4ML.mjs.map +7 -0
  12. package/dist/lib/node-esm/index.mjs +2731 -661
  13. package/dist/lib/node-esm/index.mjs.map +4 -4
  14. package/dist/lib/node-esm/meta.json +1 -1
  15. package/dist/lib/node-esm/testing/index.mjs +16 -16
  16. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  17. package/dist/types/src/components/Graph/Graph.d.ts +23 -6
  18. package/dist/types/src/components/Graph/Graph.d.ts.map +1 -1
  19. package/dist/types/src/components/Graph/Graph.stories.d.ts +6 -6
  20. package/dist/types/src/components/Graph/Graph.stories.d.ts.map +1 -1
  21. package/dist/types/src/components/Mesh/Mesh.d.ts.map +1 -1
  22. package/dist/types/src/components/Mesh/Mesh.stories.d.ts.map +1 -1
  23. package/dist/types/src/components/SVG/FPS.d.ts +20 -0
  24. package/dist/types/src/components/SVG/FPS.d.ts.map +1 -0
  25. package/dist/types/src/components/SVG/Grid.d.ts.map +1 -1
  26. package/dist/types/src/components/SVG/Markers.d.ts.map +1 -1
  27. package/dist/types/src/components/SVG/Root.d.ts +8 -4
  28. package/dist/types/src/components/SVG/Root.d.ts.map +1 -1
  29. package/dist/types/src/components/SVG/SVG.d.ts +17 -18
  30. package/dist/types/src/components/SVG/SVG.d.ts.map +1 -1
  31. package/dist/types/src/components/SVG/Svg.stories.d.ts +1 -1
  32. package/dist/types/src/components/SVG/Svg.stories.d.ts.map +1 -1
  33. package/dist/types/src/fx/fx.stories.d.ts +3 -3
  34. package/dist/types/src/fx/fx.stories.d.ts.map +1 -1
  35. package/dist/types/src/fx/pulsar.d.ts.map +1 -1
  36. package/dist/types/src/graph/markers.d.ts.map +1 -1
  37. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts +47 -0
  38. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts.map +1 -0
  39. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts +65 -0
  40. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts.map +1 -0
  41. package/dist/types/src/graph/projector/graph-drag.d.ts.map +1 -1
  42. package/dist/types/src/graph/projector/graph-force-projector.d.ts +1 -1
  43. package/dist/types/src/graph/projector/graph-force-projector.d.ts.map +1 -1
  44. package/dist/types/src/graph/projector/graph-forces.d.ts.map +1 -1
  45. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts +1 -1
  46. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts.map +1 -1
  47. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts +23 -0
  48. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts.map +1 -0
  49. package/dist/types/src/graph/projector/graph-plexus-projector.d.ts +67 -0
  50. package/dist/types/src/graph/projector/graph-plexus-projector.d.ts.map +1 -0
  51. package/dist/types/src/graph/projector/graph-plexus-projector.test.d.ts +2 -0
  52. package/dist/types/src/graph/projector/graph-plexus-projector.test.d.ts.map +1 -0
  53. package/dist/types/src/graph/projector/graph-projector.d.ts +10 -2
  54. package/dist/types/src/graph/projector/graph-projector.d.ts.map +1 -1
  55. package/dist/types/src/graph/projector/graph-radial-projector.d.ts +7 -1
  56. package/dist/types/src/graph/projector/graph-radial-projector.d.ts.map +1 -1
  57. package/dist/types/src/graph/projector/graph-relational-projector.d.ts +1 -1
  58. package/dist/types/src/graph/projector/graph-relational-projector.d.ts.map +1 -1
  59. package/dist/types/src/graph/projector/graph-swarm-projector.d.ts +72 -0
  60. package/dist/types/src/graph/projector/graph-swarm-projector.d.ts.map +1 -0
  61. package/dist/types/src/graph/projector/index.d.ts +5 -0
  62. package/dist/types/src/graph/projector/index.d.ts.map +1 -1
  63. package/dist/types/src/graph/projector/projector.d.ts +10 -1
  64. package/dist/types/src/graph/projector/projector.d.ts.map +1 -1
  65. package/dist/types/src/graph/renderer/bullets.d.ts.map +1 -1
  66. package/dist/types/src/graph/renderer/graph-renderer.d.ts +41 -1
  67. package/dist/types/src/graph/renderer/graph-renderer.d.ts.map +1 -1
  68. package/dist/types/src/graph/renderer/index.d.ts +1 -0
  69. package/dist/types/src/graph/renderer/index.d.ts.map +1 -1
  70. package/dist/types/src/graph/renderer/labels.d.ts +33 -0
  71. package/dist/types/src/graph/renderer/labels.d.ts.map +1 -0
  72. package/dist/types/src/graph/renderer/renderer.d.ts +12 -1
  73. package/dist/types/src/graph/renderer/renderer.d.ts.map +1 -1
  74. package/dist/types/src/graph/types.d.ts +15 -1
  75. package/dist/types/src/graph/types.d.ts.map +1 -1
  76. package/dist/types/src/hooks/useGrid.d.ts.map +1 -1
  77. package/dist/types/src/hooks/useStateRef.d.ts.map +1 -1
  78. package/dist/types/src/hooks/useSvgContext.d.ts.map +1 -1
  79. package/dist/types/src/hooks/useZoom.d.ts.map +1 -1
  80. package/dist/types/src/stories/experimental.stories.d.ts +7 -0
  81. package/dist/types/src/stories/experimental.stories.d.ts.map +1 -0
  82. package/dist/types/src/stories/hooks.stories.d.ts +4 -3
  83. package/dist/types/src/stories/hooks.stories.d.ts.map +1 -1
  84. package/dist/types/src/testing/data.d.ts +5 -5
  85. package/dist/types/src/testing/data.d.ts.map +1 -1
  86. package/dist/types/src/testing/hooks.d.ts +2 -16
  87. package/dist/types/src/testing/hooks.d.ts.map +1 -1
  88. package/dist/types/src/testing/model.d.ts +4 -8
  89. package/dist/types/src/testing/model.d.ts.map +1 -1
  90. package/dist/types/src/util/events.d.ts.map +1 -1
  91. package/dist/types/src/util/fraction.d.ts +1 -1
  92. package/dist/types/src/util/fraction.d.ts.map +1 -1
  93. package/dist/types/src/util/points.d.ts.map +1 -1
  94. package/dist/types/src/util/scale.d.ts.map +1 -1
  95. package/dist/types/src/util/screen.d.ts.map +1 -1
  96. package/dist/types/src/util/vector.d.ts.map +1 -1
  97. package/dist/types/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +33 -35
  99. package/src/components/Graph/Graph.stories.tsx +53 -47
  100. package/src/components/Graph/Graph.tsx +126 -23
  101. package/src/components/Mesh/Mesh.stories.tsx +8 -7
  102. package/src/components/Mesh/Mesh.tsx +43 -35
  103. package/src/components/SVG/FPS.tsx +91 -0
  104. package/src/components/SVG/Grid.tsx +1 -1
  105. package/src/components/SVG/Root.tsx +42 -9
  106. package/src/components/SVG/SVG.tsx +14 -3
  107. package/src/components/SVG/Svg.stories.tsx +4 -5
  108. package/src/fx/fx.stories.tsx +7 -8
  109. package/src/graph/projector/graph-bundle-projector.ts +210 -0
  110. package/src/graph/projector/graph-cluster-projector.ts +337 -0
  111. package/src/graph/projector/graph-drag.ts +0 -1
  112. package/src/graph/projector/graph-force-projector.ts +7 -3
  113. package/src/graph/projector/graph-hierarchical-projector.ts +4 -4
  114. package/src/graph/projector/graph-lattice-projector.ts +86 -0
  115. package/src/graph/projector/graph-plexus-projector.test.ts +102 -0
  116. package/src/graph/projector/graph-plexus-projector.ts +309 -0
  117. package/src/graph/projector/graph-projector.ts +24 -4
  118. package/src/graph/projector/graph-radial-projector.ts +31 -4
  119. package/src/graph/projector/graph-relational-projector.ts +4 -4
  120. package/src/graph/projector/graph-swarm-projector.ts +373 -0
  121. package/src/graph/projector/index.ts +5 -0
  122. package/src/graph/projector/projector.ts +12 -3
  123. package/src/graph/renderer/graph-renderer.ts +289 -31
  124. package/src/graph/renderer/index.ts +1 -0
  125. package/src/graph/renderer/labels.ts +138 -0
  126. package/src/graph/renderer/renderer.ts +15 -4
  127. package/src/graph/types.ts +15 -1
  128. package/src/stories/experimental.stories.tsx +446 -0
  129. package/src/stories/hooks.stories.tsx +21 -10
  130. package/src/testing/data.ts +14 -14
  131. package/src/testing/hooks.ts +3 -4
  132. package/src/testing/model.ts +6 -6
  133. package/src/util/fraction.ts +1 -1
  134. package/styles/graph.css +341 -43
  135. package/dist/lib/browser/chunk-EX2Q43O6.mjs +0 -966
  136. package/dist/lib/browser/chunk-EX2Q43O6.mjs.map +0 -7
  137. package/dist/lib/node-esm/chunk-SWA6OT3W.mjs +0 -968
  138. package/dist/lib/node-esm/chunk-SWA6OT3W.mjs.map +0 -7
@@ -1,31 +1,14 @@
1
1
  import {
2
- EventEmitter,
3
- FractionUtil,
4
- GridController,
5
- SVGContext,
6
- SVGContextProvider,
7
- Scale,
8
- Screen,
9
- Vector,
10
- ZoomHandler,
11
- getCircumferencePoints,
12
- normal,
13
- offsetPoints,
14
2
  useDynamicRef,
15
- useGrid,
16
3
  useStateRef,
17
- useSvgContext,
18
- useTimestamp,
19
- useZoom
20
- } from "./chunk-EX2Q43O6.mjs";
4
+ useTimestamp
5
+ } from "./chunk-EASNZZ7B.mjs";
21
6
 
22
7
  // src/components/Graph/Graph.tsx
23
- import { useSignals as _useSignals } from "@preact-signals/safe-react/tracking";
24
- import { effect } from "@preact/signals-core";
25
- import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
8
+ import React, { forwardRef, useEffect as useEffect3, useImperativeHandle, useMemo as useMemo3, useRef as useRef3 } from "react";
26
9
  import { combine } from "@dxos/async";
27
- import { log as log6 } from "@dxos/log";
28
- import { mx } from "@dxos/react-ui-theme";
10
+ import { log as log11 } from "@dxos/log";
11
+ import { mx } from "@dxos/ui-theme";
29
12
 
30
13
  // src/graph/markers.ts
31
14
  import { line, select } from "d3";
@@ -73,9 +56,1250 @@ var createMarkers = ({ arrowSize = 12 } = {}) => (group) => {
73
56
  generator: createDot(6),
74
57
  className: "dx-dot"
75
58
  }
76
- ]).join("marker").attr("id", (d) => d.id).attr("markerUnits", "strokeWidth").attr("class", (d) => d.className).each((d, i, nodes) => {
77
- select(nodes[i]).call(d.generator);
78
- });
59
+ ]).join("marker").attr("id", (d) => d.id).attr("markerUnits", "strokeWidth").attr("class", (d) => d.className).each((d, i, nodes) => {
60
+ select(nodes[i]).call(d.generator);
61
+ });
62
+ };
63
+
64
+ // src/graph/projector/graph-bundle-projector.ts
65
+ import { cluster as d3Cluster, curveBundle, hierarchy, lineRadial } from "d3";
66
+ import { log as log2 } from "@dxos/log";
67
+
68
+ // src/graph/projector/graph-radial-projector.ts
69
+ import { easeCubic, timer } from "d3";
70
+ import { log } from "@dxos/log";
71
+
72
+ // src/graph/types.ts
73
+ import { invariant } from "@dxos/invariant";
74
+ var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/types.ts";
75
+ var defaultIdAccessor = (node) => {
76
+ invariant(node.id, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 10, S: void 0, A: ["node.id", ""] });
77
+ return node.id;
78
+ };
79
+ var emptyGraph = {
80
+ nodes: [],
81
+ edges: []
82
+ };
83
+
84
+ // src/util/events.ts
85
+ var EventEmitter = class {
86
+ _listeners = /* @__PURE__ */ new Set();
87
+ clear() {
88
+ this._listeners.clear();
89
+ }
90
+ on(onEvent) {
91
+ this._listeners.add(onEvent);
92
+ return () => this._listeners.delete(onEvent);
93
+ }
94
+ emit(value) {
95
+ this._listeners.forEach((listener) => listener(value));
96
+ }
97
+ };
98
+
99
+ // src/util/fraction.ts
100
+ import { invariant as invariant2 } from "@dxos/invariant";
101
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/util/fraction.ts";
102
+ var FractionUtil = class _FractionUtil {
103
+ /**
104
+ * Convert number to fraction.
105
+ * @param n
106
+ */
107
+ static toFraction = (n) => {
108
+ return typeof n === "number" ? [
109
+ n,
110
+ 1
111
+ ] : n;
112
+ };
113
+ static validate = (...fraction) => {
114
+ fraction.forEach(([n, d]) => {
115
+ if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0) {
116
+ throw new Error(`Invalid fraction: ${n}/${d}`);
117
+ }
118
+ });
119
+ return fraction;
120
+ };
121
+ /**
122
+ * @param {Fraction}
123
+ * Convert to rounded-sm number.
124
+ */
125
+ static toNumber = ([n, d]) => {
126
+ _FractionUtil.validate([
127
+ n,
128
+ d
129
+ ]);
130
+ return n / d;
131
+ };
132
+ /**
133
+ * Round the number to the nearest fraction.
134
+ * Example: 3/5 => 1/1; 3/5 (precision 2) => 1/2.
135
+ * @param {Fraction}
136
+ * @param p Precision (e.g., 1/2, 1/4, etc.)
137
+ */
138
+ static round = ([n, d], p = 1) => {
139
+ _FractionUtil.validate([
140
+ n,
141
+ d
142
+ ]);
143
+ const v = Math.round(_FractionUtil.toNumber(_FractionUtil.divide([
144
+ n,
145
+ d
146
+ ], [
147
+ 1,
148
+ p
149
+ ])));
150
+ return _FractionUtil.simplify([
151
+ v,
152
+ p
153
+ ]);
154
+ };
155
+ //
156
+ // Boolean.
157
+ //
158
+ /**
159
+ * Tests if equals.
160
+ * @param n1
161
+ * @param n2
162
+ */
163
+ static equals = (n1, n2) => {
164
+ return n1[0] * n2[1] === n1[1] * n2[0];
165
+ };
166
+ /**
167
+ * @param {Fraction}
168
+ * True if zero.
169
+ */
170
+ static isZero = ([n]) => {
171
+ return n === 0;
172
+ };
173
+ //
174
+ // Normalization.
175
+ //
176
+ /**
177
+ * Simplify fraction finding LCDs.
178
+ * @param n
179
+ * @param d
180
+ */
181
+ static simplify = ([n, d]) => {
182
+ _FractionUtil.validate([
183
+ n,
184
+ d
185
+ ]);
186
+ if (d < 1) {
187
+ const t = n / d;
188
+ if (Math.floor(t) === t) {
189
+ n = t;
190
+ d = 1;
191
+ }
192
+ }
193
+ const fn = _FractionUtil.factors(n).reverse();
194
+ const fd = _FractionUtil.factors(d).reverse();
195
+ let c;
196
+ for (let i = 0; i < fn.length; i++) {
197
+ c = fd.find((n2) => n2 === fn[i]);
198
+ if (c) {
199
+ return [
200
+ n / c,
201
+ d / c
202
+ ];
203
+ }
204
+ }
205
+ return [
206
+ n,
207
+ d
208
+ ];
209
+ };
210
+ /**
211
+ * Return common factors.
212
+ * @param n
213
+ */
214
+ static factors = (n) => {
215
+ invariant2(Number.isFinite(n), `Invalid number: ${n}`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 113, S: this, A: ["Number.isFinite(n)", "`Invalid number: ${n}`"] });
216
+ const factors = [
217
+ 1
218
+ ];
219
+ if (Number.isSafeInteger(n)) {
220
+ let f = 1;
221
+ do {
222
+ if (n % ++f === 0) {
223
+ factors.push(f);
224
+ }
225
+ } while (n / f > 1 && f < 100);
226
+ }
227
+ return factors;
228
+ };
229
+ //
230
+ // Basic arithmetic.
231
+ //
232
+ /**
233
+ * @param n1
234
+ * @param n2
235
+ */
236
+ static add = (n1, n2) => {
237
+ _FractionUtil.validate(n1, n2);
238
+ const d = n1[1] * n2[1];
239
+ const n = n1[0] * n2[1] + n2[0] * n1[1];
240
+ return _FractionUtil.simplify([
241
+ n,
242
+ d
243
+ ]);
244
+ };
245
+ /**
246
+ * @param n1
247
+ * @param n2
248
+ */
249
+ static subtract = (n1, n2) => {
250
+ _FractionUtil.validate(n1, n2);
251
+ const d = n1[1] * n2[1];
252
+ const n = n1[0] * n2[1] - n2[0] * n1[1];
253
+ return _FractionUtil.simplify([
254
+ n,
255
+ d
256
+ ]);
257
+ };
258
+ /**
259
+ * @param n1
260
+ * @param n2
261
+ */
262
+ static multiply = (n1, n2) => {
263
+ _FractionUtil.validate(n1, n2);
264
+ const n = n1[0] * n2[0];
265
+ const d = n1[1] * n2[1];
266
+ return _FractionUtil.simplify([
267
+ n,
268
+ d
269
+ ]);
270
+ };
271
+ /**
272
+ * @param n1
273
+ * @param n2
274
+ */
275
+ static divide = (n1, n2) => {
276
+ _FractionUtil.validate(n1, n2);
277
+ const n = n1[0] * n2[1];
278
+ const d = n1[1] * n2[0];
279
+ return _FractionUtil.simplify([
280
+ n,
281
+ d
282
+ ]);
283
+ };
284
+ };
285
+
286
+ // src/util/points.ts
287
+ var getCircumferencePoints = (p1, p2, r1 = 0, r2 = 0) => {
288
+ const [x1, y1] = p1;
289
+ const [x2, y2] = p2;
290
+ const theta = Math.atan2(x2 - x1, y2 - y1);
291
+ return [
292
+ [
293
+ // p1
294
+ x1 + (r1 === 0 ? 0 : r1 * Math.sin(theta)),
295
+ y1 + (r1 === 0 ? 0 : r1 * Math.cos(theta))
296
+ ],
297
+ [
298
+ // p2
299
+ x2 - (r2 === 0 ? 0 : r2 * Math.cos(Math.PI / 2 - theta)),
300
+ y2 - (r2 === 0 ? 0 : r2 * Math.sin(Math.PI / 2 - theta))
301
+ ]
302
+ ];
303
+ };
304
+ var normal = (p1, p2) => {
305
+ const dx = p2[0] - p1[0];
306
+ const dy = p2[1] - p1[1];
307
+ const len = Math.hypot(dx, dy);
308
+ return [
309
+ dy / len,
310
+ -dx / len
311
+ ];
312
+ };
313
+ var offsetPoints = (points, distance, closed) => {
314
+ const len = points.length;
315
+ const out = [];
316
+ for (let i = 0; i < len; i++) {
317
+ const p0 = points[(i - 1 + len) % len];
318
+ const p1 = points[i];
319
+ const p2 = points[(i + 1) % len];
320
+ const n1 = normal(p0, p1);
321
+ const n2 = normal(p1, p2);
322
+ const nx = (n1[0] + n2[0]) / 2;
323
+ const ny = (n1[1] + n2[1]) / 2;
324
+ const norm = Math.hypot(nx, ny) || 1;
325
+ out.push([
326
+ p1[0] + distance * nx / norm,
327
+ p1[1] + distance * ny / norm
328
+ ]);
329
+ if (!closed && (i === 0 || i === len - 1)) {
330
+ out[i] = [
331
+ p1[0] + distance * normal(p0, p1)[0],
332
+ p1[1] + distance * normal(p0, p1)[1]
333
+ ];
334
+ }
335
+ }
336
+ return out;
337
+ };
338
+
339
+ // src/util/scale.ts
340
+ import { zoomIdentity } from "d3";
341
+ var Scale = class {
342
+ _gridSize;
343
+ _transform;
344
+ constructor(_gridSize = 32) {
345
+ this._gridSize = _gridSize;
346
+ }
347
+ get gridSize() {
348
+ return this._gridSize;
349
+ }
350
+ get transform() {
351
+ return this._transform || zoomIdentity;
352
+ }
353
+ setTransform(transform) {
354
+ if (this._transform?.x === transform.x && this._transform?.y === transform.y && this._transform?.k === transform.k) {
355
+ return false;
356
+ }
357
+ this._transform = transform;
358
+ return true;
359
+ }
360
+ /**
361
+ * Translate a screen point to a logical point.
362
+ * @param point
363
+ */
364
+ translate(point) {
365
+ const { x, y, k } = this._transform ?? {
366
+ x: 0,
367
+ y: 0,
368
+ k: 1
369
+ };
370
+ return [
371
+ (point[0] - x) / k,
372
+ (point[1] - y) / k
373
+ ];
374
+ }
375
+ /**
376
+ * Map model to screen.
377
+ * Model points are represented by fractions (to preserve precision) and use normal cartesian coordinates.
378
+ */
379
+ model = {
380
+ // TODO(burdon): Precision depends on scale.
381
+ snapValues: (array) => array.map((n) => FractionUtil.round(n)),
382
+ snapVertex: ({ x, y }) => {
383
+ const [sx, sy] = this.model.snapValues([
384
+ x,
385
+ y
386
+ ]);
387
+ return {
388
+ x: sx,
389
+ y: sy
390
+ };
391
+ },
392
+ snapBounds: ({ x, y, width, height }) => {
393
+ [x, y, width, height] = this.model.snapValues([
394
+ x,
395
+ y,
396
+ width,
397
+ height
398
+ ]);
399
+ return {
400
+ x,
401
+ y,
402
+ width,
403
+ height
404
+ };
405
+ },
406
+ toValue: (value) => {
407
+ return Math.round(FractionUtil.toNumber(value) * this._gridSize);
408
+ },
409
+ toValues: (values) => {
410
+ return values.map((value) => Math.round(FractionUtil.toNumber(value) * this._gridSize));
411
+ },
412
+ toPoint: (point) => {
413
+ const [x, y] = this.model.toValues([
414
+ point.x,
415
+ point.y
416
+ ]);
417
+ return [
418
+ x,
419
+ y === 0 ? 0 : -y
420
+ ];
421
+ },
422
+ toBounds: ({ x, y, width, height }) => {
423
+ const point = this.model.toPoint({
424
+ x,
425
+ y
426
+ });
427
+ const [width2, height2] = this.model.toValues([
428
+ width,
429
+ height
430
+ ]);
431
+ return {
432
+ x: point[0],
433
+ y: point[1] - height2,
434
+ width: width2,
435
+ height: height2
436
+ };
437
+ }
438
+ };
439
+ /**
440
+ * Map screen to model.
441
+ * Screen points are represented by floating numbers and use translated SVG coordinates (with the y-axis inverted).
442
+ */
443
+ screen = {
444
+ snapValues: (array) => array.map((n) => Math.round(n / this._gridSize) * this._gridSize),
445
+ snapPoint: ([x, y]) => [
446
+ x,
447
+ y
448
+ ].map((n) => Math.round(n / this._gridSize) * this._gridSize),
449
+ snapBounds: ({ x, y, width, height }) => {
450
+ [x, y, width, height] = this.screen.snapValues([
451
+ x,
452
+ y,
453
+ width,
454
+ height
455
+ ]);
456
+ return {
457
+ x,
458
+ y,
459
+ width,
460
+ height
461
+ };
462
+ },
463
+ toValue: (value) => {
464
+ return FractionUtil.divide(FractionUtil.toFraction(value), [
465
+ this._gridSize,
466
+ 1
467
+ ]);
468
+ },
469
+ toValues: (values) => {
470
+ return values.map((value) => FractionUtil.divide(FractionUtil.toFraction(value), [
471
+ this._gridSize,
472
+ 1
473
+ ]));
474
+ },
475
+ toVertex: (point) => {
476
+ const [x, y] = point;
477
+ return {
478
+ x: FractionUtil.toFraction(x / this._gridSize),
479
+ y: FractionUtil.toFraction(-y / this._gridSize)
480
+ };
481
+ },
482
+ toBounds: (bounds) => {
483
+ const { x, y } = this.screen.toVertex([
484
+ bounds.x,
485
+ bounds.y
486
+ ]);
487
+ const [width, height] = this.screen.toValues([
488
+ bounds.width,
489
+ bounds.height
490
+ ]);
491
+ return {
492
+ x,
493
+ y: FractionUtil.subtract(y, height),
494
+ width,
495
+ height
496
+ };
497
+ }
498
+ };
499
+ };
500
+
501
+ // src/util/screen.ts
502
+ var Screen = class {
503
+ static createBounds = ([x1, y1], [x2, y2], mod = {}) => {
504
+ const { constrain, center } = mod;
505
+ const x = Math.min(x1, x2);
506
+ const y = Math.min(y1, y2);
507
+ let width = Math.abs(x2 - x1);
508
+ let height = Math.abs(y2 - y1);
509
+ if (constrain) {
510
+ width = height = Math.max(width, height);
511
+ }
512
+ if (center) {
513
+ return {
514
+ x: x - width,
515
+ y: y - height,
516
+ width: width * 2,
517
+ height: height * 2
518
+ };
519
+ } else {
520
+ return {
521
+ x,
522
+ y,
523
+ width,
524
+ height
525
+ };
526
+ }
527
+ };
528
+ static center = ({ x, y, width, height }) => {
529
+ return [
530
+ x + width / 2,
531
+ y + height / 2
532
+ ];
533
+ };
534
+ static contains = (bounds, point) => {
535
+ const [x, y] = point;
536
+ if (x < bounds.x || y < bounds.y) {
537
+ return false;
538
+ }
539
+ if (x > bounds.x + bounds.width || y > bounds.y + bounds.height) {
540
+ return false;
541
+ }
542
+ return true;
543
+ };
544
+ /**
545
+ * Distance between two points.
546
+ * @param p1
547
+ * @param p2
548
+ */
549
+ static len = (p1, p2) => {
550
+ return Math.sqrt(Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2));
551
+ };
552
+ /**
553
+ * Distance to line segment.
554
+ * https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment#1501725
555
+ * @param v1
556
+ * @param v2
557
+ * @param p
558
+ */
559
+ static normal = (v1, v2, p) => {
560
+ const d2 = (p1, p2) => Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2);
561
+ let d;
562
+ const len2 = d2(v1, v2);
563
+ if (len2 === 0) {
564
+ d = d2(p, v1);
565
+ } else {
566
+ let t = ((p[0] - v1[0]) * (v2[0] - v1[0]) + (p[1] - v1[1]) * (v2[1] - v1[1])) / len2;
567
+ t = Math.max(0, Math.min(1, t));
568
+ d = d2(p, [
569
+ v1[0] + t * (v2[0] - v1[0]),
570
+ v1[1] + t * (v2[1] - v1[1])
571
+ ]);
572
+ }
573
+ return Math.sqrt(d);
574
+ };
575
+ };
576
+
577
+ // src/util/vector.ts
578
+ var Vector = class {
579
+ /**
580
+ * Convert to Vertex.
581
+ * @param x
582
+ * @param y
583
+ */
584
+ static toVertex = ({ x, y }) => ({
585
+ x: FractionUtil.toFraction(x),
586
+ y: FractionUtil.toFraction(y)
587
+ });
588
+ /**
589
+ * Convert to Bounds.
590
+ * @param bounds
591
+ */
592
+ static toBounds = ({ x, y, width, height }) => ({
593
+ x: FractionUtil.toFraction(x),
594
+ y: FractionUtil.toFraction(y),
595
+ width: FractionUtil.toFraction(width),
596
+ height: FractionUtil.toFraction(height)
597
+ });
598
+ /**
599
+ * Calculate center point.
600
+ * @param bounds
601
+ */
602
+ static center = ({ x, y, width, height }) => {
603
+ const cx = FractionUtil.add(x, FractionUtil.multiply(width, [
604
+ 1,
605
+ 2
606
+ ]));
607
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
608
+ 1,
609
+ 2
610
+ ]));
611
+ return {
612
+ x: cx,
613
+ y: cy
614
+ };
615
+ };
616
+ /**
617
+ * Calculate centered left edge.
618
+ * @param bounds
619
+ */
620
+ static left = ({ x, y, height }) => {
621
+ const cx = x;
622
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
623
+ 1,
624
+ 2
625
+ ]));
626
+ return {
627
+ x: cx,
628
+ y: cy
629
+ };
630
+ };
631
+ /**
632
+ * Calculate centered right edge.
633
+ * @param bounds
634
+ */
635
+ static right = ({ x, y, width, height }) => {
636
+ const cx = FractionUtil.add(x, width);
637
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
638
+ 1,
639
+ 2
640
+ ]));
641
+ return {
642
+ x: cx,
643
+ y: cy
644
+ };
645
+ };
646
+ };
647
+
648
+ // src/graph/projector/projector.ts
649
+ var Projector = class {
650
+ _context;
651
+ updated = new EventEmitter();
652
+ _options;
653
+ constructor(_context, options) {
654
+ this._context = _context;
655
+ this._options = Object.assign({
656
+ idAccessor: defaultIdAccessor
657
+ }, options);
658
+ }
659
+ get context() {
660
+ return this._context;
661
+ }
662
+ get options() {
663
+ return this._options;
664
+ }
665
+ refresh(dragging = false) {
666
+ this.onRefresh(dragging);
667
+ }
668
+ updateData(data) {
669
+ this.onUpdate(data);
670
+ }
671
+ emitUpdate(kind = "topology") {
672
+ this.updated.emit({
673
+ layout: this.layout,
674
+ kind
675
+ });
676
+ }
677
+ async clear() {
678
+ await this.onClear();
679
+ }
680
+ async start() {
681
+ await this.onStart();
682
+ }
683
+ async stop() {
684
+ await this.onStop();
685
+ }
686
+ onRefresh(dragging = false) {
687
+ }
688
+ onUpdate(data) {
689
+ }
690
+ async onClear() {
691
+ }
692
+ async onStart() {
693
+ }
694
+ async onStop() {
695
+ }
696
+ };
697
+
698
+ // src/graph/projector/graph-projector.ts
699
+ var GraphProjector = class extends Projector {
700
+ _selection;
701
+ _layout;
702
+ // TODO(burdon): Change to object props.
703
+ constructor(context, options, _selection, layout) {
704
+ super(context, options), this._selection = _selection;
705
+ this._layout = {
706
+ id: (Math.random() * 10).toString().slice(8),
707
+ graph: {
708
+ nodes: [
709
+ ...layout?.graph.nodes ?? []
710
+ ],
711
+ edges: [
712
+ ...layout?.graph.edges ?? []
713
+ ]
714
+ }
715
+ };
716
+ }
717
+ get layout() {
718
+ return this._layout;
719
+ }
720
+ get selection() {
721
+ return this._selection;
722
+ }
723
+ numChildren(node) {
724
+ return this._layout.graph.edges.filter((edge) => edge.source.id === this.options.idAccessor(node)).length;
725
+ }
726
+ reset() {
727
+ this._layout.graph.nodes = [];
728
+ this._layout.graph.edges = [];
729
+ this.emitUpdate();
730
+ }
731
+ /**
732
+ * Merge external data with internal representation (e.g., so force properties like position are preserved).
733
+ * @param data
734
+ */
735
+ mergeData(data = emptyGraph) {
736
+ const nodes = data.nodes.map((node) => {
737
+ let current = this._layout.graph.nodes.find((n) => n.id === this.options.idAccessor(node));
738
+ if (!current) {
739
+ current = {
740
+ id: this.options.idAccessor(node)
741
+ };
742
+ }
743
+ current.data = node;
744
+ current.hidden = false;
745
+ return current;
746
+ });
747
+ const edges = data.edges.map((edge) => ({
748
+ id: edge.id,
749
+ type: edge.type,
750
+ source: nodes.find((n) => n.id === edge.source),
751
+ target: nodes.find((n) => n.id === edge.target),
752
+ data: edge.data
753
+ })).filter((edge) => edge.source && edge.target);
754
+ Object.assign(this._layout, {
755
+ graph: {
756
+ nodes,
757
+ edges
758
+ }
759
+ });
760
+ }
761
+ async onClear() {
762
+ this.reset();
763
+ }
764
+ /**
765
+ * Optional projector-owned click intercept. The Graph component invokes this BEFORE
766
+ * forwarding to the consumer's `onSelect`, so projectors can implement built-in
767
+ * interactions (e.g. cluster collapse) without each consumer wiring them. Returning
768
+ * `true` indicates the click was handled — consumer's `onSelect` is suppressed.
769
+ * Default no-op returns `false` so consumer handlers still run.
770
+ */
771
+ handleNodeClick(_node, _event) {
772
+ return false;
773
+ }
774
+ };
775
+
776
+ // src/graph/projector/graph-radial-projector.ts
777
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-radial-projector.ts";
778
+ var GraphRadialProjector = class extends GraphProjector {
779
+ _timer;
780
+ findNode(x, y, radius) {
781
+ return void 0;
782
+ }
783
+ onUpdate(graph) {
784
+ log("onUpdate", {
785
+ graph: {
786
+ nodes: graph?.nodes.length,
787
+ edges: graph?.edges.length
788
+ }
789
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 13, S: this });
790
+ this.mergeData(graph);
791
+ this.emitUpdate("topology");
792
+ this.doRadialLayout();
793
+ }
794
+ animate() {
795
+ this._timer?.stop();
796
+ this._timer = void 0;
797
+ const start = Date.now();
798
+ if (this.options.duration) {
799
+ this._timer = timer(() => {
800
+ const t = Math.min(1, (Date.now() - start) / this.options.duration);
801
+ const d = easeCubic(t);
802
+ this.layout.graph.nodes.forEach((node) => {
803
+ node.x = node.sx + (node.tx - node.sx) * d;
804
+ node.y = node.sy + (node.ty - node.sy) * d;
805
+ node.r = node.sr + (node.tr - node.sr) * d;
806
+ });
807
+ this.onTickFrame(d);
808
+ this.emitUpdate("positions");
809
+ if (t >= 1) {
810
+ this._timer.stop();
811
+ this._timer = void 0;
812
+ }
813
+ });
814
+ } else {
815
+ this.layout.graph.nodes.forEach((node) => {
816
+ node.x = node.tx;
817
+ node.y = node.ty;
818
+ node.r = node.tr;
819
+ });
820
+ this.onTickFrame(1);
821
+ this.emitUpdate("positions");
822
+ }
823
+ }
824
+ /**
825
+ * Per-frame hook called after node x/y/r are interpolated and before the
826
+ * 'positions' emit. Subclasses override to update edge geometry (`edge.path`)
827
+ * so curves stay glued to moving endpoints. `t` is the eased progress in [0, 1].
828
+ */
829
+ onTickFrame(t) {
830
+ }
831
+ async onStop() {
832
+ this._timer?.stop();
833
+ this._timer = void 0;
834
+ }
835
+ doRadialLayout() {
836
+ if (!this.context.size) {
837
+ return;
838
+ }
839
+ const radial = layoutRadial(0, 0, this.options.radius ?? Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 80), this.layout.graph.nodes.length);
840
+ this.layout.graph.nodes.forEach((node, i) => {
841
+ const [tx, ty] = radial(i);
842
+ updateNode(node, [
843
+ tx,
844
+ ty
845
+ ]);
846
+ });
847
+ this.animate();
848
+ }
849
+ };
850
+ var updateNode = (node, [tx, ty], tr = 8) => {
851
+ const sx = node.x ?? tx;
852
+ const sy = node.y ?? ty;
853
+ const sr = node.r ?? tr;
854
+ Object.assign(node, {
855
+ initialized: true,
856
+ // Start.
857
+ sx,
858
+ sy,
859
+ sr,
860
+ // Target.
861
+ tx,
862
+ ty,
863
+ tr,
864
+ // Current.
865
+ x: sx,
866
+ y: sy,
867
+ r: sr
868
+ });
869
+ };
870
+ var layoutRadial = (x, y, r, n, start = -Math.PI / 2) => {
871
+ const da = 2 * Math.PI / n;
872
+ return (i) => {
873
+ const a = start + i * da;
874
+ return [
875
+ x + Math.cos(a) * r,
876
+ y + Math.sin(a) * r
877
+ ];
878
+ };
879
+ };
880
+ var layoutHorizontal = (x, y, w, n) => {
881
+ const dx = n > 1 ? w / (n - 1) : 0;
882
+ const sx = x - (n - 1) * dx / 2;
883
+ return (i) => {
884
+ return [
885
+ sx + i * dx,
886
+ y
887
+ ];
888
+ };
889
+ };
890
+ var layoutVertical = (x, y, h, n) => {
891
+ const dy = n > 1 ? h / (n - 1) : 0;
892
+ const sy = y - (n - 1) * dy / 2;
893
+ return (i) => {
894
+ return [
895
+ x,
896
+ sy + i * dy
897
+ ];
898
+ };
899
+ };
900
+
901
+ // src/graph/projector/graph-bundle-projector.ts
902
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-bundle-projector.ts";
903
+ var ROOT_ID = "__bundle_root__";
904
+ var GROUP_PREFIX = "__bundle_group__:";
905
+ var cartesianToPolar = (x, y) => ({
906
+ angle: Math.atan2(x, -y),
907
+ radius: Math.hypot(x, y)
908
+ });
909
+ var GraphBundleProjector = class extends GraphRadialProjector {
910
+ // Per-edge polar point arrays. Points 0 and N-1 are the source / target leaves and are
911
+ // overwritten from current cartesian on every tick; intermediate points stay fixed at
912
+ // their cluster-layout polar coordinates.
913
+ #edgePoints = /* @__PURE__ */ new Map();
914
+ #lineGen = lineRadial().radius((d) => d.radius).angle((d) => d.angle);
915
+ onUpdate(graph) {
916
+ log2("onUpdate", {
917
+ graph: {
918
+ nodes: graph?.nodes.length,
919
+ edges: graph?.edges.length
920
+ }
921
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 40, S: this });
922
+ this.mergeData(graph);
923
+ this.doBundleLayout();
924
+ this.emitUpdate("topology");
925
+ this.animate();
926
+ }
927
+ /**
928
+ * Refresh leaf endpoint polar values from current cartesian so the curve tracks
929
+ * its endpoints during the tween. Internal hierarchy positions stay constant.
930
+ */
931
+ onTickFrame(_t) {
932
+ for (const edge of this.layout.graph.edges) {
933
+ if (edge.type !== "bundle") {
934
+ continue;
935
+ }
936
+ const points = this.#edgePoints.get(edge.id);
937
+ if (!points || points.length < 2) {
938
+ continue;
939
+ }
940
+ const s = cartesianToPolar(edge.source.x ?? 0, edge.source.y ?? 0);
941
+ const t = cartesianToPolar(edge.target.x ?? 0, edge.target.y ?? 0);
942
+ points[0] = {
943
+ angle: s.angle,
944
+ radius: s.radius
945
+ };
946
+ points[points.length - 1] = {
947
+ angle: t.angle,
948
+ radius: t.radius
949
+ };
950
+ edge.path = this.#lineGen(points) ?? void 0;
951
+ }
952
+ }
953
+ doBundleLayout() {
954
+ if (!this.context.size) {
955
+ return;
956
+ }
957
+ const dataNodes = [
958
+ ...this.layout.graph.nodes
959
+ ];
960
+ if (!dataNodes.length) {
961
+ return;
962
+ }
963
+ const groupOf = this.options.groupOf;
964
+ const items = [
965
+ {
966
+ id: ROOT_ID
967
+ }
968
+ ];
969
+ const groupIds = /* @__PURE__ */ new Map();
970
+ for (const node of dataNodes) {
971
+ const key = groupOf?.(node);
972
+ let parent = ROOT_ID;
973
+ if (key !== void 0) {
974
+ let groupId = groupIds.get(key);
975
+ if (!groupId) {
976
+ groupId = `${GROUP_PREFIX}${key}`;
977
+ groupIds.set(key, groupId);
978
+ items.push({
979
+ id: groupId,
980
+ parent: ROOT_ID
981
+ });
982
+ }
983
+ parent = groupId;
984
+ }
985
+ items.push({
986
+ id: node.id,
987
+ parent,
988
+ node
989
+ });
990
+ }
991
+ const childrenByParent = /* @__PURE__ */ new Map();
992
+ for (const item of items) {
993
+ if (item.parent) {
994
+ const list = childrenByParent.get(item.parent) ?? [];
995
+ list.push(item);
996
+ childrenByParent.set(item.parent, list);
997
+ }
998
+ }
999
+ const root = hierarchy({
1000
+ id: ROOT_ID
1001
+ }, (d) => childrenByParent.get(d.id) ?? []);
1002
+ const { width, height } = this.context.size;
1003
+ const margin = this.options.margin ?? 120;
1004
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1005
+ d3Cluster().size([
1006
+ 2 * Math.PI,
1007
+ ringRadius
1008
+ ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1009
+ const leafR = this.options.leafRadius ?? 4;
1010
+ const tension = this.options.tension ?? 0.85;
1011
+ this.#lineGen = lineRadial().curve(curveBundle.beta(tension)).radius((d) => d.radius).angle((d) => d.angle);
1012
+ const hierById = /* @__PURE__ */ new Map();
1013
+ root.each((d) => {
1014
+ hierById.set(d.data.id, d);
1015
+ });
1016
+ root.leaves().forEach((d) => {
1017
+ const angle = d.x;
1018
+ const radius = d.y;
1019
+ const x = Math.cos(angle - Math.PI / 2) * radius;
1020
+ const y = Math.sin(angle - Math.PI / 2) * radius;
1021
+ if (d.data.node) {
1022
+ updateNode(d.data.node, [
1023
+ x,
1024
+ y
1025
+ ], leafR);
1026
+ }
1027
+ });
1028
+ this.layout.graph.nodes = dataNodes;
1029
+ this.#edgePoints.clear();
1030
+ const incomingEdges = [
1031
+ ...this.layout.graph.edges
1032
+ ];
1033
+ const bundleEdges = [];
1034
+ for (const edge of incomingEdges) {
1035
+ const sourceHier = hierById.get(edge.source.id);
1036
+ const targetHier = hierById.get(edge.target.id);
1037
+ if (!sourceHier || !targetHier || sourceHier === targetHier) {
1038
+ continue;
1039
+ }
1040
+ const pathNodes = sourceHier.path(targetHier);
1041
+ const points = pathNodes.map((n) => ({
1042
+ angle: n.x,
1043
+ radius: n.y
1044
+ }));
1045
+ this.#edgePoints.set(edge.id, points);
1046
+ bundleEdges.push({
1047
+ id: edge.id,
1048
+ type: "bundle",
1049
+ source: edge.source,
1050
+ target: edge.target,
1051
+ data: edge.data
1052
+ });
1053
+ }
1054
+ this.layout.graph.edges = bundleEdges;
1055
+ this.onTickFrame(0);
1056
+ }
1057
+ };
1058
+
1059
+ // src/graph/projector/graph-cluster-projector.ts
1060
+ import { cluster as d3Cluster2, hierarchy as hierarchy2, linkRadial } from "d3";
1061
+ import { log as log3 } from "@dxos/log";
1062
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-cluster-projector.ts";
1063
+ var ROOT_ID2 = "__cluster_root__";
1064
+ var GROUP_PREFIX2 = "__group__:";
1065
+ var HIER_EDGE_PREFIX = "__hier__:";
1066
+ var CLUSTER_NODE_TYPE_LEAF = "leaf";
1067
+ var CLUSTER_NODE_TYPE_GROUP = "group";
1068
+ var CLUSTER_NODE_TYPE_ROOT = "root";
1069
+ var linkPath = linkRadial().angle((d) => d.x).radius((d) => d.y);
1070
+ var cartesianToPolar2 = (x, y) => ({
1071
+ angle: Math.atan2(x, -y),
1072
+ radius: Math.hypot(x, y)
1073
+ });
1074
+ var GraphClusterProjector = class extends GraphRadialProjector {
1075
+ // Synthetic-node ids (root id, or `${GROUP_PREFIX}${key}`) whose subtree is currently
1076
+ // hidden. Clicking the corresponding rendered circle calls toggleCollapsed to flip
1077
+ // membership, then re-runs the layout so the renderer's exit transition fades the
1078
+ // hidden leaves + hierarchy edges out (and back in on expand).
1079
+ #collapsed = /* @__PURE__ */ new Set();
1080
+ // Snapshot of the full data-node set as of the last mergeData. doClusterLayout always
1081
+ // reads from this rather than `layout.graph.nodes` — the layout view is filtered (it
1082
+ // drops hidden leaves so the renderer doesn't see them), so re-reading from there
1083
+ // would permanently lose the hidden leaves and they couldn't reappear on expand.
1084
+ #dataNodes = [];
1085
+ /**
1086
+ * Built-in click semantics: clicking a synthetic root / group node toggles its subtree.
1087
+ * Leaf clicks fall through to the consumer's `onSelect` (returns `false`).
1088
+ */
1089
+ handleNodeClick(node, _event) {
1090
+ if (node.type !== CLUSTER_NODE_TYPE_ROOT && node.type !== CLUSTER_NODE_TYPE_GROUP) {
1091
+ return false;
1092
+ }
1093
+ this.toggleCollapsed(node.id);
1094
+ return true;
1095
+ }
1096
+ /** Toggle collapse state for a synthetic node id. Triggers a topology re-emit. */
1097
+ toggleCollapsed(id) {
1098
+ if (this.#collapsed.has(id)) {
1099
+ this.#collapsed.delete(id);
1100
+ } else {
1101
+ this.#collapsed.add(id);
1102
+ }
1103
+ this.doClusterLayout();
1104
+ this.emitUpdate("topology");
1105
+ this.animate();
1106
+ }
1107
+ /** Whether a synthetic-node id is currently collapsed. */
1108
+ isCollapsed(id) {
1109
+ return this.#collapsed.has(id);
1110
+ }
1111
+ onUpdate(graph) {
1112
+ log3("onUpdate", {
1113
+ graph: {
1114
+ nodes: graph?.nodes.length,
1115
+ edges: graph?.edges.length
1116
+ }
1117
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 79, S: this });
1118
+ this.mergeData(graph);
1119
+ this.#dataNodes = [
1120
+ ...this.layout.graph.nodes
1121
+ ];
1122
+ this.doClusterLayout();
1123
+ this.emitUpdate("topology");
1124
+ this.animate();
1125
+ }
1126
+ /**
1127
+ * Recompute each hierarchy edge's `path` from current cartesian source/target positions,
1128
+ * so the curves track moving endpoints during a cross-variant tween (e.g. force → cluster)
1129
+ * instead of being pinned to the final polar layout.
1130
+ */
1131
+ onTickFrame(_t) {
1132
+ for (const edge of this.layout.graph.edges) {
1133
+ if (edge.type !== "hierarchy") {
1134
+ continue;
1135
+ }
1136
+ const { source, target } = edge;
1137
+ const s = cartesianToPolar2(source.x ?? 0, source.y ?? 0);
1138
+ const t = cartesianToPolar2(target.x ?? 0, target.y ?? 0);
1139
+ edge.path = linkPath({
1140
+ source: {
1141
+ x: s.angle,
1142
+ y: s.radius
1143
+ },
1144
+ target: {
1145
+ x: t.angle,
1146
+ y: t.radius
1147
+ }
1148
+ });
1149
+ }
1150
+ }
1151
+ doClusterLayout() {
1152
+ if (!this.context.size) {
1153
+ return;
1154
+ }
1155
+ const dataNodes = this.#dataNodes;
1156
+ if (!dataNodes.length) {
1157
+ return;
1158
+ }
1159
+ const groupOf = this.options.groupOf;
1160
+ const rootId = this.options.rootId ?? ROOT_ID2;
1161
+ const items = [
1162
+ {
1163
+ id: rootId
1164
+ }
1165
+ ];
1166
+ const groupIds = /* @__PURE__ */ new Map();
1167
+ const rootCollapsed = this.#collapsed.has(rootId);
1168
+ if (!rootCollapsed) {
1169
+ for (const node of dataNodes) {
1170
+ const key = groupOf?.(node);
1171
+ let parent = rootId;
1172
+ if (key !== void 0) {
1173
+ let groupId = groupIds.get(key);
1174
+ if (!groupId) {
1175
+ groupId = `${GROUP_PREFIX2}${key}`;
1176
+ groupIds.set(key, groupId);
1177
+ items.push({
1178
+ id: groupId,
1179
+ parent: rootId,
1180
+ groupKey: key
1181
+ });
1182
+ }
1183
+ parent = groupId;
1184
+ }
1185
+ if (this.#collapsed.has(parent)) {
1186
+ continue;
1187
+ }
1188
+ items.push({
1189
+ id: node.id,
1190
+ parent,
1191
+ node
1192
+ });
1193
+ }
1194
+ }
1195
+ const childrenByParent = /* @__PURE__ */ new Map();
1196
+ for (const item of items) {
1197
+ if (item.parent) {
1198
+ const list = childrenByParent.get(item.parent) ?? [];
1199
+ list.push(item);
1200
+ childrenByParent.set(item.parent, list);
1201
+ }
1202
+ }
1203
+ const root = hierarchy2({
1204
+ id: rootId
1205
+ }, (d) => childrenByParent.get(d.id) ?? []);
1206
+ const { width, height } = this.context.size;
1207
+ const margin = this.options.margin ?? 80;
1208
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1209
+ d3Cluster2().size([
1210
+ 2 * Math.PI,
1211
+ ringRadius
1212
+ ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1213
+ const leafR = this.options.leafRadius ?? 4;
1214
+ const groupR = this.options.groupRadius ?? 3;
1215
+ const rootR = this.options.rootRadius ?? 5;
1216
+ const prevStubsById = /* @__PURE__ */ new Map();
1217
+ for (const node of this.layout.graph.nodes) {
1218
+ if (node.type === CLUSTER_NODE_TYPE_ROOT || node.type === CLUSTER_NODE_TYPE_GROUP) {
1219
+ prevStubsById.set(node.id, node);
1220
+ }
1221
+ }
1222
+ const syntheticNodes = /* @__PURE__ */ new Map();
1223
+ root.each((d) => {
1224
+ const id = d.data.id;
1225
+ const angle = d.x;
1226
+ const radius = d.y;
1227
+ const x = Math.cos(angle - Math.PI / 2) * radius;
1228
+ const y = Math.sin(angle - Math.PI / 2) * radius;
1229
+ if (d.data.node) {
1230
+ updateNode(d.data.node, [
1231
+ x,
1232
+ y
1233
+ ], leafR);
1234
+ d.data.node.type = CLUSTER_NODE_TYPE_LEAF;
1235
+ d.data.node.hidden = false;
1236
+ } else {
1237
+ const isRoot = id === rootId;
1238
+ const stub = prevStubsById.get(id) ?? {
1239
+ id,
1240
+ x: 0,
1241
+ y: 0
1242
+ };
1243
+ updateNode(stub, [
1244
+ x,
1245
+ y
1246
+ ], isRoot ? rootR : groupR);
1247
+ stub.type = isRoot ? CLUSTER_NODE_TYPE_ROOT : CLUSTER_NODE_TYPE_GROUP;
1248
+ if (isRoot) {
1249
+ stub.label = this.options.rootLabel;
1250
+ } else if (d.data.groupKey !== void 0) {
1251
+ stub.label = this.options.groupLabel ? this.options.groupLabel(d.data.groupKey) : d.data.groupKey;
1252
+ }
1253
+ syntheticNodes.set(id, stub);
1254
+ }
1255
+ });
1256
+ const visibleLeafIds = /* @__PURE__ */ new Set();
1257
+ for (const item of items) {
1258
+ if (item.node) {
1259
+ visibleLeafIds.add(item.id);
1260
+ }
1261
+ }
1262
+ for (const node of dataNodes) {
1263
+ if (visibleLeafIds.has(node.id)) {
1264
+ continue;
1265
+ }
1266
+ const key = groupOf?.(node);
1267
+ const parentId = key !== void 0 && groupIds.has(key) ? groupIds.get(key) : rootId;
1268
+ const parentStub = syntheticNodes.get(parentId);
1269
+ const targetX = parentStub?.tx ?? 0;
1270
+ const targetY = parentStub?.ty ?? 0;
1271
+ updateNode(node, [
1272
+ targetX,
1273
+ targetY
1274
+ ], leafR);
1275
+ node.type = CLUSTER_NODE_TYPE_LEAF;
1276
+ node.hidden = true;
1277
+ }
1278
+ const nextNodes = [];
1279
+ for (const stub of syntheticNodes.values()) {
1280
+ nextNodes.push(stub);
1281
+ }
1282
+ for (const node of dataNodes) {
1283
+ nextNodes.push(node);
1284
+ }
1285
+ this.layout.graph.nodes = nextNodes;
1286
+ const hierarchyEdges = [];
1287
+ root.links().forEach((link) => {
1288
+ const sid = link.source.data.id;
1289
+ const tid = link.target.data.id;
1290
+ const sourceNode = link.source.data.node ?? syntheticNodes.get(sid);
1291
+ const targetNode = link.target.data.node ?? syntheticNodes.get(tid);
1292
+ hierarchyEdges.push({
1293
+ id: `${HIER_EDGE_PREFIX}${sid}->${tid}`,
1294
+ type: "hierarchy",
1295
+ source: sourceNode,
1296
+ target: targetNode,
1297
+ data: void 0
1298
+ });
1299
+ });
1300
+ this.layout.graph.edges = hierarchyEdges;
1301
+ this.onTickFrame(0);
1302
+ }
79
1303
  };
80
1304
 
81
1305
  // src/graph/projector/graph-drag.ts
@@ -158,169 +1382,9 @@ var createGraphDrag = (context, projector, options = defaultDragOptions) => {
158
1382
  });
159
1383
  };
160
1384
 
161
- // src/graph/types.ts
162
- import { invariant } from "@dxos/invariant";
163
- var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/types.ts";
164
- var defaultIdAccessor = (node) => {
165
- invariant(node.id, void 0, {
166
- F: __dxlog_file,
167
- L: 18,
168
- S: void 0,
169
- A: [
170
- "node.id",
171
- ""
172
- ]
173
- });
174
- return node.id;
175
- };
176
- var emptyGraph = {
177
- nodes: [],
178
- edges: []
179
- };
180
-
181
- // src/graph/projector/projector.ts
182
- function _define_property(obj, key, value) {
183
- if (key in obj) {
184
- Object.defineProperty(obj, key, {
185
- value,
186
- enumerable: true,
187
- configurable: true,
188
- writable: true
189
- });
190
- } else {
191
- obj[key] = value;
192
- }
193
- return obj;
194
- }
195
- var Projector = class {
196
- get context() {
197
- return this._context;
198
- }
199
- get options() {
200
- return this._options;
201
- }
202
- refresh(dragging = false) {
203
- this.onRefresh(dragging);
204
- }
205
- updateData(data) {
206
- this.onUpdate(data);
207
- }
208
- emitUpdate() {
209
- this.updated.emit({
210
- layout: this.layout
211
- });
212
- }
213
- async clear() {
214
- await this.onClear();
215
- }
216
- async start() {
217
- await this.onStart();
218
- }
219
- async stop() {
220
- await this.onStop();
221
- }
222
- onRefresh(dragging = false) {
223
- }
224
- onUpdate(data) {
225
- }
226
- async onClear() {
227
- }
228
- async onStart() {
229
- }
230
- async onStop() {
231
- }
232
- constructor(_context, options) {
233
- _define_property(this, "_context", void 0);
234
- _define_property(this, "updated", void 0);
235
- _define_property(this, "_options", void 0);
236
- this._context = _context;
237
- this.updated = new EventEmitter();
238
- this._options = Object.assign({
239
- idAccessor: defaultIdAccessor
240
- }, options);
241
- }
242
- };
243
-
244
- // src/graph/projector/graph-projector.ts
245
- function _define_property2(obj, key, value) {
246
- if (key in obj) {
247
- Object.defineProperty(obj, key, {
248
- value,
249
- enumerable: true,
250
- configurable: true,
251
- writable: true
252
- });
253
- } else {
254
- obj[key] = value;
255
- }
256
- return obj;
257
- }
258
- var GraphProjector = class extends Projector {
259
- get layout() {
260
- return this._layout;
261
- }
262
- get selection() {
263
- return this._selection;
264
- }
265
- numChildren(node) {
266
- return this._layout.graph.edges.filter((edge) => edge.source.id === this.options.idAccessor(node)).length;
267
- }
268
- reset() {
269
- this._layout.graph.nodes = [];
270
- this._layout.graph.edges = [];
271
- this.emitUpdate();
272
- }
273
- /**
274
- * Merge external data with internal representation (e.g., so force properties like position are preserved).
275
- * @param data
276
- */
277
- mergeData(data = emptyGraph) {
278
- const nodes = data.nodes.map((node) => {
279
- let current = this._layout.graph.nodes.find((n) => n.id === this.options.idAccessor(node));
280
- if (!current) {
281
- current = {
282
- id: this.options.idAccessor(node)
283
- };
284
- }
285
- current.data = node;
286
- return current;
287
- });
288
- const edges = data.edges.map((edge) => ({
289
- id: edge.id,
290
- source: nodes.find((n) => n.id === edge.source),
291
- target: nodes.find((n) => n.id === edge.target),
292
- data: edge.data
293
- })).filter((edge) => edge.source && edge.target);
294
- Object.assign(this._layout, {
295
- graph: {
296
- nodes,
297
- edges
298
- }
299
- });
300
- }
301
- async onClear() {
302
- this.reset();
303
- }
304
- // TODO(burdon): Change to object props.
305
- constructor(context, options, _selection, layout) {
306
- super(context, options), _define_property2(this, "_selection", void 0), _define_property2(this, "_layout", void 0), this._selection = _selection;
307
- this._layout = {
308
- id: (Math.random() * 10).toString().slice(8),
309
- graph: {
310
- nodes: [
311
- ...layout?.graph.nodes ?? []
312
- ],
313
- edges: [
314
- ...layout?.graph.edges ?? []
315
- ]
316
- }
317
- };
318
- }
319
- };
320
-
321
1385
  // src/graph/projector/graph-force-projector.ts
322
1386
  import { forceCenter, forceCollide, forceLink, forceManyBody, forceRadial, forceSimulation, forceX as forceX2, forceY as forceY2 } from "d3";
323
- import { log } from "@dxos/log";
1387
+ import { log as log4 } from "@dxos/log";
324
1388
 
325
1389
  // src/graph/projector/graph-forces.ts
326
1390
  import { forceX, forceY } from "d3";
@@ -339,20 +1403,7 @@ var forcePoint = ({ x, y, strength = 0.01 }) => {
339
1403
  };
340
1404
 
341
1405
  // src/graph/projector/graph-force-projector.ts
342
- function _define_property3(obj, key, value) {
343
- if (key in obj) {
344
- Object.defineProperty(obj, key, {
345
- value,
346
- enumerable: true,
347
- configurable: true,
348
- writable: true
349
- });
350
- } else {
351
- obj[key] = value;
352
- }
353
- return obj;
354
- }
355
- var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-force-projector.ts";
1406
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-force-projector.ts";
356
1407
  var getValue = (valueOrFunction, invoker, defaultValue) => {
357
1408
  return (typeof valueOrFunction === "function" ? invoker(valueOrFunction) : valueOrFunction) ?? defaultValue;
358
1409
  };
@@ -369,6 +1420,9 @@ var defaultForceOptions = {
369
1420
  point: true
370
1421
  };
371
1422
  var GraphForceProjector = class extends GraphProjector {
1423
+ // https://github.com/d3/d3-force
1424
+ _simulation = forceSimulation();
1425
+ _timeout;
372
1426
  get forces() {
373
1427
  return this.options.forces ?? defaultForceOptions;
374
1428
  }
@@ -399,7 +1453,7 @@ var GraphForceProjector = class extends GraphProjector {
399
1453
  } else {
400
1454
  this.updateForces(this.forces);
401
1455
  }
402
- this._simulation.on("tick", () => propagating && this.emitUpdate()).velocityDecay(0.3).alphaDecay(1 - Math.pow(1e-3, 1 / 300)).alpha(1).restart();
1456
+ this._simulation.on("tick", () => propagating && this.emitUpdate("positions")).velocityDecay(0.3).alphaDecay(1 - Math.pow(1e-3, 1 / 300)).alpha(1).restart();
403
1457
  }
404
1458
  async onStop() {
405
1459
  clearTimeout(this._timeout);
@@ -416,21 +1470,17 @@ var GraphForceProjector = class extends GraphProjector {
416
1470
  this.restart();
417
1471
  }
418
1472
  onUpdate(graph) {
419
- log("onUpdate", {
1473
+ log4("onUpdate", {
420
1474
  graph: {
421
1475
  nodes: graph?.nodes.length,
422
1476
  edges: graph?.edges.length
423
1477
  }
424
- }, {
425
- F: __dxlog_file2,
426
- L: 227,
427
- S: this,
428
- C: (f, a) => f(...a)
429
- });
1478
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 91, S: this });
430
1479
  this._simulation.stop();
431
1480
  this.mergeData(graph);
432
1481
  this.updateLayout();
433
1482
  this.updateForces(this.forces);
1483
+ this.emitUpdate("topology");
434
1484
  this.restart();
435
1485
  }
436
1486
  updateLayout() {
@@ -474,14 +1524,9 @@ var GraphForceProjector = class extends GraphProjector {
474
1524
  * Update all forces.
475
1525
  */
476
1526
  updateForces(forces) {
477
- log("updateForces", {
1527
+ log4("updateForces", {
478
1528
  forces
479
- }, {
480
- F: __dxlog_file2,
481
- L: 288,
482
- S: this,
483
- C: (f, a) => f(...a)
484
- });
1529
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 153, S: this });
485
1530
  this._simulation.nodes(this.layout.graph.nodes).force("link", maybeForce(forces?.link, (config) => {
486
1531
  const force = forceLink().id((d) => d.id).links(this.layout.graph.edges.filter((edge) => edge.linkForce));
487
1532
  if (config.distance != null) {
@@ -523,182 +1568,42 @@ var GraphForceProjector = class extends GraphProjector {
523
1568
  }
524
1569
  return force;
525
1570
  })).force("point", maybeForce(forces?.point, ({ x = 0, y = 0, strength }) => {
526
- return forcePoint({
527
- x,
528
- y,
529
- strength
530
- });
531
- })).force("x", maybeForce(forces?.x, (config) => {
532
- const force = forceX2(config.x ?? 0);
533
- if (config.strength != null) {
534
- force.strength(config.strength);
535
- }
536
- return force;
537
- })).force("y", maybeForce(forces?.y, (config) => {
538
- const force = forceY2(config.y ?? 0);
539
- if (config.strength != null) {
540
- force.strength(config.strength);
541
- }
542
- return force;
543
- }));
544
- }
545
- constructor(...args) {
546
- super(...args), // https://github.com/d3/d3-force
547
- _define_property3(this, "_simulation", forceSimulation()), _define_property3(this, "_timeout", void 0);
548
- }
549
- };
550
-
551
- // src/graph/projector/graph-hierarchical-projector.ts
552
- import { log as log3 } from "@dxos/log";
553
-
554
- // src/graph/projector/graph-radial-projector.ts
555
- import { easeCubic, timer } from "d3";
556
- import { log as log2 } from "@dxos/log";
557
- function _define_property4(obj, key, value) {
558
- if (key in obj) {
559
- Object.defineProperty(obj, key, {
560
- value,
561
- enumerable: true,
562
- configurable: true,
563
- writable: true
564
- });
565
- } else {
566
- obj[key] = value;
567
- }
568
- return obj;
569
- }
570
- var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-radial-projector.ts";
571
- var GraphRadialProjector = class extends GraphProjector {
572
- findNode(x, y, radius) {
573
- return void 0;
574
- }
575
- onUpdate(graph) {
576
- log2("onUpdate", {
577
- graph: {
578
- nodes: graph?.nodes.length,
579
- edges: graph?.edges.length
580
- }
581
- }, {
582
- F: __dxlog_file3,
583
- L: 32,
584
- S: this,
585
- C: (f, a) => f(...a)
586
- });
587
- this.mergeData(graph);
588
- this.doRadialLayout();
589
- }
590
- animate() {
591
- const start = Date.now();
592
- if (this.options.duration) {
593
- this._timer = timer(() => {
594
- const t = Math.min(1, (Date.now() - start) / this.options.duration);
595
- const d = easeCubic(t);
596
- this.layout.graph.nodes.forEach((node) => {
597
- node.x = node.sx + (node.tx - node.sx) * d;
598
- node.y = node.sy + (node.ty - node.sy) * d;
599
- node.r = node.sr + (node.tr - node.sr) * d;
600
- });
601
- this.emitUpdate();
602
- if (t >= 1) {
603
- this._timer.stop();
604
- this._timer = void 0;
605
- }
1571
+ return forcePoint({
1572
+ x,
1573
+ y,
1574
+ strength
606
1575
  });
607
- } else {
608
- this.emitUpdate();
609
- }
610
- }
611
- async onStop() {
612
- this._timer?.stop();
613
- this._timer = void 0;
614
- }
615
- doRadialLayout() {
616
- if (!this.context.size) {
617
- return;
618
- }
619
- const radial = layoutRadial(0, 0, this.options.radius ?? Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 80), this.layout.graph.nodes.length);
620
- this.layout.graph.nodes.forEach((node, i) => {
621
- const [tx, ty] = radial(i);
622
- updateNode(node, [
623
- tx,
624
- ty
625
- ]);
626
- });
627
- this.animate();
628
- }
629
- constructor(...args) {
630
- super(...args), _define_property4(this, "_timer", void 0);
1576
+ })).force("x", maybeForce(forces?.x, (config) => {
1577
+ const force = forceX2(config.x ?? 0);
1578
+ if (config.strength != null) {
1579
+ force.strength(config.strength);
1580
+ }
1581
+ return force;
1582
+ })).force("y", maybeForce(forces?.y, (config) => {
1583
+ const force = forceY2(config.y ?? 0);
1584
+ if (config.strength != null) {
1585
+ force.strength(config.strength);
1586
+ }
1587
+ return force;
1588
+ }));
631
1589
  }
632
1590
  };
633
- var updateNode = (node, [tx, ty], tr = 8) => {
634
- const sx = node.x ?? tx;
635
- const sy = node.y ?? ty;
636
- const sr = node.r ?? tr;
637
- Object.assign(node, {
638
- initialized: true,
639
- // Start.
640
- sx,
641
- sy,
642
- sr,
643
- // Target.
644
- tx,
645
- ty,
646
- tr,
647
- // Current.
648
- x: sx,
649
- y: sy,
650
- r: sr
651
- });
652
- };
653
- var layoutRadial = (x, y, r, n, start = -Math.PI / 2) => {
654
- const da = 2 * Math.PI / n;
655
- return (i) => {
656
- const a = start + i * da;
657
- return [
658
- x + Math.cos(a) * r,
659
- y + Math.sin(a) * r
660
- ];
661
- };
662
- };
663
- var layoutHorizontal = (x, y, w, n) => {
664
- const dx = n > 1 ? w / (n - 1) : 0;
665
- const sx = x - (n - 1) * dx / 2;
666
- return (i) => {
667
- return [
668
- sx + i * dx,
669
- y
670
- ];
671
- };
672
- };
673
- var layoutVertical = (x, y, h, n) => {
674
- const dy = n > 1 ? h / (n - 1) : 0;
675
- const sy = y - (n - 1) * dy / 2;
676
- return (i) => {
677
- return [
678
- x,
679
- sy + i * dy
680
- ];
681
- };
682
- };
683
1591
 
684
1592
  // src/graph/projector/graph-hierarchical-projector.ts
685
- var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-hierarchical-projector.ts";
1593
+ import { log as log5 } from "@dxos/log";
1594
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-hierarchical-projector.ts";
686
1595
  var GraphHierarchicalProjector = class extends GraphRadialProjector {
687
1596
  onUpdate(graph) {
688
- log3("onUpdate", {
1597
+ log5("onUpdate", {
689
1598
  graph: {
690
1599
  nodes: graph?.nodes.length,
691
1600
  edges: graph?.edges.length
692
1601
  },
693
- selection: this.selection?.selected.value
694
- }, {
695
- F: __dxlog_file4,
696
- L: 24,
697
- S: this,
698
- C: (f, a) => f(...a)
699
- });
1602
+ selection: this.selection?.getSelectedIds()
1603
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 8, S: this });
700
1604
  this.mergeData(graph);
701
- const selected = this.selection?.selected.value?.[0];
1605
+ this.emitUpdate("topology");
1606
+ const selected = this.selection?.getSelectedIds()[0];
702
1607
  if (selected) {
703
1608
  const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
704
1609
  if (node) {
@@ -743,25 +1648,307 @@ var GraphHierarchicalProjector = class extends GraphRadialProjector {
743
1648
  }
744
1649
  };
745
1650
 
1651
+ // src/graph/projector/graph-lattice-projector.ts
1652
+ import { log as log6 } from "@dxos/log";
1653
+ var __dxlog_file8 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-lattice-projector.ts";
1654
+ var GraphLatticeProjector = class extends GraphRadialProjector {
1655
+ onUpdate(graph) {
1656
+ log6("onUpdate", {
1657
+ graph: {
1658
+ nodes: graph?.nodes.length,
1659
+ edges: graph?.edges.length
1660
+ }
1661
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 14, S: this });
1662
+ this.mergeData(graph);
1663
+ this.doLatticeLayout();
1664
+ this.emitUpdate("topology");
1665
+ this.animate();
1666
+ }
1667
+ doLatticeLayout() {
1668
+ if (!this.context.size) {
1669
+ return;
1670
+ }
1671
+ const nodes = this.layout.graph.nodes;
1672
+ const count = nodes.length;
1673
+ if (!count) {
1674
+ return;
1675
+ }
1676
+ const sortBy = this.options.sortBy ?? ((n) => n.data?.label ?? n.id);
1677
+ nodes.sort((a, b) => sortBy(a).localeCompare(sortBy(b)));
1678
+ const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
1679
+ const rows = Math.ceil(count / columns);
1680
+ const margin = this.options.margin ?? 16;
1681
+ const { width, height } = this.context.size;
1682
+ const innerW = Math.max(0, width - 2 * margin);
1683
+ const innerH = Math.max(0, height - 2 * margin);
1684
+ const r = this.options.radius ?? 6;
1685
+ const fit = Math.min(innerW / columns, innerH / rows);
1686
+ const cellSize = Math.max(0, Math.min(fit, r * 6));
1687
+ const gridW = cellSize * columns;
1688
+ const gridH = cellSize * rows;
1689
+ const offsetX = -gridW / 2 + cellSize / 2;
1690
+ const offsetY = -gridH / 2 + cellSize / 2;
1691
+ nodes.forEach((node, i) => {
1692
+ const tx = offsetX + i % columns * cellSize;
1693
+ const ty = offsetY + Math.floor(i / columns) * cellSize;
1694
+ updateNode(node, [
1695
+ tx,
1696
+ ty
1697
+ ], r);
1698
+ });
1699
+ }
1700
+ };
1701
+
1702
+ // src/graph/projector/graph-plexus-projector.ts
1703
+ import { cluster as d3Cluster3, hierarchy as hierarchy3, linkRadial as linkRadial2 } from "d3";
1704
+ import { log as log7 } from "@dxos/log";
1705
+ var __dxlog_file9 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-plexus-projector.ts";
1706
+ var RELATION_PREFIX = "__plexus_relation__:";
1707
+ var HIER_EDGE_PREFIX2 = "__plexus_hier__:";
1708
+ var PLEXUS_NODE_TYPE_FOCUS = "plexus-focus";
1709
+ var PLEXUS_NODE_TYPE_RELATION = "plexus-relation";
1710
+ var PLEXUS_NODE_TYPE_OBJECT = "plexus-object";
1711
+ var linkPath2 = linkRadial2().angle((d) => d.x).radius((d) => d.y);
1712
+ var cartesianToPolar3 = (x, y) => ({
1713
+ angle: Math.atan2(x, -y),
1714
+ radius: Math.hypot(x, y)
1715
+ });
1716
+ var GraphPlexusProjector = class extends GraphRadialProjector {
1717
+ // Full node / edge snapshots taken right after mergeData — doPlexusLayout reads from
1718
+ // these because it overwrites layout.graph with the filtered focus-centric view.
1719
+ #dataNodes = [];
1720
+ #dataEdges = [];
1721
+ onUpdate(graph) {
1722
+ log7("onUpdate", {
1723
+ graph: {
1724
+ nodes: graph?.nodes.length,
1725
+ edges: graph?.edges.length
1726
+ }
1727
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file9, L: 48, S: this });
1728
+ this.mergeData(graph);
1729
+ this.#dataNodes = [
1730
+ ...this.layout.graph.nodes
1731
+ ];
1732
+ this.#dataEdges = [
1733
+ ...this.layout.graph.edges
1734
+ ];
1735
+ this.doPlexusLayout();
1736
+ this.emitUpdate("topology");
1737
+ this.animate();
1738
+ }
1739
+ /**
1740
+ * Recompute each hierarchy edge's `path` from current cartesian endpoints so curves track
1741
+ * moving nodes during the tween (identical strategy to the cluster projector).
1742
+ */
1743
+ onTickFrame(_t) {
1744
+ for (const edge of this.layout.graph.edges) {
1745
+ if (edge.type !== "hierarchy") {
1746
+ continue;
1747
+ }
1748
+ const { source, target } = edge;
1749
+ const s = cartesianToPolar3(source.x ?? 0, source.y ?? 0);
1750
+ const t = cartesianToPolar3(target.x ?? 0, target.y ?? 0);
1751
+ edge.path = linkPath2({
1752
+ source: {
1753
+ x: s.angle,
1754
+ y: s.radius
1755
+ },
1756
+ target: {
1757
+ x: t.angle,
1758
+ y: t.radius
1759
+ }
1760
+ });
1761
+ }
1762
+ }
1763
+ doPlexusLayout() {
1764
+ if (!this.context.size) {
1765
+ return;
1766
+ }
1767
+ const dataNodes = this.#dataNodes;
1768
+ if (!dataNodes.length) {
1769
+ return;
1770
+ }
1771
+ const focusId = this.options.focus;
1772
+ const focusNode = focusId ? dataNodes.find((node) => node.id === focusId) : void 0;
1773
+ if (!focusNode) {
1774
+ const radial = layoutRadial(0, 0, Math.min(this.context.size.width, this.context.size.height) / 2 - (this.options.margin ?? 100), dataNodes.length);
1775
+ dataNodes.forEach((node, index) => updateNode(node, radial(index), this.options.leafRadius ?? 5));
1776
+ this.layout.graph.nodes = dataNodes;
1777
+ this.layout.graph.edges = [];
1778
+ this.animate();
1779
+ return;
1780
+ }
1781
+ const relationOf = this.options.relationOf ?? defaultRelationOf;
1782
+ const groups = /* @__PURE__ */ new Map();
1783
+ const placed = /* @__PURE__ */ new Set([
1784
+ focusId
1785
+ ]);
1786
+ for (const edge of this.#dataEdges) {
1787
+ const relation = relationOf(edge, focusId);
1788
+ if (!relation) {
1789
+ continue;
1790
+ }
1791
+ const neighbour = edge.source.id === focusId ? edge.target : edge.source;
1792
+ if (placed.has(neighbour.id)) {
1793
+ continue;
1794
+ }
1795
+ placed.add(neighbour.id);
1796
+ let group = groups.get(relation.key);
1797
+ if (!group) {
1798
+ group = {
1799
+ id: `${RELATION_PREFIX}${relation.key}`,
1800
+ label: relation.label,
1801
+ leaves: []
1802
+ };
1803
+ groups.set(relation.key, group);
1804
+ }
1805
+ group.leaves.push(neighbour);
1806
+ }
1807
+ const items = [
1808
+ {
1809
+ id: focusId,
1810
+ node: focusNode
1811
+ }
1812
+ ];
1813
+ for (const group of groups.values()) {
1814
+ items.push({
1815
+ id: group.id,
1816
+ parent: focusId,
1817
+ relationLabel: group.label
1818
+ });
1819
+ for (const leaf of group.leaves) {
1820
+ items.push({
1821
+ id: leaf.id,
1822
+ parent: group.id,
1823
+ node: leaf
1824
+ });
1825
+ }
1826
+ }
1827
+ const childrenByParent = /* @__PURE__ */ new Map();
1828
+ for (const item of items) {
1829
+ if (item.parent) {
1830
+ const list = childrenByParent.get(item.parent) ?? [];
1831
+ list.push(item);
1832
+ childrenByParent.set(item.parent, list);
1833
+ }
1834
+ }
1835
+ const root = hierarchy3({
1836
+ id: focusId,
1837
+ node: focusNode
1838
+ }, (d) => childrenByParent.get(d.id) ?? []);
1839
+ const { width, height } = this.context.size;
1840
+ const margin = this.options.margin ?? 100;
1841
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1842
+ d3Cluster3().size([
1843
+ 2 * Math.PI,
1844
+ ringRadius
1845
+ ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1846
+ const leafR = this.options.leafRadius ?? 5;
1847
+ const relationR = this.options.relationRadius ?? leafR;
1848
+ const focusR = this.options.focusRadius ?? leafR * 2;
1849
+ const prevStubsById = /* @__PURE__ */ new Map();
1850
+ for (const node of this.layout.graph.nodes) {
1851
+ if (node.type === PLEXUS_NODE_TYPE_RELATION) {
1852
+ prevStubsById.set(node.id, node);
1853
+ }
1854
+ }
1855
+ const relationStubs = /* @__PURE__ */ new Map();
1856
+ root.each((d) => {
1857
+ const angle = d.x;
1858
+ const radius = d.y;
1859
+ const x = Math.cos(angle - Math.PI / 2) * radius;
1860
+ const y = Math.sin(angle - Math.PI / 2) * radius;
1861
+ const id = d.data.id;
1862
+ if (id === focusId) {
1863
+ updateNode(focusNode, [
1864
+ x,
1865
+ y
1866
+ ], focusR);
1867
+ focusNode.type = PLEXUS_NODE_TYPE_FOCUS;
1868
+ focusNode.hidden = false;
1869
+ } else if (d.data.node) {
1870
+ updateNode(d.data.node, [
1871
+ x,
1872
+ y
1873
+ ], leafR);
1874
+ d.data.node.type = PLEXUS_NODE_TYPE_OBJECT;
1875
+ d.data.node.hidden = false;
1876
+ } else {
1877
+ const stub = prevStubsById.get(id) ?? {
1878
+ id,
1879
+ x: 0,
1880
+ y: 0
1881
+ };
1882
+ updateNode(stub, [
1883
+ x,
1884
+ y
1885
+ ], relationR);
1886
+ stub.type = PLEXUS_NODE_TYPE_RELATION;
1887
+ stub.label = d.data.relationLabel;
1888
+ relationStubs.set(id, stub);
1889
+ }
1890
+ });
1891
+ const nextNodes = [];
1892
+ for (const stub of relationStubs.values()) {
1893
+ nextNodes.push(stub);
1894
+ }
1895
+ for (const group of groups.values()) {
1896
+ for (const leaf of group.leaves) {
1897
+ nextNodes.push(leaf);
1898
+ }
1899
+ }
1900
+ nextNodes.push(focusNode);
1901
+ this.layout.graph.nodes = nextNodes;
1902
+ const edges = [];
1903
+ root.links().forEach((link) => {
1904
+ const sid = link.source.data.id;
1905
+ const tid = link.target.data.id;
1906
+ const sourceNode = sid === focusId ? focusNode : link.source.data.node ?? relationStubs.get(sid);
1907
+ const targetNode = link.target.data.node ?? relationStubs.get(tid);
1908
+ if (!sourceNode || !targetNode) {
1909
+ return;
1910
+ }
1911
+ edges.push({
1912
+ id: `${HIER_EDGE_PREFIX2}${sid}->${tid}`,
1913
+ type: "hierarchy",
1914
+ source: sourceNode,
1915
+ target: targetNode,
1916
+ data: void 0
1917
+ });
1918
+ });
1919
+ this.layout.graph.edges = edges;
1920
+ this.onTickFrame(0);
1921
+ }
1922
+ };
1923
+ var defaultRelationOf = (edge, focusId) => {
1924
+ const outgoing = edge.source.id === focusId;
1925
+ const incoming = edge.target.id === focusId;
1926
+ if (!outgoing && !incoming) {
1927
+ return void 0;
1928
+ }
1929
+ const type = edge.type ?? "edge";
1930
+ const arrow = outgoing ? "\u2192" : "\u2190";
1931
+ return {
1932
+ key: `${type}:${outgoing ? "out" : "in"}`,
1933
+ label: `${type} ${arrow}`
1934
+ };
1935
+ };
1936
+
746
1937
  // src/graph/projector/graph-relational-projector.ts
747
- import { log as log4 } from "@dxos/log";
748
- var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-relational-projector.ts";
1938
+ import { log as log8 } from "@dxos/log";
1939
+ var __dxlog_file10 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-relational-projector.ts";
749
1940
  var GraphRelationalProjector = class extends GraphRadialProjector {
750
1941
  onUpdate(graph) {
751
- log4("onUpdate", {
1942
+ log8("onUpdate", {
752
1943
  graph: {
753
1944
  nodes: graph?.nodes.length,
754
1945
  edges: graph?.edges.length
755
1946
  },
756
- selection: this.selection?.selected.value
757
- }, {
758
- F: __dxlog_file5,
759
- L: 24,
760
- S: this,
761
- C: (f, a) => f(...a)
762
- });
1947
+ selection: this.selection?.getSelectedIds()
1948
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file10, L: 8, S: this });
763
1949
  this.mergeData(graph);
764
- const selected = this.selection?.selected.value?.[0];
1950
+ this.emitUpdate("topology");
1951
+ const selected = this.selection?.getSelectedIds()[0];
765
1952
  if (selected) {
766
1953
  const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
767
1954
  if (node) {
@@ -832,10 +2019,267 @@ var GraphRelationalProjector = class extends GraphRadialProjector {
832
2019
  }
833
2020
  };
834
2021
 
2022
+ // src/graph/projector/graph-swarm-projector.ts
2023
+ import { timer as timer2 } from "d3";
2024
+ import { log as log9 } from "@dxos/log";
2025
+ var __dxlog_file11 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-swarm-projector.ts";
2026
+ var SWARMMATE_RADIUS = 60;
2027
+ var SEPARATION_DISTANCE = 30;
2028
+ var DEFAULTS = {
2029
+ spawnRadius: 200,
2030
+ maxVelocity: 1.2,
2031
+ alignment: 3,
2032
+ cohesion: 3,
2033
+ separation: 3,
2034
+ cursorRepel: 120,
2035
+ avoidance: 3,
2036
+ trailLength: 30
2037
+ };
2038
+ var GraphSwarmProjector = class extends GraphProjector {
2039
+ #timer;
2040
+ /** Cursor in SVG model coordinates, or null when the pointer is outside the surface. */
2041
+ #cursor = null;
2042
+ findNode() {
2043
+ return void 0;
2044
+ }
2045
+ /**
2046
+ * Tell the projector where the pointer is, in SVG model coordinates (the same space
2047
+ * `node.x/y` live in — center origin, post-zoom). Pass `null` (or omit args) on
2048
+ * pointer-leave to disable cursor avoidance.
2049
+ */
2050
+ setCursor(x, y) {
2051
+ if (x == null || y == null) {
2052
+ this.#cursor = null;
2053
+ } else {
2054
+ this.#cursor = {
2055
+ x,
2056
+ y
2057
+ };
2058
+ }
2059
+ }
2060
+ onUpdate(graph) {
2061
+ log9("onUpdate", {
2062
+ graph: {
2063
+ nodes: graph?.nodes.length,
2064
+ edges: graph?.edges.length
2065
+ }
2066
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file11, L: 54, S: this });
2067
+ this.mergeData(graph);
2068
+ this.initializeNodes();
2069
+ this.emitUpdate("topology");
2070
+ }
2071
+ async onStart() {
2072
+ this.startTimer();
2073
+ }
2074
+ async onStop() {
2075
+ this.stopTimer();
2076
+ }
2077
+ onRefresh() {
2078
+ if (!this.#timer) {
2079
+ this.startTimer();
2080
+ }
2081
+ }
2082
+ #opt(key) {
2083
+ return this.options[key] ?? DEFAULTS[key];
2084
+ }
2085
+ initializeNodes() {
2086
+ const spawnRadius = this.#opt("spawnRadius");
2087
+ const maxVelocity = this.#opt("maxVelocity");
2088
+ for (const node of this.layout.graph.nodes) {
2089
+ if (!node.initialized) {
2090
+ const theta = Math.random() * 2 * Math.PI;
2091
+ const r = Math.random() * spawnRadius;
2092
+ node.x = Math.cos(theta) * r;
2093
+ node.y = Math.sin(theta) * r;
2094
+ const phi = Math.random() * 2 * Math.PI;
2095
+ const speed = (0.3 + Math.random() * 0.7) * maxVelocity;
2096
+ node.vx = Math.cos(phi) * speed;
2097
+ node.vy = Math.sin(phi) * speed;
2098
+ node.ax = 0;
2099
+ node.ay = 0;
2100
+ node.initialized = true;
2101
+ } else {
2102
+ node.vx ??= 0;
2103
+ node.vy ??= 0;
2104
+ node.ax ??= 0;
2105
+ node.ay ??= 0;
2106
+ }
2107
+ node.r ??= 6;
2108
+ node.history = [
2109
+ {
2110
+ x: node.x ?? 0,
2111
+ y: node.y ?? 0
2112
+ }
2113
+ ];
2114
+ }
2115
+ }
2116
+ startTimer() {
2117
+ this.stopTimer();
2118
+ this.#timer = timer2(() => this.tick());
2119
+ }
2120
+ stopTimer() {
2121
+ this.#timer?.stop();
2122
+ this.#timer = void 0;
2123
+ }
2124
+ /**
2125
+ * One simulation step. Modeled on `tick` in Swarm.tsx, but operating in the
2126
+ * SVG centered-origin coordinate space and writing to `node.x/y` directly so
2127
+ * the existing `GraphRenderer.applyPositions` reads them unchanged.
2128
+ */
2129
+ tick() {
2130
+ const size = this.context.size;
2131
+ if (!size) {
2132
+ return;
2133
+ }
2134
+ const { width, height } = size;
2135
+ const halfW = width / 2;
2136
+ const halfH = height / 2;
2137
+ const nodes = this.layout.graph.nodes;
2138
+ const maxVelocity = this.#opt("maxVelocity");
2139
+ const alignmentW = this.#opt("alignment") / 100;
2140
+ const cohesionW = this.#opt("cohesion") / 100;
2141
+ const separationW = this.#opt("separation") / 100;
2142
+ const avoidanceW = this.#opt("avoidance") / 10;
2143
+ const cursorRepel = this.#opt("cursorRepel");
2144
+ const cursor = cursorRepel > 0 ? this.#cursor : null;
2145
+ for (const b1 of nodes) {
2146
+ let ax = 0;
2147
+ let ay = 0;
2148
+ let alignX = 0;
2149
+ let alignY = 0;
2150
+ let alignActive = false;
2151
+ let cohX = 0;
2152
+ let cohY = 0;
2153
+ let cohActive = false;
2154
+ let sepX = 0;
2155
+ let sepY = 0;
2156
+ let sepActive = false;
2157
+ let avoidX = 0;
2158
+ let avoidY = 0;
2159
+ let avoidActive = false;
2160
+ if (cursor) {
2161
+ const dx = cursor.x - (b1.x ?? 0);
2162
+ const dy = cursor.y - (b1.y ?? 0);
2163
+ const distSq = dx * dx + dy * dy;
2164
+ if (distSq > 0 && distSq < cursorRepel * cursorRepel) {
2165
+ const dist = Math.sqrt(distSq);
2166
+ avoidX = -dx / dist * (1 / dist);
2167
+ avoidY = -dy / dist * (1 / dist);
2168
+ avoidActive = true;
2169
+ }
2170
+ }
2171
+ if (!avoidActive) {
2172
+ for (const b2 of nodes) {
2173
+ if (b1 === b2) {
2174
+ continue;
2175
+ }
2176
+ const dx = (b2.x ?? 0) - (b1.x ?? 0);
2177
+ const dy = (b2.y ?? 0) - (b1.y ?? 0);
2178
+ const distSq = dx * dx + dy * dy;
2179
+ if (distSq === 0) {
2180
+ continue;
2181
+ }
2182
+ const dist = Math.sqrt(distSq);
2183
+ if (dist < SEPARATION_DISTANCE) {
2184
+ sepX += -dx / dist * (1 / dist);
2185
+ sepY += -dy / dist * (1 / dist);
2186
+ sepActive = true;
2187
+ }
2188
+ if (dist < SWARMMATE_RADIUS) {
2189
+ cohX += dx;
2190
+ cohY += dy;
2191
+ cohActive = true;
2192
+ alignX += b2.vx ?? 0;
2193
+ alignY += b2.vy ?? 0;
2194
+ alignActive = true;
2195
+ }
2196
+ }
2197
+ }
2198
+ const applyForce = (fx, fy, weight, active) => {
2199
+ if (!active || weight === 0) {
2200
+ return;
2201
+ }
2202
+ const len = Math.sqrt(fx * fx + fy * fy);
2203
+ if (len === 0) {
2204
+ return;
2205
+ }
2206
+ const sx = fx * maxVelocity / len - (b1.vx ?? 0);
2207
+ const sy = fy * maxVelocity / len - (b1.vy ?? 0);
2208
+ const slen = Math.sqrt(sx * sx + sy * sy);
2209
+ if (slen > weight) {
2210
+ ax += sx * weight / slen;
2211
+ ay += sy * weight / slen;
2212
+ } else {
2213
+ ax += sx;
2214
+ ay += sy;
2215
+ }
2216
+ };
2217
+ applyForce(alignX, alignY, alignmentW, alignActive);
2218
+ applyForce(cohX, cohY, cohesionW, cohActive);
2219
+ applyForce(sepX, sepY, separationW, sepActive);
2220
+ applyForce(avoidX, avoidY, avoidanceW, avoidActive);
2221
+ b1.ax = ax;
2222
+ b1.ay = ay;
2223
+ }
2224
+ const trailLength = Math.max(0, Math.round(this.#opt("trailLength")));
2225
+ for (const b of nodes) {
2226
+ let vx = (b.vx ?? 0) + (b.ax ?? 0);
2227
+ let vy = (b.vy ?? 0) + (b.ay ?? 0);
2228
+ const vlen = Math.sqrt(vx * vx + vy * vy);
2229
+ if (vlen > maxVelocity) {
2230
+ vx = vx * maxVelocity / vlen;
2231
+ vy = vy * maxVelocity / vlen;
2232
+ }
2233
+ b.vx = vx;
2234
+ b.vy = vy;
2235
+ if (trailLength > 0) {
2236
+ const history = b.history ?? (b.history = []);
2237
+ history.push({
2238
+ x: b.x ?? 0,
2239
+ y: b.y ?? 0
2240
+ });
2241
+ if (history.length > trailLength) {
2242
+ history.splice(0, history.length - trailLength);
2243
+ }
2244
+ }
2245
+ let x = (b.x ?? 0) + vx;
2246
+ let y = (b.y ?? 0) + vy;
2247
+ let wrapped = false;
2248
+ if (x > halfW) {
2249
+ x -= width;
2250
+ wrapped = true;
2251
+ } else if (x < -halfW) {
2252
+ x += width;
2253
+ wrapped = true;
2254
+ }
2255
+ if (y > halfH) {
2256
+ y -= height;
2257
+ wrapped = true;
2258
+ } else if (y < -halfH) {
2259
+ y += height;
2260
+ wrapped = true;
2261
+ }
2262
+ if (wrapped && b.history) {
2263
+ b.history.length = 0;
2264
+ }
2265
+ b.x = x;
2266
+ b.y = y;
2267
+ }
2268
+ for (const edge of this.layout.graph.edges) {
2269
+ const sx = edge.source.x ?? 0;
2270
+ const sy = edge.source.y ?? 0;
2271
+ const tx = edge.target.x ?? 0;
2272
+ const ty = edge.target.y ?? 0;
2273
+ edge.path = `M ${sx} ${sy} Q 0 0 ${tx} ${ty}`;
2274
+ }
2275
+ this.emitUpdate("positions");
2276
+ }
2277
+ };
2278
+
835
2279
  // src/graph/renderer/graph-renderer.ts
836
2280
  import { easeCubicOut, line as line2, polygonHull, select as select4 } from "d3";
837
2281
  import * as Clipper from "js-clipper";
838
- import { log as log5 } from "@dxos/log";
2282
+ import { log as log10 } from "@dxos/log";
839
2283
 
840
2284
  // src/graph/renderer/bullets.ts
841
2285
  import { easeLinear, interpolate, select as select3 } from "d3";
@@ -868,63 +2312,62 @@ var createBullets = (group, nodeId, options = {}) => {
868
2312
  };
869
2313
 
870
2314
  // src/graph/renderer/renderer.ts
871
- import { invariant as invariant2 } from "@dxos/invariant";
872
- function _define_property5(obj, key, value) {
873
- if (key in obj) {
874
- Object.defineProperty(obj, key, {
875
- value,
876
- enumerable: true,
877
- configurable: true,
878
- writable: true
879
- });
880
- } else {
881
- obj[key] = value;
2315
+ var Renderer = class {
2316
+ _context;
2317
+ _root;
2318
+ _options;
2319
+ constructor(_context, _root, options) {
2320
+ this._context = _context;
2321
+ this._root = _root;
2322
+ this._options = Object.assign({
2323
+ idAccessor: defaultIdAccessor
2324
+ }, options);
882
2325
  }
883
- return obj;
884
- }
885
- var __dxlog_file6 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/renderer.ts";
886
- var Renderer = class {
887
2326
  get context() {
888
2327
  return this._context;
889
2328
  }
2329
+ /**
2330
+ * Returns the SVG group root if mounted.
2331
+ * The ref may be null between mount/unmount cycles or before the SVG container has sized.
2332
+ * Callers should treat null as "skip this render" rather than as an error.
2333
+ */
890
2334
  get root() {
891
- invariant2(this._root.current, "SVG root is not initialized", {
892
- F: __dxlog_file6,
893
- L: 40,
894
- S: this,
895
- A: [
896
- "this._root.current",
897
- "'SVG root is not initialized'"
898
- ]
899
- });
900
2335
  return this._root.current;
901
2336
  }
902
2337
  get options() {
903
2338
  return this._options;
904
2339
  }
905
- constructor(_context, _root, options) {
906
- _define_property5(this, "_context", void 0);
907
- _define_property5(this, "_root", void 0);
908
- _define_property5(this, "_options", void 0);
909
- this._context = _context;
910
- this._root = _root;
911
- this._options = Object.assign({
912
- idAccessor: defaultIdAccessor
913
- }, options);
2340
+ /**
2341
+ * Fast path invoked when only positions changed.
2342
+ * Default falls back to a full `render`; subclasses can override to skip
2343
+ * enter/exit joins and attribute callbacks for per-tick updates.
2344
+ */
2345
+ applyPositions(layout) {
2346
+ this.render(layout);
914
2347
  }
915
2348
  };
916
2349
 
917
2350
  // src/graph/renderer/graph-renderer.ts
918
- var __dxlog_file7 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/graph-renderer.ts";
2351
+ var __dxlog_file12 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/graph-renderer.ts";
919
2352
  var createLine2 = line2();
2353
+ var EDGE_FADE_MS = 300;
2354
+ var NODE_HIDE_MS = 500;
920
2355
  var GraphRenderer = class extends Renderer {
2356
+ // First render of this instance — used to clear DOM left behind by a previous
2357
+ // renderer pointing at the same `<g>` (e.g. when the consumer swaps projectors
2358
+ // and a new renderer is constructed for the same SVG root). Without this, the
2359
+ // previous variant's node shapes (e.g. circles) would persist as d3.join sees
2360
+ // them in the `update` set instead of `enter`.
2361
+ #firstRender = true;
921
2362
  render(layout) {
922
- log5("render", layout, {
923
- F: __dxlog_file7,
924
- L: 63,
925
- S: this,
926
- C: (f, a) => f(...a)
927
- });
2363
+ if (!this.root) {
2364
+ return;
2365
+ }
2366
+ if (this.#firstRender) {
2367
+ this.#firstRender = false;
2368
+ this.root.replaceChildren();
2369
+ }
2370
+ log10("render", layout, { "~LogMeta": "~LogMeta", F: __dxlog_file12, L: 35, S: this });
928
2371
  const root = select4(this.root);
929
2372
  if (layout.guides) {
930
2373
  root.selectAll("g.dx-guides").data([
@@ -982,37 +2425,92 @@ var GraphRenderer = class extends Renderer {
982
2425
  {
983
2426
  id: "edges"
984
2427
  }
985
- ], (d) => d.id).join("g").classed("dx-edges", true);
2428
+ ], (d) => d.id).join("g").classed("dx-edges", true).style("opacity", this.options.edgeOpacity != null ? String(this.options.edgeOpacity) : null);
986
2429
  const nodeGroup = root.selectAll("g.dx-nodes").data([
987
2430
  {
988
2431
  id: "nodes"
989
2432
  }
990
2433
  ], (d) => d.id).join("g").classed("dx-nodes", true);
991
- nodeGroup.selectAll("g.dx-node").data(layout.graph?.nodes ?? [], (d) => d.id).join((enter) => enter.append("g").attr("data-id", (d) => d.id).attr("opacity", 1).classed("dx-node", true).call(createNode, this.options), (update) => update.call(updateNode2, this.options), (exit) => {
2434
+ nodeGroup.selectAll("g.dx-node").data(layout.graph?.nodes ?? [], (d) => d.id).join((enter) => enter.append("g").attr("data-id", (d) => d.id).attr("opacity", (d) => d.hidden ? 0 : 1).classed("dx-node", true).call(createNode, this.options), (update) => update, (exit) => {
992
2435
  return exit.transition().ease(easeCubicOut).duration(300).attr("opacity", 0).on("end", function(d) {
993
2436
  select4(this).remove();
994
2437
  });
995
- }).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
996
- edgeGroup.selectAll("g.dx-edge").data(layout.graph?.edges ?? [], (d) => d.id).join((enter) => enter.append("g").attr("data-id", (d) => d.id).classed("dx-edge", true).call(createEdge, this.options), (update) => update.call(updateEdge, this.options, nodeGroup).each((d) => {
997
- }), (exit) => exit.remove()).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
2438
+ }).call(updateNode2, this.options).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
2439
+ edgeGroup.selectAll("g.dx-edge").data(layout.graph?.edges ?? [], (d) => d.id).join(
2440
+ (enter) => enter.append("g").attr("data-id", (d) => d.id).classed("dx-edge", true).call(createEdge, this.options),
2441
+ (update) => update,
2442
+ // Exit fade: edges removed by a topology change (e.g. variant switch from cluster
2443
+ // back to force replaces hierarchy edges with data edges) ease out rather than pop.
2444
+ (exit) => exit.transition().ease(easeCubicOut).duration(EDGE_FADE_MS).attr("opacity", 0).on("end", function() {
2445
+ select4(this).remove();
2446
+ })
2447
+ ).call(updateEdge, this.options, nodeGroup).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
2448
+ }
2449
+ /**
2450
+ * Fast positions-only update. Skips enter/exit, attribute callbacks, label sizing,
2451
+ * and the subgraph hull pass; just writes `transform` per node and `d` per edge.
2452
+ * Called per simulation tick / animation frame.
2453
+ */
2454
+ applyPositions(layout) {
2455
+ if (!this.root) {
2456
+ return;
2457
+ }
2458
+ const root = select4(this.root);
2459
+ const applyNode = this.options.applyNode;
2460
+ root.select("g.dx-nodes").selectAll("g.dx-node").attr("transform", (d) => d.x != null && d.y != null ? `translate(${d.x},${d.y})` : null).each(applyNode ? function(d) {
2461
+ applyNode(this, d);
2462
+ } : () => {
2463
+ });
2464
+ root.select("g.dx-edges").selectAll("g.dx-edge").selectAll("path").attr("d", function() {
2465
+ const edge = select4(this.parentElement).datum();
2466
+ if (edge.path) {
2467
+ return edge.path;
2468
+ }
2469
+ const { source, target } = edge;
2470
+ if (!source.initialized || !target.initialized) {
2471
+ return null;
2472
+ }
2473
+ return createLine2(getCircumferencePoints([
2474
+ source.x,
2475
+ source.y
2476
+ ], [
2477
+ target.x,
2478
+ target.y
2479
+ ], source.r, target.r));
2480
+ });
998
2481
  }
999
2482
  /**
1000
2483
  * Trigger path bullets.
1001
2484
  * @param node
1002
2485
  */
1003
2486
  fireBullet(node) {
2487
+ if (!this.root) {
2488
+ return;
2489
+ }
1004
2490
  select4(this.root).selectAll("g.dx-edges").selectAll("path").call(createBullets(this.root, node.id));
1005
2491
  }
1006
2492
  };
2493
+ var SHAPE_CLASS = "dx-shape";
2494
+ var renderCustomShape = (group, options) => {
2495
+ group.each(function(d) {
2496
+ const g = select4(this);
2497
+ g.selectAll(`.${SHAPE_CLASS}`).remove();
2498
+ const shapeGroup = g.append("g").classed(SHAPE_CLASS, true);
2499
+ options.renderNode(shapeGroup, d);
2500
+ });
2501
+ };
1007
2502
  var createNode = (group, options) => {
1008
- const circle = group.append("circle");
2503
+ const useCustom = !!options.renderNode;
2504
+ if (useCustom) {
2505
+ renderCustomShape(group, options);
2506
+ }
2507
+ const hitTarget = useCustom ? group : group.append("circle");
1009
2508
  if (options.drag) {
1010
- circle.call(options.drag);
2509
+ hitTarget.call(options.drag);
1011
2510
  }
1012
2511
  if (options.onNodeClick) {
1013
- group.on("click", (event) => {
1014
- const node = select4(event.target).datum();
1015
- options.onNodeClick(node, event);
2512
+ group.on("click", (event, d) => {
2513
+ options.onNodeClick(d, event);
1016
2514
  });
1017
2515
  }
1018
2516
  if (options.labels && !options.onNodePointerEnter) {
@@ -1021,24 +2519,34 @@ var createNode = (group, options) => {
1021
2519
  g.append("rect");
1022
2520
  g.append("text").style("dominant-baseline", "middle");
1023
2521
  }
1024
- if (options.onNodePointerEnter) {
1025
- circle.on("pointerenter", function(event) {
1026
- const node = select4(this.parentElement).datum();
1027
- options.onNodePointerEnter(node, event);
2522
+ if (options.onNodePointerEnter || options.onNodePointerLeave || options.highlightOnHover) {
2523
+ hitTarget.on("pointerenter", function(event) {
2524
+ const node = select4(useCustom ? this : this.parentElement).datum();
2525
+ options.onNodePointerEnter?.(node, event);
2526
+ if (options.highlightOnHover) {
2527
+ applyHoverHighlight(this.closest("g.dx-graph"), node.id);
2528
+ }
2529
+ });
2530
+ hitTarget.on("pointerleave", function(event) {
2531
+ const node = select4(useCustom ? this : this.parentElement).datum();
2532
+ options.onNodePointerLeave?.(node, event);
2533
+ if (options.highlightOnHover) {
2534
+ applyHoverHighlight(this.closest("g.dx-graph"), null);
2535
+ }
1028
2536
  });
1029
2537
  group.attr("data-hover", "handled");
1030
- } else if (options.highlight !== false) {
1031
- circle.on("pointerenter", function() {
2538
+ } else if (options.highlight !== false && !useCustom) {
2539
+ hitTarget.on("pointerenter", function() {
1032
2540
  select4(this.closest("g.dx-node")).raise();
1033
2541
  if (options.labels) {
1034
- select4(this.parentElement).classed("dx-active", true).classed("dx-highlight", true);
2542
+ select4(this.parentElement).classed("dx-node-active", true).classed("dx-highlight", true);
1035
2543
  }
1036
2544
  });
1037
2545
  group.on("pointerleave", function() {
1038
2546
  if (options.labels) {
1039
- select4(this).classed("dx-active", false);
2547
+ select4(this).classed("dx-node-active", false);
1040
2548
  setTimeout(() => {
1041
- if (!select4(this).classed("dx-active")) {
2549
+ if (!select4(this).classed("dx-node-active")) {
1042
2550
  select4(this).classed("dx-highlight", false);
1043
2551
  }
1044
2552
  }, 300);
@@ -1050,6 +2558,11 @@ var updateNode2 = (group, options) => {
1050
2558
  group.attr("transform", (d) => {
1051
2559
  return d.x != null && d.y != null ? `translate(${d.x},${d.y})` : void 0;
1052
2560
  });
2561
+ group.classed("dx-hidden", (d) => d.hidden ?? false);
2562
+ group.transition("hide").ease(easeCubicOut).duration(NODE_HIDE_MS).attr("opacity", (d) => d.hidden ? 0 : 1);
2563
+ if (options.renderNode) {
2564
+ renderCustomShape(group, options);
2565
+ }
1053
2566
  if (options.attributes?.node) {
1054
2567
  try {
1055
2568
  group.each((d, i, nodes) => {
@@ -1065,18 +2578,15 @@ var updateNode2 = (group, options) => {
1065
2578
  }
1066
2579
  });
1067
2580
  } catch (error) {
1068
- log5.error("updateNode", {
2581
+ log10.error("updateNode", {
1069
2582
  error: error?.message
1070
- }, {
1071
- F: __dxlog_file7,
1072
- L: 305,
1073
- S: void 0,
1074
- C: (f, a) => f(...a)
1075
- });
2583
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file12, L: 303, S: void 0 });
1076
2584
  }
1077
2585
  }
1078
2586
  const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
1079
- groupOrTransition.select("circle").attr("r", (d) => d.r ?? 16);
2587
+ if (!options.renderNode) {
2588
+ groupOrTransition.select("circle").attr("r", (d) => d.r ?? 16);
2589
+ }
1080
2590
  if (options.labels) {
1081
2591
  const bx = 1;
1082
2592
  const px = 4;
@@ -1121,18 +2631,17 @@ var updateEdge = (group, options, nodeGroup) => {
1121
2631
  }
1122
2632
  });
1123
2633
  } catch (error) {
1124
- log5.error("updateEdge", {
2634
+ log10.error("updateEdge", {
1125
2635
  error: error?.message
1126
- }, {
1127
- F: __dxlog_file7,
1128
- L: 417,
1129
- S: void 0,
1130
- C: (f, a) => f(...a)
1131
- });
2636
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file12, L: 371, S: void 0 });
1132
2637
  }
1133
2638
  const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
1134
2639
  groupOrTransition.selectAll("path").attr("d", function() {
1135
- const { source, target } = select4(this.parentElement).datum();
2640
+ const edge = select4(this.parentElement).datum();
2641
+ if (edge.path) {
2642
+ return edge.path;
2643
+ }
2644
+ const { source, target } = edge;
1136
2645
  if (!source.initialized || !target.initialized) {
1137
2646
  return;
1138
2647
  }
@@ -1145,6 +2654,62 @@ var updateEdge = (group, options, nodeGroup) => {
1145
2654
  ], source.r, target.r));
1146
2655
  });
1147
2656
  };
2657
+ var applyHoverHighlight = (root, focusedId) => {
2658
+ if (!root) {
2659
+ return;
2660
+ }
2661
+ const r = select4(root);
2662
+ const on = focusedId != null;
2663
+ const outgoing = /* @__PURE__ */ new Set();
2664
+ const incoming = /* @__PURE__ */ new Set();
2665
+ if (on) {
2666
+ r.select("g.dx-edges").selectAll("g.dx-edge").each((edge) => {
2667
+ if (edge.source.id === focusedId) {
2668
+ outgoing.add(edge.target.id);
2669
+ }
2670
+ if (edge.target.id === focusedId) {
2671
+ incoming.add(edge.source.id);
2672
+ }
2673
+ });
2674
+ }
2675
+ r.select("g.dx-edges").selectAll("g.dx-edge").each(function(edge) {
2676
+ const path = select4(this).select("path:not(.dx-click)");
2677
+ if (!on) {
2678
+ path.style("stroke", null).style("stroke-width", null).style("opacity", null);
2679
+ return;
2680
+ }
2681
+ if (edge.source.id === focusedId) {
2682
+ path.style("stroke", "var(--color-orange-500)").style("stroke-width", "1.5px").style("opacity", null);
2683
+ } else if (edge.target.id === focusedId) {
2684
+ path.style("stroke", "var(--color-sky-500)").style("stroke-width", "1.5px").style("opacity", null);
2685
+ } else {
2686
+ path.style("stroke", null).style("stroke-width", null).style("opacity", "0.8");
2687
+ }
2688
+ });
2689
+ r.select("g.dx-nodes").selectAll("g.dx-node").each(function(node) {
2690
+ const groupSel = select4(this);
2691
+ const shape = groupSel.select("circle, rect");
2692
+ if (node.hidden) {
2693
+ return;
2694
+ }
2695
+ if (!on) {
2696
+ groupSel.style("opacity", null);
2697
+ shape.style("stroke", null).style("stroke-width", null);
2698
+ return;
2699
+ }
2700
+ const connected = outgoing.has(node.id) || incoming.has(node.id);
2701
+ if (node.id === focusedId) {
2702
+ groupSel.style("opacity", null);
2703
+ shape.style("stroke", null).style("stroke-width", null);
2704
+ } else if (connected) {
2705
+ groupSel.style("opacity", null);
2706
+ shape.style("stroke", "var(--color-orange-400)").style("stroke-width", "2.5px");
2707
+ } else {
2708
+ groupSel.style("opacity", "0.4");
2709
+ shape.style("stroke", null).style("stroke-width", null);
2710
+ }
2711
+ });
2712
+ };
1148
2713
  var applyClasses = (el, classes) => {
1149
2714
  for (const [className, value] of Object.entries(classes)) {
1150
2715
  el.classed(className, value);
@@ -1183,6 +2748,45 @@ var findConnectedComponents = (graph) => {
1183
2748
  return components;
1184
2749
  };
1185
2750
 
2751
+ // src/graph/renderer/labels.ts
2752
+ var DEFAULT_DURATION = 200;
2753
+ var DEFAULT_OFFSET = 4;
2754
+ var getTarget = (node) => {
2755
+ const tx = node.tx;
2756
+ const ty = node.ty;
2757
+ return {
2758
+ x: tx ?? node.x ?? 0,
2759
+ y: ty ?? node.y ?? 0
2760
+ };
2761
+ };
2762
+ var appendRadialLeafLabel = (group, node, label, r, options = {}) => {
2763
+ if (!label) {
2764
+ return;
2765
+ }
2766
+ const { delay = 0, duration = DEFAULT_DURATION, offset = DEFAULT_OFFSET, className = "dx-cluster-label" } = options;
2767
+ const { x: targetX, y: targetY } = getTarget(node);
2768
+ const angleDeg = Math.atan2(targetY, targetX) * 180 / Math.PI;
2769
+ const flipped = angleDeg > 90 || angleDeg < -90;
2770
+ group.append("text").attr("class", className).attr("dy", "0.32em").attr("transform", `rotate(${flipped ? angleDeg + 180 : angleDeg})`).attr("x", flipped ? -(r + offset) : r + offset).attr("text-anchor", flipped ? "end" : "start").attr("opacity", 0).style("cursor", "pointer").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2771
+ };
2772
+ var appendRadialGroupLabel = (group, node, label, r, options = {}) => {
2773
+ if (!label) {
2774
+ return;
2775
+ }
2776
+ const { delay = 0, duration = DEFAULT_DURATION, offset = DEFAULT_OFFSET, className = "dx-cluster-label dx-cluster-label-group" } = options;
2777
+ const { x: targetX, y: targetY } = getTarget(node);
2778
+ const angleDeg = Math.atan2(targetY, targetX) * 180 / Math.PI;
2779
+ const flipped = angleDeg > 90 || angleDeg < -90;
2780
+ group.append("text").attr("class", className).attr("dy", "0.32em").attr("transform", `rotate(${flipped ? angleDeg + 180 : angleDeg})`).attr("x", flipped ? r + offset : -(r + offset)).attr("text-anchor", flipped ? "start" : "end").attr("opacity", 0).style("pointer-events", "none").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2781
+ };
2782
+ var appendRootLabel = (group, label, r, options = {}) => {
2783
+ if (!label) {
2784
+ return;
2785
+ }
2786
+ const { delay = 0, duration = DEFAULT_DURATION, offset = 6, className = "dx-cluster-label dx-cluster-label-root" } = options;
2787
+ group.append("text").attr("class", className).attr("text-anchor", "middle").attr("y", -(r + offset)).attr("opacity", 0).style("pointer-events", "none").text(label).transition().delay(delay).duration(duration).attr("opacity", 1);
2788
+ };
2789
+
1186
2790
  // src/graph/renderer/linker.ts
1187
2791
  import { line as line3 } from "d3";
1188
2792
  var createLine3 = line3();
@@ -1206,117 +2810,504 @@ var linkerRenderer = (root, { source, target, point } = {}) => {
1206
2810
  });
1207
2811
  };
1208
2812
 
2813
+ // src/hooks/useGrid.ts
2814
+ import { line as line4, range, select as select5 } from "d3";
2815
+ import { useEffect, useMemo, useRef } from "react";
2816
+
2817
+ // src/hooks/useSvgContext.ts
2818
+ import { createContext, useContext } from "react";
2819
+ import { createRef } from "react";
2820
+ import { raise } from "@dxos/debug";
2821
+ var SVGContext = class {
2822
+ _ref = createRef();
2823
+ _scale;
2824
+ _centered;
2825
+ _size;
2826
+ _center;
2827
+ resized = new EventEmitter();
2828
+ constructor({ scale = new Scale(), centered = true }) {
2829
+ this._scale = scale;
2830
+ this._centered = centered;
2831
+ }
2832
+ get ref() {
2833
+ return this._ref;
2834
+ }
2835
+ get svg() {
2836
+ return this._ref.current;
2837
+ }
2838
+ get scale() {
2839
+ return this._scale;
2840
+ }
2841
+ get center() {
2842
+ return this._center;
2843
+ }
2844
+ get size() {
2845
+ return this._size;
2846
+ }
2847
+ /**
2848
+ * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
2849
+ */
2850
+ get viewBox() {
2851
+ const [x, y] = this.center;
2852
+ return `${x},${y},${this._size.width},${this._size.height}`;
2853
+ }
2854
+ setSize(size) {
2855
+ this._size = {
2856
+ ...size
2857
+ };
2858
+ this._center = this._centered ? [
2859
+ -Math.floor(size.width / 2),
2860
+ -Math.floor(size.height / 2)
2861
+ ] : [
2862
+ 0,
2863
+ 0
2864
+ ];
2865
+ this.resized.emit(this);
2866
+ }
2867
+ setTransform(transform) {
2868
+ if (this._scale.setTransform(transform)) {
2869
+ this.resized.emit(this);
2870
+ }
2871
+ }
2872
+ /**
2873
+ * https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint
2874
+ * @param point
2875
+ */
2876
+ elementFromPoint(point) {
2877
+ const [x, y] = point;
2878
+ const [cx, cy] = this._center;
2879
+ return document.elementFromPoint(cx + x, cy + y);
2880
+ }
2881
+ };
2882
+ var SVGContextType = createContext(void 0);
2883
+ var SVGContextProvider = SVGContextType.Provider;
2884
+ var useSvgContext = () => {
2885
+ return useContext(SVGContextType) ?? raise(new Error("Missing SVGRoot"));
2886
+ };
2887
+
2888
+ // src/hooks/useGrid.ts
2889
+ var createLine4 = line4();
2890
+ var createGrid = (context, options) => {
2891
+ if (!context.size) {
2892
+ return [];
2893
+ }
2894
+ const paths = [];
2895
+ const { width, height } = context.size;
2896
+ const { x, y, k } = context.scale.transform;
2897
+ const s = 1 / k;
2898
+ const w = width * s;
2899
+ const h = height * s;
2900
+ const dx = -(x + width / 2) * s;
2901
+ const dy = -(y + height / 2) * s;
2902
+ if (options.axis) {
2903
+ const axis = [
2904
+ [
2905
+ [
2906
+ 0,
2907
+ dy
2908
+ ],
2909
+ [
2910
+ 0,
2911
+ dy + h
2912
+ ]
2913
+ ],
2914
+ [
2915
+ [
2916
+ dx,
2917
+ 0
2918
+ ],
2919
+ [
2920
+ dx + w,
2921
+ 0
2922
+ ]
2923
+ ]
2924
+ ];
2925
+ paths.push({
2926
+ id: "axis",
2927
+ class: "dx-axis",
2928
+ path: axis.map((line5) => createLine4(line5)).join()
2929
+ });
2930
+ }
2931
+ if (options.grid) {
2932
+ const mod = (n, size, delta = 0) => Math.floor(n / size + delta) * size;
2933
+ const majorSize = context.scale.gridSize;
2934
+ const xMajor = range(-mod((x + width / 2) * s, majorSize), mod((-x + width / 2) * s, majorSize, 1), majorSize);
2935
+ const yMajor = range(-mod((y + height / 2) * s, majorSize), mod((-y + height / 2) * s, majorSize, 1), majorSize);
2936
+ const major = [
2937
+ ...xMajor.filter((x2) => !options.axis || x2).map((x2) => [
2938
+ [
2939
+ x2,
2940
+ dy
2941
+ ],
2942
+ [
2943
+ x2,
2944
+ dy + h
2945
+ ]
2946
+ ]),
2947
+ ...yMajor.filter((y2) => !options.axis || y2).map((y2) => [
2948
+ [
2949
+ dx,
2950
+ y2
2951
+ ],
2952
+ [
2953
+ dx + w,
2954
+ y2
2955
+ ]
2956
+ ])
2957
+ ];
2958
+ paths.push({
2959
+ id: "major",
2960
+ class: "dx-major",
2961
+ path: major.map((line5) => createLine4(line5)).join()
2962
+ });
2963
+ const minorSize = Math.pow(2, Math.round(Math.log2(s * context.scale.gridSize)));
2964
+ if (majorSize > minorSize) {
2965
+ const xMinor = range(-mod((x + width / 2) * s, minorSize), mod((-x + width / 2) * s, minorSize, 1), minorSize);
2966
+ const yMinor = range(-mod((y + height / 2) * s, minorSize), mod((-y + height / 2) * s, minorSize, 1), minorSize);
2967
+ const minor = [
2968
+ ...xMinor.filter((x2) => xMajor.indexOf(x2) === -1).map((x2) => [
2969
+ [
2970
+ x2,
2971
+ dy
2972
+ ],
2973
+ [
2974
+ x2,
2975
+ dy + h
2976
+ ]
2977
+ ]),
2978
+ ...yMinor.filter((y2) => yMajor.indexOf(y2) === -1).map((y2) => [
2979
+ [
2980
+ dx,
2981
+ y2
2982
+ ],
2983
+ [
2984
+ dx + w,
2985
+ y2
2986
+ ]
2987
+ ])
2988
+ ];
2989
+ paths.push({
2990
+ id: "minor",
2991
+ class: "dx-minor",
2992
+ path: minor.map((line5) => createLine4(line5)).join()
2993
+ });
2994
+ }
2995
+ }
2996
+ return paths;
2997
+ };
2998
+ var defaultGridOptions = {
2999
+ visible: true,
3000
+ axis: true,
3001
+ grid: true
3002
+ };
3003
+ var GridController = class {
3004
+ _ref;
3005
+ _context;
3006
+ _options;
3007
+ _visible = false;
3008
+ constructor(_ref, _context, _options) {
3009
+ this._ref = _ref;
3010
+ this._context = _context;
3011
+ this._options = _options;
3012
+ this._visible = this._options.visible ?? true;
3013
+ }
3014
+ get ref() {
3015
+ return this._ref;
3016
+ }
3017
+ get visible() {
3018
+ return this._visible;
3019
+ }
3020
+ draw() {
3021
+ if (!this._context.size) {
3022
+ return;
3023
+ }
3024
+ const paths = this._visible ? createGrid(this._context, this._options) : [];
3025
+ const root = select5(this._ref.current);
3026
+ root.selectAll("path").data(paths, (path) => path.id).join("path").style("pointer-events", "none").attr("d", (d) => d.path).attr("class", (d) => d.class);
3027
+ const transform = this._context.scale.transform;
3028
+ if (transform) {
3029
+ root.attr("transform", transform);
3030
+ root.attr("stroke-width", 1 / transform.k);
3031
+ }
3032
+ }
3033
+ setVisible(visible) {
3034
+ this._visible = visible;
3035
+ this.draw();
3036
+ return this;
3037
+ }
3038
+ };
3039
+ var useGrid = (options = defaultGridOptions) => {
3040
+ const ref = useRef(null);
3041
+ const context = useSvgContext();
3042
+ const controller = useMemo(() => new GridController(ref, context, options), []);
3043
+ useEffect(() => context.resized.on(() => controller.draw()), [
3044
+ context,
3045
+ controller
3046
+ ]);
3047
+ return controller;
3048
+ };
3049
+
3050
+ // src/hooks/useZoom.ts
3051
+ import { select as select6, zoom, zoomIdentity as zoomIdentity2 } from "d3";
3052
+ import defaultsDeep from "lodash.defaultsdeep";
3053
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2 } from "react";
3054
+ var defaultZoomOptions = {
3055
+ enabled: true,
3056
+ extent: [
3057
+ 1 / 4,
3058
+ 4
3059
+ ],
3060
+ onDblClick: (zoom2) => zoom2.reset()
3061
+ };
3062
+ var ZoomHandler = class {
3063
+ _ref;
3064
+ _context;
3065
+ _zoom;
3066
+ _options;
3067
+ _enabled;
3068
+ constructor(_ref, _context, options) {
3069
+ this._ref = _ref;
3070
+ this._context = _context;
3071
+ this._options = defaultsDeep({}, options, defaultZoomOptions);
3072
+ this._enabled = this._options.enabled ?? true;
3073
+ this._zoom = zoom().scaleExtent(this._options.extent ?? defaultZoomOptions.extent);
3074
+ }
3075
+ /**
3076
+ * Gets the reference which the transform is applied to.
3077
+ */
3078
+ get ref() {
3079
+ return this._ref;
3080
+ }
3081
+ get zoom() {
3082
+ return this._zoom;
3083
+ }
3084
+ init() {
3085
+ this.setEnabled(this._enabled);
3086
+ this.reset(0);
3087
+ return this;
3088
+ }
3089
+ setEnabled(enable) {
3090
+ if (enable) {
3091
+ select6(this._context.svg).call(this._zoom).on(
3092
+ "dblclick.zoom",
3093
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
3094
+ // @ts-ignore
3095
+ this._options?.onDblClick ? () => {
3096
+ this._options?.onDblClick(this);
3097
+ } : null
3098
+ );
3099
+ } else {
3100
+ select6(this._context.svg).on(".zoom", null);
3101
+ }
3102
+ this._enabled = enable;
3103
+ return this;
3104
+ }
3105
+ reset(duration = 500) {
3106
+ const scale = 1;
3107
+ const transform = zoomIdentity2.scale(scale);
3108
+ select6(this._context.svg).transition().duration(duration).call(this._zoom.transform, transform);
3109
+ return this;
3110
+ }
3111
+ };
3112
+ var useZoom = (options = defaultZoomOptions) => {
3113
+ const context = useSvgContext();
3114
+ const ref = useRef2(null);
3115
+ const handler = useMemo2(() => new ZoomHandler(ref, context, options), [
3116
+ context,
3117
+ options
3118
+ ]);
3119
+ useEffect2(() => {
3120
+ handler.zoom.on("zoom", ({ transform }) => {
3121
+ context.setTransform(transform);
3122
+ select6(ref.current).attr("transform", transform);
3123
+ });
3124
+ handler.init();
3125
+ }, [
3126
+ handler
3127
+ ]);
3128
+ return handler;
3129
+ };
3130
+
1209
3131
  // src/components/Graph/Graph.tsx
1210
- var __dxlog_file8 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/components/Graph/Graph.tsx";
1211
- var GraphInner = ({ classNames, model, projector: _projector, renderer: _renderer, drag: drag2, arrows, onSelect, onInspect, ...props }, forwardedRef) => {
1212
- var _effect = _useSignals();
1213
- try {
1214
- const context = useSvgContext();
1215
- const graphRef = useRef(null);
1216
- const { projector, renderer } = useMemo(() => {
1217
- let projector2 = _projector;
1218
- if (!projector2) {
1219
- projector2 = new GraphForceProjector(context);
1220
- }
1221
- let renderer2 = _renderer;
1222
- if (!renderer2) {
1223
- renderer2 = new GraphRenderer(context, graphRef, {
1224
- ...props,
1225
- // TODO(burdon): Replace drag when projector is updated.
1226
- drag: drag2 ? createGraphDrag(context, projector2) : void 0,
1227
- arrows: {
1228
- end: arrows
1229
- },
1230
- onNodeClick: onSelect ? (node, event) => onSelect(node, event) : void 0,
1231
- onNodePointerEnter: onInspect ? (node, event) => onInspect(node, event) : void 0
1232
- });
1233
- }
1234
- return {
1235
- projector: projector2,
1236
- renderer: renderer2
1237
- };
1238
- }, [
1239
- context,
1240
- _projector,
1241
- _renderer,
1242
- drag2
1243
- ]);
1244
- useImperativeHandle(forwardedRef, () => ({
1245
- refresh: () => {
1246
- projector.updateData(model?.graph);
1247
- },
1248
- repaint: () => {
1249
- renderer.render(projector.layout);
1250
- },
1251
- findNode: (id) => {
1252
- return graphRef.current?.querySelector(`g[data-id="${id}"]`);
1253
- }
1254
- }), [
1255
- model,
1256
- projector,
1257
- renderer
1258
- ]);
1259
- useEffect(() => {
1260
- return combine(effect(() => {
3132
+ var __dxlog_file13 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/components/Graph/Graph.tsx";
3133
+ var GraphInner = ({ classNames, model, projector: projectorProp, renderer: rendererProp, drag: drag2, arrows, onSelect, onInspect, onPointerMove, onPointerLeave, ...props }, forwardedRef) => {
3134
+ const context = useSvgContext();
3135
+ const graphRef = useRef3(null);
3136
+ const { projector, renderer } = useMemo3(() => {
3137
+ let projector2 = projectorProp;
3138
+ if (!projector2) {
3139
+ projector2 = new GraphForceProjector(context);
3140
+ }
3141
+ let renderer2 = rendererProp;
3142
+ if (!renderer2) {
3143
+ renderer2 = new GraphRenderer(context, graphRef, {
3144
+ ...props,
3145
+ // TODO(burdon): Replace drag when projector is updated.
3146
+ drag: drag2 ? createGraphDrag(context, projector2) : void 0,
3147
+ arrows: {
3148
+ end: arrows
3149
+ },
3150
+ // Projector intercept first so built-in interactions (e.g. cluster collapse) can
3151
+ // run without consumers wiring them. Returning true suppresses the user handler.
3152
+ onNodeClick: (node, event) => {
3153
+ if (projector2.handleNodeClick(node, event)) {
3154
+ return;
3155
+ }
3156
+ onSelect?.(node, event);
3157
+ },
3158
+ onNodePointerEnter: onInspect ? (node, event) => onInspect(node, event) : void 0,
3159
+ // Pair pointerenter with leave so consumers can clear hover-driven previews.
3160
+ // The callback receives `null` on leave (event still carries the source).
3161
+ onNodePointerLeave: onInspect ? (_node, event) => onInspect(null, event) : void 0
3162
+ });
3163
+ }
3164
+ return {
3165
+ projector: projector2,
3166
+ renderer: renderer2
3167
+ };
3168
+ }, [
3169
+ context,
3170
+ projectorProp,
3171
+ rendererProp,
3172
+ drag2,
3173
+ arrows,
3174
+ onSelect,
3175
+ onInspect,
3176
+ props.labels,
3177
+ props.subgraphs,
3178
+ props.attributes,
3179
+ props.renderNode,
3180
+ props.highlightOnHover,
3181
+ props.applyNode,
3182
+ props.edgeOpacity
3183
+ ]);
3184
+ useImperativeHandle(forwardedRef, () => ({
3185
+ refresh: () => {
3186
+ projector.updateData(model?.graph);
3187
+ },
3188
+ repaint: () => {
3189
+ renderer.render(projector.layout);
3190
+ },
3191
+ findNode: (id) => {
3192
+ return graphRef.current?.querySelector(`g[data-id="${id}"]`);
3193
+ }
3194
+ }), [
3195
+ model,
3196
+ projector,
3197
+ renderer
3198
+ ]);
3199
+ useEffect3(() => {
3200
+ const cleanup = combine(
3201
+ // Subscribe to model changes if reactive model.
3202
+ model ? model.subscribe(() => {
1261
3203
  projector.updateData(model?.graph);
1262
- }), projector.updated.on(({ layout }) => {
3204
+ }) : void 0,
3205
+ projector.updated.on(({ layout, kind }) => {
1263
3206
  try {
1264
- renderer.render(layout);
3207
+ if (kind === "positions") {
3208
+ renderer.applyPositions(layout);
3209
+ } else {
3210
+ renderer.render(layout);
3211
+ }
1265
3212
  } catch (error) {
3213
+ log11.catch(error, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file13, L: 95, S: void 0 });
1266
3214
  void projector.stop();
1267
- log6.catch(error, void 0, {
1268
- F: __dxlog_file8,
1269
- L: 108,
1270
- S: void 0,
1271
- C: (f, a) => f(...a)
1272
- });
1273
3215
  }
1274
- }));
1275
- }, [
1276
- model,
1277
- projector,
1278
- renderer
1279
- ]);
1280
- useEffect(() => {
1281
- void projector.start();
1282
- return () => {
1283
- void projector.stop();
1284
- };
1285
- }, [
1286
- projector
1287
- ]);
1288
- return /* @__PURE__ */ React.createElement("g", {
1289
- ref: graphRef,
1290
- className: mx("dx-graph", classNames)
1291
- });
1292
- } finally {
1293
- _effect.f();
1294
- }
3216
+ })
3217
+ );
3218
+ projector.updateData(model?.graph);
3219
+ return cleanup;
3220
+ }, [
3221
+ model,
3222
+ projector,
3223
+ renderer
3224
+ ]);
3225
+ useEffect3(() => {
3226
+ void projector.start();
3227
+ return () => {
3228
+ void projector.stop();
3229
+ };
3230
+ }, [
3231
+ projector
3232
+ ]);
3233
+ useEffect3(() => {
3234
+ if (!onPointerMove && !onPointerLeave) {
3235
+ return;
3236
+ }
3237
+ const svg = context.svg;
3238
+ if (!svg) {
3239
+ return;
3240
+ }
3241
+ const previousPointerEvents = svg.style.pointerEvents;
3242
+ svg.style.pointerEvents = "all";
3243
+ const handleMove = (event) => {
3244
+ if (!onPointerMove) {
3245
+ return;
3246
+ }
3247
+ const target = graphRef.current;
3248
+ const ctm = target?.getScreenCTM();
3249
+ if (!target || !ctm) {
3250
+ return;
3251
+ }
3252
+ const point = svg.createSVGPoint();
3253
+ point.x = event.clientX;
3254
+ point.y = event.clientY;
3255
+ const modelPoint = point.matrixTransform(ctm.inverse());
3256
+ onPointerMove({
3257
+ x: modelPoint.x,
3258
+ y: modelPoint.y
3259
+ }, event);
3260
+ };
3261
+ const handleLeave = (event) => {
3262
+ onPointerLeave?.(event);
3263
+ };
3264
+ svg.addEventListener("pointermove", handleMove);
3265
+ svg.addEventListener("pointerleave", handleLeave);
3266
+ return () => {
3267
+ svg.removeEventListener("pointermove", handleMove);
3268
+ svg.removeEventListener("pointerleave", handleLeave);
3269
+ svg.style.pointerEvents = previousPointerEvents;
3270
+ };
3271
+ }, [
3272
+ context,
3273
+ onPointerMove,
3274
+ onPointerLeave
3275
+ ]);
3276
+ return /* @__PURE__ */ React.createElement("g", {
3277
+ ref: graphRef,
3278
+ className: mx("dx-graph", classNames)
3279
+ });
1295
3280
  };
1296
3281
  var Graph = /* @__PURE__ */ forwardRef(GraphInner);
1297
3282
 
1298
3283
  // src/components/Mesh/Mesh.tsx
1299
- import { geoPath, select as select5 } from "d3";
1300
- import { useEffect as useEffect2 } from "react";
3284
+ import { geoPath, select as select7 } from "d3";
3285
+ import { useEffect as useEffect4 } from "react";
1301
3286
  import { feature, mesh } from "topojson-client";
1302
3287
  var Mesh = ({ radius = 16, value = 0.5 }) => {
1303
3288
  const { svg, size } = useSvgContext();
1304
- useEffect2(() => {
1305
- if (size) {
1306
- const topology = hexTopology(size, radius, value);
1307
- const projection = hexProjection(radius);
1308
- const path = geoPath().projection(projection);
1309
- select5(svg).append("g").attr("class", "hexagon").selectAll("path").data(topology.objects.hexagons.geometries).enter().append("path").attr("d", (d) => path(feature(topology, d))).attr("class", (d) => d.properties?.fill ? "fill" : null);
1310
- select5(svg).append("path").datum(mesh(topology, topology.objects.hexagons)).attr("class", "mesh").attr("d", path);
1311
- const redraw = (border) => {
1312
- border.attr("d", path(mesh(topology, topology.objects.hexagons, (a, b) => a.properties.fill !== b.properties.fill)));
1313
- };
1314
- select5(svg).append("path").attr("class", "border").call(redraw);
3289
+ useEffect4(() => {
3290
+ if (!size) {
3291
+ return;
1315
3292
  }
3293
+ const topology = hexTopology(size, radius, value);
3294
+ const projection = hexProjection(radius);
3295
+ const path = geoPath().projection(projection);
3296
+ const root = select7(svg).selectAll("g.dx-mesh-root").data([
3297
+ null
3298
+ ]).join("g").classed("dx-mesh-root", true);
3299
+ root.selectAll("*").remove();
3300
+ root.append("g").attr("class", "hexagon").selectAll("path").data(topology.objects.hexagons.geometries).enter().append("path").attr("d", (d) => path(feature(topology, d))).attr("class", (d) => d.properties?.fill ? "fill" : null);
3301
+ root.append("path").datum(mesh(topology, topology.objects.hexagons)).attr("class", "mesh").attr("d", path);
3302
+ const redraw = (border) => {
3303
+ border.attr("d", path(mesh(topology, topology.objects.hexagons, (a, b) => a.properties.fill !== b.properties.fill)));
3304
+ };
3305
+ root.append("path").attr("class", "border").call(redraw);
1316
3306
  }, [
1317
3307
  svg,
1318
3308
  size,
1319
- value
3309
+ value,
3310
+ radius
1320
3311
  ]);
1321
3312
  return null;
1322
3313
  };
@@ -1427,116 +3418,181 @@ var hexProjection = (radius) => {
1427
3418
  };
1428
3419
  };
1429
3420
 
3421
+ // src/components/SVG/FPS.tsx
3422
+ import React2, { useEffect as useEffect5, useState } from "react";
3423
+ import { mx as mx2 } from "@dxos/ui-theme";
3424
+ var PADDING = 8;
3425
+ var FPS = ({ classNames, corner = "top-right", margin = PADDING }) => {
3426
+ const context = useSvgContext();
3427
+ const [size, setSize] = useState(context.size);
3428
+ const [fps, setFps] = useState(null);
3429
+ useEffect5(() => {
3430
+ setSize(context.size);
3431
+ return context.resized.on((ctx) => setSize(ctx.size));
3432
+ }, [
3433
+ context
3434
+ ]);
3435
+ useEffect5(() => {
3436
+ let frames = 0;
3437
+ let windowStart = performance.now();
3438
+ let rafId = 0;
3439
+ const loop = (now) => {
3440
+ frames++;
3441
+ const elapsed = now - windowStart;
3442
+ if (elapsed >= 1e3) {
3443
+ setFps(frames * 1e3 / elapsed);
3444
+ frames = 0;
3445
+ windowStart = now;
3446
+ }
3447
+ rafId = requestAnimationFrame(loop);
3448
+ };
3449
+ rafId = requestAnimationFrame(loop);
3450
+ return () => cancelAnimationFrame(rafId);
3451
+ }, []);
3452
+ if (!size) {
3453
+ return null;
3454
+ }
3455
+ const halfW = size.width / 2;
3456
+ const halfH = size.height / 2;
3457
+ const left = corner === "top-left" || corner === "bottom-left";
3458
+ const top = corner === "top-left" || corner === "top-right";
3459
+ const x = left ? -halfW + margin : halfW - margin;
3460
+ const y = top ? -halfH + margin : halfH - margin;
3461
+ const textAnchor = left ? "start" : "end";
3462
+ const dominantBaseline = top ? "hanging" : "alphabetic";
3463
+ return /* @__PURE__ */ React2.createElement("g", {
3464
+ className: "dx-fps",
3465
+ style: {
3466
+ pointerEvents: "none"
3467
+ }
3468
+ }, /* @__PURE__ */ React2.createElement("text", {
3469
+ x,
3470
+ y,
3471
+ textAnchor,
3472
+ dominantBaseline,
3473
+ className: mx2("font-mono text-xs fill-neutral-500 tabular-nums", classNames)
3474
+ }, fps == null ? "\u2014 fps" : `${fps.toFixed(0)} fps`));
3475
+ };
3476
+
1430
3477
  // src/components/SVG/Grid.tsx
1431
- import { useSignals as _useSignals2 } from "@preact-signals/safe-react/tracking";
1432
- import React2 from "react";
1433
- import { mx as mx2 } from "@dxos/react-ui-theme";
3478
+ import React3 from "react";
3479
+ import { mx as mx3 } from "@dxos/ui-theme";
1434
3480
  var Grid = ({ classNames, ...props }) => {
1435
- var _effect = _useSignals2();
1436
- try {
1437
- const { ref } = useGrid(props);
1438
- return /* @__PURE__ */ React2.createElement("g", {
1439
- ref,
1440
- className: mx2("dx-grid", classNames)
1441
- });
1442
- } finally {
1443
- _effect.f();
1444
- }
3481
+ const { ref } = useGrid(props);
3482
+ return /* @__PURE__ */ React3.createElement("g", {
3483
+ ref,
3484
+ className: mx3("dx-grid", classNames)
3485
+ });
1445
3486
  };
1446
3487
 
1447
3488
  // src/components/SVG/Markers.tsx
1448
- import { useSignals as _useSignals3 } from "@preact-signals/safe-react/tracking";
1449
- import { select as select6 } from "d3";
1450
- import React3, { useEffect as useEffect3, useRef as useRef2 } from "react";
3489
+ import { select as select8 } from "d3";
3490
+ import React4, { useEffect as useEffect6, useRef as useRef4 } from "react";
1451
3491
  var Markers = ({ arrowSize, className }) => {
1452
- var _effect = _useSignals3();
1453
- try {
1454
- const ref = useRef2(null);
1455
- useEffect3(() => {
1456
- select6(ref.current).call(createMarkers({
1457
- arrowSize
1458
- }));
1459
- }, [
1460
- ref
1461
- ]);
1462
- return /* @__PURE__ */ React3.createElement("defs", {
1463
- ref,
1464
- className
1465
- });
1466
- } finally {
1467
- _effect.f();
1468
- }
3492
+ const ref = useRef4(null);
3493
+ useEffect6(() => {
3494
+ select8(ref.current).call(createMarkers({
3495
+ arrowSize
3496
+ }));
3497
+ }, [
3498
+ ref
3499
+ ]);
3500
+ return /* @__PURE__ */ React4.createElement("defs", {
3501
+ ref,
3502
+ className
3503
+ });
1469
3504
  };
1470
3505
 
1471
3506
  // src/components/SVG/Root.tsx
1472
- import { useSignals as _useSignals4 } from "@preact-signals/safe-react/tracking";
1473
- import { select as select7 } from "d3";
1474
- import React4, { forwardRef as forwardRef2, useEffect as useEffect4, useImperativeHandle as useImperativeHandle2, useMemo as useMemo2 } from "react";
1475
- import { useResizeDetector } from "react-resize-detector";
1476
- import { mx as mx3 } from "@dxos/react-ui-theme";
1477
- var Root = /* @__PURE__ */ forwardRef2(({ classNames, children, ...props }, ref) => {
1478
- var _effect = _useSignals4();
1479
- try {
1480
- const { ref: containerRef, width = 0, height = 0 } = useResizeDetector({
1481
- refreshRate: 200
3507
+ import { select as select9 } from "d3";
3508
+ import React5, { forwardRef as forwardRef2, useEffect as useEffect7, useImperativeHandle as useImperativeHandle2, useMemo as useMemo4, useState as useState2 } from "react";
3509
+ import { composableProps } from "@dxos/react-ui";
3510
+ import { mx as mx4 } from "@dxos/ui-theme";
3511
+ var Root = /* @__PURE__ */ forwardRef2(({ children, scale, centered, ...props }, ref) => {
3512
+ const [container, setContainer] = useState2(null);
3513
+ const [size, setSize] = useState2({
3514
+ width: 0,
3515
+ height: 0
3516
+ });
3517
+ useEffect7(() => {
3518
+ if (!container) {
3519
+ return;
3520
+ }
3521
+ const rect = container.getBoundingClientRect();
3522
+ setSize({
3523
+ width: rect.width,
3524
+ height: rect.height
1482
3525
  });
1483
- const context = useMemo2(() => {
1484
- return new SVGContext(props);
1485
- }, [
1486
- props.scale,
1487
- props.centered
1488
- ]);
1489
- useImperativeHandle2(ref, () => context, [
1490
- context
1491
- ]);
1492
- useEffect4(() => {
1493
- if (width && height) {
1494
- context.setSize({
1495
- width,
1496
- height
1497
- });
1498
- select7(context.svg).attr("display", "block").attr("viewBox", context.viewBox).attr("width", width).attr("height", height);
3526
+ const observer = new ResizeObserver((entries) => {
3527
+ const entry = entries[0];
3528
+ if (!entry) {
3529
+ return;
1499
3530
  }
1500
- }, [
1501
- context,
1502
- width,
1503
- height
1504
- ]);
1505
- const ready = width !== 0 && height !== 0;
1506
- return /* @__PURE__ */ React4.createElement(SVGContextProvider, {
1507
- value: context
1508
- }, /* @__PURE__ */ React4.createElement("div", {
1509
- ref: containerRef,
1510
- className: mx3("grid grow overflow-hidden", classNames)
1511
- }, /* @__PURE__ */ React4.createElement("svg", {
1512
- xmlns: "http://www.w3.org/2000/svg",
1513
- ref: context.ref,
1514
- className: mx3("transition-opacity opacity-0 duration-1000", ready && "opacity-100")
1515
- }, ready && children)));
1516
- } finally {
1517
- _effect.f();
1518
- }
3531
+ const { width: width2, height: height2 } = entry.contentRect;
3532
+ setSize((prev) => prev.width === width2 && prev.height === height2 ? prev : {
3533
+ width: width2,
3534
+ height: height2
3535
+ });
3536
+ });
3537
+ observer.observe(container);
3538
+ return () => observer.disconnect();
3539
+ }, [
3540
+ container
3541
+ ]);
3542
+ const { width, height } = size;
3543
+ const context = useMemo4(() => {
3544
+ return new SVGContext({
3545
+ scale,
3546
+ centered
3547
+ });
3548
+ }, [
3549
+ scale,
3550
+ centered
3551
+ ]);
3552
+ useImperativeHandle2(ref, () => context, [
3553
+ context
3554
+ ]);
3555
+ useEffect7(() => {
3556
+ if (width && height) {
3557
+ context.setSize({
3558
+ width,
3559
+ height
3560
+ });
3561
+ select9(context.svg).attr("display", "block").attr("viewBox", context.viewBox).attr("width", width).attr("height", height);
3562
+ }
3563
+ }, [
3564
+ context,
3565
+ width,
3566
+ height
3567
+ ]);
3568
+ const ready = width !== 0 && height !== 0;
3569
+ return /* @__PURE__ */ React5.createElement(SVGContextProvider, {
3570
+ value: context
3571
+ }, /* @__PURE__ */ React5.createElement("div", {
3572
+ ...composableProps(props, {
3573
+ classNames: "dx-expander"
3574
+ }),
3575
+ ref: setContainer
3576
+ }, /* @__PURE__ */ React5.createElement("svg", {
3577
+ xmlns: "http://www.w3.org/2000/svg",
3578
+ ref: context.ref,
3579
+ className: mx4("transition-opacity opacity-0 duration-1000", ready && "opacity-100")
3580
+ }, ready && children)));
1519
3581
  });
1520
3582
 
1521
3583
  // src/components/SVG/Zoom.tsx
1522
- import { useSignals as _useSignals5 } from "@preact-signals/safe-react/tracking";
1523
- import React5, { memo, useMemo as useMemo3 } from "react";
3584
+ import React6, { memo, useMemo as useMemo5 } from "react";
1524
3585
  var Zoom = /* @__PURE__ */ memo(({ extent, className, children }) => {
1525
- var _effect = _useSignals5();
1526
- try {
1527
- const options = useMemo3(() => ({
1528
- extent
1529
- }), [
1530
- JSON.stringify(extent)
1531
- ]);
1532
- const zoom = useZoom(options);
1533
- return /* @__PURE__ */ React5.createElement("g", {
1534
- ref: zoom.ref,
1535
- className
1536
- }, children);
1537
- } finally {
1538
- _effect.f();
1539
- }
3586
+ const options = useMemo5(() => ({
3587
+ extent
3588
+ }), [
3589
+ JSON.stringify(extent)
3590
+ ]);
3591
+ const zoom2 = useZoom(options);
3592
+ return /* @__PURE__ */ React6.createElement("g", {
3593
+ ref: zoom2.ref,
3594
+ className
3595
+ }, children);
1540
3596
  });
1541
3597
 
1542
3598
  // src/components/SVG/SVG.tsx
@@ -1546,11 +3602,12 @@ var SVG = {
1546
3602
  Markers,
1547
3603
  Mesh,
1548
3604
  Zoom,
1549
- Graph
3605
+ Graph,
3606
+ FPS
1550
3607
  };
1551
3608
 
1552
3609
  // src/fx/pulsar.ts
1553
- import { easeCubicOut as easeCubicOut2, select as select8 } from "d3";
3610
+ import { easeCubicOut as easeCubicOut2, select as select10 } from "d3";
1554
3611
  var PROP_PULSAR_ACTIVE = "dx-pulsar-active";
1555
3612
  (function(Pulsar2) {
1556
3613
  Pulsar2.has = (group) => group.select("circle.dx-pulsar").empty();
@@ -1565,27 +3622,37 @@ var PROP_PULSAR_ACTIVE = "dx-pulsar-active";
1565
3622
  var startAnimation = (pulsar, r, options = {}) => {
1566
3623
  const { period = 1e3, duration = 800, ratio = 3 } = options;
1567
3624
  return pulsar.attr("r", r).attr("opacity", 1).transition("pulsar").delay(period - Date.now() % period).duration(Math.min(duration, period - 20)).ease(easeCubicOut2).attr("r", r * ratio).attr("opacity", -0.1).on("end", function() {
1568
- if (select8(this).property(PROP_PULSAR_ACTIVE)) {
1569
- startAnimation(select8(this), r, options);
3625
+ if (select10(this).property(PROP_PULSAR_ACTIVE)) {
3626
+ startAnimation(select10(this), r, options);
1570
3627
  } else {
1571
- select8(this).remove();
3628
+ select10(this).remove();
1572
3629
  }
1573
3630
  });
1574
3631
  };
1575
3632
  var Pulsar;
1576
3633
  export {
3634
+ CLUSTER_NODE_TYPE_GROUP,
3635
+ CLUSTER_NODE_TYPE_LEAF,
3636
+ CLUSTER_NODE_TYPE_ROOT,
1577
3637
  EventEmitter,
1578
3638
  FractionUtil,
1579
3639
  Graph,
3640
+ GraphBundleProjector,
3641
+ GraphClusterProjector,
1580
3642
  GraphForceProjector,
1581
3643
  GraphHierarchicalProjector,
1582
- GraphInner,
3644
+ GraphLatticeProjector,
3645
+ GraphPlexusProjector,
1583
3646
  GraphProjector,
1584
3647
  GraphRadialProjector,
1585
3648
  GraphRelationalProjector,
1586
3649
  GraphRenderer,
3650
+ GraphSwarmProjector,
1587
3651
  GridController,
1588
3652
  Mesh,
3653
+ PLEXUS_NODE_TYPE_FOCUS,
3654
+ PLEXUS_NODE_TYPE_OBJECT,
3655
+ PLEXUS_NODE_TYPE_RELATION,
1589
3656
  Projector,
1590
3657
  Pulsar,
1591
3658
  Renderer,
@@ -1596,6 +3663,9 @@ export {
1596
3663
  Screen,
1597
3664
  Vector,
1598
3665
  ZoomHandler,
3666
+ appendRadialGroupLabel,
3667
+ appendRadialLeafLabel,
3668
+ appendRootLabel,
1599
3669
  createGraphDrag,
1600
3670
  createMarkers,
1601
3671
  defaultForceOptions,