@dxos/react-ui-graph 0.8.4-main.5ad4a44 → 0.8.4-main.60689f5b1c

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 (117) 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 +2031 -699
  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 +2031 -699
  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 +6 -6
  20. package/dist/types/src/components/Graph/Graph.stories.d.ts.map +1 -1
  21. package/dist/types/src/components/Mesh/Mesh.d.ts.map +1 -1
  22. package/dist/types/src/components/Mesh/Mesh.stories.d.ts.map +1 -1
  23. package/dist/types/src/components/SVG/Grid.d.ts.map +1 -1
  24. package/dist/types/src/components/SVG/Markers.d.ts.map +1 -1
  25. package/dist/types/src/components/SVG/Root.d.ts +8 -4
  26. package/dist/types/src/components/SVG/Root.d.ts.map +1 -1
  27. package/dist/types/src/components/SVG/SVG.d.ts +14 -17
  28. package/dist/types/src/components/SVG/SVG.d.ts.map +1 -1
  29. package/dist/types/src/components/SVG/Svg.stories.d.ts +1 -1
  30. package/dist/types/src/components/SVG/Svg.stories.d.ts.map +1 -1
  31. package/dist/types/src/fx/fx.stories.d.ts +3 -3
  32. package/dist/types/src/fx/fx.stories.d.ts.map +1 -1
  33. package/dist/types/src/fx/pulsar.d.ts.map +1 -1
  34. package/dist/types/src/graph/markers.d.ts.map +1 -1
  35. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts +47 -0
  36. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts.map +1 -0
  37. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts +60 -0
  38. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts.map +1 -0
  39. package/dist/types/src/graph/projector/graph-drag.d.ts.map +1 -1
  40. package/dist/types/src/graph/projector/graph-force-projector.d.ts +1 -1
  41. package/dist/types/src/graph/projector/graph-force-projector.d.ts.map +1 -1
  42. package/dist/types/src/graph/projector/graph-forces.d.ts.map +1 -1
  43. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts +1 -1
  44. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts.map +1 -1
  45. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts +23 -0
  46. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts.map +1 -0
  47. package/dist/types/src/graph/projector/graph-projector.d.ts +2 -2
  48. package/dist/types/src/graph/projector/graph-projector.d.ts.map +1 -1
  49. package/dist/types/src/graph/projector/graph-radial-projector.d.ts +7 -1
  50. package/dist/types/src/graph/projector/graph-radial-projector.d.ts.map +1 -1
  51. package/dist/types/src/graph/projector/graph-relational-projector.d.ts +1 -1
  52. package/dist/types/src/graph/projector/graph-relational-projector.d.ts.map +1 -1
  53. package/dist/types/src/graph/projector/index.d.ts +3 -0
  54. package/dist/types/src/graph/projector/index.d.ts.map +1 -1
  55. package/dist/types/src/graph/projector/projector.d.ts +10 -1
  56. package/dist/types/src/graph/projector/projector.d.ts.map +1 -1
  57. package/dist/types/src/graph/renderer/bullets.d.ts.map +1 -1
  58. package/dist/types/src/graph/renderer/graph-renderer.d.ts +21 -1
  59. package/dist/types/src/graph/renderer/graph-renderer.d.ts.map +1 -1
  60. package/dist/types/src/graph/renderer/renderer.d.ts +12 -1
  61. package/dist/types/src/graph/renderer/renderer.d.ts.map +1 -1
  62. package/dist/types/src/graph/types.d.ts +15 -1
  63. package/dist/types/src/graph/types.d.ts.map +1 -1
  64. package/dist/types/src/hooks/useGrid.d.ts.map +1 -1
  65. package/dist/types/src/hooks/useStateRef.d.ts.map +1 -1
  66. package/dist/types/src/hooks/useSvgContext.d.ts.map +1 -1
  67. package/dist/types/src/hooks/useZoom.d.ts.map +1 -1
  68. package/dist/types/src/stories/hooks.stories.d.ts +4 -3
  69. package/dist/types/src/stories/hooks.stories.d.ts.map +1 -1
  70. package/dist/types/src/testing/data.d.ts +5 -5
  71. package/dist/types/src/testing/data.d.ts.map +1 -1
  72. package/dist/types/src/testing/hooks.d.ts +2 -16
  73. package/dist/types/src/testing/hooks.d.ts.map +1 -1
  74. package/dist/types/src/testing/model.d.ts +4 -8
  75. package/dist/types/src/testing/model.d.ts.map +1 -1
  76. package/dist/types/src/util/events.d.ts.map +1 -1
  77. package/dist/types/src/util/fraction.d.ts +1 -1
  78. package/dist/types/src/util/fraction.d.ts.map +1 -1
  79. package/dist/types/src/util/points.d.ts.map +1 -1
  80. package/dist/types/src/util/scale.d.ts.map +1 -1
  81. package/dist/types/src/util/screen.d.ts.map +1 -1
  82. package/dist/types/src/util/vector.d.ts.map +1 -1
  83. package/dist/types/tsconfig.tsbuildinfo +1 -1
  84. package/package.json +33 -35
  85. package/src/components/Graph/Graph.stories.tsx +53 -47
  86. package/src/components/Graph/Graph.tsx +58 -23
  87. package/src/components/Mesh/Mesh.stories.tsx +8 -7
  88. package/src/components/Mesh/Mesh.tsx +43 -35
  89. package/src/components/SVG/Grid.tsx +1 -1
  90. package/src/components/SVG/Root.tsx +41 -9
  91. package/src/components/SVG/SVG.tsx +10 -2
  92. package/src/components/SVG/Svg.stories.tsx +4 -5
  93. package/src/fx/fx.stories.tsx +7 -8
  94. package/src/graph/projector/graph-bundle-projector.ts +210 -0
  95. package/src/graph/projector/graph-cluster-projector.ts +325 -0
  96. package/src/graph/projector/graph-drag.ts +0 -1
  97. package/src/graph/projector/graph-force-projector.ts +6 -3
  98. package/src/graph/projector/graph-hierarchical-projector.ts +4 -4
  99. package/src/graph/projector/graph-lattice-projector.ts +86 -0
  100. package/src/graph/projector/graph-projector.ts +9 -3
  101. package/src/graph/projector/graph-radial-projector.ts +31 -4
  102. package/src/graph/projector/graph-relational-projector.ts +4 -4
  103. package/src/graph/projector/index.ts +3 -0
  104. package/src/graph/projector/projector.ts +12 -3
  105. package/src/graph/renderer/graph-renderer.ts +175 -30
  106. package/src/graph/renderer/renderer.ts +15 -4
  107. package/src/graph/types.ts +15 -1
  108. package/src/stories/hooks.stories.tsx +21 -10
  109. package/src/testing/data.ts +14 -14
  110. package/src/testing/hooks.ts +3 -4
  111. package/src/testing/model.ts +6 -6
  112. package/src/util/fraction.ts +1 -1
  113. package/styles/graph.css +341 -43
  114. package/dist/lib/browser/chunk-EX2Q43O6.mjs +0 -966
  115. package/dist/lib/browser/chunk-EX2Q43O6.mjs.map +0 -7
  116. package/dist/lib/node-esm/chunk-SWA6OT3W.mjs +0 -968
  117. package/dist/lib/node-esm/chunk-SWA6OT3W.mjs.map +0 -7
@@ -9,12 +9,26 @@ import { log } from '@dxos/log';
9
9
 
10
10
  import { type D3Callable, type D3Selection, type Point, getCircumferencePoints } from '../../util';
11
11
  import { type GraphLayout, type GraphLayoutEdge, type GraphLayoutNode } from '../types';
12
-
13
12
  import { createBullets } from './bullets';
14
13
  import { Renderer, type RendererOptions } from './renderer';
15
14
 
15
+ /**
16
+ * Replace the default `<circle>` with a custom node shape. Invoked once per
17
+ * entering node — append your own elements to the supplied `<g>`. Position and
18
+ * `attributes.node` callbacks are still applied by the renderer.
19
+ */
20
+ export type RenderNode<NodeData = any> = (group: D3Selection<SVGGElement>, node: GraphLayoutNode<NodeData>) => void;
21
+
16
22
  const createLine = line<Point>();
17
23
 
24
+ /** Duration for edge opacity transitions on enter / exit (ms). Matches node enter/exit timing. */
25
+ const EDGE_FADE_MS = 300;
26
+
27
+ /** Duration for node hide/show opacity transitions (ms). Matches the projector's tween
28
+ * duration so a cluster collapse/expand fades opacity over the same window the position
29
+ * is tweening toward / away from the parent group. */
30
+ const NODE_HIDE_MS = 500;
31
+
18
32
  export type LabelOptions<NodeData = any> = {
19
33
  text: (node: GraphLayoutNode<NodeData>, highlight?: boolean) => string | undefined;
20
34
  };
@@ -41,17 +55,19 @@ export type GraphRendererOptions<NodeData = any, EdgeData = any> = RendererOptio
41
55
  labels?: LabelOptions<NodeData>;
42
56
  subgraphs?: boolean;
43
57
  attributes?: AttributesOptions<NodeData>;
58
+ /**
59
+ * Override the default `<circle>` node shape. When set, the renderer appends
60
+ * whatever this callback creates instead. Use for lattice rects, custom icons, etc.
61
+ */
62
+ renderNode?: RenderNode<NodeData>;
44
63
  transition?: () => any;
45
64
  onNodeClick?: (node: GraphLayoutNode<NodeData>, event: MouseEvent) => void;
46
65
  onNodePointerEnter?: (node: GraphLayoutNode<NodeData>, event: MouseEvent) => void;
66
+ /** Fires on pointerleave from a node hit-target. Pair with `onNodePointerEnter` to clear hover state. */
67
+ onNodePointerLeave?: (node: GraphLayoutNode<NodeData>, event: MouseEvent) => void;
47
68
  onLinkClick?: (link: GraphLayoutEdge<NodeData, EdgeData>, event: MouseEvent) => void;
48
69
  }>;
49
70
 
50
- // TODO(burdon): Perf
51
- // - Leaking JS event listeners.
52
- // - Don't update unless data changes.
53
- // - Cache subgraph components in layout.
54
-
55
71
  /**
56
72
  * Renders the Graph layout.
57
73
  */
@@ -59,7 +75,26 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
59
75
  GraphLayout<NodeData, EdgeData>,
60
76
  GraphRendererOptions<NodeData, EdgeData>
61
77
  > {
78
+ // First render of this instance — used to clear DOM left behind by a previous
79
+ // renderer pointing at the same `<g>` (e.g. when the consumer swaps projectors
80
+ // and a new renderer is constructed for the same SVG root). Without this, the
81
+ // previous variant's node shapes (e.g. circles) would persist as d3.join sees
82
+ // them in the `update` set instead of `enter`.
83
+ #firstRender = true;
84
+
62
85
  override render(layout: GraphLayout<NodeData, EdgeData>) {
86
+ // The SVG group ref is unset between mount cycles and before the container has sized;
87
+ // skip the render rather than throw — the projector will emit again on the next tick.
88
+ if (!this.root) {
89
+ return;
90
+ }
91
+
92
+ if (this.#firstRender) {
93
+ this.#firstRender = false;
94
+ // Drop any DOM left by a prior renderer so this render's `renderNode` runs from scratch.
95
+ this.root.replaceChildren();
96
+ }
97
+
63
98
  log('render', layout);
64
99
 
65
100
  const root = select(this.root);
@@ -166,10 +201,13 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
166
201
  enter
167
202
  .append('g')
168
203
  .attr('data-id', (d) => d.id)
169
- .attr('opacity', 1)
204
+ // Initial opacity matches `hidden` so a node that enters already-collapsed is
205
+ // invisible from the first frame; updateNode's named 'hide' transition then
206
+ // handles any subsequent toggles.
207
+ .attr('opacity', (d) => (d.hidden ? 0 : 1))
170
208
  .classed('dx-node', true)
171
209
  .call(createNode, this.options),
172
- (update) => update.call(updateNode, this.options),
210
+ (update) => update,
173
211
  (exit) => {
174
212
  // Fade out.
175
213
  return exit
@@ -182,6 +220,9 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
182
220
  });
183
221
  },
184
222
  )
223
+ // Apply update (transform / attributes / labels) to enter+update so the first render
224
+ // also populates `data-*` attributes and transforms — not just subsequent ticks.
225
+ .call(updateNode, this.options)
185
226
  .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
186
227
 
187
228
  //
@@ -198,17 +239,69 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
198
239
  .attr('data-id', (d) => d.id)
199
240
  .classed('dx-edge', true)
200
241
  .call(createEdge, this.options),
201
- (update) => update.call(updateEdge, this.options, nodeGroup).each((d) => {}),
202
- (exit) => exit.remove(),
242
+ (update) => update,
243
+ // Exit fade: edges removed by a topology change (e.g. variant switch from cluster
244
+ // back to force replaces hierarchy edges with data edges) ease out rather than pop.
245
+ (exit) =>
246
+ exit
247
+ .transition()
248
+ .ease(easeCubicOut)
249
+ .duration(EDGE_FADE_MS)
250
+ .attr('opacity', 0)
251
+ .on('end', function () {
252
+ select(this).remove();
253
+ }),
203
254
  )
255
+ // Apply edge updates (paths / attributes) to enter+update — see note on nodes above.
256
+ .call(updateEdge, this.options, nodeGroup)
204
257
  .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
205
258
  }
206
259
 
260
+ /**
261
+ * Fast positions-only update. Skips enter/exit, attribute callbacks, label sizing,
262
+ * and the subgraph hull pass; just writes `transform` per node and `d` per edge.
263
+ * Called per simulation tick / animation frame.
264
+ */
265
+ override applyPositions(layout: GraphLayout<NodeData, EdgeData>) {
266
+ if (!this.root) {
267
+ return;
268
+ }
269
+
270
+ const root = select(this.root);
271
+
272
+ // Transforms only — no attribute callback, no label measurement.
273
+ root
274
+ .select('g.dx-nodes')
275
+ .selectAll<SVGGElement, GraphLayoutNode<NodeData>>('g.dx-node')
276
+ .attr('transform', (d) => (d.x != null && d.y != null ? `translate(${d.x},${d.y})` : null));
277
+
278
+ // Edge geometry — either precomputed (`edge.path`) or derived from endpoint positions.
279
+ root
280
+ .select('g.dx-edges')
281
+ .selectAll<SVGGElement, GraphLayoutEdge<NodeData, EdgeData>>('g.dx-edge')
282
+ .selectAll<SVGPathElement, GraphLayoutEdge<NodeData, EdgeData>>('path')
283
+ .attr('d', function () {
284
+ // NOTE: `d` is stale after layout is switched so get the datum from the parent element.
285
+ const edge = select(this.parentElement).datum() as GraphLayoutEdge<NodeData, EdgeData>;
286
+ if (edge.path) {
287
+ return edge.path;
288
+ }
289
+ const { source, target } = edge;
290
+ if (!source.initialized || !target.initialized) {
291
+ return null;
292
+ }
293
+ return createLine(getCircumferencePoints([source.x, source.y], [target.x, target.y], source.r, target.r));
294
+ });
295
+ }
296
+
207
297
  /**
208
298
  * Trigger path bullets.
209
299
  * @param node
210
300
  */
211
301
  fireBullet(node: GraphLayoutNode<NodeData>) {
302
+ if (!this.root) {
303
+ return;
304
+ }
212
305
  select(this.root).selectAll('g.dx-edges').selectAll('path').call(createBullets(this.root, node.id));
213
306
  }
214
307
  }
@@ -218,21 +311,45 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
218
311
  * @param group
219
312
  * @param options
220
313
  */
314
+ const SHAPE_CLASS = 'dx-shape';
315
+
316
+ const renderCustomShape = <Data>(group: D3Selection, options: GraphRendererOptions<Data>) => {
317
+ group.each(function (d) {
318
+ const g = select<SVGGElement, GraphLayoutNode<Data>>(this);
319
+ // Clear any previous custom shape so subsequent renders pick up updated
320
+ // node.r / node.data without leaving stale elements behind.
321
+ g.selectAll(`.${SHAPE_CLASS}`).remove();
322
+ // Wrap the consumer's drawing in a `<g class="dx-shape">` so we have a
323
+ // stable selector for the cleanup above.
324
+ const shapeGroup = g.append('g').classed(SHAPE_CLASS, true);
325
+ options.renderNode!(shapeGroup, d);
326
+ });
327
+ };
328
+
221
329
  const createNode: D3Callable = <Data>(group: D3Selection, options: GraphRendererOptions<Data>) => {
222
- // Circle.
223
- const circle = group.append('circle');
330
+ // Custom node shape: consumer appends its own elements (e.g. <rect>) and the
331
+ // renderer skips the default <circle>. Drag/hover handlers attach to the
332
+ // wrapping <g> so the custom shape acts as the hit target.
333
+ const useCustom = !!options.renderNode;
334
+ if (useCustom) {
335
+ renderCustomShape(group, options);
336
+ }
337
+ const hitTarget = useCustom ? group : group.append('circle');
224
338
 
225
339
  // Drag.
226
340
  // TODO(burdon): Update when layout changes.
227
341
  if (options.drag) {
228
- circle.call(options.drag);
342
+ hitTarget.call(options.drag);
229
343
  }
230
344
 
231
- // Click.
345
+ // Click. d3 invokes `on` listeners as `(event, datum)` where datum is the bound data on
346
+ // the listener's host element (the dx-node `<g>`). Use it directly — reading from
347
+ // `event.target` returned undefined for the inner circle / text (which don't inherit
348
+ // __data__), and `this` plus `select(this).datum()` was producing inconsistent results
349
+ // across HMR reloads.
232
350
  if (options.onNodeClick) {
233
- group.on('click', (event: MouseEvent) => {
234
- const node = select<SVGElement, GraphLayoutNode<Data>>(event.target as SVGGElement).datum();
235
- options.onNodeClick(node, event);
351
+ group.on('click', (event: MouseEvent, d: GraphLayoutNode<Data>) => {
352
+ options.onNodeClick(d, event);
236
353
  });
237
354
  }
238
355
 
@@ -245,26 +362,30 @@ const createNode: D3Callable = <Data>(group: D3Selection, options: GraphRenderer
245
362
  }
246
363
 
247
364
  // Hover.
248
- if (options.onNodePointerEnter) {
249
- circle.on('pointerenter', function (event: PointerEvent) {
250
- const node = select<any, GraphLayoutNode<Data>>(this.parentElement).datum();
251
- options.onNodePointerEnter(node, event);
365
+ if (options.onNodePointerEnter || options.onNodePointerLeave) {
366
+ hitTarget.on('pointerenter', function (event: PointerEvent) {
367
+ const node = select<any, GraphLayoutNode<Data>>(useCustom ? this : this.parentElement).datum();
368
+ options.onNodePointerEnter?.(node, event);
369
+ });
370
+ hitTarget.on('pointerleave', function (event: PointerEvent) {
371
+ const node = select<any, GraphLayoutNode<Data>>(useCustom ? this : this.parentElement).datum();
372
+ options.onNodePointerLeave?.(node, event);
252
373
  });
253
374
 
254
- group.attr('data-hover', 'handled'); // TODO(burdon): ???
255
- } else if (options.highlight !== false) {
256
- circle.on('pointerenter', function () {
375
+ group.attr('data-hover', 'handled');
376
+ } else if (options.highlight !== false && !useCustom) {
377
+ hitTarget.on('pointerenter', function () {
257
378
  select(this.closest('g.dx-node')).raise();
258
379
  if (options.labels) {
259
- select(this.parentElement).classed('dx-active', true).classed('dx-highlight', true);
380
+ select(this.parentElement).classed('dx-node-active', true).classed('dx-highlight', true);
260
381
  }
261
382
  });
262
383
 
263
384
  group.on('pointerleave', function () {
264
385
  if (options.labels) {
265
- select(this).classed('dx-active', false);
386
+ select(this).classed('dx-node-active', false);
266
387
  setTimeout(() => {
267
- if (!select(this).classed('dx-active')) {
388
+ if (!select(this).classed('dx-node-active')) {
268
389
  select(this).classed('dx-highlight', false);
269
390
  }
270
391
  }, 300);
@@ -286,6 +407,24 @@ const updateNode: D3Callable = <NodeData = any, EdgeData = any>(
286
407
  return d.x != null && d.y != null ? `translate(${d.x},${d.y})` : undefined;
287
408
  });
288
409
 
410
+ // Hidden state: drive pointer-events + the hover opacity via the `dx-hidden` class;
411
+ // tween the actual opacity attribute on a named transition so it doesn't fight the
412
+ // CSS hover transition (different namespaces, different durations).
413
+ group.classed('dx-hidden', (d) => d.hidden ?? false);
414
+ group
415
+ .transition('hide')
416
+ .ease(easeCubicOut)
417
+ .duration(NODE_HIDE_MS)
418
+ .attr('opacity', (d) => (d.hidden ? 0 : 1));
419
+
420
+ // Re-run the custom shape on every full render so a topology / data update
421
+ // refreshes geometry (e.g. lattice node.r changes on resize, fill changes on
422
+ // typename change). The cheap fast path (`applyPositions`) doesn't touch
423
+ // shapes, so this only runs on the rarer topology-emit code path.
424
+ if (options.renderNode) {
425
+ renderCustomShape(group, options);
426
+ }
427
+
289
428
  // Custom attributes.
290
429
  if (options.attributes?.node) {
291
430
  try {
@@ -311,8 +450,10 @@ const updateNode: D3Callable = <NodeData = any, EdgeData = any>(
311
450
  ? (group.transition(options.transition()) as unknown as D3Selection)
312
451
  : group;
313
452
 
314
- // Update circles.
315
- groupOrTransition.select<SVGCircleElement>('circle').attr('r', (d) => d.r ?? 16);
453
+ // Update circles. Skipped when the consumer supplied a custom node shape.
454
+ if (!options.renderNode) {
455
+ groupOrTransition.select<SVGCircleElement>('circle').attr('r', (d) => d.r ?? 16);
456
+ }
316
457
 
317
458
  // Update labels.
318
459
  if (options.labels) {
@@ -424,7 +565,11 @@ const updateEdge: D3Callable = <NodeData = any, EdgeData = any>(
424
565
 
425
566
  groupOrTransition.selectAll<SVGPathElement, GraphLayoutEdge<NodeData, EdgeData>>('path').attr('d', function () {
426
567
  // NOTE: `d` is stale after layout is switched so get the datum from the parent element.
427
- const { source, target } = select(this.parentElement).datum() as GraphLayoutEdge<NodeData, EdgeData>;
568
+ const edge = select(this.parentElement).datum() as GraphLayoutEdge<NodeData, EdgeData>;
569
+ if (edge.path) {
570
+ return edge.path;
571
+ }
572
+ const { source, target } = edge;
428
573
  if (!source.initialized || !target.initialized) {
429
574
  return;
430
575
  }
@@ -4,8 +4,6 @@
4
4
 
5
5
  import { type RefObject } from 'react';
6
6
 
7
- import { invariant } from '@dxos/invariant';
8
-
9
7
  import { type SVGContext } from '../../hooks';
10
8
  import { type IdAccessor, defaultIdAccessor } from '../types';
11
9
 
@@ -36,8 +34,12 @@ export abstract class Renderer<LAYOUT, OPTIONS extends RendererOptions> {
36
34
  return this._context;
37
35
  }
38
36
 
39
- get root(): SVGGElement {
40
- invariant(this._root.current, 'SVG root is not initialized');
37
+ /**
38
+ * Returns the SVG group root if mounted.
39
+ * The ref may be null between mount/unmount cycles or before the SVG container has sized.
40
+ * Callers should treat null as "skip this render" rather than as an error.
41
+ */
42
+ get root(): SVGGElement | null {
41
43
  return this._root.current;
42
44
  }
43
45
 
@@ -46,4 +48,13 @@ export abstract class Renderer<LAYOUT, OPTIONS extends RendererOptions> {
46
48
  }
47
49
 
48
50
  abstract render(layout: LAYOUT): void;
51
+
52
+ /**
53
+ * Fast path invoked when only positions changed.
54
+ * Default falls back to a full `render`; subclasses can override to skip
55
+ * enter/exit joins and attribute callbacks for per-tick updates.
56
+ */
57
+ applyPositions(layout: LAYOUT): void {
58
+ this.render(layout);
59
+ }
49
60
  }
@@ -19,7 +19,7 @@ export const defaultIdAccessor: IdAccessor = (node: any) => {
19
19
  return node.id;
20
20
  };
21
21
 
22
- export const emptyGraph: Graph = {
22
+ export const emptyGraph: Graph.Any = {
23
23
  nodes: [],
24
24
  edges: [],
25
25
  };
@@ -45,6 +45,14 @@ export type GraphLayoutNode<NodeData = any> = {
45
45
  type?: string;
46
46
  order?: number;
47
47
  data?: NodeData;
48
+ /** Human-readable label. Synthetic nodes (e.g. cluster root / group) carry this so
49
+ * consumer renderNode callbacks can label them without parsing internal id formats. */
50
+ label?: string;
51
+ /** When true the node remains in the layout but is rendered with opacity 0 and no
52
+ * pointer events — used by the cluster's collapse animation so hidden leaves can
53
+ * tween to their parent's position rather than popping out, and tween back when the
54
+ * parent is re-expanded. */
55
+ hidden?: boolean;
48
56
  x?: number;
49
57
  y?: number;
50
58
  r?: number;
@@ -65,6 +73,12 @@ export type GraphLayoutEdge<NodeData = any, EdgeData = any> = {
65
73
  target: GraphLayoutNode<NodeData>;
66
74
  data?: EdgeData;
67
75
  linkForce?: boolean;
76
+ /**
77
+ * Precomputed SVG `d` attribute. When set, the renderer uses this instead of
78
+ * deriving a straight-line path from `source/target` positions. Lets projectors
79
+ * own edge geometry (e.g. radial elbows, bundled curves) without renderer changes.
80
+ */
81
+ path?: string;
68
82
  classes?: {
69
83
  path?: string;
70
84
  };
@@ -2,13 +2,18 @@
2
2
  // Copyright 2020 DXOS.org
3
3
  //
4
4
 
5
+ import '../../styles/graph.css';
6
+
7
+ import { RegistryContext } from '@effect-atom/atom-react';
5
8
  import { type Meta, type StoryObj } from '@storybook/react-vite';
6
9
  import { select } from 'd3';
7
- import React, { type PropsWithChildren, useEffect, useMemo, useRef } from 'react';
10
+ import React, { type PropsWithChildren, useContext, useEffect, useMemo, useRef } from 'react';
8
11
 
9
12
  import { combine } from '@dxos/async';
13
+ import { type Graph } from '@dxos/graph';
10
14
  import { log } from '@dxos/log';
11
- import { withTheme } from '@dxos/react-ui/testing';
15
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
16
+ import { withRegistry } from '@dxos/storybook-utils';
12
17
 
13
18
  import { SVG } from '../components';
14
19
  import {
@@ -24,10 +29,8 @@ import {
24
29
  import { useGrid, useSvgContext, useZoom } from '../hooks';
25
30
  import { TestGraphModel, type TestNode, convertTreeToGraph, createTree } from '../testing';
26
31
 
27
- import '../../styles/graph.css';
28
-
29
32
  type ComponentProps = PropsWithChildren<{
30
- model: TestGraphModel;
33
+ graph: () => Graph.Graph<TestNode, Graph.Edge.Any>;
31
34
  projectorOptions?: GraphForceProjectorOptions;
32
35
  count?: number;
33
36
  interval?: number;
@@ -36,13 +39,16 @@ type ComponentProps = PropsWithChildren<{
36
39
  }>;
37
40
 
38
41
  const Component = ({
39
- model,
42
+ graph: graphFactory,
40
43
  projectorOptions,
41
44
  count = 0,
42
45
  interval = 200,
43
46
  link = false,
44
47
  grid: showGrid = false,
45
48
  }: ComponentProps) => {
49
+ const registry = useContext(RegistryContext);
50
+ const model = useMemo(() => new TestGraphModel(registry, graphFactory()), [registry, graphFactory]);
51
+
46
52
  const context = useSvgContext();
47
53
  const graphRef = useRef<SVGGElement>(null);
48
54
  const markersRef = useRef<SVGGElement>(null);
@@ -103,9 +109,14 @@ const Component = ({
103
109
  }, [markersRef]);
104
110
 
105
111
  useEffect(() => {
112
+ // Prime the projector with the initial graph — `model.subscribe` only fires on changes by default,
113
+ // so without this the simulation starts empty and the renderer never sees any nodes.
114
+ // The subscribe callback receives `(model, graph)` from GraphModel; use the model reference
115
+ // we already have to fetch the current snapshot.
116
+ projector.updateData(model.graph);
106
117
  void projector.start();
107
118
  return combine(
108
- model.subscribe((graph) => projector.updateData(graph)),
119
+ model.subscribe(() => projector.updateData(model.graph)),
109
120
  projector.updated.on(({ layout }) => renderer.render(layout)),
110
121
  () => projector.stop(),
111
122
  );
@@ -152,7 +163,7 @@ const DefaultStory = ({ children, ...props }: ComponentProps) => {
152
163
  const meta = {
153
164
  title: 'ui/react-ui-graph/hooks',
154
165
  render: DefaultStory,
155
- decorators: [withTheme],
166
+ decorators: [withRegistry, withTheme(), withLayout({ layout: 'fullscreen' })],
156
167
  parameters: {
157
168
  layout: 'fullscreen',
158
169
  },
@@ -164,7 +175,7 @@ type Story = StoryObj<typeof meta>;
164
175
 
165
176
  export const Default: Story = {
166
177
  args: {
167
- model: new TestGraphModel(convertTreeToGraph(createTree({ depth: 3 }))),
178
+ graph: () => convertTreeToGraph(createTree({ depth: 3 })),
168
179
  grid: true,
169
180
  count: 300,
170
181
  interval: 20,
@@ -189,7 +200,7 @@ export const Default: Story = {
189
200
 
190
201
  export const Bullets: Story = {
191
202
  args: {
192
- model: new TestGraphModel(convertTreeToGraph(createTree({ depth: 4 }))),
203
+ graph: () => convertTreeToGraph(createTree({ depth: 4 })),
193
204
  children: <span>⌘-DRAG to edge or create node; ⌘-CLICK to delete edge.</span>,
194
205
  link: true,
195
206
  grid: false,
@@ -2,28 +2,28 @@
2
2
  // Copyright 2020 DXOS.org
3
3
  //
4
4
 
5
- import { type BaseGraphEdge, type Graph } from '@dxos/graph';
6
- import { faker } from '@dxos/random';
5
+ import { type Graph } from '@dxos/graph';
6
+ import { random } from '@dxos/random';
7
7
 
8
8
  import { type TestNode } from './model';
9
9
 
10
- // https://www.npmjs.com/package/faker#setting-a-randomness-seed
11
- export const seed = (seed: number) => faker.seed(seed);
10
+ // https://www.npmjs.com/package/random#setting-a-randomness-seed
11
+ export const seed = (seed: number) => random.seed(seed);
12
12
 
13
13
  //
14
14
  // Create data.
15
15
  //
16
16
 
17
17
  export const createNode = (type: string = undefined): TestNode => ({
18
- id: faker.string.uuid(),
18
+ id: random.string.uuid(),
19
19
  type,
20
- label: faker.lorem.words(3).replace(/ /g, '-'),
20
+ label: random.lorem.words(3).replace(/ /g, '-'),
21
21
  });
22
22
 
23
23
  export const createNodes = (n = 0, types?: string[]): TestNode[] =>
24
- Array.from({ length: n }, () => createNode(types ? faker.helpers.arrayElement(types) : undefined));
24
+ Array.from({ length: n }, () => createNode(types ? random.helpers.arrayElement(types) : undefined));
25
25
 
26
- export const createEdge = (source: TestNode, target: TestNode): BaseGraphEdge => ({
26
+ export const createEdge = (source: TestNode, target: TestNode): Graph.Edge.Any => ({
27
27
  id: `${source.id}-${target.id}`,
28
28
  source: source.id,
29
29
  target: target.id,
@@ -38,7 +38,7 @@ export const createTree = ({ depth = 2, children = 3 } = {}): TestNode => {
38
38
  const createChildren = (root: TestNode, d = 0) => {
39
39
  if (d < depth) {
40
40
  const max = Math.round(Math.log(depth + 1 - d) * children);
41
- const num = faker.number.int({ min: 1, max });
41
+ const num = random.number.int({ min: 1, max });
42
42
  root.children = [...new Array(num)].map(() => {
43
43
  return createChildren(createNode(), d + 1);
44
44
  });
@@ -54,8 +54,8 @@ export const createTree = ({ depth = 2, children = 3 } = {}): TestNode => {
54
54
  * Converts a tree into a graph.
55
55
  * @param root
56
56
  */
57
- export const convertTreeToGraph = (root: TestNode): Graph => {
58
- const traverse = (node: TestNode, graph: Graph) => {
57
+ export const convertTreeToGraph = (root: TestNode): Graph.Any => {
58
+ const traverse = (node: TestNode, graph: Graph.Any) => {
59
59
  graph.nodes.push(node);
60
60
  node.children?.forEach((child) => {
61
61
  graph.edges.push(createEdge(node, child));
@@ -76,14 +76,14 @@ export const convertTreeToGraph = (root: TestNode): Graph => {
76
76
  * @param numNodes
77
77
  * @param numEdges
78
78
  */
79
- export const createGraph = (numNodes = 0, numEdges = 0, types?: string[]): Graph => {
79
+ export const createGraph = (numNodes = 0, numEdges = 0, types?: string[]): Graph.Any => {
80
80
  const nodes = createNodes(numNodes, types);
81
81
 
82
82
  const edges = new Map();
83
83
  if (numEdges && nodes.length >= 2) {
84
84
  for (let i = 0; i < numEdges; i++) {
85
- const source = faker.helpers.arrayElement(nodes);
86
- const target = faker.helpers.arrayElement(nodes);
85
+ const source = random.helpers.arrayElement(nodes);
86
+ const target = random.helpers.arrayElement(nodes);
87
87
  if (source.id !== target.id) {
88
88
  const edge = createEdge(source, target);
89
89
  if (!edges.get(edge.id)) {
@@ -5,10 +5,9 @@
5
5
  import update from 'immutability-helper';
6
6
 
7
7
  import { type Graph } from '@dxos/graph';
8
- import { faker } from '@dxos/random';
8
+ import { random } from '@dxos/random';
9
9
 
10
10
  import { useStateRef } from '../hooks';
11
-
12
11
  import { createEdge, createNode } from './data';
13
12
  import { type TestNode } from './model';
14
13
 
@@ -47,13 +46,13 @@ export const useObjectMutator = <T>(initalValue: T): ObjectMutator<T> => {
47
46
  /**
48
47
  * Test data set generator and mutator.
49
48
  */
50
- export const useGraphGenerator = (options: { data?: Graph } = {}) => {
49
+ export const useGraphGenerator = (options: { data?: Graph.Any } = {}) => {
51
50
  const [data, setData, updateData] = useObjectMutator(options.data || { nodes: [], edges: [] });
52
51
 
53
52
  let interval;
54
53
 
55
54
  const mutator = () => {
56
- const parent = data.nodes.length ? faker.helpers.arrayElement(data.nodes) : undefined;
55
+ const parent = data.nodes.length ? random.helpers.arrayElement(data.nodes) : undefined;
57
56
  const node = createNode();
58
57
 
59
58
  updateData({
@@ -2,25 +2,25 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
- import { type BaseGraphNode, ReactiveGraphModel } from '@dxos/graph';
6
- import { faker } from '@dxos/random';
5
+ import { type Graph, GraphModel } from '@dxos/graph';
6
+ import { random } from '@dxos/random';
7
7
 
8
8
  import { createEdge, createNode } from './data';
9
9
 
10
- export type TestNode = BaseGraphNode & {
10
+ export type TestNode = Graph.Node.Any & {
11
11
  label?: string;
12
12
  children?: TestNode[];
13
13
  };
14
14
 
15
- export class TestGraphModel extends ReactiveGraphModel<TestNode> {
15
+ export class TestGraphModel extends GraphModel.ReactiveGraphModel<TestNode> {
16
16
  getRandomNode() {
17
- return faker.helpers.arrayElement(this._graph.nodes);
17
+ return random.helpers.arrayElement(this._graph.nodes);
18
18
  }
19
19
 
20
20
  createNodes(node: TestNode = undefined, n = 1): void {
21
21
  Array.from({ length: n }).forEach(() => {
22
22
  const child = this.addNode(createNode());
23
- const parent = node || faker.helpers.arrayElement(this._graph.nodes);
23
+ const parent = node || random.helpers.arrayElement(this._graph.nodes);
24
24
  if (parent) {
25
25
  this.addEdge(createEdge(parent, child));
26
26
  }
@@ -30,7 +30,7 @@ export class FractionUtil {
30
30
 
31
31
  /**
32
32
  * @param {Fraction}
33
- * Convert to rounded number.
33
+ * Convert to rounded-sm number.
34
34
  */
35
35
  static toNumber = ([n, d]: Fraction): number => {
36
36
  FractionUtil.validate([n, d]);