@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
@@ -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
+ }
@@ -4,10 +4,10 @@
4
4
 
5
5
  import { drag, pointer, select } from 'd3';
6
6
 
7
- import { type GraphProjector } from './graph-projector';
8
7
  import { type SVGContext } from '../../hooks';
9
8
  import { type Point } from '../../util';
10
9
  import { type GraphLayoutNode } from '../types';
10
+ import { type GraphProjector } from './graph-projector';
11
11
 
12
12
  enum Mode {
13
13
  MOVE = 0,
@@ -17,9 +17,9 @@ import {
17
17
  import { type Graph } from '@dxos/graph';
18
18
  import { log } from '@dxos/log';
19
19
 
20
+ import { type GraphLayoutEdge, type GraphLayoutNode } from '../types';
20
21
  import { forcePoint } from './graph-forces';
21
22
  import { GraphProjector, type GraphProjectorOptions } from './graph-projector';
22
- import { type GraphLayoutEdge, type GraphLayoutNode } from '../types';
23
23
 
24
24
  /**
25
25
  * Return value or invoke function.
@@ -50,7 +50,7 @@ const maybeForce = <Config>(
50
50
  cb: (config: Config) => Force<any, any>,
51
51
  defaultValue = undefined,
52
52
  ) => {
53
- const value = typeof options === 'boolean' ? (options ? {} : undefined) : options ?? defaultValue;
53
+ const value = typeof options === 'boolean' ? (options ? {} : undefined) : (options ?? defaultValue);
54
54
  if (value) {
55
55
  return cb(value);
56
56
  }
@@ -197,7 +197,8 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
197
197
  }
198
198
 
199
199
  this._simulation
200
- .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'))
201
202
  .velocityDecay(0.3)
202
203
  .alphaDecay(1 - Math.pow(0.001, 1 / 300))
203
204
  .alpha(1)
@@ -222,12 +223,15 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
222
223
  this.restart();
223
224
  }
224
225
 
225
- override onUpdate(graph?: Graph): void {
226
+ override onUpdate(graph?: Graph.Any): void {
226
227
  log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
227
228
  this._simulation.stop();
228
229
  this.mergeData(graph);
229
230
  this.updateLayout();
230
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');
231
235
  this.restart();
232
236
  }
233
237
 
@@ -2,7 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type Force, forceX, forceY, type SimulationLinkDatum, type SimulationNodeDatum } from 'd3';
5
+ import { type Force, type SimulationLinkDatum, type SimulationNodeDatum, forceX, forceY } from 'd3';
6
6
 
7
7
  export type ForcePointOptions = {
8
8
  x?: number;
@@ -5,9 +5,9 @@
5
5
  import { type Graph } from '@dxos/graph';
6
6
  import { log } from '@dxos/log';
7
7
 
8
+ import { type GraphLayoutNode } from '../types';
8
9
  import { type GraphProjectorOptions } from './graph-projector';
9
10
  import { GraphRadialProjector, layoutRadial, updateNode } from './graph-radial-projector';
10
- import { type GraphLayoutNode } from '../types';
11
11
 
12
12
  export type GraphHierarchicalProjectorOptions = GraphProjectorOptions & {
13
13
  radius?: number;
@@ -19,14 +19,15 @@ export class GraphHierarchicalProjector<
19
19
  NodeData = any,
20
20
  Options extends GraphHierarchicalProjectorOptions = any,
21
21
  > extends GraphRadialProjector<NodeData, Options> {
22
- protected override onUpdate(graph?: Graph) {
22
+ protected override onUpdate(graph?: Graph.Any) {
23
23
  log('onUpdate', {
24
24
  graph: { nodes: graph?.nodes.length, edges: graph?.edges.length },
25
- selection: this.selection?.selected.value,
25
+ selection: this.selection?.getSelectedIds(),
26
26
  });
27
27
 
28
28
  this.mergeData(graph);
29
- const selected = this.selection?.selected.value?.[0];
29
+ this.emitUpdate('topology');
30
+ const selected = this.selection?.getSelectedIds()[0];
30
31
  if (selected) {
31
32
  const node = this.layout.graph.nodes.find((node) => node.id === selected);
32
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
+ }
@@ -2,11 +2,11 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type SelectionModel, type Graph } from '@dxos/graph';
5
+ import { type Graph, type SelectionModel } from '@dxos/graph';
6
6
 
7
- import { Projector, type ProjectorOptions } from './projector';
8
7
  import { type SVGContext } from '../../hooks';
9
- import { emptyGraph, type GraphLayout, type GraphLayoutNode } from '../types';
8
+ import { type GraphLayout, type GraphLayoutNode, emptyGraph } from '../types';
9
+ import { Projector, type ProjectorOptions } from './projector';
10
10
 
11
11
  export type GraphProjectorOptions = ProjectorOptions & {};
12
12
 
@@ -14,7 +14,7 @@ export type GraphProjectorOptions = ProjectorOptions & {};
14
14
  * Base class for graph projectors.
15
15
  */
16
16
  export abstract class GraphProjector<NodeData = any, Options extends GraphProjectorOptions = any> extends Projector<
17
- Graph,
17
+ Graph.Any,
18
18
  GraphLayout<NodeData>,
19
19
  Options
20
20
  > {
@@ -59,7 +59,7 @@ export abstract class GraphProjector<NodeData = any, Options extends GraphProjec
59
59
  * Merge external data with internal representation (e.g., so force properties like position are preserved).
60
60
  * @param data
61
61
  */
62
- protected mergeData(data: Graph = emptyGraph) {
62
+ protected mergeData(data: Graph.Any = emptyGraph) {
63
63
  // Merge nodes.
64
64
  const nodes: GraphLayoutNode[] = data.nodes.map((node) => {
65
65
  let current: GraphLayoutNode = this._layout.graph.nodes.find((n) => n.id === this.options.idAccessor(node));
@@ -70,6 +70,13 @@ export abstract class GraphProjector<NodeData = any, Options extends GraphProjec
70
70
  }
71
71
 
72
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;
73
80
  return current;
74
81
  });
75
82
 
@@ -2,14 +2,14 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { easeCubic, timer, type Timer } from 'd3';
5
+ import { type Timer, easeCubic, timer } from 'd3';
6
6
 
7
7
  import { type Graph } from '@dxos/graph';
8
8
  import { log } from '@dxos/log';
9
9
 
10
- import { GraphProjector, type GraphProjectorOptions } from './graph-projector';
11
10
  import { type Point } from '../../util';
12
11
  import { type GraphLayoutNode } from '../types';
12
+ import { GraphProjector, type GraphProjectorOptions } from './graph-projector';
13
13
 
14
14
  export type GraphRadialProjectorOptions = GraphProjectorOptions & {
15
15
  radius?: number;
@@ -27,13 +27,20 @@ export class GraphRadialProjector<
27
27
  return undefined;
28
28
  }
29
29
 
30
- protected override onUpdate(graph?: Graph) {
30
+ protected override onUpdate(graph?: Graph.Any) {
31
31
  log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
32
32
  this.mergeData(graph);
33
+ // Bind enter/exit once before the tween starts; subsequent animate frames emit 'positions'.
34
+ this.emitUpdate('topology');
33
35
  this.doRadialLayout();
34
36
  }
35
37
 
36
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
+
37
44
  const start = Date.now();
38
45
  if (this.options.duration) {
39
46
  this._timer = timer(() => {
@@ -46,17 +53,38 @@ export class GraphRadialProjector<
46
53
  node.r = node.sr + (node.tr - node.sr) * d;
47
54
  });
48
55
 
49
- 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');
50
63
  if (t >= 1) {
51
64
  this._timer.stop();
52
65
  this._timer = undefined;
53
66
  }
54
67
  });
55
68
  } else {
56
- 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');
57
78
  }
58
79
  }
59
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
+
60
88
  protected override async onStop() {
61
89
  this._timer?.stop();
62
90
  this._timer = undefined;
@@ -5,9 +5,9 @@
5
5
  import { type Graph } from '@dxos/graph';
6
6
  import { log } from '@dxos/log';
7
7
 
8
+ import { type GraphLayoutNode } from '../types';
8
9
  import { type GraphProjectorOptions } from './graph-projector';
9
10
  import { GraphRadialProjector, layoutHorizontal, layoutRadial, updateNode } from './graph-radial-projector';
10
- import { type GraphLayoutNode } from '../types';
11
11
 
12
12
  export type GraphRelationalProjectorOptions = GraphProjectorOptions & {
13
13
  radius?: number;
@@ -19,14 +19,15 @@ export class GraphRelationalProjector<
19
19
  NodeData = any,
20
20
  Options extends GraphRelationalProjectorOptions = any,
21
21
  > extends GraphRadialProjector<NodeData, Options> {
22
- protected override onUpdate(graph?: Graph) {
22
+ protected override onUpdate(graph?: Graph.Any) {
23
23
  log('onUpdate', {
24
24
  graph: { nodes: graph?.nodes.length, edges: graph?.edges.length },
25
- selection: this.selection?.selected.value,
25
+ selection: this.selection?.getSelectedIds(),
26
26
  });
27
27
 
28
28
  this.mergeData(graph);
29
- const selected = this.selection?.selected.value?.[0];
29
+ this.emitUpdate('topology');
30
+ const selected = this.selection?.getSelectedIds()[0];
30
31
  if (selected) {
31
32
  const node = this.layout.graph.nodes.find((node) => node.id === selected);
32
33
  if (node) {