@dxos/react-ui-graph 0.8.4-main.5ea62a8 → 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 (120) 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 +7 -7
  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 +3 -1
  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 +4 -2
  31. package/dist/types/src/components/SVG/Svg.stories.d.ts.map +1 -1
  32. package/dist/types/src/fx/fx.stories.d.ts +6 -4
  33. package/dist/types/src/fx/fx.stories.d.ts.map +1 -1
  34. package/dist/types/src/fx/pulsar.d.ts.map +1 -1
  35. package/dist/types/src/graph/markers.d.ts.map +1 -1
  36. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts +47 -0
  37. package/dist/types/src/graph/projector/graph-bundle-projector.d.ts.map +1 -0
  38. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts +60 -0
  39. package/dist/types/src/graph/projector/graph-cluster-projector.d.ts.map +1 -0
  40. package/dist/types/src/graph/projector/graph-drag.d.ts.map +1 -1
  41. package/dist/types/src/graph/projector/graph-force-projector.d.ts +1 -1
  42. package/dist/types/src/graph/projector/graph-force-projector.d.ts.map +1 -1
  43. package/dist/types/src/graph/projector/graph-forces.d.ts.map +1 -1
  44. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts +1 -1
  45. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts.map +1 -1
  46. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts +23 -0
  47. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts.map +1 -0
  48. package/dist/types/src/graph/projector/graph-projector.d.ts +2 -2
  49. package/dist/types/src/graph/projector/graph-projector.d.ts.map +1 -1
  50. package/dist/types/src/graph/projector/graph-radial-projector.d.ts +7 -1
  51. package/dist/types/src/graph/projector/graph-radial-projector.d.ts.map +1 -1
  52. package/dist/types/src/graph/projector/graph-relational-projector.d.ts +1 -1
  53. package/dist/types/src/graph/projector/graph-relational-projector.d.ts.map +1 -1
  54. package/dist/types/src/graph/projector/index.d.ts +3 -0
  55. package/dist/types/src/graph/projector/index.d.ts.map +1 -1
  56. package/dist/types/src/graph/projector/projector.d.ts +10 -1
  57. package/dist/types/src/graph/projector/projector.d.ts.map +1 -1
  58. package/dist/types/src/graph/renderer/bullets.d.ts.map +1 -1
  59. package/dist/types/src/graph/renderer/graph-renderer.d.ts +21 -1
  60. package/dist/types/src/graph/renderer/graph-renderer.d.ts.map +1 -1
  61. package/dist/types/src/graph/renderer/renderer.d.ts +12 -1
  62. package/dist/types/src/graph/renderer/renderer.d.ts.map +1 -1
  63. package/dist/types/src/graph/types.d.ts +15 -1
  64. package/dist/types/src/graph/types.d.ts.map +1 -1
  65. package/dist/types/src/hooks/useGrid.d.ts.map +1 -1
  66. package/dist/types/src/hooks/useStateRef.d.ts.map +1 -1
  67. package/dist/types/src/hooks/useSvgContext.d.ts.map +1 -1
  68. package/dist/types/src/hooks/useZoom.d.ts.map +1 -1
  69. package/dist/types/src/stories/hooks.stories.d.ts +7 -4
  70. package/dist/types/src/stories/hooks.stories.d.ts.map +1 -1
  71. package/dist/types/src/testing/data.d.ts +5 -5
  72. package/dist/types/src/testing/data.d.ts.map +1 -1
  73. package/dist/types/src/testing/hooks.d.ts +2 -16
  74. package/dist/types/src/testing/hooks.d.ts.map +1 -1
  75. package/dist/types/src/testing/model.d.ts +4 -8
  76. package/dist/types/src/testing/model.d.ts.map +1 -1
  77. package/dist/types/src/util/events.d.ts.map +1 -1
  78. package/dist/types/src/util/fraction.d.ts +1 -1
  79. package/dist/types/src/util/fraction.d.ts.map +1 -1
  80. package/dist/types/src/util/points.d.ts.map +1 -1
  81. package/dist/types/src/util/scale.d.ts.map +1 -1
  82. package/dist/types/src/util/screen.d.ts.map +1 -1
  83. package/dist/types/src/util/vector.d.ts.map +1 -1
  84. package/dist/types/tsconfig.tsbuildinfo +1 -1
  85. package/package.json +33 -35
  86. package/src/components/Graph/Graph.stories.tsx +55 -50
  87. package/src/components/Graph/Graph.tsx +59 -24
  88. package/src/components/Mesh/Mesh.stories.tsx +11 -9
  89. package/src/components/Mesh/Mesh.tsx +43 -35
  90. package/src/components/SVG/Grid.tsx +1 -1
  91. package/src/components/SVG/Markers.tsx +1 -1
  92. package/src/components/SVG/Root.tsx +41 -9
  93. package/src/components/SVG/SVG.tsx +10 -2
  94. package/src/components/SVG/Svg.stories.tsx +6 -6
  95. package/src/fx/fx.stories.tsx +10 -10
  96. package/src/graph/projector/graph-bundle-projector.ts +210 -0
  97. package/src/graph/projector/graph-cluster-projector.ts +325 -0
  98. package/src/graph/projector/graph-drag.ts +0 -1
  99. package/src/graph/projector/graph-force-projector.ts +6 -3
  100. package/src/graph/projector/graph-hierarchical-projector.ts +4 -4
  101. package/src/graph/projector/graph-lattice-projector.ts +86 -0
  102. package/src/graph/projector/graph-projector.ts +9 -3
  103. package/src/graph/projector/graph-radial-projector.ts +31 -4
  104. package/src/graph/projector/graph-relational-projector.ts +4 -4
  105. package/src/graph/projector/index.ts +3 -0
  106. package/src/graph/projector/projector.ts +12 -3
  107. package/src/graph/renderer/graph-renderer.ts +175 -30
  108. package/src/graph/renderer/renderer.ts +15 -4
  109. package/src/graph/types.ts +15 -1
  110. package/src/hooks/useStateRef.ts +1 -1
  111. package/src/stories/hooks.stories.tsx +25 -13
  112. package/src/testing/data.ts +14 -14
  113. package/src/testing/hooks.ts +3 -4
  114. package/src/testing/model.ts +6 -6
  115. package/src/util/fraction.ts +1 -1
  116. package/styles/graph.css +341 -43
  117. package/dist/lib/browser/chunk-PDEA4KBO.mjs +0 -966
  118. package/dist/lib/browser/chunk-PDEA4KBO.mjs.map +0 -7
  119. package/dist/lib/node-esm/chunk-NJGJKPL7.mjs +0 -968
  120. package/dist/lib/node-esm/chunk-NJGJKPL7.mjs.map +0 -7
@@ -0,0 +1,325 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { cluster as d3Cluster, hierarchy, linkRadial } from 'd3';
6
+
7
+ import { type Graph } from '@dxos/graph';
8
+ import { log } from '@dxos/log';
9
+
10
+ import { type GraphLayoutEdge, type GraphLayoutNode } from '../types';
11
+ import { GraphRadialProjector, type GraphRadialProjectorOptions, updateNode } from './graph-radial-projector';
12
+
13
+ export type GraphClusterProjectorOptions = GraphRadialProjectorOptions & {
14
+ /** Reserved space around the cluster (screen pixels). */
15
+ margin?: number;
16
+ /** Radius for leaf nodes. Default 4. */
17
+ leafRadius?: number;
18
+ /** Radius for the synthetic group nodes (visible as smaller intermediate dots). Default 3. */
19
+ groupRadius?: number;
20
+ /** Radius for the synthetic root node. Default 5. */
21
+ rootRadius?: number;
22
+ /**
23
+ * Group key for each node — synthetic intermediate nodes are created per unique key,
24
+ * giving a root → group → leaf hierarchy. Return `undefined` to attach the node
25
+ * directly to the root.
26
+ */
27
+ groupOf?: (node: GraphLayoutNode) => string | undefined;
28
+ /** Root id used for the synthetic root node. */
29
+ rootId?: string;
30
+ /** Display label set on the synthetic root node. Renderers read `node.label`. */
31
+ rootLabel?: string;
32
+ /** Optional formatter applied to the `groupOf` key to derive the group's display label.
33
+ * Defaults to the key itself. */
34
+ groupLabel?: (key: string) => string;
35
+ };
36
+
37
+ const ROOT_ID = '__cluster_root__';
38
+ const GROUP_PREFIX = '__group__:';
39
+ const HIER_EDGE_PREFIX = '__hier__:';
40
+
41
+ /** Node type tags so consumer renderers can distinguish leaves from synthetic structural nodes. */
42
+ export const CLUSTER_NODE_TYPE_LEAF = 'leaf';
43
+ export const CLUSTER_NODE_TYPE_GROUP = 'group';
44
+ export const CLUSTER_NODE_TYPE_ROOT = 'root';
45
+
46
+ /**
47
+ * Standard d3 radial link generator — `curveBumpRadial`. Same shape as the original
48
+ * `RadialTree` component (and the d3 radial-cluster observable notebook).
49
+ *
50
+ * IMPORTANT: relies on the `dx-edge path` CSS setting `fill: none`. Without that, the SVG
51
+ * default fill (black) closes the curve across the source-target chord and visually
52
+ * swallows part of the stroke. The Graph engine's `createEdge` doesn't set `fill='none'`
53
+ * inline (unlike the original RadialTree), so the rule lives in graph.css.
54
+ */
55
+ const linkPath = linkRadial<any, any>()
56
+ .angle((d: any) => d.x)
57
+ .radius((d: any) => d.y);
58
+
59
+ /**
60
+ * Cartesian → d3-radial polar. d3 measures angle clockwise from "up" (the -y direction).
61
+ * Inverse of `[cos(a - π/2) * r, sin(a - π/2) * r]`.
62
+ */
63
+ const cartesianToPolar = (x: number, y: number): { angle: number; radius: number } => ({
64
+ angle: Math.atan2(x, -y),
65
+ radius: Math.hypot(x, y),
66
+ });
67
+
68
+ /**
69
+ * Radial cluster (d3.cluster) layout. Materializes a root → group → leaf
70
+ * hierarchy from the `groupOf` callback, runs d3.cluster, and:
71
+ *
72
+ * - Places leaves around the outer ring; synthetic group nodes sit on an
73
+ * inner ring; the root sits at the origin. All three kinds are added to the
74
+ * layout so they render via the consumer's `renderNode` (the `type` field
75
+ * identifies which is which).
76
+ * - Each hierarchy edge carries a `path` string (d3's `linkRadial` curve)
77
+ * computed from CURRENT cartesian endpoint positions every frame via
78
+ * `onTickFrame`. The curve therefore tracks moving endpoints during a
79
+ * cross-variant tween (e.g. force → cluster) instead of snapping to the
80
+ * final polar shape.
81
+ */
82
+ export class GraphClusterProjector<
83
+ NodeData = any,
84
+ Options extends GraphClusterProjectorOptions = any,
85
+ > extends GraphRadialProjector<NodeData, Options> {
86
+ // Synthetic-node ids (root id, or `${GROUP_PREFIX}${key}`) whose subtree is currently
87
+ // hidden. Clicking the corresponding rendered circle calls toggleCollapsed to flip
88
+ // membership, then re-runs the layout so the renderer's exit transition fades the
89
+ // hidden leaves + hierarchy edges out (and back in on expand).
90
+ readonly #collapsed = new Set<string>();
91
+
92
+ // Snapshot of the full data-node set as of the last mergeData. doClusterLayout always
93
+ // reads from this rather than `layout.graph.nodes` — the layout view is filtered (it
94
+ // drops hidden leaves so the renderer doesn't see them), so re-reading from there
95
+ // would permanently lose the hidden leaves and they couldn't reappear on expand.
96
+ #dataNodes: GraphLayoutNode<NodeData>[] = [];
97
+
98
+ /** Toggle collapse state for a synthetic node id. Triggers a topology re-emit. */
99
+ toggleCollapsed(id: string): void {
100
+ if (this.#collapsed.has(id)) {
101
+ this.#collapsed.delete(id);
102
+ } else {
103
+ this.#collapsed.add(id);
104
+ }
105
+ // Re-run the layout against the current model data so hidden / re-shown nodes are
106
+ // exited / entered through the renderer's join.
107
+ this.doClusterLayout();
108
+ this.emitUpdate('topology');
109
+ this.animate();
110
+ }
111
+
112
+ /** Whether a synthetic-node id is currently collapsed. */
113
+ isCollapsed(id: string): boolean {
114
+ return this.#collapsed.has(id);
115
+ }
116
+
117
+ protected override onUpdate(graph?: Graph.Any) {
118
+ log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
119
+ this.mergeData(graph);
120
+ // Snapshot the full data-node set right after mergeData — before doClusterLayout
121
+ // overwrites `layout.graph.nodes` with the filtered (collapse-aware) view.
122
+ this.#dataNodes = [...this.layout.graph.nodes];
123
+ this.doClusterLayout();
124
+ this.emitUpdate('topology');
125
+ this.animate();
126
+ }
127
+
128
+ /**
129
+ * Recompute each hierarchy edge's `path` from current cartesian source/target positions,
130
+ * so the curves track moving endpoints during a cross-variant tween (e.g. force → cluster)
131
+ * instead of being pinned to the final polar layout.
132
+ */
133
+ protected override onTickFrame(_t: number): void {
134
+ for (const edge of this.layout.graph.edges) {
135
+ if (edge.type !== 'hierarchy') {
136
+ continue;
137
+ }
138
+ const { source, target } = edge;
139
+ const s = cartesianToPolar(source.x ?? 0, source.y ?? 0);
140
+ const t = cartesianToPolar(target.x ?? 0, target.y ?? 0);
141
+ edge.path = linkPath({ source: { x: s.angle, y: s.radius }, target: { x: t.angle, y: t.radius } });
142
+ }
143
+ }
144
+
145
+ private doClusterLayout() {
146
+ if (!this.context.size) {
147
+ return;
148
+ }
149
+
150
+ // Read from the post-mergeData snapshot, not from `layout.graph.nodes`. The layout
151
+ // view is a FILTERED projection (hidden leaves are dropped so the renderer's d3 join
152
+ // fades them out); reading from it would shrink monotonically across collapses and
153
+ // hidden leaves could never reappear on expand. The snapshot also avoids the
154
+ // "synthetic root re-pushed as its own child → d3.hierarchy infinite recursion" hang
155
+ // we'd otherwise hit, because synthetic stubs were never in this set to begin with.
156
+ const dataNodes = this.#dataNodes;
157
+ if (!dataNodes.length) {
158
+ return;
159
+ }
160
+
161
+ const groupOf = this.options.groupOf;
162
+ const rootId = this.options.rootId ?? ROOT_ID;
163
+
164
+ // Synthesize the hierarchy: root → groups → leaves. `groupKey` is carried on synthetic
165
+ // group HierNodes so the rendered stub can pick up the original groupOf return value
166
+ // (the typename, in plugin-explorer's case) as its display label.
167
+ type HierNode = { id: string; parent?: string; node?: GraphLayoutNode<NodeData>; groupKey?: string };
168
+ const items: HierNode[] = [{ id: rootId }];
169
+ const groupIds = new Map<string, string>();
170
+ // Collapsed root → render only the root circle (no groups, no leaves).
171
+ const rootCollapsed = this.#collapsed.has(rootId);
172
+ if (!rootCollapsed) {
173
+ for (const node of dataNodes) {
174
+ const key = groupOf?.(node);
175
+ let parent = rootId;
176
+ if (key !== undefined) {
177
+ let groupId = groupIds.get(key);
178
+ if (!groupId) {
179
+ groupId = `${GROUP_PREFIX}${key}`;
180
+ groupIds.set(key, groupId);
181
+ items.push({ id: groupId, parent: rootId, groupKey: key });
182
+ }
183
+ parent = groupId;
184
+ }
185
+ // Collapsed group → drop its leaves. The group itself still renders so the user
186
+ // can click it again to expand.
187
+ if (this.#collapsed.has(parent)) {
188
+ continue;
189
+ }
190
+ items.push({ id: node.id, parent, node });
191
+ }
192
+ }
193
+
194
+ const childrenByParent = new Map<string, HierNode[]>();
195
+ for (const item of items) {
196
+ if (item.parent) {
197
+ const list = childrenByParent.get(item.parent) ?? [];
198
+ list.push(item);
199
+ childrenByParent.set(item.parent, list);
200
+ }
201
+ }
202
+
203
+ const root = hierarchy<HierNode>({ id: rootId }, (d) => childrenByParent.get(d.id) ?? []);
204
+
205
+ const { width, height } = this.context.size;
206
+ const margin = this.options.margin ?? 80;
207
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
208
+
209
+ d3Cluster<HierNode>()
210
+ .size([2 * Math.PI, ringRadius])
211
+ // Tighter sibling spacing at deeper levels — matches the previous standalone
212
+ // RadialTree component. Without the `/depth` divisor, large groups span a
213
+ // wide angular arc; the linkRadial(curveBumpPolar) curve to a leaf at the
214
+ // edge of that arc then has its control points placed far apart in
215
+ // cartesian, producing a wide swoop that visually misses the target.
216
+ .separation((a: any, b: any) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
217
+
218
+ const leafR = this.options.leafRadius ?? 4;
219
+ const groupR = this.options.groupRadius ?? 3;
220
+ const rootR = this.options.rootRadius ?? 5;
221
+
222
+ // Index any synthetic root / group stubs from the previous layout pass so we can
223
+ // REUSE them (preserving their current x/y as the tween start) instead of creating
224
+ // fresh `{x:0,y:0}` stubs that would snap the DOM element to the origin first.
225
+ const prevStubsById = new Map<string, GraphLayoutNode<NodeData>>();
226
+ for (const node of this.layout.graph.nodes) {
227
+ if (node.type === CLUSTER_NODE_TYPE_ROOT || node.type === CLUSTER_NODE_TYPE_GROUP) {
228
+ prevStubsById.set(node.id, node);
229
+ }
230
+ }
231
+
232
+ // Build the new node set: existing data nodes (re-positioned), plus synthetic root + groups.
233
+ const syntheticNodes = new Map<string, GraphLayoutNode<NodeData>>();
234
+ root.each((d: any) => {
235
+ const id = d.data.id;
236
+ const angle = d.x;
237
+ const radius = d.y;
238
+ const x = Math.cos(angle - Math.PI / 2) * radius;
239
+ const y = Math.sin(angle - Math.PI / 2) * radius;
240
+
241
+ if (d.data.node) {
242
+ // Real leaf — tween its position and mark visible.
243
+ updateNode(d.data.node, [x, y], leafR);
244
+ (d.data.node as any).type = CLUSTER_NODE_TYPE_LEAF;
245
+ (d.data.node as any).hidden = false;
246
+ } else {
247
+ // Synthetic root or group. On the very first cluster mount the stub is brand-new
248
+ // so seed it at origin — root stays put while groups grow outward. On subsequent
249
+ // mounts (toggleCollapsed) we reuse the previous-render stub so its current x/y
250
+ // becomes the tween start; otherwise the DOM element would jump to origin before
251
+ // animating to the new target position.
252
+ const isRoot = id === rootId;
253
+ const stub = prevStubsById.get(id) ?? ({ id, x: 0, y: 0 } as GraphLayoutNode<NodeData>);
254
+ updateNode(stub, [x, y], isRoot ? rootR : groupR);
255
+ stub.type = isRoot ? CLUSTER_NODE_TYPE_ROOT : CLUSTER_NODE_TYPE_GROUP;
256
+ // Surface a display label so renderNode callbacks don't have to parse internal ids.
257
+ if (isRoot) {
258
+ stub.label = this.options.rootLabel;
259
+ } else if (d.data.groupKey !== undefined) {
260
+ stub.label = this.options.groupLabel ? this.options.groupLabel(d.data.groupKey) : d.data.groupKey;
261
+ }
262
+ syntheticNodes.set(id, stub);
263
+ }
264
+ });
265
+
266
+ // Collapse animation: hidden leaves stay in the layout but their target position is
267
+ // the parent group's target (or root for ungrouped leaves). animate() then tweens them
268
+ // toward the parent — visually "absorbed in", while their opacity transitions to 0 via
269
+ // the renderer's hidden-flag transition. On re-expand they tween back out to their ring.
270
+ const visibleLeafIds = new Set<string>();
271
+ for (const item of items) {
272
+ if (item.node) {
273
+ visibleLeafIds.add(item.id);
274
+ }
275
+ }
276
+ for (const node of dataNodes) {
277
+ if (visibleLeafIds.has(node.id)) {
278
+ continue;
279
+ }
280
+ // Hidden leaf — find its parent group's target. groupOf may have changed since the
281
+ // last layout pass (rare in practice but cheap to handle), so re-compute the key.
282
+ const key = groupOf?.(node);
283
+ const parentId = key !== undefined && groupIds.has(key) ? (groupIds.get(key) as string) : rootId;
284
+ const parentStub = syntheticNodes.get(parentId);
285
+ const targetX = (parentStub as any)?.tx ?? 0;
286
+ const targetY = (parentStub as any)?.ty ?? 0;
287
+ updateNode(node, [targetX, targetY], leafR);
288
+ (node as any).type = CLUSTER_NODE_TYPE_LEAF;
289
+ node.hidden = true;
290
+ }
291
+
292
+ // Compose the rendered node list: synthetic structure first (so leaves draw on top).
293
+ const nextNodes: GraphLayoutNode<NodeData>[] = [];
294
+ for (const stub of syntheticNodes.values()) {
295
+ nextNodes.push(stub);
296
+ }
297
+ for (const node of dataNodes) {
298
+ nextNodes.push(node);
299
+ }
300
+ this.layout.graph.nodes = nextNodes;
301
+
302
+ // Build hierarchy edges referencing source/target nodes. The `path` is filled by
303
+ // onTickFrame (and again per tween frame) from current cartesian positions, so we
304
+ // don't precompute it here — leaving it undefined would briefly produce a straight
305
+ // line on first paint, but the tween's first tick (t=0) writes the correct path
306
+ // before the renderer's positions-emit reaches the DOM.
307
+ const hierarchyEdges: GraphLayoutEdge<NodeData>[] = [];
308
+ root.links().forEach((link: any) => {
309
+ const sid = link.source.data.id;
310
+ const tid = link.target.data.id;
311
+ const sourceNode = link.source.data.node ?? syntheticNodes.get(sid);
312
+ const targetNode = link.target.data.node ?? syntheticNodes.get(tid);
313
+ hierarchyEdges.push({
314
+ id: `${HIER_EDGE_PREFIX}${sid}->${tid}`,
315
+ type: 'hierarchy',
316
+ source: sourceNode!,
317
+ target: targetNode!,
318
+ data: undefined,
319
+ });
320
+ });
321
+ this.layout.graph.edges = hierarchyEdges;
322
+ // Seed initial paths so the topology emit has correct geometry to enter into the DOM.
323
+ this.onTickFrame(0);
324
+ }
325
+ }
@@ -7,7 +7,6 @@ import { drag, pointer, select } from 'd3';
7
7
  import { type SVGContext } from '../../hooks';
8
8
  import { type Point } from '../../util';
9
9
  import { type GraphLayoutNode } from '../types';
10
-
11
10
  import { type GraphProjector } from './graph-projector';
12
11
 
13
12
  enum Mode {
@@ -18,7 +18,6 @@ import { type Graph } from '@dxos/graph';
18
18
  import { log } from '@dxos/log';
19
19
 
20
20
  import { type GraphLayoutEdge, type GraphLayoutNode } from '../types';
21
-
22
21
  import { forcePoint } from './graph-forces';
23
22
  import { GraphProjector, type GraphProjectorOptions } from './graph-projector';
24
23
 
@@ -198,7 +197,8 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
198
197
  }
199
198
 
200
199
  this._simulation
201
- .on('tick', () => propagating && this.emitUpdate())
200
+ // Each tick only mutates `x/y` — emit 'positions' so the renderer can fast-path.
201
+ .on('tick', () => propagating && this.emitUpdate('positions'))
202
202
  .velocityDecay(0.3)
203
203
  .alphaDecay(1 - Math.pow(0.001, 1 / 300))
204
204
  .alpha(1)
@@ -223,12 +223,15 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
223
223
  this.restart();
224
224
  }
225
225
 
226
- override onUpdate(graph?: Graph): void {
226
+ override onUpdate(graph?: Graph.Any): void {
227
227
  log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
228
228
  this._simulation.stop();
229
229
  this.mergeData(graph);
230
230
  this.updateLayout();
231
231
  this.updateForces(this.forces);
232
+ // Signal topology change so the renderer rebinds enter/exit and runs attribute callbacks once.
233
+ // Subsequent ticks emit 'positions' and skip the expensive path.
234
+ this.emitUpdate('topology');
232
235
  this.restart();
233
236
  }
234
237
 
@@ -6,7 +6,6 @@ import { type Graph } from '@dxos/graph';
6
6
  import { log } from '@dxos/log';
7
7
 
8
8
  import { type GraphLayoutNode } from '../types';
9
-
10
9
  import { type GraphProjectorOptions } from './graph-projector';
11
10
  import { GraphRadialProjector, layoutRadial, updateNode } from './graph-radial-projector';
12
11
 
@@ -20,14 +19,15 @@ export class GraphHierarchicalProjector<
20
19
  NodeData = any,
21
20
  Options extends GraphHierarchicalProjectorOptions = any,
22
21
  > extends GraphRadialProjector<NodeData, Options> {
23
- protected override onUpdate(graph?: Graph) {
22
+ protected override onUpdate(graph?: Graph.Any) {
24
23
  log('onUpdate', {
25
24
  graph: { nodes: graph?.nodes.length, edges: graph?.edges.length },
26
- selection: this.selection?.selected.value,
25
+ selection: this.selection?.getSelectedIds(),
27
26
  });
28
27
 
29
28
  this.mergeData(graph);
30
- const selected = this.selection?.selected.value?.[0];
29
+ this.emitUpdate('topology');
30
+ const selected = this.selection?.getSelectedIds()[0];
31
31
  if (selected) {
32
32
  const node = this.layout.graph.nodes.find((node) => node.id === selected);
33
33
  if (node) {
@@ -0,0 +1,86 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type Graph } from '@dxos/graph';
6
+ import { log } from '@dxos/log';
7
+
8
+ import { type GraphLayoutNode } from '../types';
9
+ import { GraphRadialProjector, type GraphRadialProjectorOptions, updateNode } from './graph-radial-projector';
10
+
11
+ export type GraphLatticeProjectorOptions = GraphRadialProjectorOptions & {
12
+ /** Reserved space around the lattice (screen pixels). */
13
+ margin?: number;
14
+ /** Node radius used by `renderNode` consumers. Defaults to the force-graph default (6) so animations across variants don't resize nodes. */
15
+ radius?: number;
16
+ /** Sort key for cells; defaults to the node label / id. Same-typename nodes naturally cluster. */
17
+ sortBy?: (node: GraphLayoutNode) => string;
18
+ };
19
+
20
+ /**
21
+ * Lays out nodes as a square-as-possible grid that fits the container.
22
+ * Extends `GraphRadialProjector` to inherit the tween (`updateNode` + `animate`),
23
+ * so switching to / from this layout animates each node from its current
24
+ * position to the grid cell — and the initial mount can also "grow" from
25
+ * existing positions if seeded with a prior projector's layout.
26
+ */
27
+ export class GraphLatticeProjector<
28
+ NodeData = any,
29
+ Options extends GraphLatticeProjectorOptions = any,
30
+ > extends GraphRadialProjector<NodeData, Options> {
31
+ protected override onUpdate(graph?: Graph.Any) {
32
+ log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
33
+ this.mergeData(graph);
34
+ // Compute layout (assigns sx/sy/tx/ty + initial x/y) BEFORE emitting topology so the
35
+ // renderer's first render uses meaningful positions. animate() then tweens to target.
36
+ this.doLatticeLayout();
37
+ this.emitUpdate('topology');
38
+ this.animate();
39
+ }
40
+
41
+ private doLatticeLayout() {
42
+ if (!this.context.size) {
43
+ return;
44
+ }
45
+
46
+ const nodes = this.layout.graph.nodes;
47
+ const count = nodes.length;
48
+ if (!count) {
49
+ return;
50
+ }
51
+
52
+ const sortBy = this.options.sortBy ?? ((n: GraphLayoutNode) => (n.data as any)?.label ?? n.id);
53
+ nodes.sort((a, b) => sortBy(a).localeCompare(sortBy(b)));
54
+
55
+ // Columns ≈ √N so the grid stays as square as possible.
56
+ const columns = Math.max(1, Math.ceil(Math.sqrt(count)));
57
+ const rows = Math.ceil(count / columns);
58
+
59
+ const margin = this.options.margin ?? 16;
60
+ const { width, height } = this.context.size;
61
+ const innerW = Math.max(0, width - 2 * margin);
62
+ const innerH = Math.max(0, height - 2 * margin);
63
+ // Default radius matches the force-graph default (6) so cross-variant animations
64
+ // tween position only, not size. Consumers can pass a smaller `radius` for a
65
+ // denser matrix look.
66
+ const r = this.options.radius ?? 6;
67
+ // Cell size sets the spacing between nodes. Cap at a small multiple of `r`
68
+ // so the lattice stays tight rather than ballooning to fill the container;
69
+ // wide enough that edges crossing between non-adjacent cells remain visible
70
+ // in the gaps between nodes.
71
+ const fit = Math.min(innerW / columns, innerH / rows);
72
+ const cellSize = Math.max(0, Math.min(fit, r * 6));
73
+
74
+ // Center the lattice (SVG viewBox is centered at origin in `<SVG.Root>`).
75
+ const gridW = cellSize * columns;
76
+ const gridH = cellSize * rows;
77
+ const offsetX = -gridW / 2 + cellSize / 2;
78
+ const offsetY = -gridH / 2 + cellSize / 2;
79
+
80
+ nodes.forEach((node, i) => {
81
+ const tx = offsetX + (i % columns) * cellSize;
82
+ const ty = offsetY + Math.floor(i / columns) * cellSize;
83
+ updateNode(node, [tx, ty], r);
84
+ });
85
+ }
86
+ }
@@ -6,7 +6,6 @@ import { type Graph, type SelectionModel } from '@dxos/graph';
6
6
 
7
7
  import { type SVGContext } from '../../hooks';
8
8
  import { type GraphLayout, type GraphLayoutNode, emptyGraph } from '../types';
9
-
10
9
  import { Projector, type ProjectorOptions } from './projector';
11
10
 
12
11
  export type GraphProjectorOptions = ProjectorOptions & {};
@@ -15,7 +14,7 @@ export type GraphProjectorOptions = ProjectorOptions & {};
15
14
  * Base class for graph projectors.
16
15
  */
17
16
  export abstract class GraphProjector<NodeData = any, Options extends GraphProjectorOptions = any> extends Projector<
18
- Graph,
17
+ Graph.Any,
19
18
  GraphLayout<NodeData>,
20
19
  Options
21
20
  > {
@@ -60,7 +59,7 @@ export abstract class GraphProjector<NodeData = any, Options extends GraphProjec
60
59
  * Merge external data with internal representation (e.g., so force properties like position are preserved).
61
60
  * @param data
62
61
  */
63
- protected mergeData(data: Graph = emptyGraph) {
62
+ protected mergeData(data: Graph.Any = emptyGraph) {
64
63
  // Merge nodes.
65
64
  const nodes: GraphLayoutNode[] = data.nodes.map((node) => {
66
65
  let current: GraphLayoutNode = this._layout.graph.nodes.find((n) => n.id === this.options.idAccessor(node));
@@ -71,6 +70,13 @@ export abstract class GraphProjector<NodeData = any, Options extends GraphProjec
71
70
  }
72
71
 
73
72
  current.data = node;
73
+ // `hidden` is a transient flag set by the cluster projector to fade
74
+ // collapsed leaves. Reset it on every merge so that (a) switching
75
+ // away from cluster to another projector — which inherits the
76
+ // previous layout via `prev` — doesn't carry forward stale hidden
77
+ // flags, and (b) the cluster projector itself re-applies the flag
78
+ // each `doClusterLayout` pass.
79
+ current.hidden = false;
74
80
  return current;
75
81
  });
76
82
 
@@ -9,7 +9,6 @@ import { log } from '@dxos/log';
9
9
 
10
10
  import { type Point } from '../../util';
11
11
  import { type GraphLayoutNode } from '../types';
12
-
13
12
  import { GraphProjector, type GraphProjectorOptions } from './graph-projector';
14
13
 
15
14
  export type GraphRadialProjectorOptions = GraphProjectorOptions & {
@@ -28,13 +27,20 @@ export class GraphRadialProjector<
28
27
  return undefined;
29
28
  }
30
29
 
31
- protected override onUpdate(graph?: Graph) {
30
+ protected override onUpdate(graph?: Graph.Any) {
32
31
  log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
33
32
  this.mergeData(graph);
33
+ // Bind enter/exit once before the tween starts; subsequent animate frames emit 'positions'.
34
+ this.emitUpdate('topology');
34
35
  this.doRadialLayout();
35
36
  }
36
37
 
37
38
  protected animate() {
39
+ // Cancel any in-flight tween so a fresh onUpdate doesn't race against the
40
+ // previous timer (both would be mutating x/y at different rates).
41
+ this._timer?.stop();
42
+ this._timer = undefined;
43
+
38
44
  const start = Date.now();
39
45
  if (this.options.duration) {
40
46
  this._timer = timer(() => {
@@ -47,17 +53,38 @@ export class GraphRadialProjector<
47
53
  node.r = node.sr + (node.tr - node.sr) * d;
48
54
  });
49
55
 
50
- this.emitUpdate();
56
+ // Subclass hook: derived projectors (e.g. cluster) can mutate edge.path
57
+ // here so curves track moving endpoints during the tween. The renderer's
58
+ // applyPositions reads edge.path fresh each frame.
59
+ this.onTickFrame(d);
60
+
61
+ // Tween frames only mutate `x/y/r`; emit 'positions' so the renderer can fast-path.
62
+ this.emitUpdate('positions');
51
63
  if (t >= 1) {
52
64
  this._timer.stop();
53
65
  this._timer = undefined;
54
66
  }
55
67
  });
56
68
  } else {
57
- this.emitUpdate();
69
+ // No duration: snap nodes to their target. Without this the layout would
70
+ // sit at `sx/sy/sr` (= previous positions) and never reach the new target.
71
+ this.layout.graph.nodes.forEach((node: any) => {
72
+ node.x = node.tx;
73
+ node.y = node.ty;
74
+ node.r = node.tr;
75
+ });
76
+ this.onTickFrame(1);
77
+ this.emitUpdate('positions');
58
78
  }
59
79
  }
60
80
 
81
+ /**
82
+ * Per-frame hook called after node x/y/r are interpolated and before the
83
+ * 'positions' emit. Subclasses override to update edge geometry (`edge.path`)
84
+ * so curves stay glued to moving endpoints. `t` is the eased progress in [0, 1].
85
+ */
86
+ protected onTickFrame(t: number): void {}
87
+
61
88
  protected override async onStop() {
62
89
  this._timer?.stop();
63
90
  this._timer = undefined;
@@ -6,7 +6,6 @@ import { type Graph } from '@dxos/graph';
6
6
  import { log } from '@dxos/log';
7
7
 
8
8
  import { type GraphLayoutNode } from '../types';
9
-
10
9
  import { type GraphProjectorOptions } from './graph-projector';
11
10
  import { GraphRadialProjector, layoutHorizontal, layoutRadial, updateNode } from './graph-radial-projector';
12
11
 
@@ -20,14 +19,15 @@ export class GraphRelationalProjector<
20
19
  NodeData = any,
21
20
  Options extends GraphRelationalProjectorOptions = any,
22
21
  > extends GraphRadialProjector<NodeData, Options> {
23
- protected override onUpdate(graph?: Graph) {
22
+ protected override onUpdate(graph?: Graph.Any) {
24
23
  log('onUpdate', {
25
24
  graph: { nodes: graph?.nodes.length, edges: graph?.edges.length },
26
- selection: this.selection?.selected.value,
25
+ selection: this.selection?.getSelectedIds(),
27
26
  });
28
27
 
29
28
  this.mergeData(graph);
30
- const selected = this.selection?.selected.value?.[0];
29
+ this.emitUpdate('topology');
30
+ const selected = this.selection?.getSelectedIds()[0];
31
31
  if (selected) {
32
32
  const node = this.layout.graph.nodes.find((node) => node.id === selected);
33
33
  if (node) {
@@ -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';
@@ -10,11 +10,20 @@ 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() {