@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,91 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import React, { useEffect, useState } from 'react';
6
+
7
+ import { type ThemedClassName } from '@dxos/react-ui';
8
+ import { mx } from '@dxos/ui-theme';
9
+
10
+ import { useSvgContext } from '../../hooks';
11
+
12
+ export type FPSCorner = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
13
+
14
+ export type FPSProps = ThemedClassName<{
15
+ /** Which corner of the SVG viewport to anchor the readout to. */
16
+ corner?: FPSCorner;
17
+ /** Pixels of padding from the chosen corner. */
18
+ margin?: number;
19
+ }>;
20
+
21
+ const PADDING = 8;
22
+
23
+ /**
24
+ * Frame-rate readout — drops into an `<SVG.Root>` alongside `<SVG.Graph>` to display a
25
+ * rolling 1-second average of the browser's repaint rate. Self-contained: runs its own
26
+ * `requestAnimationFrame` loop, so the number reflects actual render rate independent of
27
+ * whichever projector is driving the graph.
28
+ *
29
+ * Anchored to a corner of the SVG viewBox via the `<text>`'s `text-anchor` and `dy`
30
+ * attributes — re-renders on `context.resized` so the position tracks container resizes.
31
+ */
32
+ export const FPS = ({ classNames, corner = 'top-right', margin = PADDING }: FPSProps) => {
33
+ const context = useSvgContext();
34
+ const [size, setSize] = useState(context.size);
35
+ const [fps, setFps] = useState<number | null>(null);
36
+
37
+ // Keep `size` in sync with the SVG context so the corner anchor follows container resizes.
38
+ useEffect(() => {
39
+ setSize(context.size);
40
+ return context.resized.on((ctx) => setSize(ctx.size));
41
+ }, [context]);
42
+
43
+ // Independent rAF loop — measures the browser's actual repaint rate, not any specific
44
+ // projector's tick rate. Rolling 1-second window so the number is responsive but stable.
45
+ useEffect(() => {
46
+ let frames = 0;
47
+ let windowStart = performance.now();
48
+ let rafId = 0;
49
+ const loop = (now: number) => {
50
+ frames++;
51
+ const elapsed = now - windowStart;
52
+ if (elapsed >= 1000) {
53
+ setFps((frames * 1000) / elapsed);
54
+ frames = 0;
55
+ windowStart = now;
56
+ }
57
+ rafId = requestAnimationFrame(loop);
58
+ };
59
+ rafId = requestAnimationFrame(loop);
60
+ return () => cancelAnimationFrame(rafId);
61
+ }, []);
62
+
63
+ if (!size) {
64
+ return null;
65
+ }
66
+
67
+ // The SVG.Root viewBox is centered ([-w/2, w/2] × [-h/2, h/2]); offset from the chosen
68
+ // corner inward by `margin` and pick the corresponding text-anchor / dominant-baseline.
69
+ const halfW = size.width / 2;
70
+ const halfH = size.height / 2;
71
+ const left = corner === 'top-left' || corner === 'bottom-left';
72
+ const top = corner === 'top-left' || corner === 'top-right';
73
+ const x = left ? -halfW + margin : halfW - margin;
74
+ const y = top ? -halfH + margin : halfH - margin;
75
+ const textAnchor = left ? 'start' : 'end';
76
+ const dominantBaseline = top ? 'hanging' : 'alphabetic';
77
+
78
+ return (
79
+ <g className='dx-fps' style={{ pointerEvents: 'none' }}>
80
+ <text
81
+ x={x}
82
+ y={y}
83
+ textAnchor={textAnchor}
84
+ dominantBaseline={dominantBaseline}
85
+ className={mx('font-mono text-xs fill-neutral-500 tabular-nums', classNames)}
86
+ >
87
+ {fps == null ? '— fps' : `${fps.toFixed(0)} fps`}
88
+ </text>
89
+ </g>
90
+ );
91
+ };
@@ -5,7 +5,7 @@
5
5
  import React from 'react';
6
6
 
7
7
  import { type ThemedClassName } from '@dxos/react-ui';
8
- import { mx } from '@dxos/react-ui-theme';
8
+ import { mx } from '@dxos/ui-theme';
9
9
 
10
10
  import { type GridOptions, useGrid } from '../../hooks';
11
11
 
@@ -3,26 +3,59 @@
3
3
  //
4
4
 
5
5
  import { select } from 'd3';
6
- import React, { type PropsWithChildren, forwardRef, useEffect, useImperativeHandle, useMemo } from 'react';
7
- import { useResizeDetector } from 'react-resize-detector';
6
+ import React, {
7
+ type ComponentPropsWithoutRef,
8
+ type PropsWithChildren,
9
+ forwardRef,
10
+ useEffect,
11
+ useImperativeHandle,
12
+ useMemo,
13
+ useState,
14
+ } from 'react';
8
15
 
9
16
  import { type ThemedClassName } from '@dxos/react-ui';
10
- import { mx } from '@dxos/react-ui-theme';
17
+ import { composableProps } from '@dxos/react-ui';
18
+ import { mx } from '@dxos/ui-theme';
11
19
 
12
20
  import { SVGContext, type SVGContextOptions, SVGContextProvider } from '../../hooks';
13
21
 
14
- export type RootProps = ThemedClassName<PropsWithChildren<SVGContextOptions>>;
22
+ export type RootProps = ThemedClassName<PropsWithChildren<SVGContextOptions & ComponentPropsWithoutRef<'div'>>>;
15
23
 
16
24
  /**
17
25
  * Makes the SVG context available to child nodes.
18
26
  * Automatically resizes the SVG element, which expands to fit the container.
27
+ *
28
+ * NOTE: Uses `ResizeObserver` directly rather than `react-resize-detector` — the latter's
29
+ * `useResizeDetector` was flaky in our Storybook environment (sometimes never fired its
30
+ * initial measurement), leaving the SVG stuck at `opacity-0` with no rendered content.
19
31
  */
20
- export const Root = forwardRef<SVGContext, RootProps>(({ classNames, children, ...props }, ref) => {
21
- const { ref: containerRef, width = 0, height = 0 } = useResizeDetector({ refreshRate: 200 });
32
+ export const Root = forwardRef<SVGContext, RootProps>(({ children, scale, centered, ...props }, ref) => {
33
+ const [container, setContainer] = useState<HTMLDivElement | null>(null);
34
+ const [size, setSize] = useState<{ width: number; height: number }>({ width: 0, height: 0 });
35
+
36
+ useEffect(() => {
37
+ if (!container) {
38
+ return;
39
+ }
40
+ const rect = container.getBoundingClientRect();
41
+ setSize({ width: rect.width, height: rect.height });
42
+ const observer = new ResizeObserver((entries) => {
43
+ const entry = entries[0];
44
+ if (!entry) {
45
+ return;
46
+ }
47
+ const { width, height } = entry.contentRect;
48
+ setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));
49
+ });
50
+ observer.observe(container);
51
+ return () => observer.disconnect();
52
+ }, [container]);
53
+
54
+ const { width, height } = size;
22
55
 
23
56
  const context = useMemo<SVGContext>(() => {
24
- return new SVGContext(props);
25
- }, [props.scale, props.centered]);
57
+ return new SVGContext({ scale, centered });
58
+ }, [scale, centered]);
26
59
 
27
60
  useImperativeHandle(ref, () => context, [context]);
28
61
 
@@ -41,7 +74,7 @@ export const Root = forwardRef<SVGContext, RootProps>(({ classNames, children, .
41
74
 
42
75
  return (
43
76
  <SVGContextProvider value={context}>
44
- <div ref={containerRef} className={mx('grid grow overflow-hidden', classNames)}>
77
+ <div {...composableProps(props, { classNames: 'dx-expander' })} ref={setContainer}>
45
78
  <svg
46
79
  xmlns='http://www.w3.org/2000/svg'
47
80
  ref={context.ref}
@@ -8,7 +8,7 @@ import { type ThemedClassName } from '@dxos/react-ui';
8
8
 
9
9
  import { Graph, type GraphProps as SVGGraphProps } from '../Graph';
10
10
  import { Mesh, type MeshProps as SVGMeshProps } from '../Mesh';
11
-
11
+ import { FPS, type FPSProps as SVGFPSProps } from './FPS';
12
12
  import { Grid, type GridProps as SVGGridProps } from './Grid';
13
13
  import { Markers, type MarkersProps as SVGMarkersProps } from './Markers';
14
14
  import { Root, type RootProps as SVGRootProps } from './Root';
@@ -16,13 +16,24 @@ import { type ZoomProps as SVGZoomProps, Zoom } from './Zoom';
16
16
 
17
17
  export type SVGProps = PropsWithChildren<ThemedClassName>;
18
18
 
19
- export const SVG = {
19
+ type SVG = {
20
+ Root: typeof Root;
21
+ Grid: typeof Grid;
22
+ Markers: typeof Markers;
23
+ Mesh: typeof Mesh;
24
+ Zoom: typeof Zoom;
25
+ Graph: typeof Graph;
26
+ FPS: typeof FPS;
27
+ };
28
+
29
+ export const SVG: SVG = {
20
30
  Root,
21
31
  Grid,
22
32
  Markers,
23
33
  Mesh,
24
34
  Zoom,
25
35
  Graph,
36
+ FPS,
26
37
  };
27
38
 
28
- export type { SVGRootProps, SVGGridProps, SVGMarkersProps, SVGZoomProps, SVGGraphProps, SVGMeshProps };
39
+ export type { SVGRootProps, SVGGridProps, SVGMarkersProps, SVGZoomProps, SVGGraphProps, SVGMeshProps, SVGFPSProps };
@@ -2,17 +2,16 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
+ import '../../../styles/graph.css';
6
+
5
7
  import { type Meta, type StoryObj } from '@storybook/react-vite';
6
8
  import React, { useRef } from 'react';
7
9
 
8
- import { withTheme } from '@dxos/react-ui/testing';
10
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
9
11
 
10
12
  import { type SVGContext, useGrid, useZoom } from '../../hooks';
11
-
12
13
  import { SVG } from './SVG';
13
14
 
14
- import '../../../styles/graph.css';
15
-
16
15
  type ComponentProps = {
17
16
  grid?: boolean;
18
17
  zoom?: boolean;
@@ -45,7 +44,7 @@ const DefaultStory = (props: ComponentProps) => {
45
44
  const meta = {
46
45
  title: 'ui/react-ui-graph/SVGRoot',
47
46
  render: DefaultStory,
48
- decorators: [withTheme],
47
+ decorators: [withTheme(), withLayout({ layout: 'fullscreen' })],
49
48
  parameters: {
50
49
  layout: 'fullscreen',
51
50
  },
@@ -2,31 +2,30 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import '../../styles/graph.css';
6
+
5
7
  import { type Meta, type StoryObj } from '@storybook/react-vite';
6
8
  import { select } from 'd3';
7
9
  import React, { type FC, useEffect, useMemo, useRef } from 'react';
8
10
 
9
- import { withTheme } from '@dxos/react-ui/testing';
11
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
10
12
 
11
13
  import { SVG } from '../components';
12
14
  import { useGrid, useZoom } from '../hooks';
13
15
  import { type D3Callable } from '../util';
14
-
15
16
  import { Pulsar } from './pulsar';
16
17
 
17
- import '../../styles/graph.css';
18
-
19
18
  type Datum = {
20
19
  x: number;
21
20
  y: number;
22
21
  r: number;
23
22
  };
24
23
 
25
- type StoryProps = {
24
+ type DefaultStoryProps = {
26
25
  count: number;
27
26
  } & Pulsar.Options;
28
27
 
29
- const DefaultStory = (props: StoryProps) => {
28
+ const DefaultStory = (props: DefaultStoryProps) => {
30
29
  return (
31
30
  <SVG.Root>
32
31
  <StoryComponent {...props} />
@@ -34,7 +33,7 @@ const DefaultStory = (props: StoryProps) => {
34
33
  );
35
34
  };
36
35
 
37
- const StoryComponent: FC<StoryProps> = ({ count = 1, ...options }) => {
36
+ const StoryComponent: FC<DefaultStoryProps> = ({ count = 1, ...options }) => {
38
37
  const items = useMemo<Datum[]>(
39
38
  () =>
40
39
  Array.from({ length: count }, () => {
@@ -94,7 +93,7 @@ const createNode: D3Callable<SVGGElement, Datum> = (group, classNames, options)
94
93
  const meta = {
95
94
  title: 'ui/react-ui-graph/fx',
96
95
  render: DefaultStory,
97
- decorators: [withTheme],
96
+ decorators: [withTheme(), withLayout({ layout: 'fullscreen' })],
98
97
  parameters: {
99
98
  layout: 'fullscreen',
100
99
  },
@@ -0,0 +1,210 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { type HierarchyNode, cluster as d3Cluster, curveBundle, hierarchy, lineRadial } 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 GraphBundleProjectorOptions = GraphRadialProjectorOptions & {
14
+ /** Reserved space around the bundle (screen pixels). */
15
+ margin?: number;
16
+ /** Radius for leaf nodes. Default 4. */
17
+ leafRadius?: number;
18
+ /**
19
+ * Group key for each node — synthetic intermediate nodes are created per unique key
20
+ * to give the bundling layout a routing point (lowest common ancestor) for edges
21
+ * between leaves in different groups. Return `undefined` to attach the node directly
22
+ * to the root (all such leaves bundle through the root).
23
+ */
24
+ groupOf?: (node: GraphLayoutNode) => string | undefined;
25
+ /** Bundling tension passed to `d3.curveBundle.beta`. 0 = straight chord, 1 = max bundled. */
26
+ tension?: number;
27
+ };
28
+
29
+ const ROOT_ID = '__bundle_root__';
30
+ const GROUP_PREFIX = '__bundle_group__:';
31
+
32
+ /**
33
+ * Cartesian → d3-radial polar. d3 measures angle clockwise from "up" (the -y direction).
34
+ * Inverse of `[cos(a - π/2) * r, sin(a - π/2) * r]`.
35
+ */
36
+ const cartesianToPolar = (x: number, y: number): { angle: number; radius: number } => ({
37
+ angle: Math.atan2(x, -y),
38
+ radius: Math.hypot(x, y),
39
+ });
40
+
41
+ type PolarPoint = { angle: number; radius: number };
42
+
43
+ /**
44
+ * Hierarchical edge bundling — Holten 2006 / d3 observable notebook
45
+ * (https://observablehq.com/@d3/hierarchical-edge-bundling).
46
+ *
47
+ * Synthesizes the same root → group → leaf hierarchy as `GraphClusterProjector`, runs
48
+ * d3.cluster to give every node a polar position, but renders ONLY the leaves
49
+ * (root + groups are routing anchors, not visible nodes). Each data edge is replaced
50
+ * with a curve generated by `lineRadial(curveBundle.beta(tension))` over the polar
51
+ * positions of `source.path(target)` — i.e. the chain of ancestors through the lowest
52
+ * common ancestor.
53
+ *
54
+ * Per-frame `onTickFrame` refreshes the leaf endpoints (first + last point of every
55
+ * path) from current cartesian positions so the curves stay glued to leaves during a
56
+ * cross-variant tween (force → bundle, lattice → bundle). Internal ancestor positions
57
+ * are fixed at d3.cluster's final polar layout, which means during the tween curves
58
+ * route through the destination "pivot points" while the leaf endpoints catch up —
59
+ * visually the bundle "snaps into shape" as the leaves arrive.
60
+ */
61
+ export class GraphBundleProjector<
62
+ NodeData = any,
63
+ Options extends GraphBundleProjectorOptions = any,
64
+ > extends GraphRadialProjector<NodeData, Options> {
65
+ // Per-edge polar point arrays. Points 0 and N-1 are the source / target leaves and are
66
+ // overwritten from current cartesian on every tick; intermediate points stay fixed at
67
+ // their cluster-layout polar coordinates.
68
+ #edgePoints = new Map<string, PolarPoint[]>();
69
+ #lineGen = lineRadial<PolarPoint>()
70
+ .radius((d) => d.radius)
71
+ .angle((d) => d.angle);
72
+
73
+ protected override onUpdate(graph?: Graph.Any) {
74
+ log('onUpdate', { graph: { nodes: graph?.nodes.length, edges: graph?.edges.length } });
75
+ this.mergeData(graph);
76
+ this.doBundleLayout();
77
+ this.emitUpdate('topology');
78
+ this.animate();
79
+ }
80
+
81
+ /**
82
+ * Refresh leaf endpoint polar values from current cartesian so the curve tracks
83
+ * its endpoints during the tween. Internal hierarchy positions stay constant.
84
+ */
85
+ protected override onTickFrame(_t: number): void {
86
+ for (const edge of this.layout.graph.edges) {
87
+ if (edge.type !== 'bundle') {
88
+ continue;
89
+ }
90
+ const points = this.#edgePoints.get(edge.id);
91
+ if (!points || points.length < 2) {
92
+ continue;
93
+ }
94
+ const s = cartesianToPolar(edge.source.x ?? 0, edge.source.y ?? 0);
95
+ const t = cartesianToPolar(edge.target.x ?? 0, edge.target.y ?? 0);
96
+ points[0] = { angle: s.angle, radius: s.radius };
97
+ points[points.length - 1] = { angle: t.angle, radius: t.radius };
98
+ edge.path = this.#lineGen(points) ?? undefined;
99
+ }
100
+ }
101
+
102
+ private doBundleLayout() {
103
+ if (!this.context.size) {
104
+ return;
105
+ }
106
+ const dataNodes = [...this.layout.graph.nodes];
107
+ if (!dataNodes.length) {
108
+ return;
109
+ }
110
+
111
+ const groupOf = this.options.groupOf;
112
+
113
+ // Synthesize root → groups → leaves hierarchy so d3.cluster gives every node
114
+ // (including the routing-only internal ones) a polar coordinate.
115
+ type HierNode = { id: string; parent?: string; node?: GraphLayoutNode<NodeData> };
116
+ const items: HierNode[] = [{ id: ROOT_ID }];
117
+ const groupIds = new Map<string, string>();
118
+ for (const node of dataNodes) {
119
+ const key = groupOf?.(node);
120
+ let parent = ROOT_ID;
121
+ if (key !== undefined) {
122
+ let groupId = groupIds.get(key);
123
+ if (!groupId) {
124
+ groupId = `${GROUP_PREFIX}${key}`;
125
+ groupIds.set(key, groupId);
126
+ items.push({ id: groupId, parent: ROOT_ID });
127
+ }
128
+ parent = groupId;
129
+ }
130
+ items.push({ id: node.id, parent, node });
131
+ }
132
+
133
+ const childrenByParent = new Map<string, HierNode[]>();
134
+ for (const item of items) {
135
+ if (item.parent) {
136
+ const list = childrenByParent.get(item.parent) ?? [];
137
+ list.push(item);
138
+ childrenByParent.set(item.parent, list);
139
+ }
140
+ }
141
+
142
+ const root = hierarchy<HierNode>({ id: ROOT_ID }, (d) => childrenByParent.get(d.id) ?? []);
143
+
144
+ const { width, height } = this.context.size;
145
+ const margin = this.options.margin ?? 120;
146
+ const ringRadius = Math.max(0, Math.min(width, height) / 2 - margin);
147
+
148
+ d3Cluster<HierNode>()
149
+ .size([2 * Math.PI, ringRadius])
150
+ .separation((a: any, b: any) => (a.parent === b.parent ? 1 : 2) / Math.max(1, a.depth))(root);
151
+
152
+ const leafR = this.options.leafRadius ?? 4;
153
+
154
+ // Re-bake the line generator with the configured tension. d3 curve factories return
155
+ // a new curve when `.beta` is called, so this must happen whenever options change.
156
+ const tension = this.options.tension ?? 0.85;
157
+ this.#lineGen = lineRadial<PolarPoint>()
158
+ .curve(curveBundle.beta(tension))
159
+ .radius((d) => d.radius)
160
+ .angle((d) => d.angle);
161
+
162
+ // Index hierarchy nodes by data id for fast lookup when building edge paths.
163
+ const hierById = new Map<string, HierarchyNode<HierNode>>();
164
+ root.each((d) => {
165
+ hierById.set(d.data.id, d);
166
+ });
167
+
168
+ // Position the leaf data nodes (cartesian); internal nodes stay layout-only.
169
+ root.leaves().forEach((d: any) => {
170
+ const angle = d.x;
171
+ const radius = d.y;
172
+ const x = Math.cos(angle - Math.PI / 2) * radius;
173
+ const y = Math.sin(angle - Math.PI / 2) * radius;
174
+ if (d.data.node) {
175
+ updateNode(d.data.node, [x, y], leafR);
176
+ }
177
+ });
178
+ this.layout.graph.nodes = dataNodes;
179
+
180
+ // Build bundle edges. `mergeData` already populated `layout.graph.edges` with data
181
+ // edges referencing the leaf GraphLayoutNodes — keep those references (so node
182
+ // animations & hover wiring continue to work) and enhance each with a routed path
183
+ // through the hierarchy.
184
+ this.#edgePoints.clear();
185
+ const incomingEdges = [...this.layout.graph.edges];
186
+ const bundleEdges: GraphLayoutEdge<NodeData>[] = [];
187
+ for (const edge of incomingEdges) {
188
+ const sourceHier = hierById.get(edge.source.id);
189
+ const targetHier = hierById.get(edge.target.id);
190
+ if (!sourceHier || !targetHier || sourceHier === targetHier) {
191
+ continue;
192
+ }
193
+ // hierarchy.path returns [source, ...up to LCA, ...down to target] (inclusive endpoints).
194
+ const pathNodes = sourceHier.path(targetHier);
195
+ const points: PolarPoint[] = pathNodes.map((n: any) => ({ angle: n.x, radius: n.y }));
196
+ this.#edgePoints.set(edge.id, points);
197
+ bundleEdges.push({
198
+ id: edge.id,
199
+ type: 'bundle',
200
+ source: edge.source,
201
+ target: edge.target,
202
+ data: edge.data,
203
+ });
204
+ }
205
+ this.layout.graph.edges = bundleEdges;
206
+
207
+ // Seed initial paths so the topology emit has correct geometry to enter into the DOM.
208
+ this.onTickFrame(0);
209
+ }
210
+ }