@dxos/react-ui-graph 0.8.4-main.84f28bd → 0.8.4-main.8baae0fced

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 (134) 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 +1965 -560
  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 +1965 -560
  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 +9 -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 +20 -11
  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 +9 -5
  23. package/dist/types/src/components/Mesh/Mesh.stories.d.ts.map +1 -1
  24. package/dist/types/src/components/SVG/Grid.d.ts.map +1 -1
  25. package/dist/types/src/components/SVG/Markers.d.ts.map +1 -1
  26. package/dist/types/src/components/SVG/Root.d.ts +8 -4
  27. package/dist/types/src/components/SVG/Root.d.ts.map +1 -1
  28. package/dist/types/src/components/SVG/SVG.d.ts +14 -17
  29. package/dist/types/src/components/SVG/SVG.d.ts.map +1 -1
  30. package/dist/types/src/components/SVG/Svg.stories.d.ts +11 -9
  31. package/dist/types/src/components/SVG/Svg.stories.d.ts.map +1 -1
  32. package/dist/types/src/components/SVG/Zoom.d.ts.map +1 -1
  33. package/dist/types/src/fx/fx.stories.d.ts +16 -15
  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 +60 -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 +1 -1
  42. package/dist/types/src/graph/projector/graph-drag.d.ts.map +1 -1
  43. package/dist/types/src/graph/projector/graph-force-projector.d.ts +2 -2
  44. package/dist/types/src/graph/projector/graph-force-projector.d.ts.map +1 -1
  45. package/dist/types/src/graph/projector/graph-forces.d.ts.map +1 -1
  46. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts +2 -2
  47. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts.map +1 -1
  48. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts +23 -0
  49. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts.map +1 -0
  50. package/dist/types/src/graph/projector/graph-projector.d.ts +4 -4
  51. package/dist/types/src/graph/projector/graph-projector.d.ts.map +1 -1
  52. package/dist/types/src/graph/projector/graph-radial-projector.d.ts +8 -2
  53. package/dist/types/src/graph/projector/graph-radial-projector.d.ts.map +1 -1
  54. package/dist/types/src/graph/projector/graph-relational-projector.d.ts +2 -2
  55. package/dist/types/src/graph/projector/graph-relational-projector.d.ts.map +1 -1
  56. package/dist/types/src/graph/projector/index.d.ts +3 -0
  57. package/dist/types/src/graph/projector/index.d.ts.map +1 -1
  58. package/dist/types/src/graph/projector/projector.d.ts +10 -1
  59. package/dist/types/src/graph/projector/projector.d.ts.map +1 -1
  60. package/dist/types/src/graph/renderer/bullets.d.ts.map +1 -1
  61. package/dist/types/src/graph/renderer/graph-renderer.d.ts +22 -2
  62. package/dist/types/src/graph/renderer/graph-renderer.d.ts.map +1 -1
  63. package/dist/types/src/graph/renderer/renderer.d.ts +12 -1
  64. package/dist/types/src/graph/renderer/renderer.d.ts.map +1 -1
  65. package/dist/types/src/graph/types.d.ts +15 -1
  66. package/dist/types/src/graph/types.d.ts.map +1 -1
  67. package/dist/types/src/hooks/useGrid.d.ts.map +1 -1
  68. package/dist/types/src/hooks/useStateRef.d.ts.map +1 -1
  69. package/dist/types/src/hooks/useSvgContext.d.ts.map +1 -1
  70. package/dist/types/src/hooks/useZoom.d.ts.map +1 -1
  71. package/dist/types/src/stories/hooks.stories.d.ts +14 -9
  72. package/dist/types/src/stories/hooks.stories.d.ts.map +1 -1
  73. package/dist/types/src/testing/data.d.ts +5 -5
  74. package/dist/types/src/testing/data.d.ts.map +1 -1
  75. package/dist/types/src/testing/hooks.d.ts +2 -16
  76. package/dist/types/src/testing/hooks.d.ts.map +1 -1
  77. package/dist/types/src/testing/model.d.ts +4 -8
  78. package/dist/types/src/testing/model.d.ts.map +1 -1
  79. package/dist/types/src/util/events.d.ts.map +1 -1
  80. package/dist/types/src/util/fraction.d.ts +1 -1
  81. package/dist/types/src/util/fraction.d.ts.map +1 -1
  82. package/dist/types/src/util/index.d.ts +2 -2
  83. package/dist/types/src/util/index.d.ts.map +1 -1
  84. package/dist/types/src/util/points.d.ts.map +1 -1
  85. package/dist/types/src/util/scale.d.ts.map +1 -1
  86. package/dist/types/src/util/screen.d.ts +1 -1
  87. package/dist/types/src/util/screen.d.ts.map +1 -1
  88. package/dist/types/src/util/vector.d.ts +1 -1
  89. package/dist/types/src/util/vector.d.ts.map +1 -1
  90. package/dist/types/tsconfig.tsbuildinfo +1 -1
  91. package/package.json +33 -35
  92. package/src/components/Graph/Graph.stories.tsx +73 -69
  93. package/src/components/Graph/Graph.tsx +60 -25
  94. package/src/components/Mesh/Mesh.stories.tsx +16 -13
  95. package/src/components/Mesh/Mesh.tsx +44 -36
  96. package/src/components/SVG/Grid.tsx +2 -2
  97. package/src/components/SVG/Markers.tsx +1 -1
  98. package/src/components/SVG/Root.tsx +41 -9
  99. package/src/components/SVG/SVG.tsx +13 -4
  100. package/src/components/SVG/Svg.stories.tsx +23 -19
  101. package/src/components/SVG/Zoom.tsx +1 -1
  102. package/src/fx/fx.stories.tsx +18 -15
  103. package/src/graph/projector/graph-bundle-projector.ts +210 -0
  104. package/src/graph/projector/graph-cluster-projector.ts +325 -0
  105. package/src/graph/projector/graph-drag.ts +1 -1
  106. package/src/graph/projector/graph-force-projector.ts +8 -4
  107. package/src/graph/projector/graph-forces.ts +1 -1
  108. package/src/graph/projector/graph-hierarchical-projector.ts +5 -4
  109. package/src/graph/projector/graph-lattice-projector.ts +86 -0
  110. package/src/graph/projector/graph-projector.ts +12 -5
  111. package/src/graph/projector/graph-radial-projector.ts +33 -5
  112. package/src/graph/projector/graph-relational-projector.ts +5 -4
  113. package/src/graph/projector/index.ts +3 -0
  114. package/src/graph/projector/projector.ts +13 -4
  115. package/src/graph/renderer/bullets.ts +1 -1
  116. package/src/graph/renderer/graph-renderer.ts +178 -32
  117. package/src/graph/renderer/renderer.ts +16 -5
  118. package/src/graph/types.ts +15 -1
  119. package/src/hooks/useStateRef.ts +1 -1
  120. package/src/hooks/useZoom.ts +1 -1
  121. package/src/stories/hooks.stories.tsx +49 -37
  122. package/src/testing/data.ts +14 -14
  123. package/src/testing/hooks.ts +5 -5
  124. package/src/testing/model.ts +6 -6
  125. package/src/util/fraction.ts +1 -1
  126. package/src/util/index.ts +2 -2
  127. package/src/util/screen.test.ts +1 -1
  128. package/src/util/screen.ts +1 -1
  129. package/src/util/vector.ts +1 -1
  130. package/styles/graph.css +341 -43
  131. package/dist/lib/browser/chunk-4C5Z5DAE.mjs +0 -979
  132. package/dist/lib/browser/chunk-4C5Z5DAE.mjs.map +0 -7
  133. package/dist/lib/node-esm/chunk-AK6HNA4R.mjs +0 -981
  134. package/dist/lib/node-esm/chunk-AK6HNA4R.mjs.map +0 -7
@@ -1,32 +1,15 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
2
  import {
3
- EventEmitter,
4
- FractionUtil,
5
- GridController,
6
- SVGContext,
7
- SVGContextProvider,
8
- Scale,
9
- Screen,
10
- Vector,
11
- ZoomHandler,
12
- getCircumferencePoints,
13
- normal,
14
- offsetPoints,
15
3
  useDynamicRef,
16
- useGrid,
17
4
  useStateRef,
18
- useSvgContext,
19
- useTimestamp,
20
- useZoom
21
- } from "./chunk-AK6HNA4R.mjs";
5
+ useTimestamp
6
+ } from "./chunk-JSE2X4ML.mjs";
22
7
 
23
8
  // src/components/Graph/Graph.tsx
24
- import { useSignals as _useSignals } from "@preact-signals/safe-react/tracking";
25
- import { effect } from "@preact/signals-core";
26
- import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
9
+ import React, { forwardRef, useEffect as useEffect3, useImperativeHandle, useMemo as useMemo3, useRef as useRef3 } from "react";
27
10
  import { combine } from "@dxos/async";
28
- import { log as log6 } from "@dxos/log";
29
- import { mx } from "@dxos/react-ui-theme";
11
+ import { log as log9 } from "@dxos/log";
12
+ import { mx } from "@dxos/ui-theme";
30
13
 
31
14
  // src/graph/markers.ts
32
15
  import { line, select } from "d3";
@@ -79,111 +62,597 @@ var createMarkers = ({ arrowSize = 12 } = {}) => (group) => {
79
62
  });
80
63
  };
81
64
 
82
- // src/graph/projector/graph-drag.ts
83
- import { drag, pointer, select as select2 } from "d3";
84
- var defaultDragOptions = {
85
- linkMod: "metaKey",
86
- freezeMod: "shiftKey"
65
+ // src/graph/projector/graph-bundle-projector.ts
66
+ import { cluster as d3Cluster, curveBundle, hierarchy, lineRadial } from "d3";
67
+ import { log as log2 } from "@dxos/log";
68
+
69
+ // src/graph/projector/graph-radial-projector.ts
70
+ import { easeCubic, timer } from "d3";
71
+ import { log } from "@dxos/log";
72
+
73
+ // src/graph/types.ts
74
+ import { invariant } from "@dxos/invariant";
75
+ var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/types.ts";
76
+ var defaultIdAccessor = (node) => {
77
+ invariant(node.id, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 10, S: void 0, A: ["node.id", ""] });
78
+ return node.id;
87
79
  };
88
- var createGraphDrag = (context, projector, options = defaultDragOptions) => {
89
- let mode;
90
- let source;
91
- let target;
92
- let offset;
93
- let moved = false;
94
- const keyMod = (event, key) => {
95
- const modKey = options?.[key] ?? defaultDragOptions[key];
96
- return modKey === void 0 || event[modKey];
80
+ var emptyGraph = {
81
+ nodes: [],
82
+ edges: []
83
+ };
84
+
85
+ // src/util/events.ts
86
+ var EventEmitter = class {
87
+ _listeners = /* @__PURE__ */ new Set();
88
+ clear() {
89
+ this._listeners.clear();
90
+ }
91
+ on(onEvent) {
92
+ this._listeners.add(onEvent);
93
+ return () => this._listeners.delete(onEvent);
94
+ }
95
+ emit(value) {
96
+ this._listeners.forEach((listener) => listener(value));
97
+ }
98
+ };
99
+
100
+ // src/util/fraction.ts
101
+ import { invariant as invariant2 } from "@dxos/invariant";
102
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/util/fraction.ts";
103
+ var FractionUtil = class _FractionUtil {
104
+ /**
105
+ * Convert number to fraction.
106
+ * @param n
107
+ */
108
+ static toFraction = (n) => {
109
+ return typeof n === "number" ? [
110
+ n,
111
+ 1
112
+ ] : n;
97
113
  };
98
- return drag().filter((event) => !event.ctrlKey).on("start", function(event, d) {
99
- source = d;
100
- offset = pointer(event, this.parentElement);
101
- if (options?.onDrop && keyMod(event.sourceEvent, "linkMod")) {
102
- mode = 1;
103
- } else if (keyMod(event.sourceEvent, "dragMod")) {
104
- mode = 0;
105
- }
106
- }).on("drag", function(event, d) {
107
- const parent = this.closest("g.node");
108
- select2(parent).classed("dragging", true).raise();
109
- const [dx, dy] = pointer(event, this.parentElement);
110
- const x = d.x + dx - offset[0];
111
- const y = d.y + dy - offset[1];
112
- const point = [
113
- x,
114
- y
115
- ];
116
- switch (mode) {
117
- case 0: {
118
- select2(context.svg).attr("cursor", "grabbing");
119
- event.subject.x = event.subject.fx = point[0];
120
- event.subject.y = event.subject.fy = point[1];
121
- projector.refresh(true);
122
- moved = true;
123
- break;
114
+ static validate = (...fraction) => {
115
+ fraction.forEach(([n, d]) => {
116
+ if (!Number.isFinite(n) || !Number.isFinite(d) || d === 0) {
117
+ throw new Error(`Invalid fraction: ${n}/${d}`);
124
118
  }
125
- case 1: {
126
- if (options?.onDrag) {
127
- target = projector.findNode(event.x, event.y, 16);
128
- if (source === target) {
129
- select2(context.svg).attr("cursor", void 0);
130
- options?.onDrag?.();
131
- } else {
132
- select2(context.svg).attr("cursor", target ? "alias" : "cell");
133
- options?.onDrag?.(source, target, point);
134
- }
135
- }
119
+ });
120
+ return fraction;
121
+ };
122
+ /**
123
+ * @param {Fraction}
124
+ * Convert to rounded-sm number.
125
+ */
126
+ static toNumber = ([n, d]) => {
127
+ _FractionUtil.validate([
128
+ n,
129
+ d
130
+ ]);
131
+ return n / d;
132
+ };
133
+ /**
134
+ * Round the number to the nearest fraction.
135
+ * Example: 3/5 => 1/1; 3/5 (precision 2) => 1/2.
136
+ * @param {Fraction}
137
+ * @param p Precision (e.g., 1/2, 1/4, etc.)
138
+ */
139
+ static round = ([n, d], p = 1) => {
140
+ _FractionUtil.validate([
141
+ n,
142
+ d
143
+ ]);
144
+ const v = Math.round(_FractionUtil.toNumber(_FractionUtil.divide([
145
+ n,
146
+ d
147
+ ], [
148
+ 1,
149
+ p
150
+ ])));
151
+ return _FractionUtil.simplify([
152
+ v,
153
+ p
154
+ ]);
155
+ };
156
+ //
157
+ // Boolean.
158
+ //
159
+ /**
160
+ * Tests if equals.
161
+ * @param n1
162
+ * @param n2
163
+ */
164
+ static equals = (n1, n2) => {
165
+ return n1[0] * n2[1] === n1[1] * n2[0];
166
+ };
167
+ /**
168
+ * @param {Fraction}
169
+ * True if zero.
170
+ */
171
+ static isZero = ([n]) => {
172
+ return n === 0;
173
+ };
174
+ //
175
+ // Normalization.
176
+ //
177
+ /**
178
+ * Simplify fraction finding LCDs.
179
+ * @param n
180
+ * @param d
181
+ */
182
+ static simplify = ([n, d]) => {
183
+ _FractionUtil.validate([
184
+ n,
185
+ d
186
+ ]);
187
+ if (d < 1) {
188
+ const t = n / d;
189
+ if (Math.floor(t) === t) {
190
+ n = t;
191
+ d = 1;
136
192
  }
137
193
  }
138
- }).on("end", function(event) {
139
- select2(context.svg).attr("cursor", void 0);
140
- select2(this.parentElement).classed("dragging", false);
141
- switch (mode) {
142
- case 1: {
143
- options?.onDrop?.(source, target);
144
- break;
194
+ const fn = _FractionUtil.factors(n).reverse();
195
+ const fd = _FractionUtil.factors(d).reverse();
196
+ let c;
197
+ for (let i = 0; i < fn.length; i++) {
198
+ c = fd.find((n2) => n2 === fn[i]);
199
+ if (c) {
200
+ return [
201
+ n / c,
202
+ d / c
203
+ ];
145
204
  }
146
205
  }
147
- if (!keyMod(event.sourceEvent, "freezeMod")) {
148
- event.subject.fx = null;
149
- event.subject.fy = null;
150
- }
151
- mode = void 0;
152
- source = void 0;
153
- target = void 0;
154
- offset = void 0;
155
- if (moved) {
156
- projector.refresh(false);
157
- moved = false;
206
+ return [
207
+ n,
208
+ d
209
+ ];
210
+ };
211
+ /**
212
+ * Return common factors.
213
+ * @param n
214
+ */
215
+ static factors = (n) => {
216
+ invariant2(Number.isFinite(n), `Invalid number: ${n}`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 113, S: this, A: ["Number.isFinite(n)", "`Invalid number: ${n}`"] });
217
+ const factors = [
218
+ 1
219
+ ];
220
+ if (Number.isSafeInteger(n)) {
221
+ let f = 1;
222
+ do {
223
+ if (n % ++f === 0) {
224
+ factors.push(f);
225
+ }
226
+ } while (n / f > 1 && f < 100);
158
227
  }
159
- });
228
+ return factors;
229
+ };
230
+ //
231
+ // Basic arithmetic.
232
+ //
233
+ /**
234
+ * @param n1
235
+ * @param n2
236
+ */
237
+ static add = (n1, n2) => {
238
+ _FractionUtil.validate(n1, n2);
239
+ const d = n1[1] * n2[1];
240
+ const n = n1[0] * n2[1] + n2[0] * n1[1];
241
+ return _FractionUtil.simplify([
242
+ n,
243
+ d
244
+ ]);
245
+ };
246
+ /**
247
+ * @param n1
248
+ * @param n2
249
+ */
250
+ static subtract = (n1, n2) => {
251
+ _FractionUtil.validate(n1, n2);
252
+ const d = n1[1] * n2[1];
253
+ const n = n1[0] * n2[1] - n2[0] * n1[1];
254
+ return _FractionUtil.simplify([
255
+ n,
256
+ d
257
+ ]);
258
+ };
259
+ /**
260
+ * @param n1
261
+ * @param n2
262
+ */
263
+ static multiply = (n1, n2) => {
264
+ _FractionUtil.validate(n1, n2);
265
+ const n = n1[0] * n2[0];
266
+ const d = n1[1] * n2[1];
267
+ return _FractionUtil.simplify([
268
+ n,
269
+ d
270
+ ]);
271
+ };
272
+ /**
273
+ * @param n1
274
+ * @param n2
275
+ */
276
+ static divide = (n1, n2) => {
277
+ _FractionUtil.validate(n1, n2);
278
+ const n = n1[0] * n2[1];
279
+ const d = n1[1] * n2[0];
280
+ return _FractionUtil.simplify([
281
+ n,
282
+ d
283
+ ]);
284
+ };
160
285
  };
161
286
 
162
- // src/graph/types.ts
163
- import { invariant } from "@dxos/invariant";
164
- var __dxlog_file = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/types.ts";
165
- var defaultIdAccessor = (node) => {
166
- invariant(node.id, void 0, {
167
- F: __dxlog_file,
168
- L: 18,
169
- S: void 0,
170
- A: [
171
- "node.id",
172
- ""
287
+ // src/util/points.ts
288
+ var getCircumferencePoints = (p1, p2, r1 = 0, r2 = 0) => {
289
+ const [x1, y1] = p1;
290
+ const [x2, y2] = p2;
291
+ const theta = Math.atan2(x2 - x1, y2 - y1);
292
+ return [
293
+ [
294
+ // p1
295
+ x1 + (r1 === 0 ? 0 : r1 * Math.sin(theta)),
296
+ y1 + (r1 === 0 ? 0 : r1 * Math.cos(theta))
297
+ ],
298
+ [
299
+ // p2
300
+ x2 - (r2 === 0 ? 0 : r2 * Math.cos(Math.PI / 2 - theta)),
301
+ y2 - (r2 === 0 ? 0 : r2 * Math.sin(Math.PI / 2 - theta))
173
302
  ]
174
- });
175
- return node.id;
303
+ ];
176
304
  };
177
- var emptyGraph = {
178
- nodes: [],
179
- edges: []
305
+ var normal = (p1, p2) => {
306
+ const dx = p2[0] - p1[0];
307
+ const dy = p2[1] - p1[1];
308
+ const len = Math.hypot(dx, dy);
309
+ return [
310
+ dy / len,
311
+ -dx / len
312
+ ];
313
+ };
314
+ var offsetPoints = (points, distance, closed) => {
315
+ const len = points.length;
316
+ const out = [];
317
+ for (let i = 0; i < len; i++) {
318
+ const p0 = points[(i - 1 + len) % len];
319
+ const p1 = points[i];
320
+ const p2 = points[(i + 1) % len];
321
+ const n1 = normal(p0, p1);
322
+ const n2 = normal(p1, p2);
323
+ const nx = (n1[0] + n2[0]) / 2;
324
+ const ny = (n1[1] + n2[1]) / 2;
325
+ const norm = Math.hypot(nx, ny) || 1;
326
+ out.push([
327
+ p1[0] + distance * nx / norm,
328
+ p1[1] + distance * ny / norm
329
+ ]);
330
+ if (!closed && (i === 0 || i === len - 1)) {
331
+ out[i] = [
332
+ p1[0] + distance * normal(p0, p1)[0],
333
+ p1[1] + distance * normal(p0, p1)[1]
334
+ ];
335
+ }
336
+ }
337
+ return out;
338
+ };
339
+
340
+ // src/util/scale.ts
341
+ import { zoomIdentity } from "d3";
342
+ var Scale = class {
343
+ _gridSize;
344
+ _transform;
345
+ constructor(_gridSize = 32) {
346
+ this._gridSize = _gridSize;
347
+ }
348
+ get gridSize() {
349
+ return this._gridSize;
350
+ }
351
+ get transform() {
352
+ return this._transform || zoomIdentity;
353
+ }
354
+ setTransform(transform) {
355
+ if (this._transform?.x === transform.x && this._transform?.y === transform.y && this._transform?.k === transform.k) {
356
+ return false;
357
+ }
358
+ this._transform = transform;
359
+ return true;
360
+ }
361
+ /**
362
+ * Translate a screen point to a logical point.
363
+ * @param point
364
+ */
365
+ translate(point) {
366
+ const { x, y, k } = this._transform ?? {
367
+ x: 0,
368
+ y: 0,
369
+ k: 1
370
+ };
371
+ return [
372
+ (point[0] - x) / k,
373
+ (point[1] - y) / k
374
+ ];
375
+ }
376
+ /**
377
+ * Map model to screen.
378
+ * Model points are represented by fractions (to preserve precision) and use normal cartesian coordinates.
379
+ */
380
+ model = {
381
+ // TODO(burdon): Precision depends on scale.
382
+ snapValues: (array) => array.map((n) => FractionUtil.round(n)),
383
+ snapVertex: ({ x, y }) => {
384
+ const [sx, sy] = this.model.snapValues([
385
+ x,
386
+ y
387
+ ]);
388
+ return {
389
+ x: sx,
390
+ y: sy
391
+ };
392
+ },
393
+ snapBounds: ({ x, y, width, height }) => {
394
+ [x, y, width, height] = this.model.snapValues([
395
+ x,
396
+ y,
397
+ width,
398
+ height
399
+ ]);
400
+ return {
401
+ x,
402
+ y,
403
+ width,
404
+ height
405
+ };
406
+ },
407
+ toValue: (value) => {
408
+ return Math.round(FractionUtil.toNumber(value) * this._gridSize);
409
+ },
410
+ toValues: (values) => {
411
+ return values.map((value) => Math.round(FractionUtil.toNumber(value) * this._gridSize));
412
+ },
413
+ toPoint: (point) => {
414
+ const [x, y] = this.model.toValues([
415
+ point.x,
416
+ point.y
417
+ ]);
418
+ return [
419
+ x,
420
+ y === 0 ? 0 : -y
421
+ ];
422
+ },
423
+ toBounds: ({ x, y, width, height }) => {
424
+ const point = this.model.toPoint({
425
+ x,
426
+ y
427
+ });
428
+ const [width2, height2] = this.model.toValues([
429
+ width,
430
+ height
431
+ ]);
432
+ return {
433
+ x: point[0],
434
+ y: point[1] - height2,
435
+ width: width2,
436
+ height: height2
437
+ };
438
+ }
439
+ };
440
+ /**
441
+ * Map screen to model.
442
+ * Screen points are represented by floating numbers and use translated SVG coordinates (with the y-axis inverted).
443
+ */
444
+ screen = {
445
+ snapValues: (array) => array.map((n) => Math.round(n / this._gridSize) * this._gridSize),
446
+ snapPoint: ([x, y]) => [
447
+ x,
448
+ y
449
+ ].map((n) => Math.round(n / this._gridSize) * this._gridSize),
450
+ snapBounds: ({ x, y, width, height }) => {
451
+ [x, y, width, height] = this.screen.snapValues([
452
+ x,
453
+ y,
454
+ width,
455
+ height
456
+ ]);
457
+ return {
458
+ x,
459
+ y,
460
+ width,
461
+ height
462
+ };
463
+ },
464
+ toValue: (value) => {
465
+ return FractionUtil.divide(FractionUtil.toFraction(value), [
466
+ this._gridSize,
467
+ 1
468
+ ]);
469
+ },
470
+ toValues: (values) => {
471
+ return values.map((value) => FractionUtil.divide(FractionUtil.toFraction(value), [
472
+ this._gridSize,
473
+ 1
474
+ ]));
475
+ },
476
+ toVertex: (point) => {
477
+ const [x, y] = point;
478
+ return {
479
+ x: FractionUtil.toFraction(x / this._gridSize),
480
+ y: FractionUtil.toFraction(-y / this._gridSize)
481
+ };
482
+ },
483
+ toBounds: (bounds) => {
484
+ const { x, y } = this.screen.toVertex([
485
+ bounds.x,
486
+ bounds.y
487
+ ]);
488
+ const [width, height] = this.screen.toValues([
489
+ bounds.width,
490
+ bounds.height
491
+ ]);
492
+ return {
493
+ x,
494
+ y: FractionUtil.subtract(y, height),
495
+ width,
496
+ height
497
+ };
498
+ }
499
+ };
500
+ };
501
+
502
+ // src/util/screen.ts
503
+ var Screen = class {
504
+ static createBounds = ([x1, y1], [x2, y2], mod = {}) => {
505
+ const { constrain, center } = mod;
506
+ const x = Math.min(x1, x2);
507
+ const y = Math.min(y1, y2);
508
+ let width = Math.abs(x2 - x1);
509
+ let height = Math.abs(y2 - y1);
510
+ if (constrain) {
511
+ width = height = Math.max(width, height);
512
+ }
513
+ if (center) {
514
+ return {
515
+ x: x - width,
516
+ y: y - height,
517
+ width: width * 2,
518
+ height: height * 2
519
+ };
520
+ } else {
521
+ return {
522
+ x,
523
+ y,
524
+ width,
525
+ height
526
+ };
527
+ }
528
+ };
529
+ static center = ({ x, y, width, height }) => {
530
+ return [
531
+ x + width / 2,
532
+ y + height / 2
533
+ ];
534
+ };
535
+ static contains = (bounds, point) => {
536
+ const [x, y] = point;
537
+ if (x < bounds.x || y < bounds.y) {
538
+ return false;
539
+ }
540
+ if (x > bounds.x + bounds.width || y > bounds.y + bounds.height) {
541
+ return false;
542
+ }
543
+ return true;
544
+ };
545
+ /**
546
+ * Distance between two points.
547
+ * @param p1
548
+ * @param p2
549
+ */
550
+ static len = (p1, p2) => {
551
+ return Math.sqrt(Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2));
552
+ };
553
+ /**
554
+ * Distance to line segment.
555
+ * https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment#1501725
556
+ * @param v1
557
+ * @param v2
558
+ * @param p
559
+ */
560
+ static normal = (v1, v2, p) => {
561
+ const d2 = (p1, p2) => Math.pow(Math.abs(p1[0] - p2[0]), 2) + Math.pow(Math.abs(p1[1] - p2[1]), 2);
562
+ let d;
563
+ const len2 = d2(v1, v2);
564
+ if (len2 === 0) {
565
+ d = d2(p, v1);
566
+ } else {
567
+ let t = ((p[0] - v1[0]) * (v2[0] - v1[0]) + (p[1] - v1[1]) * (v2[1] - v1[1])) / len2;
568
+ t = Math.max(0, Math.min(1, t));
569
+ d = d2(p, [
570
+ v1[0] + t * (v2[0] - v1[0]),
571
+ v1[1] + t * (v2[1] - v1[1])
572
+ ]);
573
+ }
574
+ return Math.sqrt(d);
575
+ };
576
+ };
577
+
578
+ // src/util/vector.ts
579
+ var Vector = class {
580
+ /**
581
+ * Convert to Vertex.
582
+ * @param x
583
+ * @param y
584
+ */
585
+ static toVertex = ({ x, y }) => ({
586
+ x: FractionUtil.toFraction(x),
587
+ y: FractionUtil.toFraction(y)
588
+ });
589
+ /**
590
+ * Convert to Bounds.
591
+ * @param bounds
592
+ */
593
+ static toBounds = ({ x, y, width, height }) => ({
594
+ x: FractionUtil.toFraction(x),
595
+ y: FractionUtil.toFraction(y),
596
+ width: FractionUtil.toFraction(width),
597
+ height: FractionUtil.toFraction(height)
598
+ });
599
+ /**
600
+ * Calculate center point.
601
+ * @param bounds
602
+ */
603
+ static center = ({ x, y, width, height }) => {
604
+ const cx = FractionUtil.add(x, FractionUtil.multiply(width, [
605
+ 1,
606
+ 2
607
+ ]));
608
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
609
+ 1,
610
+ 2
611
+ ]));
612
+ return {
613
+ x: cx,
614
+ y: cy
615
+ };
616
+ };
617
+ /**
618
+ * Calculate centered left edge.
619
+ * @param bounds
620
+ */
621
+ static left = ({ x, y, height }) => {
622
+ const cx = x;
623
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
624
+ 1,
625
+ 2
626
+ ]));
627
+ return {
628
+ x: cx,
629
+ y: cy
630
+ };
631
+ };
632
+ /**
633
+ * Calculate centered right edge.
634
+ * @param bounds
635
+ */
636
+ static right = ({ x, y, width, height }) => {
637
+ const cx = FractionUtil.add(x, width);
638
+ const cy = FractionUtil.add(y, FractionUtil.multiply(height, [
639
+ 1,
640
+ 2
641
+ ]));
642
+ return {
643
+ x: cx,
644
+ y: cy
645
+ };
646
+ };
180
647
  };
181
648
 
182
649
  // src/graph/projector/projector.ts
183
650
  var Projector = class {
651
+ _context;
652
+ updated = new EventEmitter();
653
+ _options;
184
654
  constructor(_context, options) {
185
655
  this._context = _context;
186
- this.updated = new EventEmitter();
187
656
  this._options = Object.assign({
188
657
  idAccessor: defaultIdAccessor
189
658
  }, options);
@@ -200,9 +669,10 @@ var Projector = class {
200
669
  updateData(data) {
201
670
  this.onUpdate(data);
202
671
  }
203
- emitUpdate() {
672
+ emitUpdate(kind = "topology") {
204
673
  this.updated.emit({
205
- layout: this.layout
674
+ layout: this.layout,
675
+ kind
206
676
  });
207
677
  }
208
678
  async clear() {
@@ -228,6 +698,8 @@ var Projector = class {
228
698
 
229
699
  // src/graph/projector/graph-projector.ts
230
700
  var GraphProjector = class extends Projector {
701
+ _selection;
702
+ _layout;
231
703
  // TODO(burdon): Change to object props.
232
704
  constructor(context, options, _selection, layout) {
233
705
  super(context, options), this._selection = _selection;
@@ -269,30 +741,629 @@ var GraphProjector = class extends Projector {
269
741
  id: this.options.idAccessor(node)
270
742
  };
271
743
  }
272
- current.data = node;
273
- return current;
744
+ current.data = node;
745
+ current.hidden = false;
746
+ return current;
747
+ });
748
+ const edges = data.edges.map((edge) => ({
749
+ id: edge.id,
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
+
766
+ // src/graph/projector/graph-radial-projector.ts
767
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-radial-projector.ts";
768
+ var GraphRadialProjector = class extends GraphProjector {
769
+ _timer;
770
+ findNode(x, y, radius) {
771
+ return void 0;
772
+ }
773
+ onUpdate(graph) {
774
+ log("onUpdate", {
775
+ graph: {
776
+ nodes: graph?.nodes.length,
777
+ edges: graph?.edges.length
778
+ }
779
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 13, S: this });
780
+ this.mergeData(graph);
781
+ this.emitUpdate("topology");
782
+ this.doRadialLayout();
783
+ }
784
+ animate() {
785
+ this._timer?.stop();
786
+ this._timer = void 0;
787
+ const start = Date.now();
788
+ if (this.options.duration) {
789
+ this._timer = timer(() => {
790
+ const t = Math.min(1, (Date.now() - start) / this.options.duration);
791
+ const d = easeCubic(t);
792
+ this.layout.graph.nodes.forEach((node) => {
793
+ node.x = node.sx + (node.tx - node.sx) * d;
794
+ node.y = node.sy + (node.ty - node.sy) * d;
795
+ node.r = node.sr + (node.tr - node.sr) * d;
796
+ });
797
+ this.onTickFrame(d);
798
+ this.emitUpdate("positions");
799
+ if (t >= 1) {
800
+ this._timer.stop();
801
+ this._timer = void 0;
802
+ }
803
+ });
804
+ } else {
805
+ this.layout.graph.nodes.forEach((node) => {
806
+ node.x = node.tx;
807
+ node.y = node.ty;
808
+ node.r = node.tr;
809
+ });
810
+ this.onTickFrame(1);
811
+ this.emitUpdate("positions");
812
+ }
813
+ }
814
+ /**
815
+ * Per-frame hook called after node x/y/r are interpolated and before the
816
+ * 'positions' emit. Subclasses override to update edge geometry (`edge.path`)
817
+ * so curves stay glued to moving endpoints. `t` is the eased progress in [0, 1].
818
+ */
819
+ onTickFrame(t) {
820
+ }
821
+ async onStop() {
822
+ this._timer?.stop();
823
+ this._timer = void 0;
824
+ }
825
+ doRadialLayout() {
826
+ if (!this.context.size) {
827
+ return;
828
+ }
829
+ 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);
830
+ this.layout.graph.nodes.forEach((node, i) => {
831
+ const [tx, ty] = radial(i);
832
+ updateNode(node, [
833
+ tx,
834
+ ty
835
+ ]);
836
+ });
837
+ this.animate();
838
+ }
839
+ };
840
+ var updateNode = (node, [tx, ty], tr = 8) => {
841
+ const sx = node.x ?? tx;
842
+ const sy = node.y ?? ty;
843
+ const sr = node.r ?? tr;
844
+ Object.assign(node, {
845
+ initialized: true,
846
+ // Start.
847
+ sx,
848
+ sy,
849
+ sr,
850
+ // Target.
851
+ tx,
852
+ ty,
853
+ tr,
854
+ // Current.
855
+ x: sx,
856
+ y: sy,
857
+ r: sr
858
+ });
859
+ };
860
+ var layoutRadial = (x, y, r, n, start = -Math.PI / 2) => {
861
+ const da = 2 * Math.PI / n;
862
+ return (i) => {
863
+ const a = start + i * da;
864
+ return [
865
+ x + Math.cos(a) * r,
866
+ y + Math.sin(a) * r
867
+ ];
868
+ };
869
+ };
870
+ var layoutHorizontal = (x, y, w, n) => {
871
+ const dx = n > 1 ? w / (n - 1) : 0;
872
+ const sx = x - (n - 1) * dx / 2;
873
+ return (i) => {
874
+ return [
875
+ sx + i * dx,
876
+ y
877
+ ];
878
+ };
879
+ };
880
+ var layoutVertical = (x, y, h, n) => {
881
+ const dy = n > 1 ? h / (n - 1) : 0;
882
+ const sy = y - (n - 1) * dy / 2;
883
+ return (i) => {
884
+ return [
885
+ x,
886
+ sy + i * dy
887
+ ];
888
+ };
889
+ };
890
+
891
+ // src/graph/projector/graph-bundle-projector.ts
892
+ var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-bundle-projector.ts";
893
+ var ROOT_ID = "__bundle_root__";
894
+ var GROUP_PREFIX = "__bundle_group__:";
895
+ var cartesianToPolar = (x, y) => ({
896
+ angle: Math.atan2(x, -y),
897
+ radius: Math.hypot(x, y)
898
+ });
899
+ var GraphBundleProjector = class extends GraphRadialProjector {
900
+ // Per-edge polar point arrays. Points 0 and N-1 are the source / target leaves and are
901
+ // overwritten from current cartesian on every tick; intermediate points stay fixed at
902
+ // their cluster-layout polar coordinates.
903
+ #edgePoints = /* @__PURE__ */ new Map();
904
+ #lineGen = lineRadial().radius((d) => d.radius).angle((d) => d.angle);
905
+ onUpdate(graph) {
906
+ log2("onUpdate", {
907
+ graph: {
908
+ nodes: graph?.nodes.length,
909
+ edges: graph?.edges.length
910
+ }
911
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file4, L: 40, S: this });
912
+ this.mergeData(graph);
913
+ this.doBundleLayout();
914
+ this.emitUpdate("topology");
915
+ this.animate();
916
+ }
917
+ /**
918
+ * Refresh leaf endpoint polar values from current cartesian so the curve tracks
919
+ * its endpoints during the tween. Internal hierarchy positions stay constant.
920
+ */
921
+ onTickFrame(_t) {
922
+ for (const edge of this.layout.graph.edges) {
923
+ if (edge.type !== "bundle") {
924
+ continue;
925
+ }
926
+ const points = this.#edgePoints.get(edge.id);
927
+ if (!points || points.length < 2) {
928
+ continue;
929
+ }
930
+ const s = cartesianToPolar(edge.source.x ?? 0, edge.source.y ?? 0);
931
+ const t = cartesianToPolar(edge.target.x ?? 0, edge.target.y ?? 0);
932
+ points[0] = {
933
+ angle: s.angle,
934
+ radius: s.radius
935
+ };
936
+ points[points.length - 1] = {
937
+ angle: t.angle,
938
+ radius: t.radius
939
+ };
940
+ edge.path = this.#lineGen(points) ?? void 0;
941
+ }
942
+ }
943
+ doBundleLayout() {
944
+ if (!this.context.size) {
945
+ return;
946
+ }
947
+ const dataNodes = [
948
+ ...this.layout.graph.nodes
949
+ ];
950
+ if (!dataNodes.length) {
951
+ return;
952
+ }
953
+ const groupOf = this.options.groupOf;
954
+ const items = [
955
+ {
956
+ id: ROOT_ID
957
+ }
958
+ ];
959
+ const groupIds = /* @__PURE__ */ new Map();
960
+ for (const node of dataNodes) {
961
+ const key = groupOf?.(node);
962
+ let parent = ROOT_ID;
963
+ if (key !== void 0) {
964
+ let groupId = groupIds.get(key);
965
+ if (!groupId) {
966
+ groupId = `${GROUP_PREFIX}${key}`;
967
+ groupIds.set(key, groupId);
968
+ items.push({
969
+ id: groupId,
970
+ parent: ROOT_ID
971
+ });
972
+ }
973
+ parent = groupId;
974
+ }
975
+ items.push({
976
+ id: node.id,
977
+ parent,
978
+ node
979
+ });
980
+ }
981
+ const childrenByParent = /* @__PURE__ */ new Map();
982
+ for (const item of items) {
983
+ if (item.parent) {
984
+ const list = childrenByParent.get(item.parent) ?? [];
985
+ list.push(item);
986
+ childrenByParent.set(item.parent, list);
987
+ }
988
+ }
989
+ const root = hierarchy({
990
+ id: ROOT_ID
991
+ }, (d) => childrenByParent.get(d.id) ?? []);
992
+ const { width, height } = this.context.size;
993
+ const margin = this.options.margin ?? 120;
994
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
995
+ d3Cluster().size([
996
+ 2 * Math.PI,
997
+ ringRadius
998
+ ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
999
+ const leafR = this.options.leafRadius ?? 4;
1000
+ const tension = this.options.tension ?? 0.85;
1001
+ this.#lineGen = lineRadial().curve(curveBundle.beta(tension)).radius((d) => d.radius).angle((d) => d.angle);
1002
+ const hierById = /* @__PURE__ */ new Map();
1003
+ root.each((d) => {
1004
+ hierById.set(d.data.id, d);
1005
+ });
1006
+ root.leaves().forEach((d) => {
1007
+ const angle = d.x;
1008
+ const radius = d.y;
1009
+ const x = Math.cos(angle - Math.PI / 2) * radius;
1010
+ const y = Math.sin(angle - Math.PI / 2) * radius;
1011
+ if (d.data.node) {
1012
+ updateNode(d.data.node, [
1013
+ x,
1014
+ y
1015
+ ], leafR);
1016
+ }
1017
+ });
1018
+ this.layout.graph.nodes = dataNodes;
1019
+ this.#edgePoints.clear();
1020
+ const incomingEdges = [
1021
+ ...this.layout.graph.edges
1022
+ ];
1023
+ const bundleEdges = [];
1024
+ for (const edge of incomingEdges) {
1025
+ const sourceHier = hierById.get(edge.source.id);
1026
+ const targetHier = hierById.get(edge.target.id);
1027
+ if (!sourceHier || !targetHier || sourceHier === targetHier) {
1028
+ continue;
1029
+ }
1030
+ const pathNodes = sourceHier.path(targetHier);
1031
+ const points = pathNodes.map((n) => ({
1032
+ angle: n.x,
1033
+ radius: n.y
1034
+ }));
1035
+ this.#edgePoints.set(edge.id, points);
1036
+ bundleEdges.push({
1037
+ id: edge.id,
1038
+ type: "bundle",
1039
+ source: edge.source,
1040
+ target: edge.target,
1041
+ data: edge.data
1042
+ });
1043
+ }
1044
+ this.layout.graph.edges = bundleEdges;
1045
+ this.onTickFrame(0);
1046
+ }
1047
+ };
1048
+
1049
+ // src/graph/projector/graph-cluster-projector.ts
1050
+ import { cluster as d3Cluster2, hierarchy as hierarchy2, linkRadial } from "d3";
1051
+ import { log as log3 } from "@dxos/log";
1052
+ var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-cluster-projector.ts";
1053
+ var ROOT_ID2 = "__cluster_root__";
1054
+ var GROUP_PREFIX2 = "__group__:";
1055
+ var HIER_EDGE_PREFIX = "__hier__:";
1056
+ var CLUSTER_NODE_TYPE_LEAF = "leaf";
1057
+ var CLUSTER_NODE_TYPE_GROUP = "group";
1058
+ var CLUSTER_NODE_TYPE_ROOT = "root";
1059
+ var linkPath = linkRadial().angle((d) => d.x).radius((d) => d.y);
1060
+ var cartesianToPolar2 = (x, y) => ({
1061
+ angle: Math.atan2(x, -y),
1062
+ radius: Math.hypot(x, y)
1063
+ });
1064
+ var GraphClusterProjector = class extends GraphRadialProjector {
1065
+ // Synthetic-node ids (root id, or `${GROUP_PREFIX}${key}`) whose subtree is currently
1066
+ // hidden. Clicking the corresponding rendered circle calls toggleCollapsed to flip
1067
+ // membership, then re-runs the layout so the renderer's exit transition fades the
1068
+ // hidden leaves + hierarchy edges out (and back in on expand).
1069
+ #collapsed = /* @__PURE__ */ new Set();
1070
+ // Snapshot of the full data-node set as of the last mergeData. doClusterLayout always
1071
+ // reads from this rather than `layout.graph.nodes` — the layout view is filtered (it
1072
+ // drops hidden leaves so the renderer doesn't see them), so re-reading from there
1073
+ // would permanently lose the hidden leaves and they couldn't reappear on expand.
1074
+ #dataNodes = [];
1075
+ /** Toggle collapse state for a synthetic node id. Triggers a topology re-emit. */
1076
+ toggleCollapsed(id) {
1077
+ if (this.#collapsed.has(id)) {
1078
+ this.#collapsed.delete(id);
1079
+ } else {
1080
+ this.#collapsed.add(id);
1081
+ }
1082
+ this.doClusterLayout();
1083
+ this.emitUpdate("topology");
1084
+ this.animate();
1085
+ }
1086
+ /** Whether a synthetic-node id is currently collapsed. */
1087
+ isCollapsed(id) {
1088
+ return this.#collapsed.has(id);
1089
+ }
1090
+ onUpdate(graph) {
1091
+ log3("onUpdate", {
1092
+ graph: {
1093
+ nodes: graph?.nodes.length,
1094
+ edges: graph?.edges.length
1095
+ }
1096
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file5, L: 69, S: this });
1097
+ this.mergeData(graph);
1098
+ this.#dataNodes = [
1099
+ ...this.layout.graph.nodes
1100
+ ];
1101
+ this.doClusterLayout();
1102
+ this.emitUpdate("topology");
1103
+ this.animate();
1104
+ }
1105
+ /**
1106
+ * Recompute each hierarchy edge's `path` from current cartesian source/target positions,
1107
+ * so the curves track moving endpoints during a cross-variant tween (e.g. force → cluster)
1108
+ * instead of being pinned to the final polar layout.
1109
+ */
1110
+ onTickFrame(_t) {
1111
+ for (const edge of this.layout.graph.edges) {
1112
+ if (edge.type !== "hierarchy") {
1113
+ continue;
1114
+ }
1115
+ const { source, target } = edge;
1116
+ const s = cartesianToPolar2(source.x ?? 0, source.y ?? 0);
1117
+ const t = cartesianToPolar2(target.x ?? 0, target.y ?? 0);
1118
+ edge.path = linkPath({
1119
+ source: {
1120
+ x: s.angle,
1121
+ y: s.radius
1122
+ },
1123
+ target: {
1124
+ x: t.angle,
1125
+ y: t.radius
1126
+ }
1127
+ });
1128
+ }
1129
+ }
1130
+ doClusterLayout() {
1131
+ if (!this.context.size) {
1132
+ return;
1133
+ }
1134
+ const dataNodes = this.#dataNodes;
1135
+ if (!dataNodes.length) {
1136
+ return;
1137
+ }
1138
+ const groupOf = this.options.groupOf;
1139
+ const rootId = this.options.rootId ?? ROOT_ID2;
1140
+ const items = [
1141
+ {
1142
+ id: rootId
1143
+ }
1144
+ ];
1145
+ const groupIds = /* @__PURE__ */ new Map();
1146
+ const rootCollapsed = this.#collapsed.has(rootId);
1147
+ if (!rootCollapsed) {
1148
+ for (const node of dataNodes) {
1149
+ const key = groupOf?.(node);
1150
+ let parent = rootId;
1151
+ if (key !== void 0) {
1152
+ let groupId = groupIds.get(key);
1153
+ if (!groupId) {
1154
+ groupId = `${GROUP_PREFIX2}${key}`;
1155
+ groupIds.set(key, groupId);
1156
+ items.push({
1157
+ id: groupId,
1158
+ parent: rootId,
1159
+ groupKey: key
1160
+ });
1161
+ }
1162
+ parent = groupId;
1163
+ }
1164
+ if (this.#collapsed.has(parent)) {
1165
+ continue;
1166
+ }
1167
+ items.push({
1168
+ id: node.id,
1169
+ parent,
1170
+ node
1171
+ });
1172
+ }
1173
+ }
1174
+ const childrenByParent = /* @__PURE__ */ new Map();
1175
+ for (const item of items) {
1176
+ if (item.parent) {
1177
+ const list = childrenByParent.get(item.parent) ?? [];
1178
+ list.push(item);
1179
+ childrenByParent.set(item.parent, list);
1180
+ }
1181
+ }
1182
+ const root = hierarchy2({
1183
+ id: rootId
1184
+ }, (d) => childrenByParent.get(d.id) ?? []);
1185
+ const { width, height } = this.context.size;
1186
+ const margin = this.options.margin ?? 80;
1187
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
1188
+ d3Cluster2().size([
1189
+ 2 * Math.PI,
1190
+ ringRadius
1191
+ ]).separation((a, b) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
1192
+ const leafR = this.options.leafRadius ?? 4;
1193
+ const groupR = this.options.groupRadius ?? 3;
1194
+ const rootR = this.options.rootRadius ?? 5;
1195
+ const prevStubsById = /* @__PURE__ */ new Map();
1196
+ for (const node of this.layout.graph.nodes) {
1197
+ if (node.type === CLUSTER_NODE_TYPE_ROOT || node.type === CLUSTER_NODE_TYPE_GROUP) {
1198
+ prevStubsById.set(node.id, node);
1199
+ }
1200
+ }
1201
+ const syntheticNodes = /* @__PURE__ */ new Map();
1202
+ root.each((d) => {
1203
+ const id = d.data.id;
1204
+ const angle = d.x;
1205
+ const radius = d.y;
1206
+ const x = Math.cos(angle - Math.PI / 2) * radius;
1207
+ const y = Math.sin(angle - Math.PI / 2) * radius;
1208
+ if (d.data.node) {
1209
+ updateNode(d.data.node, [
1210
+ x,
1211
+ y
1212
+ ], leafR);
1213
+ d.data.node.type = CLUSTER_NODE_TYPE_LEAF;
1214
+ d.data.node.hidden = false;
1215
+ } else {
1216
+ const isRoot = id === rootId;
1217
+ const stub = prevStubsById.get(id) ?? {
1218
+ id,
1219
+ x: 0,
1220
+ y: 0
1221
+ };
1222
+ updateNode(stub, [
1223
+ x,
1224
+ y
1225
+ ], isRoot ? rootR : groupR);
1226
+ stub.type = isRoot ? CLUSTER_NODE_TYPE_ROOT : CLUSTER_NODE_TYPE_GROUP;
1227
+ if (isRoot) {
1228
+ stub.label = this.options.rootLabel;
1229
+ } else if (d.data.groupKey !== void 0) {
1230
+ stub.label = this.options.groupLabel ? this.options.groupLabel(d.data.groupKey) : d.data.groupKey;
1231
+ }
1232
+ syntheticNodes.set(id, stub);
1233
+ }
274
1234
  });
275
- const edges = data.edges.map((edge) => ({
276
- id: edge.id,
277
- source: nodes.find((n) => n.id === edge.source),
278
- target: nodes.find((n) => n.id === edge.target),
279
- data: edge.data
280
- })).filter((edge) => edge.source && edge.target);
281
- Object.assign(this._layout, {
282
- graph: {
283
- nodes,
284
- edges
1235
+ const visibleLeafIds = /* @__PURE__ */ new Set();
1236
+ for (const item of items) {
1237
+ if (item.node) {
1238
+ visibleLeafIds.add(item.id);
1239
+ }
1240
+ }
1241
+ for (const node of dataNodes) {
1242
+ if (visibleLeafIds.has(node.id)) {
1243
+ continue;
285
1244
  }
1245
+ const key = groupOf?.(node);
1246
+ const parentId = key !== void 0 && groupIds.has(key) ? groupIds.get(key) : rootId;
1247
+ const parentStub = syntheticNodes.get(parentId);
1248
+ const targetX = parentStub?.tx ?? 0;
1249
+ const targetY = parentStub?.ty ?? 0;
1250
+ updateNode(node, [
1251
+ targetX,
1252
+ targetY
1253
+ ], leafR);
1254
+ node.type = CLUSTER_NODE_TYPE_LEAF;
1255
+ node.hidden = true;
1256
+ }
1257
+ const nextNodes = [];
1258
+ for (const stub of syntheticNodes.values()) {
1259
+ nextNodes.push(stub);
1260
+ }
1261
+ for (const node of dataNodes) {
1262
+ nextNodes.push(node);
1263
+ }
1264
+ this.layout.graph.nodes = nextNodes;
1265
+ const hierarchyEdges = [];
1266
+ root.links().forEach((link) => {
1267
+ const sid = link.source.data.id;
1268
+ const tid = link.target.data.id;
1269
+ const sourceNode = link.source.data.node ?? syntheticNodes.get(sid);
1270
+ const targetNode = link.target.data.node ?? syntheticNodes.get(tid);
1271
+ hierarchyEdges.push({
1272
+ id: `${HIER_EDGE_PREFIX}${sid}->${tid}`,
1273
+ type: "hierarchy",
1274
+ source: sourceNode,
1275
+ target: targetNode,
1276
+ data: void 0
1277
+ });
286
1278
  });
1279
+ this.layout.graph.edges = hierarchyEdges;
1280
+ this.onTickFrame(0);
287
1281
  }
288
- async onClear() {
289
- this.reset();
290
- }
1282
+ };
1283
+
1284
+ // src/graph/projector/graph-drag.ts
1285
+ import { drag, pointer, select as select2 } from "d3";
1286
+ var defaultDragOptions = {
1287
+ linkMod: "metaKey",
1288
+ freezeMod: "shiftKey"
1289
+ };
1290
+ var createGraphDrag = (context, projector, options = defaultDragOptions) => {
1291
+ let mode;
1292
+ let source;
1293
+ let target;
1294
+ let offset;
1295
+ let moved = false;
1296
+ const keyMod = (event, key) => {
1297
+ const modKey = options?.[key] ?? defaultDragOptions[key];
1298
+ return modKey === void 0 || event[modKey];
1299
+ };
1300
+ return drag().filter((event) => !event.ctrlKey).on("start", function(event, d) {
1301
+ source = d;
1302
+ offset = pointer(event, this.parentElement);
1303
+ if (options?.onDrop && keyMod(event.sourceEvent, "linkMod")) {
1304
+ mode = 1;
1305
+ } else if (keyMod(event.sourceEvent, "dragMod")) {
1306
+ mode = 0;
1307
+ }
1308
+ }).on("drag", function(event, d) {
1309
+ const parent = this.closest("g.node");
1310
+ select2(parent).classed("dragging", true).raise();
1311
+ const [dx, dy] = pointer(event, this.parentElement);
1312
+ const x = d.x + dx - offset[0];
1313
+ const y = d.y + dy - offset[1];
1314
+ const point = [
1315
+ x,
1316
+ y
1317
+ ];
1318
+ switch (mode) {
1319
+ case 0: {
1320
+ select2(context.svg).attr("cursor", "grabbing");
1321
+ event.subject.x = event.subject.fx = point[0];
1322
+ event.subject.y = event.subject.fy = point[1];
1323
+ projector.refresh(true);
1324
+ moved = true;
1325
+ break;
1326
+ }
1327
+ case 1: {
1328
+ if (options?.onDrag) {
1329
+ target = projector.findNode(event.x, event.y, 16);
1330
+ if (source === target) {
1331
+ select2(context.svg).attr("cursor", void 0);
1332
+ options?.onDrag?.();
1333
+ } else {
1334
+ select2(context.svg).attr("cursor", target ? "alias" : "cell");
1335
+ options?.onDrag?.(source, target, point);
1336
+ }
1337
+ }
1338
+ }
1339
+ }
1340
+ }).on("end", function(event) {
1341
+ select2(context.svg).attr("cursor", void 0);
1342
+ select2(this.parentElement).classed("dragging", false);
1343
+ switch (mode) {
1344
+ case 1: {
1345
+ options?.onDrop?.(source, target);
1346
+ break;
1347
+ }
1348
+ }
1349
+ if (!keyMod(event.sourceEvent, "freezeMod")) {
1350
+ event.subject.fx = null;
1351
+ event.subject.fy = null;
1352
+ }
1353
+ mode = void 0;
1354
+ source = void 0;
1355
+ target = void 0;
1356
+ offset = void 0;
1357
+ if (moved) {
1358
+ projector.refresh(false);
1359
+ moved = false;
1360
+ }
1361
+ });
291
1362
  };
292
1363
 
293
1364
  // src/graph/projector/graph-force-projector.ts
294
1365
  import { forceCenter, forceCollide, forceLink, forceManyBody, forceRadial, forceSimulation, forceX as forceX2, forceY as forceY2 } from "d3";
295
- import { log } from "@dxos/log";
1366
+ import { log as log4 } from "@dxos/log";
296
1367
 
297
1368
  // src/graph/projector/graph-forces.ts
298
1369
  import { forceX, forceY } from "d3";
@@ -311,7 +1382,7 @@ var forcePoint = ({ x, y, strength = 0.01 }) => {
311
1382
  };
312
1383
 
313
1384
  // src/graph/projector/graph-force-projector.ts
314
- var __dxlog_file2 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-force-projector.ts";
1385
+ var __dxlog_file6 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-force-projector.ts";
315
1386
  var getValue = (valueOrFunction, invoker, defaultValue) => {
316
1387
  return (typeof valueOrFunction === "function" ? invoker(valueOrFunction) : valueOrFunction) ?? defaultValue;
317
1388
  };
@@ -328,11 +1399,9 @@ var defaultForceOptions = {
328
1399
  point: true
329
1400
  };
330
1401
  var GraphForceProjector = class extends GraphProjector {
331
- constructor() {
332
- super(...arguments);
333
- // https://github.com/d3/d3-force
334
- this._simulation = forceSimulation();
335
- }
1402
+ // https://github.com/d3/d3-force
1403
+ _simulation = forceSimulation();
1404
+ _timeout;
336
1405
  get forces() {
337
1406
  return this.options.forces ?? defaultForceOptions;
338
1407
  }
@@ -363,7 +1432,7 @@ var GraphForceProjector = class extends GraphProjector {
363
1432
  } else {
364
1433
  this.updateForces(this.forces);
365
1434
  }
366
- this._simulation.on("tick", () => propagating && this.emitUpdate()).velocityDecay(0.3).alphaDecay(1 - Math.pow(1e-3, 1 / 300)).alpha(1).restart();
1435
+ this._simulation.on("tick", () => propagating && this.emitUpdate("positions")).velocityDecay(0.3).alphaDecay(1 - Math.pow(1e-3, 1 / 300)).alpha(1).restart();
367
1436
  }
368
1437
  async onStop() {
369
1438
  clearTimeout(this._timeout);
@@ -380,21 +1449,17 @@ var GraphForceProjector = class extends GraphProjector {
380
1449
  this.restart();
381
1450
  }
382
1451
  onUpdate(graph) {
383
- log("onUpdate", {
1452
+ log4("onUpdate", {
384
1453
  graph: {
385
1454
  nodes: graph?.nodes.length,
386
1455
  edges: graph?.edges.length
387
1456
  }
388
- }, {
389
- F: __dxlog_file2,
390
- L: 226,
391
- S: this,
392
- C: (f, a) => f(...a)
393
- });
1457
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 90, S: this });
394
1458
  this._simulation.stop();
395
1459
  this.mergeData(graph);
396
1460
  this.updateLayout();
397
1461
  this.updateForces(this.forces);
1462
+ this.emitUpdate("topology");
398
1463
  this.restart();
399
1464
  }
400
1465
  updateLayout() {
@@ -438,14 +1503,9 @@ var GraphForceProjector = class extends GraphProjector {
438
1503
  * Update all forces.
439
1504
  */
440
1505
  updateForces(forces) {
441
- log("updateForces", {
1506
+ log4("updateForces", {
442
1507
  forces
443
- }, {
444
- F: __dxlog_file2,
445
- L: 287,
446
- S: this,
447
- C: (f, a) => f(...a)
448
- });
1508
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file6, L: 152, S: this });
449
1509
  this._simulation.nodes(this.layout.graph.nodes).force("link", maybeForce(forces?.link, (config) => {
450
1510
  const force = forceLink().id((d) => d.id).links(this.layout.graph.edges.filter((edge) => edge.linkForce));
451
1511
  if (config.distance != null) {
@@ -479,170 +1539,50 @@ var GraphForceProjector = class extends GraphProjector {
479
1539
  if (config.strength != null) {
480
1540
  force.strength(config.strength);
481
1541
  }
482
- return force;
483
- })).force("center", maybeForce(forces?.center, (config) => {
484
- const force = forceCenter().x(config.x ?? 0).y(config.y ?? 0);
485
- if (config.strength != null) {
486
- force.strength(config.strength);
487
- }
488
- return force;
489
- })).force("point", maybeForce(forces?.point, ({ x = 0, y = 0, strength }) => {
490
- return forcePoint({
491
- x,
492
- y,
493
- strength
494
- });
495
- })).force("x", maybeForce(forces?.x, (config) => {
496
- const force = forceX2(config.x ?? 0);
497
- if (config.strength != null) {
498
- force.strength(config.strength);
499
- }
500
- return force;
501
- })).force("y", maybeForce(forces?.y, (config) => {
502
- const force = forceY2(config.y ?? 0);
503
- if (config.strength != null) {
504
- force.strength(config.strength);
505
- }
506
- return force;
507
- }));
508
- }
509
- };
510
-
511
- // src/graph/projector/graph-hierarchical-projector.ts
512
- import { log as log3 } from "@dxos/log";
513
-
514
- // src/graph/projector/graph-radial-projector.ts
515
- import { easeCubic, timer } from "d3";
516
- import { log as log2 } from "@dxos/log";
517
- var __dxlog_file3 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-radial-projector.ts";
518
- var GraphRadialProjector = class extends GraphProjector {
519
- findNode(x, y, radius) {
520
- return void 0;
521
- }
522
- onUpdate(graph) {
523
- log2("onUpdate", {
524
- graph: {
525
- nodes: graph?.nodes.length,
526
- edges: graph?.edges.length
527
- }
528
- }, {
529
- F: __dxlog_file3,
530
- L: 31,
531
- S: this,
532
- C: (f, a) => f(...a)
533
- });
534
- this.mergeData(graph);
535
- this.doRadialLayout();
536
- }
537
- animate() {
538
- const start = Date.now();
539
- if (this.options.duration) {
540
- this._timer = timer(() => {
541
- const t = Math.min(1, (Date.now() - start) / this.options.duration);
542
- const d = easeCubic(t);
543
- this.layout.graph.nodes.forEach((node) => {
544
- node.x = node.sx + (node.tx - node.sx) * d;
545
- node.y = node.sy + (node.ty - node.sy) * d;
546
- node.r = node.sr + (node.tr - node.sr) * d;
547
- });
548
- this.emitUpdate();
549
- if (t >= 1) {
550
- this._timer.stop();
551
- this._timer = void 0;
552
- }
553
- });
554
- } else {
555
- this.emitUpdate();
556
- }
557
- }
558
- async onStop() {
559
- this._timer?.stop();
560
- this._timer = void 0;
561
- }
562
- doRadialLayout() {
563
- if (!this.context.size) {
564
- return;
565
- }
566
- 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);
567
- this.layout.graph.nodes.forEach((node, i) => {
568
- const [tx, ty] = radial(i);
569
- updateNode(node, [
570
- tx,
571
- ty
572
- ]);
573
- });
574
- this.animate();
575
- }
576
- };
577
- var updateNode = (node, [tx, ty], tr = 8) => {
578
- const sx = node.x ?? tx;
579
- const sy = node.y ?? ty;
580
- const sr = node.r ?? tr;
581
- Object.assign(node, {
582
- initialized: true,
583
- // Start.
584
- sx,
585
- sy,
586
- sr,
587
- // Target.
588
- tx,
589
- ty,
590
- tr,
591
- // Current.
592
- x: sx,
593
- y: sy,
594
- r: sr
595
- });
596
- };
597
- var layoutRadial = (x, y, r, n, start = -Math.PI / 2) => {
598
- const da = 2 * Math.PI / n;
599
- return (i) => {
600
- const a = start + i * da;
601
- return [
602
- x + Math.cos(a) * r,
603
- y + Math.sin(a) * r
604
- ];
605
- };
606
- };
607
- var layoutHorizontal = (x, y, w, n) => {
608
- const dx = n > 1 ? w / (n - 1) : 0;
609
- const sx = x - (n - 1) * dx / 2;
610
- return (i) => {
611
- return [
612
- sx + i * dx,
613
- y
614
- ];
615
- };
616
- };
617
- var layoutVertical = (x, y, h, n) => {
618
- const dy = n > 1 ? h / (n - 1) : 0;
619
- const sy = y - (n - 1) * dy / 2;
620
- return (i) => {
621
- return [
622
- x,
623
- sy + i * dy
624
- ];
625
- };
1542
+ return force;
1543
+ })).force("center", maybeForce(forces?.center, (config) => {
1544
+ const force = forceCenter().x(config.x ?? 0).y(config.y ?? 0);
1545
+ if (config.strength != null) {
1546
+ force.strength(config.strength);
1547
+ }
1548
+ return force;
1549
+ })).force("point", maybeForce(forces?.point, ({ x = 0, y = 0, strength }) => {
1550
+ return forcePoint({
1551
+ x,
1552
+ y,
1553
+ strength
1554
+ });
1555
+ })).force("x", maybeForce(forces?.x, (config) => {
1556
+ const force = forceX2(config.x ?? 0);
1557
+ if (config.strength != null) {
1558
+ force.strength(config.strength);
1559
+ }
1560
+ return force;
1561
+ })).force("y", maybeForce(forces?.y, (config) => {
1562
+ const force = forceY2(config.y ?? 0);
1563
+ if (config.strength != null) {
1564
+ force.strength(config.strength);
1565
+ }
1566
+ return force;
1567
+ }));
1568
+ }
626
1569
  };
627
1570
 
628
1571
  // src/graph/projector/graph-hierarchical-projector.ts
629
- var __dxlog_file4 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-hierarchical-projector.ts";
1572
+ import { log as log5 } from "@dxos/log";
1573
+ var __dxlog_file7 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-hierarchical-projector.ts";
630
1574
  var GraphHierarchicalProjector = class extends GraphRadialProjector {
631
1575
  onUpdate(graph) {
632
- log3("onUpdate", {
1576
+ log5("onUpdate", {
633
1577
  graph: {
634
1578
  nodes: graph?.nodes.length,
635
1579
  edges: graph?.edges.length
636
1580
  },
637
- selection: this.selection?.selected.value
638
- }, {
639
- F: __dxlog_file4,
640
- L: 23,
641
- S: this,
642
- C: (f, a) => f(...a)
643
- });
1581
+ selection: this.selection?.getSelectedIds()
1582
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file7, L: 8, S: this });
644
1583
  this.mergeData(graph);
645
- const selected = this.selection?.selected.value?.[0];
1584
+ this.emitUpdate("topology");
1585
+ const selected = this.selection?.getSelectedIds()[0];
646
1586
  if (selected) {
647
1587
  const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
648
1588
  if (node) {
@@ -687,25 +1627,72 @@ var GraphHierarchicalProjector = class extends GraphRadialProjector {
687
1627
  }
688
1628
  };
689
1629
 
1630
+ // src/graph/projector/graph-lattice-projector.ts
1631
+ import { log as log6 } from "@dxos/log";
1632
+ var __dxlog_file8 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-lattice-projector.ts";
1633
+ var GraphLatticeProjector = class extends GraphRadialProjector {
1634
+ onUpdate(graph) {
1635
+ log6("onUpdate", {
1636
+ graph: {
1637
+ nodes: graph?.nodes.length,
1638
+ edges: graph?.edges.length
1639
+ }
1640
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file8, L: 14, S: this });
1641
+ this.mergeData(graph);
1642
+ this.doLatticeLayout();
1643
+ this.emitUpdate("topology");
1644
+ this.animate();
1645
+ }
1646
+ doLatticeLayout() {
1647
+ if (!this.context.size) {
1648
+ return;
1649
+ }
1650
+ const nodes = this.layout.graph.nodes;
1651
+ const count = nodes.length;
1652
+ if (!count) {
1653
+ return;
1654
+ }
1655
+ const sortBy = this.options.sortBy ?? ((n) => n.data?.label ?? n.id);
1656
+ nodes.sort((a, b) => sortBy(a).localeCompare(sortBy(b)));
1657
+ const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
1658
+ const rows = Math.ceil(count / columns);
1659
+ const margin = this.options.margin ?? 16;
1660
+ const { width, height } = this.context.size;
1661
+ const innerW = Math.max(0, width - 2 * margin);
1662
+ const innerH = Math.max(0, height - 2 * margin);
1663
+ const r = this.options.radius ?? 6;
1664
+ const fit = Math.min(innerW / columns, innerH / rows);
1665
+ const cellSize = Math.max(0, Math.min(fit, r * 6));
1666
+ const gridW = cellSize * columns;
1667
+ const gridH = cellSize * rows;
1668
+ const offsetX = -gridW / 2 + cellSize / 2;
1669
+ const offsetY = -gridH / 2 + cellSize / 2;
1670
+ nodes.forEach((node, i) => {
1671
+ const tx = offsetX + i % columns * cellSize;
1672
+ const ty = offsetY + Math.floor(i / columns) * cellSize;
1673
+ updateNode(node, [
1674
+ tx,
1675
+ ty
1676
+ ], r);
1677
+ });
1678
+ }
1679
+ };
1680
+
690
1681
  // src/graph/projector/graph-relational-projector.ts
691
- import { log as log4 } from "@dxos/log";
692
- var __dxlog_file5 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-relational-projector.ts";
1682
+ import { log as log7 } from "@dxos/log";
1683
+ var __dxlog_file9 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/projector/graph-relational-projector.ts";
693
1684
  var GraphRelationalProjector = class extends GraphRadialProjector {
694
1685
  onUpdate(graph) {
695
- log4("onUpdate", {
1686
+ log7("onUpdate", {
696
1687
  graph: {
697
1688
  nodes: graph?.nodes.length,
698
1689
  edges: graph?.edges.length
699
1690
  },
700
- selection: this.selection?.selected.value
701
- }, {
702
- F: __dxlog_file5,
703
- L: 23,
704
- S: this,
705
- C: (f, a) => f(...a)
706
- });
1691
+ selection: this.selection?.getSelectedIds()
1692
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file9, L: 8, S: this });
707
1693
  this.mergeData(graph);
708
- const selected = this.selection?.selected.value?.[0];
1694
+ this.emitUpdate("topology");
1695
+ const selected = this.selection?.getSelectedIds()[0];
709
1696
  if (selected) {
710
1697
  const node = this.layout.graph.nodes.find((node2) => node2.id === selected);
711
1698
  if (node) {
@@ -777,9 +1764,9 @@ var GraphRelationalProjector = class extends GraphRadialProjector {
777
1764
  };
778
1765
 
779
1766
  // src/graph/renderer/graph-renderer.ts
780
- import { line as line2, select as select4, polygonHull, easeCubicOut } from "d3";
1767
+ import { easeCubicOut, line as line2, polygonHull, select as select4 } from "d3";
781
1768
  import * as Clipper from "js-clipper";
782
- import { log as log5 } from "@dxos/log";
1769
+ import { log as log8 } from "@dxos/log";
783
1770
 
784
1771
  // src/graph/renderer/bullets.ts
785
1772
  import { easeLinear, interpolate, select as select3 } from "d3";
@@ -812,9 +1799,10 @@ var createBullets = (group, nodeId, options = {}) => {
812
1799
  };
813
1800
 
814
1801
  // src/graph/renderer/renderer.ts
815
- import { invariant as invariant2 } from "@dxos/invariant";
816
- var __dxlog_file6 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/renderer.ts";
817
1802
  var Renderer = class {
1803
+ _context;
1804
+ _root;
1805
+ _options;
818
1806
  constructor(_context, _root, options) {
819
1807
  this._context = _context;
820
1808
  this._root = _root;
@@ -825,34 +1813,48 @@ var Renderer = class {
825
1813
  get context() {
826
1814
  return this._context;
827
1815
  }
1816
+ /**
1817
+ * Returns the SVG group root if mounted.
1818
+ * The ref may be null between mount/unmount cycles or before the SVG container has sized.
1819
+ * Callers should treat null as "skip this render" rather than as an error.
1820
+ */
828
1821
  get root() {
829
- invariant2(this._root.current, "SVG root is not initialized", {
830
- F: __dxlog_file6,
831
- L: 40,
832
- S: this,
833
- A: [
834
- "this._root.current",
835
- "'SVG root is not initialized'"
836
- ]
837
- });
838
1822
  return this._root.current;
839
1823
  }
840
1824
  get options() {
841
1825
  return this._options;
842
1826
  }
1827
+ /**
1828
+ * Fast path invoked when only positions changed.
1829
+ * Default falls back to a full `render`; subclasses can override to skip
1830
+ * enter/exit joins and attribute callbacks for per-tick updates.
1831
+ */
1832
+ applyPositions(layout) {
1833
+ this.render(layout);
1834
+ }
843
1835
  };
844
1836
 
845
1837
  // src/graph/renderer/graph-renderer.ts
846
- var __dxlog_file7 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/graph-renderer.ts";
1838
+ var __dxlog_file10 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/graph/renderer/graph-renderer.ts";
847
1839
  var createLine2 = line2();
1840
+ var EDGE_FADE_MS = 300;
1841
+ var NODE_HIDE_MS = 500;
848
1842
  var GraphRenderer = class extends Renderer {
1843
+ // First render of this instance — used to clear DOM left behind by a previous
1844
+ // renderer pointing at the same `<g>` (e.g. when the consumer swaps projectors
1845
+ // and a new renderer is constructed for the same SVG root). Without this, the
1846
+ // previous variant's node shapes (e.g. circles) would persist as d3.join sees
1847
+ // them in the `update` set instead of `enter`.
1848
+ #firstRender = true;
849
1849
  render(layout) {
850
- log5("render", layout, {
851
- F: __dxlog_file7,
852
- L: 62,
853
- S: this,
854
- C: (f, a) => f(...a)
855
- });
1850
+ if (!this.root) {
1851
+ return;
1852
+ }
1853
+ if (this.#firstRender) {
1854
+ this.#firstRender = false;
1855
+ this.root.replaceChildren();
1856
+ }
1857
+ log8("render", layout, { "~LogMeta": "~LogMeta", F: __dxlog_file10, L: 35, S: this });
856
1858
  const root = select4(this.root);
857
1859
  if (layout.guides) {
858
1860
  root.selectAll("g.dx-guides").data([
@@ -916,31 +1918,82 @@ var GraphRenderer = class extends Renderer {
916
1918
  id: "nodes"
917
1919
  }
918
1920
  ], (d) => d.id).join("g").classed("dx-nodes", true);
919
- 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) => {
1921
+ 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) => {
920
1922
  return exit.transition().ease(easeCubicOut).duration(300).attr("opacity", 0).on("end", function(d) {
921
1923
  select4(this).remove();
922
1924
  });
923
- }).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
924
- 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) => {
925
- }), (exit) => exit.remove()).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1925
+ }).call(updateNode2, this.options).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1926
+ edgeGroup.selectAll("g.dx-edge").data(layout.graph?.edges ?? [], (d) => d.id).join(
1927
+ (enter) => enter.append("g").attr("data-id", (d) => d.id).classed("dx-edge", true).call(createEdge, this.options),
1928
+ (update) => update,
1929
+ // Exit fade: edges removed by a topology change (e.g. variant switch from cluster
1930
+ // back to force replaces hierarchy edges with data edges) ease out rather than pop.
1931
+ (exit) => exit.transition().ease(easeCubicOut).duration(EDGE_FADE_MS).attr("opacity", 0).on("end", function() {
1932
+ select4(this).remove();
1933
+ })
1934
+ ).call(updateEdge, this.options, nodeGroup).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
1935
+ }
1936
+ /**
1937
+ * Fast positions-only update. Skips enter/exit, attribute callbacks, label sizing,
1938
+ * and the subgraph hull pass; just writes `transform` per node and `d` per edge.
1939
+ * Called per simulation tick / animation frame.
1940
+ */
1941
+ applyPositions(layout) {
1942
+ if (!this.root) {
1943
+ return;
1944
+ }
1945
+ const root = select4(this.root);
1946
+ root.select("g.dx-nodes").selectAll("g.dx-node").attr("transform", (d) => d.x != null && d.y != null ? `translate(${d.x},${d.y})` : null);
1947
+ root.select("g.dx-edges").selectAll("g.dx-edge").selectAll("path").attr("d", function() {
1948
+ const edge = select4(this.parentElement).datum();
1949
+ if (edge.path) {
1950
+ return edge.path;
1951
+ }
1952
+ const { source, target } = edge;
1953
+ if (!source.initialized || !target.initialized) {
1954
+ return null;
1955
+ }
1956
+ return createLine2(getCircumferencePoints([
1957
+ source.x,
1958
+ source.y
1959
+ ], [
1960
+ target.x,
1961
+ target.y
1962
+ ], source.r, target.r));
1963
+ });
926
1964
  }
927
1965
  /**
928
1966
  * Trigger path bullets.
929
1967
  * @param node
930
1968
  */
931
1969
  fireBullet(node) {
1970
+ if (!this.root) {
1971
+ return;
1972
+ }
932
1973
  select4(this.root).selectAll("g.dx-edges").selectAll("path").call(createBullets(this.root, node.id));
933
1974
  }
934
1975
  };
1976
+ var SHAPE_CLASS = "dx-shape";
1977
+ var renderCustomShape = (group, options) => {
1978
+ group.each(function(d) {
1979
+ const g = select4(this);
1980
+ g.selectAll(`.${SHAPE_CLASS}`).remove();
1981
+ const shapeGroup = g.append("g").classed(SHAPE_CLASS, true);
1982
+ options.renderNode(shapeGroup, d);
1983
+ });
1984
+ };
935
1985
  var createNode = (group, options) => {
936
- const circle = group.append("circle");
1986
+ const useCustom = !!options.renderNode;
1987
+ if (useCustom) {
1988
+ renderCustomShape(group, options);
1989
+ }
1990
+ const hitTarget = useCustom ? group : group.append("circle");
937
1991
  if (options.drag) {
938
- circle.call(options.drag);
1992
+ hitTarget.call(options.drag);
939
1993
  }
940
1994
  if (options.onNodeClick) {
941
- group.on("click", (event) => {
942
- const node = select4(event.target).datum();
943
- options.onNodeClick(node, event);
1995
+ group.on("click", (event, d) => {
1996
+ options.onNodeClick(d, event);
944
1997
  });
945
1998
  }
946
1999
  if (options.labels && !options.onNodePointerEnter) {
@@ -949,24 +2002,28 @@ var createNode = (group, options) => {
949
2002
  g.append("rect");
950
2003
  g.append("text").style("dominant-baseline", "middle");
951
2004
  }
952
- if (options.onNodePointerEnter) {
953
- circle.on("pointerenter", function(event) {
954
- const node = select4(this.parentElement).datum();
955
- options.onNodePointerEnter(node, event);
2005
+ if (options.onNodePointerEnter || options.onNodePointerLeave) {
2006
+ hitTarget.on("pointerenter", function(event) {
2007
+ const node = select4(useCustom ? this : this.parentElement).datum();
2008
+ options.onNodePointerEnter?.(node, event);
2009
+ });
2010
+ hitTarget.on("pointerleave", function(event) {
2011
+ const node = select4(useCustom ? this : this.parentElement).datum();
2012
+ options.onNodePointerLeave?.(node, event);
956
2013
  });
957
2014
  group.attr("data-hover", "handled");
958
- } else if (options.highlight !== false) {
959
- circle.on("pointerenter", function() {
2015
+ } else if (options.highlight !== false && !useCustom) {
2016
+ hitTarget.on("pointerenter", function() {
960
2017
  select4(this.closest("g.dx-node")).raise();
961
2018
  if (options.labels) {
962
- select4(this.parentElement).classed("dx-active", true).classed("dx-highlight", true);
2019
+ select4(this.parentElement).classed("dx-node-active", true).classed("dx-highlight", true);
963
2020
  }
964
2021
  });
965
2022
  group.on("pointerleave", function() {
966
2023
  if (options.labels) {
967
- select4(this).classed("dx-active", false);
2024
+ select4(this).classed("dx-node-active", false);
968
2025
  setTimeout(() => {
969
- if (!select4(this).classed("dx-active")) {
2026
+ if (!select4(this).classed("dx-node-active")) {
970
2027
  select4(this).classed("dx-highlight", false);
971
2028
  }
972
2029
  }, 300);
@@ -978,6 +2035,11 @@ var updateNode2 = (group, options) => {
978
2035
  group.attr("transform", (d) => {
979
2036
  return d.x != null && d.y != null ? `translate(${d.x},${d.y})` : void 0;
980
2037
  });
2038
+ group.classed("dx-hidden", (d) => d.hidden ?? false);
2039
+ group.transition("hide").ease(easeCubicOut).duration(NODE_HIDE_MS).attr("opacity", (d) => d.hidden ? 0 : 1);
2040
+ if (options.renderNode) {
2041
+ renderCustomShape(group, options);
2042
+ }
981
2043
  if (options.attributes?.node) {
982
2044
  try {
983
2045
  group.each((d, i, nodes) => {
@@ -993,18 +2055,15 @@ var updateNode2 = (group, options) => {
993
2055
  }
994
2056
  });
995
2057
  } catch (error) {
996
- log5.error("updateNode", {
2058
+ log8.error("updateNode", {
997
2059
  error: error?.message
998
- }, {
999
- F: __dxlog_file7,
1000
- L: 304,
1001
- S: void 0,
1002
- C: (f, a) => f(...a)
1003
- });
2060
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file10, L: 292, S: void 0 });
1004
2061
  }
1005
2062
  }
1006
2063
  const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
1007
- groupOrTransition.select("circle").attr("r", (d) => d.r ?? 16);
2064
+ if (!options.renderNode) {
2065
+ groupOrTransition.select("circle").attr("r", (d) => d.r ?? 16);
2066
+ }
1008
2067
  if (options.labels) {
1009
2068
  const bx = 1;
1010
2069
  const px = 4;
@@ -1049,18 +2108,17 @@ var updateEdge = (group, options, nodeGroup) => {
1049
2108
  }
1050
2109
  });
1051
2110
  } catch (error) {
1052
- log5.error("updateEdge", {
2111
+ log8.error("updateEdge", {
1053
2112
  error: error?.message
1054
- }, {
1055
- F: __dxlog_file7,
1056
- L: 416,
1057
- S: void 0,
1058
- C: (f, a) => f(...a)
1059
- });
2113
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file10, L: 360, S: void 0 });
1060
2114
  }
1061
2115
  const groupOrTransition = options.transition ? group.transition(options.transition()) : group;
1062
2116
  groupOrTransition.selectAll("path").attr("d", function() {
1063
- const { source, target } = select4(this.parentElement).datum();
2117
+ const edge = select4(this.parentElement).datum();
2118
+ if (edge.path) {
2119
+ return edge.path;
2120
+ }
2121
+ const { source, target } = edge;
1064
2122
  if (!source.initialized || !target.initialized) {
1065
2123
  return;
1066
2124
  }
@@ -1134,117 +2192,451 @@ var linkerRenderer = (root, { source, target, point } = {}) => {
1134
2192
  });
1135
2193
  };
1136
2194
 
2195
+ // src/hooks/useGrid.ts
2196
+ import { line as line4, range, select as select5 } from "d3";
2197
+ import { useEffect, useMemo, useRef } from "react";
2198
+
2199
+ // src/hooks/useSvgContext.ts
2200
+ import { createContext, useContext } from "react";
2201
+ import { createRef } from "react";
2202
+ import { raise } from "@dxos/debug";
2203
+ var SVGContext = class {
2204
+ _ref = createRef();
2205
+ _scale;
2206
+ _centered;
2207
+ _size;
2208
+ _center;
2209
+ resized = new EventEmitter();
2210
+ constructor({ scale = new Scale(), centered = true }) {
2211
+ this._scale = scale;
2212
+ this._centered = centered;
2213
+ }
2214
+ get ref() {
2215
+ return this._ref;
2216
+ }
2217
+ get svg() {
2218
+ return this._ref.current;
2219
+ }
2220
+ get scale() {
2221
+ return this._scale;
2222
+ }
2223
+ get center() {
2224
+ return this._center;
2225
+ }
2226
+ get size() {
2227
+ return this._size;
2228
+ }
2229
+ /**
2230
+ * https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
2231
+ */
2232
+ get viewBox() {
2233
+ const [x, y] = this.center;
2234
+ return `${x},${y},${this._size.width},${this._size.height}`;
2235
+ }
2236
+ setSize(size) {
2237
+ this._size = {
2238
+ ...size
2239
+ };
2240
+ this._center = this._centered ? [
2241
+ -Math.floor(size.width / 2),
2242
+ -Math.floor(size.height / 2)
2243
+ ] : [
2244
+ 0,
2245
+ 0
2246
+ ];
2247
+ this.resized.emit(this);
2248
+ }
2249
+ setTransform(transform) {
2250
+ if (this._scale.setTransform(transform)) {
2251
+ this.resized.emit(this);
2252
+ }
2253
+ }
2254
+ /**
2255
+ * https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint
2256
+ * @param point
2257
+ */
2258
+ elementFromPoint(point) {
2259
+ const [x, y] = point;
2260
+ const [cx, cy] = this._center;
2261
+ return document.elementFromPoint(cx + x, cy + y);
2262
+ }
2263
+ };
2264
+ var SVGContextType = createContext(void 0);
2265
+ var SVGContextProvider = SVGContextType.Provider;
2266
+ var useSvgContext = () => {
2267
+ return useContext(SVGContextType) ?? raise(new Error("Missing SVGRoot"));
2268
+ };
2269
+
2270
+ // src/hooks/useGrid.ts
2271
+ var createLine4 = line4();
2272
+ var createGrid = (context, options) => {
2273
+ if (!context.size) {
2274
+ return [];
2275
+ }
2276
+ const paths = [];
2277
+ const { width, height } = context.size;
2278
+ const { x, y, k } = context.scale.transform;
2279
+ const s = 1 / k;
2280
+ const w = width * s;
2281
+ const h = height * s;
2282
+ const dx = -(x + width / 2) * s;
2283
+ const dy = -(y + height / 2) * s;
2284
+ if (options.axis) {
2285
+ const axis = [
2286
+ [
2287
+ [
2288
+ 0,
2289
+ dy
2290
+ ],
2291
+ [
2292
+ 0,
2293
+ dy + h
2294
+ ]
2295
+ ],
2296
+ [
2297
+ [
2298
+ dx,
2299
+ 0
2300
+ ],
2301
+ [
2302
+ dx + w,
2303
+ 0
2304
+ ]
2305
+ ]
2306
+ ];
2307
+ paths.push({
2308
+ id: "axis",
2309
+ class: "dx-axis",
2310
+ path: axis.map((line5) => createLine4(line5)).join()
2311
+ });
2312
+ }
2313
+ if (options.grid) {
2314
+ const mod = (n, size, delta = 0) => Math.floor(n / size + delta) * size;
2315
+ const majorSize = context.scale.gridSize;
2316
+ const xMajor = range(-mod((x + width / 2) * s, majorSize), mod((-x + width / 2) * s, majorSize, 1), majorSize);
2317
+ const yMajor = range(-mod((y + height / 2) * s, majorSize), mod((-y + height / 2) * s, majorSize, 1), majorSize);
2318
+ const major = [
2319
+ ...xMajor.filter((x2) => !options.axis || x2).map((x2) => [
2320
+ [
2321
+ x2,
2322
+ dy
2323
+ ],
2324
+ [
2325
+ x2,
2326
+ dy + h
2327
+ ]
2328
+ ]),
2329
+ ...yMajor.filter((y2) => !options.axis || y2).map((y2) => [
2330
+ [
2331
+ dx,
2332
+ y2
2333
+ ],
2334
+ [
2335
+ dx + w,
2336
+ y2
2337
+ ]
2338
+ ])
2339
+ ];
2340
+ paths.push({
2341
+ id: "major",
2342
+ class: "dx-major",
2343
+ path: major.map((line5) => createLine4(line5)).join()
2344
+ });
2345
+ const minorSize = Math.pow(2, Math.round(Math.log2(s * context.scale.gridSize)));
2346
+ if (majorSize > minorSize) {
2347
+ const xMinor = range(-mod((x + width / 2) * s, minorSize), mod((-x + width / 2) * s, minorSize, 1), minorSize);
2348
+ const yMinor = range(-mod((y + height / 2) * s, minorSize), mod((-y + height / 2) * s, minorSize, 1), minorSize);
2349
+ const minor = [
2350
+ ...xMinor.filter((x2) => xMajor.indexOf(x2) === -1).map((x2) => [
2351
+ [
2352
+ x2,
2353
+ dy
2354
+ ],
2355
+ [
2356
+ x2,
2357
+ dy + h
2358
+ ]
2359
+ ]),
2360
+ ...yMinor.filter((y2) => yMajor.indexOf(y2) === -1).map((y2) => [
2361
+ [
2362
+ dx,
2363
+ y2
2364
+ ],
2365
+ [
2366
+ dx + w,
2367
+ y2
2368
+ ]
2369
+ ])
2370
+ ];
2371
+ paths.push({
2372
+ id: "minor",
2373
+ class: "dx-minor",
2374
+ path: minor.map((line5) => createLine4(line5)).join()
2375
+ });
2376
+ }
2377
+ }
2378
+ return paths;
2379
+ };
2380
+ var defaultGridOptions = {
2381
+ visible: true,
2382
+ axis: true,
2383
+ grid: true
2384
+ };
2385
+ var GridController = class {
2386
+ _ref;
2387
+ _context;
2388
+ _options;
2389
+ _visible = false;
2390
+ constructor(_ref, _context, _options) {
2391
+ this._ref = _ref;
2392
+ this._context = _context;
2393
+ this._options = _options;
2394
+ this._visible = this._options.visible ?? true;
2395
+ }
2396
+ get ref() {
2397
+ return this._ref;
2398
+ }
2399
+ get visible() {
2400
+ return this._visible;
2401
+ }
2402
+ draw() {
2403
+ if (!this._context.size) {
2404
+ return;
2405
+ }
2406
+ const paths = this._visible ? createGrid(this._context, this._options) : [];
2407
+ const root = select5(this._ref.current);
2408
+ root.selectAll("path").data(paths, (path) => path.id).join("path").style("pointer-events", "none").attr("d", (d) => d.path).attr("class", (d) => d.class);
2409
+ const transform = this._context.scale.transform;
2410
+ if (transform) {
2411
+ root.attr("transform", transform);
2412
+ root.attr("stroke-width", 1 / transform.k);
2413
+ }
2414
+ }
2415
+ setVisible(visible) {
2416
+ this._visible = visible;
2417
+ this.draw();
2418
+ return this;
2419
+ }
2420
+ };
2421
+ var useGrid = (options = defaultGridOptions) => {
2422
+ const ref = useRef(null);
2423
+ const context = useSvgContext();
2424
+ const controller = useMemo(() => new GridController(ref, context, options), []);
2425
+ useEffect(() => context.resized.on(() => controller.draw()), [
2426
+ context,
2427
+ controller
2428
+ ]);
2429
+ return controller;
2430
+ };
2431
+
2432
+ // src/hooks/useZoom.ts
2433
+ import { select as select6, zoom, zoomIdentity as zoomIdentity2 } from "d3";
2434
+ import defaultsDeep from "lodash.defaultsdeep";
2435
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2 } from "react";
2436
+ var defaultZoomOptions = {
2437
+ enabled: true,
2438
+ extent: [
2439
+ 1 / 4,
2440
+ 4
2441
+ ],
2442
+ onDblClick: (zoom2) => zoom2.reset()
2443
+ };
2444
+ var ZoomHandler = class {
2445
+ _ref;
2446
+ _context;
2447
+ _zoom;
2448
+ _options;
2449
+ _enabled;
2450
+ constructor(_ref, _context, options) {
2451
+ this._ref = _ref;
2452
+ this._context = _context;
2453
+ this._options = defaultsDeep({}, options, defaultZoomOptions);
2454
+ this._enabled = this._options.enabled ?? true;
2455
+ this._zoom = zoom().scaleExtent(this._options.extent ?? defaultZoomOptions.extent);
2456
+ }
2457
+ /**
2458
+ * Gets the reference which the transform is applied to.
2459
+ */
2460
+ get ref() {
2461
+ return this._ref;
2462
+ }
2463
+ get zoom() {
2464
+ return this._zoom;
2465
+ }
2466
+ init() {
2467
+ this.setEnabled(this._enabled);
2468
+ this.reset(0);
2469
+ return this;
2470
+ }
2471
+ setEnabled(enable) {
2472
+ if (enable) {
2473
+ select6(this._context.svg).call(this._zoom).on(
2474
+ "dblclick.zoom",
2475
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2476
+ // @ts-ignore
2477
+ this._options?.onDblClick ? () => {
2478
+ this._options?.onDblClick(this);
2479
+ } : null
2480
+ );
2481
+ } else {
2482
+ select6(this._context.svg).on(".zoom", null);
2483
+ }
2484
+ this._enabled = enable;
2485
+ return this;
2486
+ }
2487
+ reset(duration = 500) {
2488
+ const scale = 1;
2489
+ const transform = zoomIdentity2.scale(scale);
2490
+ select6(this._context.svg).transition().duration(duration).call(this._zoom.transform, transform);
2491
+ return this;
2492
+ }
2493
+ };
2494
+ var useZoom = (options = defaultZoomOptions) => {
2495
+ const context = useSvgContext();
2496
+ const ref = useRef2(null);
2497
+ const handler = useMemo2(() => new ZoomHandler(ref, context, options), [
2498
+ context,
2499
+ options
2500
+ ]);
2501
+ useEffect2(() => {
2502
+ handler.zoom.on("zoom", ({ transform }) => {
2503
+ context.setTransform(transform);
2504
+ select6(ref.current).attr("transform", transform);
2505
+ });
2506
+ handler.init();
2507
+ }, [
2508
+ handler
2509
+ ]);
2510
+ return handler;
2511
+ };
2512
+
1137
2513
  // src/components/Graph/Graph.tsx
1138
- var __dxlog_file8 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/components/Graph/Graph.tsx";
1139
- var GraphInner = ({ classNames, model, projector: _projector, renderer: _renderer, drag: drag2, arrows, onSelect, onInspect, ...props }, forwardedRef) => {
1140
- var _effect = _useSignals();
1141
- try {
1142
- const context = useSvgContext();
1143
- const graphRef = useRef();
1144
- const { projector, renderer } = useMemo(() => {
1145
- let projector2 = _projector;
1146
- if (!projector2) {
1147
- projector2 = new GraphForceProjector(context);
1148
- }
1149
- let renderer2 = _renderer;
1150
- if (!renderer2) {
1151
- renderer2 = new GraphRenderer(context, graphRef, {
1152
- ...props,
1153
- // TODO(burdon): Replace drag when projector is updated.
1154
- drag: drag2 ? createGraphDrag(context, projector2) : void 0,
1155
- arrows: {
1156
- end: arrows
1157
- },
1158
- onNodeClick: onSelect ? (node, event) => onSelect(node, event) : void 0,
1159
- onNodePointerEnter: onInspect ? (node, event) => onInspect(node, event) : void 0
1160
- });
1161
- }
1162
- return {
1163
- projector: projector2,
1164
- renderer: renderer2
1165
- };
1166
- }, [
1167
- context,
1168
- _projector,
1169
- _renderer,
1170
- drag2
1171
- ]);
1172
- useImperativeHandle(forwardedRef, () => ({
1173
- refresh: () => {
1174
- projector.updateData(model?.graph);
1175
- },
1176
- repaint: () => {
1177
- renderer.render(projector.layout);
1178
- },
1179
- findNode: (id) => {
1180
- return graphRef.current?.querySelector(`g[data-id="${id}"]`);
1181
- }
1182
- }), [
1183
- model,
1184
- projector,
1185
- renderer
1186
- ]);
1187
- useEffect(() => {
1188
- return combine(effect(() => {
2514
+ var __dxlog_file11 = "/__w/dxos/dxos/packages/ui/react-ui-graph/src/components/Graph/Graph.tsx";
2515
+ var GraphInner = ({ classNames, model, projector: projectorProp, renderer: rendererProp, drag: drag2, arrows, onSelect, onInspect, ...props }, forwardedRef) => {
2516
+ const context = useSvgContext();
2517
+ const graphRef = useRef3(null);
2518
+ const { projector, renderer } = useMemo3(() => {
2519
+ let projector2 = projectorProp;
2520
+ if (!projector2) {
2521
+ projector2 = new GraphForceProjector(context);
2522
+ }
2523
+ let renderer2 = rendererProp;
2524
+ if (!renderer2) {
2525
+ renderer2 = new GraphRenderer(context, graphRef, {
2526
+ ...props,
2527
+ // TODO(burdon): Replace drag when projector is updated.
2528
+ drag: drag2 ? createGraphDrag(context, projector2) : void 0,
2529
+ arrows: {
2530
+ end: arrows
2531
+ },
2532
+ onNodeClick: onSelect,
2533
+ onNodePointerEnter: onInspect ? (node, event) => onInspect(node, event) : void 0,
2534
+ // Pair pointerenter with leave so consumers can clear hover-driven previews.
2535
+ // The callback receives `null` on leave (event still carries the source).
2536
+ onNodePointerLeave: onInspect ? (_node, event) => onInspect(null, event) : void 0
2537
+ });
2538
+ }
2539
+ return {
2540
+ projector: projector2,
2541
+ renderer: renderer2
2542
+ };
2543
+ }, [
2544
+ context,
2545
+ projectorProp,
2546
+ rendererProp,
2547
+ drag2,
2548
+ arrows,
2549
+ onSelect,
2550
+ onInspect,
2551
+ props.labels,
2552
+ props.subgraphs,
2553
+ props.attributes,
2554
+ props.renderNode
2555
+ ]);
2556
+ useImperativeHandle(forwardedRef, () => ({
2557
+ refresh: () => {
2558
+ projector.updateData(model?.graph);
2559
+ },
2560
+ repaint: () => {
2561
+ renderer.render(projector.layout);
2562
+ },
2563
+ findNode: (id) => {
2564
+ return graphRef.current?.querySelector(`g[data-id="${id}"]`);
2565
+ }
2566
+ }), [
2567
+ model,
2568
+ projector,
2569
+ renderer
2570
+ ]);
2571
+ useEffect3(() => {
2572
+ const cleanup = combine(
2573
+ // Subscribe to model changes if reactive model.
2574
+ model ? model.subscribe(() => {
1189
2575
  projector.updateData(model?.graph);
1190
- }), projector.updated.on(({ layout }) => {
2576
+ }) : void 0,
2577
+ projector.updated.on(({ layout, kind }) => {
1191
2578
  try {
1192
- renderer.render(layout);
2579
+ if (kind === "positions") {
2580
+ renderer.applyPositions(layout);
2581
+ } else {
2582
+ renderer.render(layout);
2583
+ }
1193
2584
  } catch (error) {
2585
+ log9.catch(error, void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file11, L: 85, S: void 0 });
1194
2586
  void projector.stop();
1195
- log6.catch(error, void 0, {
1196
- F: __dxlog_file8,
1197
- L: 108,
1198
- S: void 0,
1199
- C: (f, a) => f(...a)
1200
- });
1201
2587
  }
1202
- }));
1203
- }, [
1204
- model,
1205
- projector,
1206
- renderer
1207
- ]);
1208
- useEffect(() => {
1209
- void projector.start();
1210
- return () => {
1211
- void projector.stop();
1212
- };
1213
- }, [
1214
- projector
1215
- ]);
1216
- return /* @__PURE__ */ React.createElement("g", {
1217
- ref: graphRef,
1218
- className: mx("dx-graph", classNames)
1219
- });
1220
- } finally {
1221
- _effect.f();
1222
- }
2588
+ })
2589
+ );
2590
+ projector.updateData(model?.graph);
2591
+ return cleanup;
2592
+ }, [
2593
+ model,
2594
+ projector,
2595
+ renderer
2596
+ ]);
2597
+ useEffect3(() => {
2598
+ void projector.start();
2599
+ return () => {
2600
+ void projector.stop();
2601
+ };
2602
+ }, [
2603
+ projector
2604
+ ]);
2605
+ return /* @__PURE__ */ React.createElement("g", {
2606
+ ref: graphRef,
2607
+ className: mx("dx-graph", classNames)
2608
+ });
1223
2609
  };
1224
2610
  var Graph = /* @__PURE__ */ forwardRef(GraphInner);
1225
2611
 
1226
2612
  // src/components/Mesh/Mesh.tsx
1227
- import { geoPath, select as select5 } from "d3";
1228
- import { useEffect as useEffect2 } from "react";
2613
+ import { geoPath, select as select7 } from "d3";
2614
+ import { useEffect as useEffect4 } from "react";
1229
2615
  import { feature, mesh } from "topojson-client";
1230
2616
  var Mesh = ({ radius = 16, value = 0.5 }) => {
1231
2617
  const { svg, size } = useSvgContext();
1232
- useEffect2(() => {
1233
- if (size) {
1234
- const topology = hexTopology(size, radius, value);
1235
- const projection = hexProjection(radius);
1236
- const path = geoPath().projection(projection);
1237
- 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);
1238
- select5(svg).append("path").datum(mesh(topology, topology.objects.hexagons)).attr("class", "mesh").attr("d", path);
1239
- const redraw = (border) => {
1240
- border.attr("d", path(mesh(topology, topology.objects.hexagons, (a, b) => a.properties.fill !== b.properties.fill)));
1241
- };
1242
- select5(svg).append("path").attr("class", "border").call(redraw);
2618
+ useEffect4(() => {
2619
+ if (!size) {
2620
+ return;
1243
2621
  }
2622
+ const topology = hexTopology(size, radius, value);
2623
+ const projection = hexProjection(radius);
2624
+ const path = geoPath().projection(projection);
2625
+ const root = select7(svg).selectAll("g.dx-mesh-root").data([
2626
+ null
2627
+ ]).join("g").classed("dx-mesh-root", true);
2628
+ root.selectAll("*").remove();
2629
+ 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);
2630
+ root.append("path").datum(mesh(topology, topology.objects.hexagons)).attr("class", "mesh").attr("d", path);
2631
+ const redraw = (border) => {
2632
+ border.attr("d", path(mesh(topology, topology.objects.hexagons, (a, b) => a.properties.fill !== b.properties.fill)));
2633
+ };
2634
+ root.append("path").attr("class", "border").call(redraw);
1244
2635
  }, [
1245
2636
  svg,
1246
2637
  size,
1247
- value
2638
+ value,
2639
+ radius
1248
2640
  ]);
1249
2641
  return null;
1250
2642
  };
@@ -1356,115 +2748,123 @@ var hexProjection = (radius) => {
1356
2748
  };
1357
2749
 
1358
2750
  // src/components/SVG/Grid.tsx
1359
- import { useSignals as _useSignals2 } from "@preact-signals/safe-react/tracking";
1360
2751
  import React2 from "react";
1361
- import { mx as mx2 } from "@dxos/react-ui-theme";
2752
+ import { mx as mx2 } from "@dxos/ui-theme";
1362
2753
  var Grid = ({ classNames, ...props }) => {
1363
- var _effect = _useSignals2();
1364
- try {
1365
- const { ref } = useGrid(props);
1366
- return /* @__PURE__ */ React2.createElement("g", {
1367
- ref,
1368
- className: mx2("dx-grid", classNames)
1369
- });
1370
- } finally {
1371
- _effect.f();
1372
- }
2754
+ const { ref } = useGrid(props);
2755
+ return /* @__PURE__ */ React2.createElement("g", {
2756
+ ref,
2757
+ className: mx2("dx-grid", classNames)
2758
+ });
1373
2759
  };
1374
2760
 
1375
2761
  // src/components/SVG/Markers.tsx
1376
- import { useSignals as _useSignals3 } from "@preact-signals/safe-react/tracking";
1377
- import { select as select6 } from "d3";
1378
- import React3, { useEffect as useEffect3, useRef as useRef2 } from "react";
2762
+ import { select as select8 } from "d3";
2763
+ import React3, { useEffect as useEffect5, useRef as useRef4 } from "react";
1379
2764
  var Markers = ({ arrowSize, className }) => {
1380
- var _effect = _useSignals3();
1381
- try {
1382
- const ref = useRef2();
1383
- useEffect3(() => {
1384
- select6(ref.current).call(createMarkers({
1385
- arrowSize
1386
- }));
1387
- }, [
1388
- ref
1389
- ]);
1390
- return /* @__PURE__ */ React3.createElement("defs", {
1391
- ref,
1392
- className
1393
- });
1394
- } finally {
1395
- _effect.f();
1396
- }
2765
+ const ref = useRef4(null);
2766
+ useEffect5(() => {
2767
+ select8(ref.current).call(createMarkers({
2768
+ arrowSize
2769
+ }));
2770
+ }, [
2771
+ ref
2772
+ ]);
2773
+ return /* @__PURE__ */ React3.createElement("defs", {
2774
+ ref,
2775
+ className
2776
+ });
1397
2777
  };
1398
2778
 
1399
2779
  // src/components/SVG/Root.tsx
1400
- import { useSignals as _useSignals4 } from "@preact-signals/safe-react/tracking";
1401
- import { select as select7 } from "d3";
1402
- import React4, { forwardRef as forwardRef2, useEffect as useEffect4, useMemo as useMemo2, useImperativeHandle as useImperativeHandle2 } from "react";
1403
- import { useResizeDetector } from "react-resize-detector";
1404
- import { mx as mx3 } from "@dxos/react-ui-theme";
1405
- var Root = /* @__PURE__ */ forwardRef2(({ classNames, children, ...props }, ref) => {
1406
- var _effect = _useSignals4();
1407
- try {
1408
- const { ref: containerRef, width = 0, height = 0 } = useResizeDetector({
1409
- refreshRate: 200
2780
+ import { select as select9 } from "d3";
2781
+ import React4, { forwardRef as forwardRef2, useEffect as useEffect6, useImperativeHandle as useImperativeHandle2, useMemo as useMemo4, useState } from "react";
2782
+ import { composableProps, mx as mx3 } from "@dxos/ui-theme";
2783
+ var Root = /* @__PURE__ */ forwardRef2(({ children, scale, centered, ...props }, ref) => {
2784
+ const [container, setContainer] = useState(null);
2785
+ const [size, setSize] = useState({
2786
+ width: 0,
2787
+ height: 0
2788
+ });
2789
+ useEffect6(() => {
2790
+ if (!container) {
2791
+ return;
2792
+ }
2793
+ const rect = container.getBoundingClientRect();
2794
+ setSize({
2795
+ width: rect.width,
2796
+ height: rect.height
1410
2797
  });
1411
- const context = useMemo2(() => {
1412
- return new SVGContext(props);
1413
- }, [
1414
- props.scale,
1415
- props.centered
1416
- ]);
1417
- useImperativeHandle2(ref, () => context, [
1418
- context
1419
- ]);
1420
- useEffect4(() => {
1421
- if (width && height) {
1422
- context.setSize({
1423
- width,
1424
- height
1425
- });
1426
- select7(context.svg).attr("display", "block").attr("viewBox", context.viewBox).attr("width", width).attr("height", height);
2798
+ const observer = new ResizeObserver((entries) => {
2799
+ const entry = entries[0];
2800
+ if (!entry) {
2801
+ return;
1427
2802
  }
1428
- }, [
1429
- context,
1430
- width,
1431
- height
1432
- ]);
1433
- const ready = width !== 0 && height !== 0;
1434
- return /* @__PURE__ */ React4.createElement(SVGContextProvider, {
1435
- value: context
1436
- }, /* @__PURE__ */ React4.createElement("div", {
1437
- ref: containerRef,
1438
- className: mx3("grid grow overflow-hidden", classNames)
1439
- }, /* @__PURE__ */ React4.createElement("svg", {
1440
- xmlns: "http://www.w3.org/2000/svg",
1441
- ref: context.ref,
1442
- className: mx3("transition-opacity opacity-0 duration-1000", ready && "opacity-100")
1443
- }, ready && children)));
1444
- } finally {
1445
- _effect.f();
1446
- }
2803
+ const { width: width2, height: height2 } = entry.contentRect;
2804
+ setSize((prev) => prev.width === width2 && prev.height === height2 ? prev : {
2805
+ width: width2,
2806
+ height: height2
2807
+ });
2808
+ });
2809
+ observer.observe(container);
2810
+ return () => observer.disconnect();
2811
+ }, [
2812
+ container
2813
+ ]);
2814
+ const { width, height } = size;
2815
+ const context = useMemo4(() => {
2816
+ return new SVGContext({
2817
+ scale,
2818
+ centered
2819
+ });
2820
+ }, [
2821
+ scale,
2822
+ centered
2823
+ ]);
2824
+ useImperativeHandle2(ref, () => context, [
2825
+ context
2826
+ ]);
2827
+ useEffect6(() => {
2828
+ if (width && height) {
2829
+ context.setSize({
2830
+ width,
2831
+ height
2832
+ });
2833
+ select9(context.svg).attr("display", "block").attr("viewBox", context.viewBox).attr("width", width).attr("height", height);
2834
+ }
2835
+ }, [
2836
+ context,
2837
+ width,
2838
+ height
2839
+ ]);
2840
+ const ready = width !== 0 && height !== 0;
2841
+ return /* @__PURE__ */ React4.createElement(SVGContextProvider, {
2842
+ value: context
2843
+ }, /* @__PURE__ */ React4.createElement("div", {
2844
+ ...composableProps(props, {
2845
+ classNames: "dx-expander"
2846
+ }),
2847
+ ref: setContainer
2848
+ }, /* @__PURE__ */ React4.createElement("svg", {
2849
+ xmlns: "http://www.w3.org/2000/svg",
2850
+ ref: context.ref,
2851
+ className: mx3("transition-opacity opacity-0 duration-1000", ready && "opacity-100")
2852
+ }, ready && children)));
1447
2853
  });
1448
2854
 
1449
2855
  // src/components/SVG/Zoom.tsx
1450
- import { useSignals as _useSignals5 } from "@preact-signals/safe-react/tracking";
1451
- import React5, { memo, useMemo as useMemo3 } from "react";
2856
+ import React5, { memo, useMemo as useMemo5 } from "react";
1452
2857
  var Zoom = /* @__PURE__ */ memo(({ extent, className, children }) => {
1453
- var _effect = _useSignals5();
1454
- try {
1455
- const options = useMemo3(() => ({
1456
- extent
1457
- }), [
1458
- JSON.stringify(extent)
1459
- ]);
1460
- const zoom = useZoom(options);
1461
- return /* @__PURE__ */ React5.createElement("g", {
1462
- ref: zoom.ref,
1463
- className
1464
- }, children);
1465
- } finally {
1466
- _effect.f();
1467
- }
2858
+ const options = useMemo5(() => ({
2859
+ extent
2860
+ }), [
2861
+ JSON.stringify(extent)
2862
+ ]);
2863
+ const zoom2 = useZoom(options);
2864
+ return /* @__PURE__ */ React5.createElement("g", {
2865
+ ref: zoom2.ref,
2866
+ className
2867
+ }, children);
1468
2868
  });
1469
2869
 
1470
2870
  // src/components/SVG/SVG.tsx
@@ -1478,7 +2878,7 @@ var SVG = {
1478
2878
  };
1479
2879
 
1480
2880
  // src/fx/pulsar.ts
1481
- import { easeCubicOut as easeCubicOut2, select as select8 } from "d3";
2881
+ import { easeCubicOut as easeCubicOut2, select as select10 } from "d3";
1482
2882
  var PROP_PULSAR_ACTIVE = "dx-pulsar-active";
1483
2883
  (function(Pulsar2) {
1484
2884
  Pulsar2.has = (group) => group.select("circle.dx-pulsar").empty();
@@ -1493,21 +2893,26 @@ var PROP_PULSAR_ACTIVE = "dx-pulsar-active";
1493
2893
  var startAnimation = (pulsar, r, options = {}) => {
1494
2894
  const { period = 1e3, duration = 800, ratio = 3 } = options;
1495
2895
  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() {
1496
- if (select8(this).property(PROP_PULSAR_ACTIVE)) {
1497
- startAnimation(select8(this), r, options);
2896
+ if (select10(this).property(PROP_PULSAR_ACTIVE)) {
2897
+ startAnimation(select10(this), r, options);
1498
2898
  } else {
1499
- select8(this).remove();
2899
+ select10(this).remove();
1500
2900
  }
1501
2901
  });
1502
2902
  };
1503
2903
  var Pulsar;
1504
2904
  export {
2905
+ CLUSTER_NODE_TYPE_GROUP,
2906
+ CLUSTER_NODE_TYPE_LEAF,
2907
+ CLUSTER_NODE_TYPE_ROOT,
1505
2908
  EventEmitter,
1506
2909
  FractionUtil,
1507
2910
  Graph,
2911
+ GraphBundleProjector,
2912
+ GraphClusterProjector,
1508
2913
  GraphForceProjector,
1509
2914
  GraphHierarchicalProjector,
1510
- GraphInner,
2915
+ GraphLatticeProjector,
1511
2916
  GraphProjector,
1512
2917
  GraphRadialProjector,
1513
2918
  GraphRelationalProjector,