@dxos/react-ui-graph 0.8.4-main.fffef41 → 0.9.0

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 (138) 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 +2729 -592
  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 +2729 -592
  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 +23 -6
  18. package/dist/types/src/components/Graph/Graph.d.ts.map +1 -1
  19. package/dist/types/src/components/Graph/Graph.stories.d.ts +6 -6
  20. package/dist/types/src/components/Graph/Graph.stories.d.ts.map +1 -1
  21. package/dist/types/src/components/Mesh/Mesh.d.ts.map +1 -1
  22. package/dist/types/src/components/Mesh/Mesh.stories.d.ts.map +1 -1
  23. package/dist/types/src/components/SVG/FPS.d.ts +20 -0
  24. package/dist/types/src/components/SVG/FPS.d.ts.map +1 -0
  25. package/dist/types/src/components/SVG/Grid.d.ts.map +1 -1
  26. package/dist/types/src/components/SVG/Markers.d.ts.map +1 -1
  27. package/dist/types/src/components/SVG/Root.d.ts +8 -4
  28. package/dist/types/src/components/SVG/Root.d.ts.map +1 -1
  29. package/dist/types/src/components/SVG/SVG.d.ts +17 -18
  30. package/dist/types/src/components/SVG/SVG.d.ts.map +1 -1
  31. package/dist/types/src/components/SVG/Svg.stories.d.ts +1 -1
  32. package/dist/types/src/components/SVG/Svg.stories.d.ts.map +1 -1
  33. package/dist/types/src/fx/fx.stories.d.ts +3 -3
  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 +65 -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.map +1 -1
  42. package/dist/types/src/graph/projector/graph-force-projector.d.ts +1 -1
  43. package/dist/types/src/graph/projector/graph-force-projector.d.ts.map +1 -1
  44. package/dist/types/src/graph/projector/graph-forces.d.ts.map +1 -1
  45. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts +1 -1
  46. package/dist/types/src/graph/projector/graph-hierarchical-projector.d.ts.map +1 -1
  47. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts +23 -0
  48. package/dist/types/src/graph/projector/graph-lattice-projector.d.ts.map +1 -0
  49. package/dist/types/src/graph/projector/graph-plexus-projector.d.ts +67 -0
  50. package/dist/types/src/graph/projector/graph-plexus-projector.d.ts.map +1 -0
  51. package/dist/types/src/graph/projector/graph-plexus-projector.test.d.ts +2 -0
  52. package/dist/types/src/graph/projector/graph-plexus-projector.test.d.ts.map +1 -0
  53. package/dist/types/src/graph/projector/graph-projector.d.ts +10 -2
  54. package/dist/types/src/graph/projector/graph-projector.d.ts.map +1 -1
  55. package/dist/types/src/graph/projector/graph-radial-projector.d.ts +7 -1
  56. package/dist/types/src/graph/projector/graph-radial-projector.d.ts.map +1 -1
  57. package/dist/types/src/graph/projector/graph-relational-projector.d.ts +1 -1
  58. package/dist/types/src/graph/projector/graph-relational-projector.d.ts.map +1 -1
  59. package/dist/types/src/graph/projector/graph-swarm-projector.d.ts +72 -0
  60. package/dist/types/src/graph/projector/graph-swarm-projector.d.ts.map +1 -0
  61. package/dist/types/src/graph/projector/index.d.ts +5 -0
  62. package/dist/types/src/graph/projector/index.d.ts.map +1 -1
  63. package/dist/types/src/graph/projector/projector.d.ts +10 -1
  64. package/dist/types/src/graph/projector/projector.d.ts.map +1 -1
  65. package/dist/types/src/graph/renderer/bullets.d.ts.map +1 -1
  66. package/dist/types/src/graph/renderer/graph-renderer.d.ts +41 -1
  67. package/dist/types/src/graph/renderer/graph-renderer.d.ts.map +1 -1
  68. package/dist/types/src/graph/renderer/index.d.ts +1 -0
  69. package/dist/types/src/graph/renderer/index.d.ts.map +1 -1
  70. package/dist/types/src/graph/renderer/labels.d.ts +33 -0
  71. package/dist/types/src/graph/renderer/labels.d.ts.map +1 -0
  72. package/dist/types/src/graph/renderer/renderer.d.ts +12 -1
  73. package/dist/types/src/graph/renderer/renderer.d.ts.map +1 -1
  74. package/dist/types/src/graph/types.d.ts +15 -1
  75. package/dist/types/src/graph/types.d.ts.map +1 -1
  76. package/dist/types/src/hooks/useGrid.d.ts.map +1 -1
  77. package/dist/types/src/hooks/useStateRef.d.ts.map +1 -1
  78. package/dist/types/src/hooks/useSvgContext.d.ts.map +1 -1
  79. package/dist/types/src/hooks/useZoom.d.ts.map +1 -1
  80. package/dist/types/src/stories/experimental.stories.d.ts +7 -0
  81. package/dist/types/src/stories/experimental.stories.d.ts.map +1 -0
  82. package/dist/types/src/stories/hooks.stories.d.ts +4 -3
  83. package/dist/types/src/stories/hooks.stories.d.ts.map +1 -1
  84. package/dist/types/src/testing/data.d.ts +5 -5
  85. package/dist/types/src/testing/data.d.ts.map +1 -1
  86. package/dist/types/src/testing/hooks.d.ts +2 -16
  87. package/dist/types/src/testing/hooks.d.ts.map +1 -1
  88. package/dist/types/src/testing/model.d.ts +4 -8
  89. package/dist/types/src/testing/model.d.ts.map +1 -1
  90. package/dist/types/src/util/events.d.ts.map +1 -1
  91. package/dist/types/src/util/fraction.d.ts +1 -1
  92. package/dist/types/src/util/fraction.d.ts.map +1 -1
  93. package/dist/types/src/util/points.d.ts.map +1 -1
  94. package/dist/types/src/util/scale.d.ts.map +1 -1
  95. package/dist/types/src/util/screen.d.ts.map +1 -1
  96. package/dist/types/src/util/vector.d.ts.map +1 -1
  97. package/dist/types/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +33 -35
  99. package/src/components/Graph/Graph.stories.tsx +45 -39
  100. package/src/components/Graph/Graph.tsx +126 -23
  101. package/src/components/Mesh/Mesh.stories.tsx +8 -7
  102. package/src/components/Mesh/Mesh.tsx +43 -35
  103. package/src/components/SVG/FPS.tsx +91 -0
  104. package/src/components/SVG/Grid.tsx +1 -1
  105. package/src/components/SVG/Root.tsx +42 -9
  106. package/src/components/SVG/SVG.tsx +14 -3
  107. package/src/components/SVG/Svg.stories.tsx +4 -5
  108. package/src/fx/fx.stories.tsx +7 -8
  109. package/src/graph/projector/graph-bundle-projector.ts +210 -0
  110. package/src/graph/projector/graph-cluster-projector.ts +337 -0
  111. package/src/graph/projector/graph-drag.ts +0 -1
  112. package/src/graph/projector/graph-force-projector.ts +7 -3
  113. package/src/graph/projector/graph-hierarchical-projector.ts +4 -4
  114. package/src/graph/projector/graph-lattice-projector.ts +86 -0
  115. package/src/graph/projector/graph-plexus-projector.test.ts +102 -0
  116. package/src/graph/projector/graph-plexus-projector.ts +309 -0
  117. package/src/graph/projector/graph-projector.ts +24 -4
  118. package/src/graph/projector/graph-radial-projector.ts +31 -4
  119. package/src/graph/projector/graph-relational-projector.ts +4 -4
  120. package/src/graph/projector/graph-swarm-projector.ts +373 -0
  121. package/src/graph/projector/index.ts +5 -0
  122. package/src/graph/projector/projector.ts +12 -3
  123. package/src/graph/renderer/graph-renderer.ts +289 -31
  124. package/src/graph/renderer/index.ts +1 -0
  125. package/src/graph/renderer/labels.ts +138 -0
  126. package/src/graph/renderer/renderer.ts +15 -4
  127. package/src/graph/types.ts +15 -1
  128. package/src/stories/experimental.stories.tsx +446 -0
  129. package/src/stories/hooks.stories.tsx +21 -10
  130. package/src/testing/data.ts +14 -14
  131. package/src/testing/hooks.ts +3 -4
  132. package/src/testing/model.ts +6 -6
  133. package/src/util/fraction.ts +1 -1
  134. package/styles/graph.css +341 -43
  135. package/dist/lib/browser/chunk-XWA2XJDX.mjs +0 -955
  136. package/dist/lib/browser/chunk-XWA2XJDX.mjs.map +0 -7
  137. package/dist/lib/node-esm/chunk-3RLSFEEV.mjs +0 -957
  138. package/dist/lib/node-esm/chunk-3RLSFEEV.mjs.map +0 -7
@@ -0,0 +1,337 @@
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
+ /**
99
+ * Built-in click semantics: clicking a synthetic root / group node toggles its subtree.
100
+ * Leaf clicks fall through to the consumer's `onSelect` (returns `false`).
101
+ */
102
+ override handleNodeClick(node: GraphLayoutNode<NodeData>, _event: MouseEvent): boolean {
103
+ if (node.type !== CLUSTER_NODE_TYPE_ROOT && node.type !== CLUSTER_NODE_TYPE_GROUP) {
104
+ return false;
105
+ }
106
+ this.toggleCollapsed(node.id);
107
+ return true;
108
+ }
109
+
110
+ /** Toggle collapse state for a synthetic node id. Triggers a topology re-emit. */
111
+ toggleCollapsed(id: string): void {
112
+ if (this.#collapsed.has(id)) {
113
+ this.#collapsed.delete(id);
114
+ } else {
115
+ this.#collapsed.add(id);
116
+ }
117
+ // Re-run the layout against the current model data so hidden / re-shown nodes are
118
+ // exited / entered through the renderer's join.
119
+ this.doClusterLayout();
120
+ this.emitUpdate('topology');
121
+ this.animate();
122
+ }
123
+
124
+ /** Whether a synthetic-node id is currently collapsed. */
125
+ isCollapsed(id: string): boolean {
126
+ return this.#collapsed.has(id);
127
+ }
128
+
129
+ protected override onUpdate(graph?: Graph.Any) {
130
+ log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
131
+ this.mergeData(graph);
132
+ // Snapshot the full data-node set right after mergeData — before doClusterLayout
133
+ // overwrites `layout.graph.nodes` with the filtered (collapse-aware) view.
134
+ this.#dataNodes = [...this.layout.graph.nodes];
135
+ this.doClusterLayout();
136
+ this.emitUpdate('topology');
137
+ this.animate();
138
+ }
139
+
140
+ /**
141
+ * Recompute each hierarchy edge's `path` from current cartesian source/target positions,
142
+ * so the curves track moving endpoints during a cross-variant tween (e.g. force → cluster)
143
+ * instead of being pinned to the final polar layout.
144
+ */
145
+ protected override onTickFrame(_t: number): void {
146
+ for (const edge of this.layout.graph.edges) {
147
+ if (edge.type !== 'hierarchy') {
148
+ continue;
149
+ }
150
+ const { source, target } = edge;
151
+ const s = cartesianToPolar(source.x ?? 0, source.y ?? 0);
152
+ const t = cartesianToPolar(target.x ?? 0, target.y ?? 0);
153
+ edge.path = linkPath({ source: { x: s.angle, y: s.radius }, target: { x: t.angle, y: t.radius } });
154
+ }
155
+ }
156
+
157
+ private doClusterLayout() {
158
+ if (!this.context.size) {
159
+ return;
160
+ }
161
+
162
+ // Read from the post-mergeData snapshot, not from `layout.graph.nodes`. The layout
163
+ // view is a FILTERED projection (hidden leaves are dropped so the renderer's d3 join
164
+ // fades them out); reading from it would shrink monotonically across collapses and
165
+ // hidden leaves could never reappear on expand. The snapshot also avoids the
166
+ // "synthetic root re-pushed as its own child → d3.hierarchy infinite recursion" hang
167
+ // we'd otherwise hit, because synthetic stubs were never in this set to begin with.
168
+ const dataNodes = this.#dataNodes;
169
+ if (!dataNodes.length) {
170
+ return;
171
+ }
172
+
173
+ const groupOf = this.options.groupOf;
174
+ const rootId = this.options.rootId ?? ROOT_ID;
175
+
176
+ // Synthesize the hierarchy: root → groups → leaves. `groupKey` is carried on synthetic
177
+ // group HierNodes so the rendered stub can pick up the original groupOf return value
178
+ // (the typename, in plugin-explorer's case) as its display label.
179
+ type HierNode = { id: string; parent?: string; node?: GraphLayoutNode<NodeData>; groupKey?: string };
180
+ const items: HierNode[] = [{ id: rootId }];
181
+ const groupIds = new Map<string, string>();
182
+ // Collapsed root → render only the root circle (no groups, no leaves).
183
+ const rootCollapsed = this.#collapsed.has(rootId);
184
+ if (!rootCollapsed) {
185
+ for (const node of dataNodes) {
186
+ const key = groupOf?.(node);
187
+ let parent = rootId;
188
+ if (key !== undefined) {
189
+ let groupId = groupIds.get(key);
190
+ if (!groupId) {
191
+ groupId = `${GROUP_PREFIX}${key}`;
192
+ groupIds.set(key, groupId);
193
+ items.push({ id: groupId, parent: rootId, groupKey: key });
194
+ }
195
+ parent = groupId;
196
+ }
197
+ // Collapsed group → drop its leaves. The group itself still renders so the user
198
+ // can click it again to expand.
199
+ if (this.#collapsed.has(parent)) {
200
+ continue;
201
+ }
202
+ items.push({ id: node.id, parent, node });
203
+ }
204
+ }
205
+
206
+ const childrenByParent = new Map<string, HierNode[]>();
207
+ for (const item of items) {
208
+ if (item.parent) {
209
+ const list = childrenByParent.get(item.parent) ?? [];
210
+ list.push(item);
211
+ childrenByParent.set(item.parent, list);
212
+ }
213
+ }
214
+
215
+ const root = hierarchy<HierNode>({ id: rootId }, (d) => childrenByParent.get(d.id) ?? []);
216
+
217
+ const { width, height } = this.context.size;
218
+ const margin = this.options.margin ?? 80;
219
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
220
+
221
+ d3Cluster<HierNode>()
222
+ .size([2 * Math.PI, ringRadius])
223
+ // Tighter sibling spacing at deeper levels — matches the previous standalone
224
+ // RadialTree component. Without the `/depth` divisor, large groups span a
225
+ // wide angular arc; the linkRadial(curveBumpPolar) curve to a leaf at the
226
+ // edge of that arc then has its control points placed far apart in
227
+ // cartesian, producing a wide swoop that visually misses the target.
228
+ .separation((a: any, b: any) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
229
+
230
+ const leafR = this.options.leafRadius ?? 4;
231
+ const groupR = this.options.groupRadius ?? 3;
232
+ const rootR = this.options.rootRadius ?? 5;
233
+
234
+ // Index any synthetic root / group stubs from the previous layout pass so we can
235
+ // REUSE them (preserving their current x/y as the tween start) instead of creating
236
+ // fresh `{x:0,y:0}` stubs that would snap the DOM element to the origin first.
237
+ const prevStubsById = new Map<string, GraphLayoutNode<NodeData>>();
238
+ for (const node of this.layout.graph.nodes) {
239
+ if (node.type === CLUSTER_NODE_TYPE_ROOT || node.type === CLUSTER_NODE_TYPE_GROUP) {
240
+ prevStubsById.set(node.id, node);
241
+ }
242
+ }
243
+
244
+ // Build the new node set: existing data nodes (re-positioned), plus synthetic root + groups.
245
+ const syntheticNodes = new Map<string, GraphLayoutNode<NodeData>>();
246
+ root.each((d: any) => {
247
+ const id = d.data.id;
248
+ const angle = d.x;
249
+ const radius = d.y;
250
+ const x = Math.cos(angle - Math.PI / 2) * radius;
251
+ const y = Math.sin(angle - Math.PI / 2) * radius;
252
+
253
+ if (d.data.node) {
254
+ // Real leaf — tween its position and mark visible.
255
+ updateNode(d.data.node, [x, y], leafR);
256
+ (d.data.node as any).type = CLUSTER_NODE_TYPE_LEAF;
257
+ (d.data.node as any).hidden = false;
258
+ } else {
259
+ // Synthetic root or group. On the very first cluster mount the stub is brand-new
260
+ // so seed it at origin — root stays put while groups grow outward. On subsequent
261
+ // mounts (toggleCollapsed) we reuse the previous-render stub so its current x/y
262
+ // becomes the tween start; otherwise the DOM element would jump to origin before
263
+ // animating to the new target position.
264
+ const isRoot = id === rootId;
265
+ const stub = prevStubsById.get(id) ?? ({ id, x: 0, y: 0 } as GraphLayoutNode<NodeData>);
266
+ updateNode(stub, [x, y], isRoot ? rootR : groupR);
267
+ stub.type = isRoot ? CLUSTER_NODE_TYPE_ROOT : CLUSTER_NODE_TYPE_GROUP;
268
+ // Surface a display label so renderNode callbacks don't have to parse internal ids.
269
+ if (isRoot) {
270
+ stub.label = this.options.rootLabel;
271
+ } else if (d.data.groupKey !== undefined) {
272
+ stub.label = this.options.groupLabel ? this.options.groupLabel(d.data.groupKey) : d.data.groupKey;
273
+ }
274
+ syntheticNodes.set(id, stub);
275
+ }
276
+ });
277
+
278
+ // Collapse animation: hidden leaves stay in the layout but their target position is
279
+ // the parent group's target (or root for ungrouped leaves). animate() then tweens them
280
+ // toward the parent — visually "absorbed in", while their opacity transitions to 0 via
281
+ // the renderer's hidden-flag transition. On re-expand they tween back out to their ring.
282
+ const visibleLeafIds = new Set<string>();
283
+ for (const item of items) {
284
+ if (item.node) {
285
+ visibleLeafIds.add(item.id);
286
+ }
287
+ }
288
+ for (const node of dataNodes) {
289
+ if (visibleLeafIds.has(node.id)) {
290
+ continue;
291
+ }
292
+ // Hidden leaf — find its parent group's target. groupOf may have changed since the
293
+ // last layout pass (rare in practice but cheap to handle), so re-compute the key.
294
+ const key = groupOf?.(node);
295
+ const parentId = key !== undefined && groupIds.has(key) ? (groupIds.get(key) as string) : rootId;
296
+ const parentStub = syntheticNodes.get(parentId);
297
+ const targetX = (parentStub as any)?.tx ?? 0;
298
+ const targetY = (parentStub as any)?.ty ?? 0;
299
+ updateNode(node, [targetX, targetY], leafR);
300
+ (node as any).type = CLUSTER_NODE_TYPE_LEAF;
301
+ node.hidden = true;
302
+ }
303
+
304
+ // Compose the rendered node list: synthetic structure first (so leaves draw on top).
305
+ const nextNodes: GraphLayoutNode<NodeData>[] = [];
306
+ for (const stub of syntheticNodes.values()) {
307
+ nextNodes.push(stub);
308
+ }
309
+ for (const node of dataNodes) {
310
+ nextNodes.push(node);
311
+ }
312
+ this.layout.graph.nodes = nextNodes;
313
+
314
+ // Build hierarchy edges referencing source/target nodes. The `path` is filled by
315
+ // onTickFrame (and again per tween frame) from current cartesian positions, so we
316
+ // don't precompute it here — leaving it undefined would briefly produce a straight
317
+ // line on first paint, but the tween's first tick (t=0) writes the correct path
318
+ // before the renderer's positions-emit reaches the DOM.
319
+ const hierarchyEdges: GraphLayoutEdge<NodeData>[] = [];
320
+ root.links().forEach((link: any) => {
321
+ const sid = link.source.data.id;
322
+ const tid = link.target.data.id;
323
+ const sourceNode = link.source.data.node ?? syntheticNodes.get(sid);
324
+ const targetNode = link.target.data.node ?? syntheticNodes.get(tid);
325
+ hierarchyEdges.push({
326
+ id: `${HIER_EDGE_PREFIX}${sid}->${tid}`,
327
+ type: 'hierarchy',
328
+ source: sourceNode!,
329
+ target: targetNode!,
330
+ data: undefined,
331
+ });
332
+ });
333
+ this.layout.graph.edges = hierarchyEdges;
334
+ // Seed initial paths so the topology emit has correct geometry to enter into the DOM.
335
+ this.onTickFrame(0);
336
+ }
337
+ }
@@ -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
 
@@ -154,6 +153,7 @@ export type GraphForceProjectorOptions = GraphProjectorOptions & {
154
153
  /**
155
154
  * D3 force directed graph layout using d3 simulation..
156
155
  */
156
+ // TODO(burdon): Rename ForceGraphProjector.
157
157
  export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData, GraphForceProjectorOptions> {
158
158
  // https://github.com/d3/d3-force
159
159
  private _simulation = forceSimulation<GraphLayoutNode, GraphLayoutEdge>();
@@ -198,7 +198,8 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
198
198
  }
199
199
 
200
200
  this._simulation
201
- .on('tick', () => propagating && this.emitUpdate())
201
+ // Each tick only mutates `x/y` — emit 'positions' so the renderer can fast-path.
202
+ .on('tick', () => propagating && this.emitUpdate('positions'))
202
203
  .velocityDecay(0.3)
203
204
  .alphaDecay(1 - Math.pow(0.001, 1 / 300))
204
205
  .alpha(1)
@@ -223,12 +224,15 @@ export class GraphForceProjector<NodeData = any> extends GraphProjector<NodeData
223
224
  this.restart();
224
225
  }
225
226
 
226
- override onUpdate(graph?: Graph): void {
227
+ override onUpdate(graph?: Graph.Any): void {
227
228
  log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
228
229
  this._simulation.stop();
229
230
  this.mergeData(graph);
230
231
  this.updateLayout();
231
232
  this.updateForces(this.forces);
233
+ // Signal topology change so the renderer rebinds enter/exit and runs attribute callbacks once.
234
+ // Subsequent ticks emit 'positions' and skip the expensive path.
235
+ this.emitUpdate('topology');
232
236
  this.restart();
233
237
  }
234
238
 
@@ -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
+ }
@@ -0,0 +1,102 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { type Graph } from '@dxos/graph';
8
+
9
+ import { SVGContext } from '../../hooks';
10
+ import { type GraphLayoutEdge } from '../types';
11
+ import {
12
+ GraphPlexusProjector,
13
+ PLEXUS_NODE_TYPE_FOCUS,
14
+ PLEXUS_NODE_TYPE_OBJECT,
15
+ PLEXUS_NODE_TYPE_RELATION,
16
+ type PlexusRelation,
17
+ } from './graph-plexus-projector';
18
+
19
+ const makeContext = () => {
20
+ const context = new SVGContext({});
21
+ context.setSize({ width: 800, height: 600 });
22
+ return context;
23
+ };
24
+
25
+ // Mirrors plugin-explorer's relationOf: each relation/ref gets separate nodes for the outgoing
26
+ // (focus is source, `→`) and incoming (focus is target, `←`) directions.
27
+ const relationOf = (edge: GraphLayoutEdge, focusId: string): PlexusRelation | undefined => {
28
+ const outgoing = edge.source.id === focusId;
29
+ const incoming = edge.target.id === focusId;
30
+ if (!outgoing && !incoming) {
31
+ return undefined;
32
+ }
33
+ const direction = outgoing ? 'out' : 'in';
34
+ const arrow = outgoing ? '→' : '←';
35
+ if (edge.type === 'relation') {
36
+ return { key: `relation:${direction}:HasRelationship`, label: `HasRelationship ${arrow}` };
37
+ }
38
+ if (edge.type === 'ref') {
39
+ const property = (edge.data as any)?.property ?? 'references';
40
+ return { key: `ref:${direction}:${property}`, label: `${property} ${arrow}` };
41
+ }
42
+ return undefined;
43
+ };
44
+
45
+ const graph: Graph.Any = {
46
+ nodes: [{ id: 'p1' }, { id: 'org' }, { id: 'p2' }, { id: 'p3' }, { id: 'p4' }, { id: 'other' }] as any,
47
+ edges: [
48
+ // Outgoing ref from focus → grouped under "organization →".
49
+ { id: 'e1', type: 'ref', source: 'p1', target: 'org', data: { property: 'organization' } },
50
+ // Outgoing relations from focus → grouped under "HasRelationship →".
51
+ { id: 'e2', type: 'relation', source: 'p1', target: 'p2', data: {} },
52
+ { id: 'e3', type: 'relation', source: 'p1', target: 'p3', data: {} },
53
+ // Incoming relation to focus → separate "HasRelationship ←" node.
54
+ { id: 'e4', type: 'relation', source: 'p4', target: 'p1', data: {} },
55
+ // Edge NOT incident to focus → ignored.
56
+ { id: 'e5', type: 'ref', source: 'other', target: 'org', data: { property: 'organization' } },
57
+ ] as any,
58
+ };
59
+
60
+ describe('GraphPlexusProjector', () => {
61
+ test('fans the focus neighbourhood out by relation and direction', ({ expect }) => {
62
+ const projector = new GraphPlexusProjector(makeContext(), { focus: 'p1', relationOf });
63
+ projector.updateData(graph);
64
+
65
+ const nodes = projector.layout.graph.nodes;
66
+ const byType = (type: string) => nodes.filter((node) => node.type === type);
67
+
68
+ // Exactly one focus node.
69
+ const focus = byType(PLEXUS_NODE_TYPE_FOCUS);
70
+ expect(focus).toHaveLength(1);
71
+ expect(focus[0].id).toBe('p1');
72
+ expect(focus[0].x).toBe(0);
73
+ expect(focus[0].y).toBe(0);
74
+
75
+ // Three relation nodes: outgoing relation, incoming relation, outgoing ref.
76
+ const relations = byType(PLEXUS_NODE_TYPE_RELATION);
77
+ expect(relations.map((node) => node.label).sort()).toEqual([
78
+ 'HasRelationship ←',
79
+ 'HasRelationship →',
80
+ 'organization →',
81
+ ]);
82
+
83
+ // Four object leaves (org, p2, p3 outgoing; p4 incoming); the non-incident edge is excluded.
84
+ const objects = byType(PLEXUS_NODE_TYPE_OBJECT);
85
+ expect(objects.map((node) => node.id).sort()).toEqual(['org', 'p2', 'p3', 'p4']);
86
+ expect(nodes.find((node) => node.id === 'other')).toBeUndefined();
87
+
88
+ // Hierarchy edges: focus→relation (3) + relation→object (4) = 7.
89
+ const edges = projector.layout.graph.edges;
90
+ expect(edges).toHaveLength(7);
91
+ expect(edges.every((edge) => edge.type === 'hierarchy')).toBe(true);
92
+ });
93
+
94
+ test('degrades to a ring when the focus is absent', ({ expect }) => {
95
+ const projector = new GraphPlexusProjector(makeContext(), { focus: 'missing', relationOf });
96
+ projector.updateData(graph);
97
+
98
+ // All nodes laid out, no relation structure.
99
+ expect(projector.layout.graph.nodes).toHaveLength(graph.nodes.length);
100
+ expect(projector.layout.graph.edges).toHaveLength(0);
101
+ });
102
+ });