@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
@@ -2,10 +2,13 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
+ export * from './graph-bundle-projector';
6
+ export * from './graph-cluster-projector';
5
7
  export * from './graph-drag';
6
8
  export * from './graph-projector';
7
9
  export * from './graph-force-projector';
8
10
  export * from './graph-hierarchical-projector';
11
+ export * from './graph-lattice-projector';
9
12
  export * from './graph-relational-projector';
10
13
  export * from './graph-radial-projector';
11
14
  export * from './projector';
@@ -4,17 +4,26 @@
4
4
 
5
5
  import { type SVGContext } from '../../hooks';
6
6
  import { EventEmitter } from '../../util';
7
- import { defaultIdAccessor, type IdAccessor } from '../types';
7
+ import { type IdAccessor, defaultIdAccessor } from '../types';
8
8
 
9
9
  export type ProjectorOptions = {
10
10
  idAccessor?: IdAccessor;
11
11
  };
12
12
 
13
+ /**
14
+ * Update kinds signal what changed since the previous render.
15
+ * - `topology`: nodes/edges added or removed, or per-node attributes may have changed.
16
+ * The renderer should perform a full enter/exit join and re-run attribute callbacks.
17
+ * - `positions`: only `x/y` (and similar transient layout state) changed.
18
+ * The renderer can fast-path: just update transforms and edge geometry.
19
+ */
20
+ export type ProjectorUpdateKind = 'topology' | 'positions';
21
+
13
22
  /**
14
23
  * Generates a layout to be rendered.
15
24
  */
16
25
  export abstract class Projector<NodeData, Layout, Options extends ProjectorOptions> {
17
- public readonly updated = new EventEmitter<{ layout: Layout }>();
26
+ public readonly updated = new EventEmitter<{ layout: Layout; kind: ProjectorUpdateKind }>();
18
27
 
19
28
  private readonly _options: Options;
20
29
 
@@ -48,8 +57,8 @@ export abstract class Projector<NodeData, Layout, Options extends ProjectorOptio
48
57
  this.onUpdate(data);
49
58
  }
50
59
 
51
- emitUpdate() {
52
- this.updated.emit({ layout: this.layout });
60
+ emitUpdate(kind: ProjectorUpdateKind = 'topology') {
61
+ this.updated.emit({ layout: this.layout, kind });
53
62
  }
54
63
 
55
64
  async clear() {
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { easeLinear, interpolate, select } from 'd3';
6
6
 
7
- import { type D3Selection, type D3Callable } from '../../util';
7
+ import { type D3Callable, type D3Selection } from '../../util';
8
8
 
9
9
  export type BulletOptions = {
10
10
  max?: number;
@@ -2,18 +2,33 @@
2
2
  // Copyright 2021 DXOS.org
3
3
  //
4
4
 
5
- import { line, select, polygonHull, easeCubicOut } from 'd3';
5
+ import { easeCubicOut, line, polygonHull, select } from 'd3';
6
6
  import * as Clipper from 'js-clipper';
7
7
 
8
8
  import { log } from '@dxos/log';
9
9
 
10
+ import { type D3Callable, type D3Selection, type Point, getCircumferencePoints } from '../../util';
11
+ import { type GraphLayout, type GraphLayoutEdge, type GraphLayoutNode } from '../types';
10
12
  import { createBullets } from './bullets';
11
13
  import { Renderer, type RendererOptions } from './renderer';
12
- import { getCircumferencePoints, type D3Selection, type D3Callable, type Point } from '../../util';
13
- import { type GraphLayout, type GraphLayoutEdge, type GraphLayoutNode } from '../types';
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;
14
21
 
15
22
  const createLine = line<Point>();
16
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
+
17
32
  export type LabelOptions<NodeData = any> = {
18
33
  text: (node: GraphLayoutNode<NodeData>, highlight?: boolean) => string | undefined;
19
34
  };
@@ -40,17 +55,19 @@ export type GraphRendererOptions<NodeData = any, EdgeData = any> = RendererOptio
40
55
  labels?: LabelOptions<NodeData>;
41
56
  subgraphs?: boolean;
42
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>;
43
63
  transition?: () => any;
44
64
  onNodeClick?: (node: GraphLayoutNode<NodeData>, event: MouseEvent) => void;
45
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;
46
68
  onLinkClick?: (link: GraphLayoutEdge<NodeData, EdgeData>, event: MouseEvent) => void;
47
69
  }>;
48
70
 
49
- // TODO(burdon): Perf
50
- // - Leaking JS event listeners.
51
- // - Don't update unless data changes.
52
- // - Cache subgraph components in layout.
53
-
54
71
  /**
55
72
  * Renders the Graph layout.
56
73
  */
@@ -58,7 +75,26 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
58
75
  GraphLayout<NodeData, EdgeData>,
59
76
  GraphRendererOptions<NodeData, EdgeData>
60
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
+
61
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
+
62
98
  log('render', layout);
63
99
 
64
100
  const root = select(this.root);
@@ -165,10 +201,13 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
165
201
  enter
166
202
  .append('g')
167
203
  .attr('data-id', (d) => d.id)
168
- .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))
169
208
  .classed('dx-node', true)
170
209
  .call(createNode, this.options),
171
- (update) => update.call(updateNode, this.options),
210
+ (update) => update,
172
211
  (exit) => {
173
212
  // Fade out.
174
213
  return exit
@@ -181,6 +220,9 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
181
220
  });
182
221
  },
183
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)
184
226
  .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
185
227
 
186
228
  //
@@ -197,17 +239,69 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
197
239
  .attr('data-id', (d) => d.id)
198
240
  .classed('dx-edge', true)
199
241
  .call(createEdge, this.options),
200
- (update) => update.call(updateEdge, this.options, nodeGroup).each((d) => {}),
201
- (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
+ }),
202
254
  )
255
+ // Apply edge updates (paths / attributes) to enter+update — see note on nodes above.
256
+ .call(updateEdge, this.options, nodeGroup)
203
257
  .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
204
258
  }
205
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
+
206
297
  /**
207
298
  * Trigger path bullets.
208
299
  * @param node
209
300
  */
210
301
  fireBullet(node: GraphLayoutNode<NodeData>) {
302
+ if (!this.root) {
303
+ return;
304
+ }
211
305
  select(this.root).selectAll('g.dx-edges').selectAll('path').call(createBullets(this.root, node.id));
212
306
  }
213
307
  }
@@ -217,21 +311,45 @@ export class GraphRenderer<NodeData = any, EdgeData = any> extends Renderer<
217
311
  * @param group
218
312
  * @param options
219
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
+
220
329
  const createNode: D3Callable = <Data>(group: D3Selection, options: GraphRendererOptions<Data>) => {
221
- // Circle.
222
- 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');
223
338
 
224
339
  // Drag.
225
340
  // TODO(burdon): Update when layout changes.
226
341
  if (options.drag) {
227
- circle.call(options.drag);
342
+ hitTarget.call(options.drag);
228
343
  }
229
344
 
230
- // 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.
231
350
  if (options.onNodeClick) {
232
- group.on('click', (event: MouseEvent) => {
233
- const node = select<SVGElement, GraphLayoutNode<Data>>(event.target as SVGGElement).datum();
234
- options.onNodeClick(node, event);
351
+ group.on('click', (event: MouseEvent, d: GraphLayoutNode<Data>) => {
352
+ options.onNodeClick(d, event);
235
353
  });
236
354
  }
237
355
 
@@ -244,26 +362,30 @@ const createNode: D3Callable = <Data>(group: D3Selection, options: GraphRenderer
244
362
  }
245
363
 
246
364
  // Hover.
247
- if (options.onNodePointerEnter) {
248
- circle.on('pointerenter', function (event: PointerEvent) {
249
- const node = select<any, GraphLayoutNode<Data>>(this.parentElement).datum();
250
- 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);
251
373
  });
252
374
 
253
- group.attr('data-hover', 'handled'); // TODO(burdon): ???
254
- } else if (options.highlight !== false) {
255
- circle.on('pointerenter', function () {
375
+ group.attr('data-hover', 'handled');
376
+ } else if (options.highlight !== false && !useCustom) {
377
+ hitTarget.on('pointerenter', function () {
256
378
  select(this.closest('g.dx-node')).raise();
257
379
  if (options.labels) {
258
- select(this.parentElement).classed('dx-active', true).classed('dx-highlight', true);
380
+ select(this.parentElement).classed('dx-node-active', true).classed('dx-highlight', true);
259
381
  }
260
382
  });
261
383
 
262
384
  group.on('pointerleave', function () {
263
385
  if (options.labels) {
264
- select(this).classed('dx-active', false);
386
+ select(this).classed('dx-node-active', false);
265
387
  setTimeout(() => {
266
- if (!select(this).classed('dx-active')) {
388
+ if (!select(this).classed('dx-node-active')) {
267
389
  select(this).classed('dx-highlight', false);
268
390
  }
269
391
  }, 300);
@@ -285,6 +407,24 @@ const updateNode: D3Callable = <NodeData = any, EdgeData = any>(
285
407
  return d.x != null && d.y != null ? `translate(${d.x},${d.y})` : undefined;
286
408
  });
287
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
+
288
428
  // Custom attributes.
289
429
  if (options.attributes?.node) {
290
430
  try {
@@ -310,8 +450,10 @@ const updateNode: D3Callable = <NodeData = any, EdgeData = any>(
310
450
  ? (group.transition(options.transition()) as unknown as D3Selection)
311
451
  : group;
312
452
 
313
- // Update circles.
314
- 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
+ }
315
457
 
316
458
  // Update labels.
317
459
  if (options.labels) {
@@ -423,7 +565,11 @@ const updateEdge: D3Callable = <NodeData = any, EdgeData = any>(
423
565
 
424
566
  groupOrTransition.selectAll<SVGPathElement, GraphLayoutEdge<NodeData, EdgeData>>('path').attr('d', function () {
425
567
  // NOTE: `d` is stale after layout is switched so get the datum from the parent element.
426
- 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;
427
573
  if (!source.initialized || !target.initialized) {
428
574
  return;
429
575
  }
@@ -4,10 +4,8 @@
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
- import { defaultIdAccessor, type IdAccessor } from '../types';
8
+ import { type IdAccessor, defaultIdAccessor } from '../types';
11
9
 
12
10
  export type RendererOptions<T = any> = {
13
11
  idAccessor: IdAccessor;
@@ -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
  };
@@ -16,7 +16,7 @@ export const useStateRef = <V>(
16
16
  initialValue?: V | (() => V),
17
17
  ): [V | undefined, Dispatch<SetStateAction<V | undefined>>, RefObject<V | undefined>] => {
18
18
  const [value, setValue] = useState<V | undefined>(initialValue);
19
- const ref = useRef<V>();
19
+ const ref = useRef<V>(null);
20
20
  useEffect(() => {
21
21
  ref.current = value;
22
22
  }, [initialValue, value]);
@@ -2,7 +2,7 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
- import { select, zoom, type ZoomBehavior, zoomIdentity, type ZoomTransform } from 'd3';
5
+ import { type ZoomBehavior, type ZoomTransform, select, zoom, zoomIdentity } from 'd3';
6
6
  import defaultsDeep from 'lodash.defaultsdeep';
7
7
  import { type RefObject, useEffect, useMemo, useRef } from 'react';
8
8
 
@@ -2,34 +2,35 @@
2
2
  // Copyright 2020 DXOS.org
3
3
  //
4
4
 
5
- import '@dxos-theme';
5
+ import '../../styles/graph.css';
6
6
 
7
- import { type StoryObj } from '@storybook/react-vite';
7
+ import { RegistryContext } from '@effect-atom/atom-react';
8
+ import { type Meta, type StoryObj } from '@storybook/react-vite';
8
9
  import { select } from 'd3';
9
- import React, { type PropsWithChildren, useEffect, useMemo, useRef } from 'react';
10
+ import React, { type PropsWithChildren, useContext, useEffect, useMemo, useRef } from 'react';
10
11
 
11
12
  import { combine } from '@dxos/async';
13
+ import { type Graph } from '@dxos/graph';
12
14
  import { log } from '@dxos/log';
13
- import { type Meta, withLayout, withTheme } from '@dxos/storybook-utils';
15
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
16
+ import { withRegistry } from '@dxos/storybook-utils';
14
17
 
15
18
  import { SVG } from '../components';
16
19
  import {
17
20
  GraphForceProjector,
18
- type GraphLayoutNode,
21
+ type GraphForceProjectorOptions,
19
22
  type GraphLayoutEdge,
23
+ type GraphLayoutNode,
20
24
  GraphRenderer,
21
- type GraphForceProjectorOptions,
22
- createMarkers,
23
25
  createGraphDrag,
26
+ createMarkers,
24
27
  linkerRenderer,
25
28
  } from '../graph';
26
- import { useSvgContext, useZoom, useGrid } from '../hooks';
27
- import { convertTreeToGraph, createTree, TestGraphModel, type TestNode } from '../testing';
29
+ import { useGrid, useSvgContext, useZoom } from '../hooks';
30
+ import { TestGraphModel, type TestNode, convertTreeToGraph, createTree } from '../testing';
28
31
 
29
- import '../../styles/graph.css';
30
-
31
- type StoryProps = PropsWithChildren<{
32
- model: TestGraphModel;
32
+ type ComponentProps = PropsWithChildren<{
33
+ graph: () => Graph.Graph<TestNode, Graph.Edge.Any>;
33
34
  projectorOptions?: GraphForceProjectorOptions;
34
35
  count?: number;
35
36
  interval?: number;
@@ -37,28 +38,20 @@ type StoryProps = PropsWithChildren<{
37
38
  grid?: boolean;
38
39
  }>;
39
40
 
40
- const DefaultStory = ({ children, ...props }: StoryProps) => {
41
- return (
42
- <>
43
- <SVG.Root>
44
- <StoryComponent {...props} />
45
- </SVG.Root>
46
- {children && <div className='absolute left-4 bottom-4 font-mono text-green-500 text-xs'>{children}</div>}
47
- </>
48
- );
49
- };
50
-
51
- const StoryComponent = ({
52
- model,
41
+ const Component = ({
42
+ graph: graphFactory,
53
43
  projectorOptions,
54
44
  count = 0,
55
45
  interval = 200,
56
46
  link = false,
57
47
  grid: showGrid = false,
58
- }: StoryProps) => {
48
+ }: ComponentProps) => {
49
+ const registry = useContext(RegistryContext);
50
+ const model = useMemo(() => new TestGraphModel(registry, graphFactory()), [registry, graphFactory]);
51
+
59
52
  const context = useSvgContext();
60
- const graphRef = useRef<SVGGElement>();
61
- const markersRef = useRef<SVGGElement>();
53
+ const graphRef = useRef<SVGGElement>(null);
54
+ const markersRef = useRef<SVGGElement>(null);
62
55
  const grid = useGrid({ visible: showGrid });
63
56
  const zoom = useZoom();
64
57
 
@@ -94,7 +87,7 @@ const StoryComponent = ({
94
87
  labels: {
95
88
  text: (node: GraphLayoutNode<TestNode>) => node.id.substring(0, 4),
96
89
  },
97
- onNodeClick: (node: GraphLayoutNode<TestNode>, event: MouseEvent) => {
90
+ onNodeClick: (node: GraphLayoutNode<TestNode>) => {
98
91
  renderer.fireBullet(node);
99
92
  },
100
93
  onLinkClick: (edge: GraphLayoutEdge<TestNode>, event: MouseEvent) => {
@@ -116,9 +109,14 @@ const StoryComponent = ({
116
109
  }, [markersRef]);
117
110
 
118
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);
119
117
  void projector.start();
120
118
  return combine(
121
- model.subscribe((graph) => projector.updateData(graph)),
119
+ model.subscribe(() => projector.updateData(model.graph)),
122
120
  projector.updated.on(({ layout }) => renderer.render(layout)),
123
121
  () => projector.stop(),
124
122
  );
@@ -151,19 +149,33 @@ const StoryComponent = ({
151
149
  );
152
150
  };
153
151
 
154
- const meta: Meta = {
152
+ const DefaultStory = ({ children, ...props }: ComponentProps) => {
153
+ return (
154
+ <>
155
+ <SVG.Root>
156
+ <Component {...props} />
157
+ </SVG.Root>
158
+ {children && <div className='absolute left-4 bottom-4 font-mono text-green-500 text-xs'>{children}</div>}
159
+ </>
160
+ );
161
+ };
162
+
163
+ const meta = {
155
164
  title: 'ui/react-ui-graph/hooks',
156
165
  render: DefaultStory,
157
- decorators: [withTheme, withLayout({ fullscreen: true })],
158
- };
166
+ decorators: [withRegistry, withTheme(), withLayout({ layout: 'fullscreen' })],
167
+ parameters: {
168
+ layout: 'fullscreen',
169
+ },
170
+ } satisfies Meta<typeof DefaultStory>;
159
171
 
160
172
  export default meta;
161
173
 
162
- type Story = StoryObj<typeof DefaultStory>;
174
+ type Story = StoryObj<typeof meta>;
163
175
 
164
176
  export const Default: Story = {
165
177
  args: {
166
- model: new TestGraphModel(convertTreeToGraph(createTree({ depth: 3 }))),
178
+ graph: () => convertTreeToGraph(createTree({ depth: 3 })),
167
179
  grid: true,
168
180
  count: 300,
169
181
  interval: 20,
@@ -188,7 +200,7 @@ export const Default: Story = {
188
200
 
189
201
  export const Bullets: Story = {
190
202
  args: {
191
- model: new TestGraphModel(convertTreeToGraph(createTree({ depth: 4 }))),
203
+ graph: () => convertTreeToGraph(createTree({ depth: 4 })),
192
204
  children: <span>⌘-DRAG to edge or create node; ⌘-CLICK to delete edge.</span>,
193
205
  link: true,
194
206
  grid: false,