@molecule/app-feature-graph-view-svelte 0.0.0-stage → 1.1.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.
@@ -0,0 +1,151 @@
1
+ <!--
2
+ GraphView: the Svelte counterpart of
3
+ `@molecule/app-feature-graph-view-react`'s `<GraphView>` — a force-directed
4
+ node-and-edge map with built-in `force`, `circular` and `grid` layouts, click
5
+ and keyboard activation, `selectedNodeId` highlighting, and pluggable node /
6
+ edge snippets. Same props (React names), same classes, same DOM for the same
7
+ input.
8
+ -->
9
+ <script lang="ts">
10
+ import { useTranslation } from '@molecule/app-svelte'
11
+ import { getClassMap } from '@molecule/app-ui'
12
+
13
+ import { boundingBox, layoutNodes } from './layout.js'
14
+ import type { GraphViewProps, PositionedNode } from './types.js'
15
+
16
+ let {
17
+ nodes,
18
+ edges,
19
+ onNodeClick,
20
+ selectedNodeId,
21
+ layout = 'force',
22
+ nodeRenderer,
23
+ edgeRenderer,
24
+ forceOptions,
25
+ className,
26
+ }: GraphViewProps = $props()
27
+
28
+ /** Default base radius (world units) of an unweighted node. */
29
+ const NODE_RADIUS = 8
30
+
31
+ const cm = getClassMap()
32
+ const { t } = useTranslation()
33
+
34
+ // Positions depend only on (nodes, edges, layout, forceOptions), and the
35
+ // simulation is deterministic given a fixed seed — the same computation
36
+ // React memoizes.
37
+ const positioned = $derived(layoutNodes(nodes, edges, layout, forceOptions))
38
+
39
+ /**
40
+ * The positioned node with this id, when the layout produced one.
41
+ *
42
+ * @param id - The node id.
43
+ * @returns The positioned node, or undefined.
44
+ */
45
+ const findNode = (id: string): PositionedNode | undefined =>
46
+ positioned.find((node) => node.id === id)
47
+
48
+ // Compute viewBox so the graph always fits the SVG bounds, regardless of
49
+ // the world-space size produced by the layout.
50
+ const viewBox = $derived.by(() => {
51
+ const box = boundingBox(positioned, 40)
52
+ return box
53
+ ? `${box.minX} ${box.minY} ${Math.max(1, box.maxX - box.minX)} ${Math.max(1, box.maxY - box.minY)}`
54
+ : '-100 -100 200 200'
55
+ })
56
+
57
+ const ariaLabel = $derived(t('graphView.aria.canvas', {}, { defaultValue: 'Graph view' }))
58
+ const emptyLabel = $derived(t('graphView.empty', {}, { defaultValue: 'No nodes to display' }))
59
+ </script>
60
+
61
+ <div
62
+ role="application"
63
+ aria-label={ariaLabel}
64
+ data-mol-id="graph-view"
65
+ class={cm.cn(cm.position('relative'), cm.surfaceSecondary, className)}
66
+ style:width="100%"
67
+ style:height="100%"
68
+ style:overflow="hidden"
69
+ >
70
+ {#if positioned.length === 0}
71
+ <div
72
+ data-mol-id="graph-view-empty"
73
+ role="status"
74
+ class={cm.cn(cm.position('absolute'), cm.sp('p', 6))}
75
+ style:inset="0px"
76
+ style:display="grid"
77
+ style:place-items="center"
78
+ >
79
+ {emptyLabel}
80
+ </div>
81
+ {:else}
82
+ <svg
83
+ data-mol-id="graph-view-svg"
84
+ width="100%"
85
+ height="100%"
86
+ {viewBox}
87
+ preserveAspectRatio="xMidYMid meet"
88
+ style:display="block"
89
+ >
90
+ <g data-mol-id="graph-view-edges"
91
+ >{#each edges as edge (edge.id)}{@const src = findNode(edge.source)}{@const tgt = findNode(
92
+ edge.target,
93
+ )}{#if src && tgt}{#if edgeRenderer}<g data-mol-id="graph-view-edge-{edge.id}"
94
+ >{@render edgeRenderer(edge, src, tgt)}</g
95
+ >{:else}<line
96
+ data-mol-id="graph-view-edge-{edge.id}"
97
+ x1={src.x}
98
+ y1={src.y}
99
+ x2={tgt.x}
100
+ y2={tgt.y}
101
+ stroke="currentColor"
102
+ stroke-width="1"
103
+ opacity="0.4"
104
+ ></line>{/if}{/if}{/each}</g
105
+ >
106
+ <g data-mol-id="graph-view-nodes"
107
+ >{#each positioned as node (node.id)}{@const isSelected =
108
+ node.id === selectedNodeId}{@const r =
109
+ NODE_RADIUS * Math.sqrt(Math.max(0.25, node.weight ?? 1))}<g
110
+ data-mol-id="graph-view-node-hit-{node.id}"
111
+ role="button"
112
+ aria-label={t(
113
+ 'graphView.aria.node',
114
+ { label: node.label },
115
+ { defaultValue: 'Node {{label}}' },
116
+ )}
117
+ tabindex="0"
118
+ onclick={() => onNodeClick?.(node)}
119
+ onkeydown={(event) => {
120
+ if (event.key === 'Enter' || event.key === ' ') {
121
+ event.preventDefault()
122
+ onNodeClick?.(node)
123
+ }
124
+ }}
125
+ style:cursor={onNodeClick ? 'pointer' : 'default'}
126
+ style:outline="none"
127
+ >{#if nodeRenderer}{@render nodeRenderer(node)}{:else}<g
128
+ data-mol-id="graph-view-node-{node.id}"
129
+ data-selected={isSelected ? 'true' : 'false'}
130
+ transform="translate({node.x}, {node.y})"
131
+ ><circle
132
+ {r}
133
+ fill="currentColor"
134
+ opacity={isSelected ? 1 : 0.85}
135
+ stroke="currentColor"
136
+ stroke-width={isSelected ? 2 : 0}
137
+ ></circle><text
138
+ x={r + 4}
139
+ y="4"
140
+ font-size="11"
141
+ fill="currentColor"
142
+ opacity={isSelected ? 1 : 0.75}
143
+ style:pointer-events="none"
144
+ style:user-select="none">{node.label}</text
145
+ ></g
146
+ >{/if}</g
147
+ >{/each}</g
148
+ >
149
+ </svg>
150
+ {/if}
151
+ </div>
@@ -0,0 +1,5 @@
1
+ import type { GraphViewProps } from './types.js';
2
+ declare const GraphView: import("svelte").Component<GraphViewProps, {}, "">;
3
+ type GraphView = ReturnType<typeof GraphView>;
4
+ export default GraphView;
5
+ //# sourceMappingURL=GraphView.svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GraphView.svelte.d.ts","sourceRoot":"","sources":["../src/GraphView.svelte"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,YAAY,CAAC;AAmFjE,QAAA,MAAM,SAAS,oDAAwC,CAAC;AACxD,KAAK,SAAS,GAAG,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;AAC9C,eAAe,SAAS,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The package's components: one Svelte 5 component per React component in
3
+ * `@molecule/app-feature-graph-view-react`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as GraphView } from './GraphView.svelte';
8
+ //# sourceMappingURL=components.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The package's components: one Svelte 5 component per React component in
3
+ * `@molecule/app-feature-graph-view-react`, under the same React name.
4
+ *
5
+ * @module
6
+ */
7
+ export { default as GraphView } from './GraphView.svelte';
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Svelte force-directed graph view (Obsidian-style) — the Svelte counterpart of
3
+ * `@molecule/app-feature-graph-view-react`: the same exports, the same props
4
+ * (React names), and the same DOM for the same input.
5
+ *
6
+ * Exports:
7
+ * - `<GraphView>` — top-level node-and-edge visualization with built-in
8
+ * `force`, `circular`, and `grid` layouts, click + selection support,
9
+ * and pluggable node / edge snippets.
10
+ * - `GraphNode`, `GraphEdge`, `GraphLayout`, `GraphPoint`, `PositionedNode`,
11
+ * `GraphNodeRenderer`, `GraphEdgeRenderer`, `GraphViewProps` types.
12
+ * - Pure layout helpers (`forceLayout`, `circularLayout`, `gridLayout`,
13
+ * `layoutNodes`, `boundingBox`, `createRng`).
14
+ *
15
+ * Used by note-taking and other apps to visualize page / note linkages
16
+ * the same way Obsidian does — a force-directed map of which notes link
17
+ * to which.
18
+ *
19
+ * @example
20
+ * ```svelte
21
+ * <script lang="ts">
22
+ * import { GraphView, type GraphEdge, type GraphNode } from '@molecule/app-feature-graph-view-svelte'
23
+ *
24
+ * let { notes, links } = $props()
25
+ * const nodes: GraphNode[] = $derived(
26
+ * notes.map((n) => ({ id: n.id, label: n.title, weight: n.linkCount })),
27
+ * )
28
+ * const edges: GraphEdge[] = $derived(
29
+ * links.map((l) => ({ id: l.id, source: l.from, target: l.to })),
30
+ * )
31
+ * </script>
32
+ *
33
+ * <GraphView {nodes} {edges} onNodeClick={(n) => open(n.id)} />
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * The root element fills 100% of its parent — the PARENT must have an
38
+ * explicit height (e.g. a fixed-height panel or a flex/grid track) or
39
+ * the graph renders zero-tall and appears blank.
40
+ *
41
+ * Interaction surface is click / keyboard-activate + `selectedNodeId`
42
+ * highlighting only. Nodes are NOT draggable and there is no built-in
43
+ * pan / zoom — the SVG `viewBox` auto-fits the layout bounds. For a
44
+ * pannable / zoomable surface, compose with
45
+ * `@molecule/app-feature-canvas-svelte` instead.
46
+ *
47
+ * Layout is deterministic (seeded RNG), computed once per
48
+ * `(nodes, edges, layout, forceOptions)` change. `forceOptions` is
49
+ * ignored by the `circular` and `grid` layouts.
50
+ *
51
+ * @module
52
+ */
53
+ export * from './components.js';
54
+ export * from './layout.js';
55
+ export * from './types.js';
56
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH,cAAc,iBAAiB,CAAA;AAC/B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Svelte force-directed graph view (Obsidian-style) — the Svelte counterpart of
3
+ * `@molecule/app-feature-graph-view-react`: the same exports, the same props
4
+ * (React names), and the same DOM for the same input.
5
+ *
6
+ * Exports:
7
+ * - `<GraphView>` — top-level node-and-edge visualization with built-in
8
+ * `force`, `circular`, and `grid` layouts, click + selection support,
9
+ * and pluggable node / edge snippets.
10
+ * - `GraphNode`, `GraphEdge`, `GraphLayout`, `GraphPoint`, `PositionedNode`,
11
+ * `GraphNodeRenderer`, `GraphEdgeRenderer`, `GraphViewProps` types.
12
+ * - Pure layout helpers (`forceLayout`, `circularLayout`, `gridLayout`,
13
+ * `layoutNodes`, `boundingBox`, `createRng`).
14
+ *
15
+ * Used by note-taking and other apps to visualize page / note linkages
16
+ * the same way Obsidian does — a force-directed map of which notes link
17
+ * to which.
18
+ *
19
+ * @example
20
+ * ```svelte
21
+ * <script lang="ts">
22
+ * import { GraphView, type GraphEdge, type GraphNode } from '@molecule/app-feature-graph-view-svelte'
23
+ *
24
+ * let { notes, links } = $props()
25
+ * const nodes: GraphNode[] = $derived(
26
+ * notes.map((n) => ({ id: n.id, label: n.title, weight: n.linkCount })),
27
+ * )
28
+ * const edges: GraphEdge[] = $derived(
29
+ * links.map((l) => ({ id: l.id, source: l.from, target: l.to })),
30
+ * )
31
+ * </script>
32
+ *
33
+ * <GraphView {nodes} {edges} onNodeClick={(n) => open(n.id)} />
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * The root element fills 100% of its parent — the PARENT must have an
38
+ * explicit height (e.g. a fixed-height panel or a flex/grid track) or
39
+ * the graph renders zero-tall and appears blank.
40
+ *
41
+ * Interaction surface is click / keyboard-activate + `selectedNodeId`
42
+ * highlighting only. Nodes are NOT draggable and there is no built-in
43
+ * pan / zoom — the SVG `viewBox` auto-fits the layout bounds. For a
44
+ * pannable / zoomable surface, compose with
45
+ * `@molecule/app-feature-canvas-svelte` instead.
46
+ *
47
+ * Layout is deterministic (seeded RNG), computed once per
48
+ * `(nodes, edges, layout, forceOptions)` change. `forceOptions` is
49
+ * ignored by the `circular` and `grid` layouts.
50
+ *
51
+ * @module
52
+ */
53
+ export * from './components.js';
54
+ export * from './layout.js';
55
+ export * from './types.js';
@@ -0,0 +1,101 @@
1
+ import type { GraphEdge, GraphLayout, GraphNode, PositionedNode } from './types.js';
2
+ /**
3
+ * Pure (framework-free) layout helpers for `<GraphView>`. Extracted so the
4
+ * math is unit-testable without a component library or jsdom.
5
+ *
6
+ * @module
7
+ */
8
+ /** Default cap on force-layout iterations. */
9
+ export declare const DEFAULT_FORCE_ITERATIONS = 200;
10
+ /** Default repulsion strength used by `forceLayout`. */
11
+ export declare const DEFAULT_REPULSION = 800;
12
+ /** Default spring stiffness used by `forceLayout`. */
13
+ export declare const DEFAULT_SPRING = 0.05;
14
+ /** Default ideal edge length used by `forceLayout`. */
15
+ export declare const DEFAULT_REST_LENGTH = 80;
16
+ /** Default velocity damping used by `forceLayout`. */
17
+ export declare const DEFAULT_DAMPING = 0.85;
18
+ /** Convergence threshold (max per-node displacement squared). */
19
+ export declare const CONVERGENCE_EPSILON = 0.01;
20
+ /** Force-layout tunables. */
21
+ export interface ForceLayoutOptions {
22
+ /** Hard cap on iterations. Defaults to {@link DEFAULT_FORCE_ITERATIONS}. */
23
+ iterations?: number;
24
+ /** Repulsive constant between every pair of nodes. */
25
+ repulsion?: number;
26
+ /** Spring (Hooke) constant for edges. */
27
+ spring?: number;
28
+ /** Ideal edge length (rest distance). */
29
+ restLength?: number;
30
+ /** Velocity damping per step (0–1). */
31
+ damping?: number;
32
+ /** Optional deterministic seed (for tests). Defaults to a fixed value. */
33
+ seed?: number;
34
+ }
35
+ /**
36
+ * Tiny deterministic PRNG (mulberry32). Allows reproducible initial
37
+ * positions in tests without depending on `Math.random()`.
38
+ *
39
+ * @param seed - 32-bit unsigned seed.
40
+ * @returns A function returning floats in `[0, 1)`.
41
+ */
42
+ export declare function createRng(seed: number): () => number;
43
+ /**
44
+ * Place nodes evenly around the unit circle (scaled by `radius`).
45
+ *
46
+ * @param nodes - Nodes to position.
47
+ * @param radius - Circle radius in world units.
48
+ * @returns Positioned nodes, in input order.
49
+ */
50
+ export declare function circularLayout(nodes: GraphNode[], radius: number): PositionedNode[];
51
+ /**
52
+ * Place nodes on a square-ish grid, centred on the origin.
53
+ *
54
+ * @param nodes - Nodes to position.
55
+ * @param spacing - Pixel spacing between adjacent grid cells.
56
+ * @returns Positioned nodes, in input order.
57
+ */
58
+ export declare function gridLayout(nodes: GraphNode[], spacing: number): PositionedNode[];
59
+ /**
60
+ * Run a minimal velocity-Verlet force-directed simulation.
61
+ *
62
+ * Implements:
63
+ * - Pairwise repulsion (Coulomb-like, O(n²)) between every node pair.
64
+ * - Spring (Hooke) attraction along each edge toward `restLength`.
65
+ * - Per-step velocity damping for stability.
66
+ *
67
+ * Stops early once the maximum per-node displacement-squared drops below
68
+ * {@link CONVERGENCE_EPSILON}, or after `iterations` steps — whichever
69
+ * comes first.
70
+ *
71
+ * @param nodes - Nodes to lay out.
72
+ * @param edges - Edges (used only for attractive springs).
73
+ * @param options - Force-layout tunables.
74
+ * @returns Positioned nodes, in input order.
75
+ */
76
+ export declare function forceLayout(nodes: GraphNode[], edges: GraphEdge[], options?: ForceLayoutOptions): PositionedNode[];
77
+ /**
78
+ * Compute world-space positions for every node using the chosen layout.
79
+ *
80
+ * @param nodes - Nodes to position.
81
+ * @param edges - Edges (consumed only by `force`).
82
+ * @param layout - Layout strategy.
83
+ * @param options - Optional force-layout tunables (ignored for non-force).
84
+ * @returns Positioned nodes.
85
+ */
86
+ export declare function layoutNodes(nodes: GraphNode[], edges: GraphEdge[], layout: GraphLayout, options?: ForceLayoutOptions): PositionedNode[];
87
+ /**
88
+ * Compute the world-space bounding box of a set of positioned nodes,
89
+ * with a small padding for visual breathing room.
90
+ *
91
+ * @param nodes - Positioned nodes.
92
+ * @param padding - Padding (world units) added to every side. Default 40.
93
+ * @returns Bounding box `{ minX, minY, maxX, maxY }` — or `null` if empty.
94
+ */
95
+ export declare function boundingBox(nodes: PositionedNode[], padding?: number): {
96
+ minX: number;
97
+ minY: number;
98
+ maxX: number;
99
+ maxY: number;
100
+ } | null;
101
+ //# sourceMappingURL=layout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layout.d.ts","sourceRoot":"","sources":["../src/layout.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAEnF;;;;;GAKG;AAEH,8CAA8C;AAC9C,eAAO,MAAM,wBAAwB,MAAM,CAAA;AAE3C,wDAAwD;AACxD,eAAO,MAAM,iBAAiB,MAAM,CAAA;AAEpC,sDAAsD;AACtD,eAAO,MAAM,cAAc,OAAO,CAAA;AAElC,uDAAuD;AACvD,eAAO,MAAM,mBAAmB,KAAK,CAAA;AAErC,sDAAsD;AACtD,eAAO,MAAM,eAAe,OAAO,CAAA;AAEnC,iEAAiE;AACjE,eAAO,MAAM,mBAAmB,OAAO,CAAA;AAEvC,6BAA6B;AAC7B,MAAM,WAAW,kBAAkB;IACjC,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,sDAAsD;IACtD,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,yCAAyC;IACzC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,0EAA0E;IAC1E,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,MAAM,CASpD;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,EAAE,CAOnF;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,cAAc,EAAE,CAWhF;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,SAAS,EAAE,EAClB,KAAK,EAAE,SAAS,EAAE,EAClB,OAAO,GAAE,kBAAuB,GAC/B,cAAc,EAAE,CA0GlB;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,SAAS,EAAE,EAClB,KAAK,EAAE,SAAS,EAAE,EAClB,MAAM,EAAE,WAAW,EACnB,OAAO,CAAC,EAAE,kBAAkB,GAC3B,cAAc,EAAE,CAUlB;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,cAAc,EAAE,EACvB,OAAO,SAAK,GACX;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAanE"}
package/dist/layout.js ADDED
@@ -0,0 +1,238 @@
1
+ /**
2
+ * Pure (framework-free) layout helpers for `<GraphView>`. Extracted so the
3
+ * math is unit-testable without a component library or jsdom.
4
+ *
5
+ * @module
6
+ */
7
+ /** Default cap on force-layout iterations. */
8
+ export const DEFAULT_FORCE_ITERATIONS = 200;
9
+ /** Default repulsion strength used by `forceLayout`. */
10
+ export const DEFAULT_REPULSION = 800;
11
+ /** Default spring stiffness used by `forceLayout`. */
12
+ export const DEFAULT_SPRING = 0.05;
13
+ /** Default ideal edge length used by `forceLayout`. */
14
+ export const DEFAULT_REST_LENGTH = 80;
15
+ /** Default velocity damping used by `forceLayout`. */
16
+ export const DEFAULT_DAMPING = 0.85;
17
+ /** Convergence threshold (max per-node displacement squared). */
18
+ export const CONVERGENCE_EPSILON = 0.01;
19
+ /**
20
+ * Tiny deterministic PRNG (mulberry32). Allows reproducible initial
21
+ * positions in tests without depending on `Math.random()`.
22
+ *
23
+ * @param seed - 32-bit unsigned seed.
24
+ * @returns A function returning floats in `[0, 1)`.
25
+ */
26
+ export function createRng(seed) {
27
+ let s = seed >>> 0;
28
+ return function rand() {
29
+ s = (s + 0x6d2b79f5) >>> 0;
30
+ let t = s;
31
+ t = Math.imul(t ^ (t >>> 15), t | 1);
32
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
33
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
34
+ };
35
+ }
36
+ /**
37
+ * Place nodes evenly around the unit circle (scaled by `radius`).
38
+ *
39
+ * @param nodes - Nodes to position.
40
+ * @param radius - Circle radius in world units.
41
+ * @returns Positioned nodes, in input order.
42
+ */
43
+ export function circularLayout(nodes, radius) {
44
+ if (nodes.length === 0)
45
+ return [];
46
+ if (nodes.length === 1)
47
+ return [{ ...nodes[0], x: 0, y: 0 }];
48
+ return nodes.map((n, i) => {
49
+ const angle = (i / nodes.length) * Math.PI * 2;
50
+ return { ...n, x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
51
+ });
52
+ }
53
+ /**
54
+ * Place nodes on a square-ish grid, centred on the origin.
55
+ *
56
+ * @param nodes - Nodes to position.
57
+ * @param spacing - Pixel spacing between adjacent grid cells.
58
+ * @returns Positioned nodes, in input order.
59
+ */
60
+ export function gridLayout(nodes, spacing) {
61
+ if (nodes.length === 0)
62
+ return [];
63
+ const cols = Math.max(1, Math.ceil(Math.sqrt(nodes.length)));
64
+ const rows = Math.ceil(nodes.length / cols);
65
+ const offsetX = ((cols - 1) * spacing) / 2;
66
+ const offsetY = ((rows - 1) * spacing) / 2;
67
+ return nodes.map((n, i) => {
68
+ const col = i % cols;
69
+ const row = Math.floor(i / cols);
70
+ return { ...n, x: col * spacing - offsetX, y: row * spacing - offsetY };
71
+ });
72
+ }
73
+ /**
74
+ * Run a minimal velocity-Verlet force-directed simulation.
75
+ *
76
+ * Implements:
77
+ * - Pairwise repulsion (Coulomb-like, O(n²)) between every node pair.
78
+ * - Spring (Hooke) attraction along each edge toward `restLength`.
79
+ * - Per-step velocity damping for stability.
80
+ *
81
+ * Stops early once the maximum per-node displacement-squared drops below
82
+ * {@link CONVERGENCE_EPSILON}, or after `iterations` steps — whichever
83
+ * comes first.
84
+ *
85
+ * @param nodes - Nodes to lay out.
86
+ * @param edges - Edges (used only for attractive springs).
87
+ * @param options - Force-layout tunables.
88
+ * @returns Positioned nodes, in input order.
89
+ */
90
+ export function forceLayout(nodes, edges, options = {}) {
91
+ const iterations = options.iterations ?? DEFAULT_FORCE_ITERATIONS;
92
+ const repulsion = options.repulsion ?? DEFAULT_REPULSION;
93
+ const spring = options.spring ?? DEFAULT_SPRING;
94
+ const restLength = options.restLength ?? DEFAULT_REST_LENGTH;
95
+ const damping = options.damping ?? DEFAULT_DAMPING;
96
+ const rand = createRng(options.seed ?? 0x9e3779b9);
97
+ const n = nodes.length;
98
+ if (n === 0)
99
+ return [];
100
+ // Seed positions on a small circle so all-pairs repulsion has somewhere
101
+ // to push from on iteration 0 (true zero-vectors give NaN directions).
102
+ const seedRadius = Math.max(20, Math.sqrt(n) * 10);
103
+ const x = new Float64Array(n);
104
+ const y = new Float64Array(n);
105
+ const vx = new Float64Array(n);
106
+ const vy = new Float64Array(n);
107
+ for (let i = 0; i < n; i++) {
108
+ const angle = (i / Math.max(1, n)) * Math.PI * 2 + rand() * 0.5;
109
+ const jitter = 1 + rand() * 0.5;
110
+ x[i] = Math.cos(angle) * seedRadius * jitter;
111
+ y[i] = Math.sin(angle) * seedRadius * jitter;
112
+ }
113
+ // Map id → index once (edges reference ids).
114
+ const idx = new Map();
115
+ for (let i = 0; i < n; i++)
116
+ idx.set(nodes[i].id, i);
117
+ // Precompute valid edges (both endpoints present, not self-loops).
118
+ const ea = [];
119
+ const eb = [];
120
+ const ew = [];
121
+ for (const e of edges) {
122
+ const a = idx.get(e.source);
123
+ const b = idx.get(e.target);
124
+ if (a === undefined || b === undefined || a === b)
125
+ continue;
126
+ ea.push(a);
127
+ eb.push(b);
128
+ ew.push(e.weight ?? 1);
129
+ }
130
+ for (let step = 0; step < iterations; step++) {
131
+ // Reset force accumulator (we reuse vx/vy as fx/fy then integrate).
132
+ const fx = new Float64Array(n);
133
+ const fy = new Float64Array(n);
134
+ // Pairwise repulsion — O(n²). Acceptable for the small graphs the
135
+ // note-taking app will throw at this (hundreds, not millions, of nodes).
136
+ for (let i = 0; i < n; i++) {
137
+ for (let j = i + 1; j < n; j++) {
138
+ let dx = x[i] - x[j];
139
+ let dy = y[i] - y[j];
140
+ let distSq = dx * dx + dy * dy;
141
+ if (distSq < 1e-4) {
142
+ // Two nodes on top of each other — nudge them apart.
143
+ dx = (rand() - 0.5) * 0.1;
144
+ dy = (rand() - 0.5) * 0.1;
145
+ distSq = dx * dx + dy * dy + 1e-4;
146
+ }
147
+ const dist = Math.sqrt(distSq);
148
+ const f = repulsion / distSq;
149
+ const fxi = (dx / dist) * f;
150
+ const fyi = (dy / dist) * f;
151
+ fx[i] += fxi;
152
+ fy[i] += fyi;
153
+ fx[j] -= fxi;
154
+ fy[j] -= fyi;
155
+ }
156
+ }
157
+ // Edge springs.
158
+ for (let k = 0; k < ea.length; k++) {
159
+ const a = ea[k];
160
+ const b = eb[k];
161
+ const w = ew[k];
162
+ const dx = x[b] - x[a];
163
+ const dy = y[b] - y[a];
164
+ const dist = Math.sqrt(dx * dx + dy * dy) || 1e-4;
165
+ const displacement = dist - restLength;
166
+ const f = spring * displacement * w;
167
+ const fxk = (dx / dist) * f;
168
+ const fyk = (dy / dist) * f;
169
+ fx[a] += fxk;
170
+ fy[a] += fyk;
171
+ fx[b] -= fxk;
172
+ fy[b] -= fyk;
173
+ }
174
+ // Integrate (semi-implicit Euler with damping).
175
+ let maxDispSq = 0;
176
+ for (let i = 0; i < n; i++) {
177
+ vx[i] = (vx[i] + fx[i]) * damping;
178
+ vy[i] = (vy[i] + fy[i]) * damping;
179
+ const dx = vx[i];
180
+ const dy = vy[i];
181
+ x[i] += dx;
182
+ y[i] += dy;
183
+ const dispSq = dx * dx + dy * dy;
184
+ if (dispSq > maxDispSq)
185
+ maxDispSq = dispSq;
186
+ }
187
+ if (maxDispSq < CONVERGENCE_EPSILON)
188
+ break;
189
+ }
190
+ return nodes.map((node, i) => ({ ...node, x: x[i], y: y[i] }));
191
+ }
192
+ /**
193
+ * Compute world-space positions for every node using the chosen layout.
194
+ *
195
+ * @param nodes - Nodes to position.
196
+ * @param edges - Edges (consumed only by `force`).
197
+ * @param layout - Layout strategy.
198
+ * @param options - Optional force-layout tunables (ignored for non-force).
199
+ * @returns Positioned nodes.
200
+ */
201
+ export function layoutNodes(nodes, edges, layout, options) {
202
+ switch (layout) {
203
+ case 'circular':
204
+ return circularLayout(nodes, Math.max(40, Math.sqrt(nodes.length) * 30));
205
+ case 'grid':
206
+ return gridLayout(nodes, 60);
207
+ case 'force':
208
+ default:
209
+ return forceLayout(nodes, edges, options);
210
+ }
211
+ }
212
+ /**
213
+ * Compute the world-space bounding box of a set of positioned nodes,
214
+ * with a small padding for visual breathing room.
215
+ *
216
+ * @param nodes - Positioned nodes.
217
+ * @param padding - Padding (world units) added to every side. Default 40.
218
+ * @returns Bounding box `{ minX, minY, maxX, maxY }` — or `null` if empty.
219
+ */
220
+ export function boundingBox(nodes, padding = 40) {
221
+ if (nodes.length === 0)
222
+ return null;
223
+ let minX = Infinity;
224
+ let minY = Infinity;
225
+ let maxX = -Infinity;
226
+ let maxY = -Infinity;
227
+ for (const n of nodes) {
228
+ if (n.x < minX)
229
+ minX = n.x;
230
+ if (n.y < minY)
231
+ minY = n.y;
232
+ if (n.x > maxX)
233
+ maxX = n.x;
234
+ if (n.y > maxY)
235
+ maxY = n.y;
236
+ }
237
+ return { minX: minX - padding, minY: minY - padding, maxX: maxX + padding, maxY: maxY + padding };
238
+ }