@staix/vault-mem-ui 0.0.0-stage → 0.0.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.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/THIRD_PARTY_NOTICES.md +164 -0
- package/bin/vmem-ui.ts +26 -0
- package/dist/panel.css +666 -0
- package/dist/panel.js +355 -0
- package/package.json +53 -4
- package/src/client/App.tsx +167 -0
- package/src/client/a11y.ts +54 -0
- package/src/client/acon.ts +46 -0
- package/src/client/components.tsx +243 -0
- package/src/client/data.ts +66 -0
- package/src/client/fake.ts +48 -0
- package/src/client/graph-export.tsx +21 -0
- package/src/client/host.ts +80 -0
- package/src/client/markdown/parse.ts +620 -0
- package/src/client/markdown/render.tsx +270 -0
- package/src/client/panel.css +666 -0
- package/src/client/panel.tsx +66 -0
- package/src/client/prefs.ts +76 -0
- package/src/client/standalone.ts +44 -0
- package/src/client/store.ts +201 -0
- package/src/client/views/assertions.tsx +109 -0
- package/src/client/views/common.ts +15 -0
- package/src/client/views/history.tsx +205 -0
- package/src/client/views/lint.tsx +27 -0
- package/src/client/views/log.tsx +64 -0
- package/src/client/views/note.tsx +128 -0
- package/src/client/views/notes.tsx +34 -0
- package/src/client/views/overview.tsx +74 -0
- package/src/client/views/promote.tsx +112 -0
- package/src/client/views/proposals.tsx +55 -0
- package/src/client/views/settings.tsx +57 -0
- package/src/client/write.ts +144 -0
- package/src/graph/decisionChains.ts +122 -0
- package/src/graph/derive.ts +338 -0
- package/src/graph/export.ts +44 -0
- package/src/graph/insights.ts +254 -0
- package/src/graph/labels.ts +67 -0
- package/src/graph/layout/client.ts +139 -0
- package/src/graph/layout/engine.ts +107 -0
- package/src/graph/layout/fa2.d.ts +8 -0
- package/src/graph/layout/protocol.ts +70 -0
- package/src/graph/layout/worker.ts +132 -0
- package/src/graph/model.ts +230 -0
- package/src/graph/positions.ts +41 -0
- package/src/graph/search.ts +54 -0
- package/src/graph/style.ts +301 -0
- package/src/graph/target.ts +38 -0
- package/src/graph/types.ts +64 -0
- package/src/graph/view/GraphView.tsx +279 -0
- package/src/graph/view/SidePanels.tsx +141 -0
- package/src/graph/view/cache.ts +42 -0
- package/src/graph/view/canvas.ts +309 -0
- package/src/graph/view/graph-snapshot.ts +75 -0
- package/src/graph/view/lod.ts +30 -0
- package/src/graph/view/motion.ts +4 -0
- package/src/graph/view/state.ts +240 -0
- package/src/plugin/assets.ts +33 -0
- package/src/plugin/graph.ts +71 -0
- package/src/plugin/index.ts +23 -0
- package/src/server/cli.ts +99 -0
- package/src/server/host.ts +287 -0
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
// Sigma 3 canvas for the graph view. Adapted from STAIxBWLB/maru@b33341df src/components/graph/GraphCanvas.tsx
|
|
2
|
+
// (graph building, node/edge reducers for hover, selection, path and dimming, hash fallback positions), without the
|
|
3
|
+
// SVG fallback, export, reference focus, favourites or React. The view drives it imperatively.
|
|
4
|
+
//
|
|
5
|
+
// Sigma is passed in (or loaded lazily by the view) because importing it touches WebGLRenderingContext at module
|
|
6
|
+
// load; that must not happen in the layout worker, which runs this same panel module.
|
|
7
|
+
|
|
8
|
+
import type { GraphModel } from "../model";
|
|
9
|
+
import { graphEdgeVisibilityKey } from "../model";
|
|
10
|
+
import { isUsableCoordinate } from "../positions";
|
|
11
|
+
import { communityColor, edgeColor, graphTheme, nodeColor, nodeRadius, refreshGraphTheme } from "../style";
|
|
12
|
+
import { drawNodeHover, drawNodeLabel } from "../labels";
|
|
13
|
+
import type { GraphDisplaySettings } from "../types";
|
|
14
|
+
import type { GraphViewState } from "./state";
|
|
15
|
+
import { pathEdgeKeys } from "./state";
|
|
16
|
+
import { prefersReducedMotion } from "./motion";
|
|
17
|
+
|
|
18
|
+
/** The part of a Sigma instance the canvas uses; tests supply a fake. */
|
|
19
|
+
export interface SigmaLike {
|
|
20
|
+
on(event: string, handler: (payload: { node?: string }) => void): unknown;
|
|
21
|
+
getCamera(): { getState(): { ratio: number }; on(event: "updated", handler: (s: { ratio: number }) => void): unknown; animate(state: Partial<{ x: number; y: number; ratio: number }>, opts?: { duration?: number }): unknown };
|
|
22
|
+
getNodeDisplayData(node: string): { x: number; y: number } | undefined;
|
|
23
|
+
setSetting(key: string, value: unknown): unknown;
|
|
24
|
+
refresh(opts?: { partialGraph?: { nodes?: string[]; edges?: string[] }; skipIndexation?: boolean; schedule?: boolean }): unknown;
|
|
25
|
+
/** Whether Sigma's program index covers every node and edge right now. A scheduled full refresh (window resize,
|
|
26
|
+
* setSetting) empties the edge half until its frame runs, and a skipIndexation repaint throws until then. */
|
|
27
|
+
hasProgramIndices(): boolean;
|
|
28
|
+
kill(): void;
|
|
29
|
+
}
|
|
30
|
+
export interface GraphLike {
|
|
31
|
+
addNode(id: string, attrs: Record<string, unknown>): unknown;
|
|
32
|
+
addEdgeWithKey(key: string, source: string, target: string, attrs: Record<string, unknown>): unknown;
|
|
33
|
+
hasNode(id: string): boolean;
|
|
34
|
+
getNodeAttribute(id: string, name: string): unknown;
|
|
35
|
+
/** One pass over every node; graphology emits a single eachNodeAttributesUpdated that Sigma handles itself. */
|
|
36
|
+
updateEachNodeAttributes(updater: (node: string, attrs: Record<string, unknown>) => Record<string, unknown>, hints?: { attributes?: string[] }): void;
|
|
37
|
+
/** One pass over every edge; graphology emits a single eachEdgeAttributesUpdated that Sigma handles itself. */
|
|
38
|
+
updateEachEdgeAttributes(updater: (key: string, attrs: Record<string, unknown>) => Record<string, unknown>, hints?: { attributes?: string[] }): void;
|
|
39
|
+
}
|
|
40
|
+
export interface CanvasDeps {
|
|
41
|
+
createGraph(): GraphLike;
|
|
42
|
+
createSigma(graph: GraphLike, container: HTMLElement, settings: Record<string, unknown>): SigmaLike;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const DISPLAY: GraphDisplaySettings = { arrows: "typed", labels: "balanced", colorMode: "neutral", relationColors: false, nodeScale: 1, edgeScale: 1 };
|
|
46
|
+
|
|
47
|
+
/** Deterministic spiral position for a node with no cached coordinates (maru's hashPosition). */
|
|
48
|
+
export function hashPosition(id: string, index: number): [number, number] {
|
|
49
|
+
let hash = 2166136261;
|
|
50
|
+
for (let i = 0; i < id.length; i += 1) {
|
|
51
|
+
hash ^= id.charCodeAt(i);
|
|
52
|
+
hash = Math.imul(hash, 16777619);
|
|
53
|
+
}
|
|
54
|
+
const angle = ((hash >>> 0) / 0xffffffff) * Math.PI * 2;
|
|
55
|
+
const radius = 20 + Math.sqrt(index + 1) * 18;
|
|
56
|
+
return [Math.cos(angle) * radius, Math.sin(angle) * radius];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface GraphCanvasHandle {
|
|
60
|
+
/** Re-applies reducers after a state change. */
|
|
61
|
+
update(state: GraphViewState): void;
|
|
62
|
+
/** Applies a layout batch (model node order). */
|
|
63
|
+
applyPositions(positions: ArrayLike<number>): void;
|
|
64
|
+
focusNode(id: string): void;
|
|
65
|
+
/** Centre the camera on the extent of the selected nodes. */
|
|
66
|
+
focusNodes(ids: readonly string[]): void;
|
|
67
|
+
/** Re-reads the graph colours from the container's computed tokens (after a host or person theme change) and redraws. */
|
|
68
|
+
refreshTheme(): void;
|
|
69
|
+
/** The node's current graph coordinates, or null. */
|
|
70
|
+
positionOf(id: string): [number, number] | null;
|
|
71
|
+
destroy(): void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface CanvasCallbacks {
|
|
75
|
+
onHover(id: string | null): void;
|
|
76
|
+
onClick(id: string | null): void;
|
|
77
|
+
onCamera(ratio: number): void;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function mountGraphCanvas(
|
|
81
|
+
container: HTMLElement,
|
|
82
|
+
model: GraphModel,
|
|
83
|
+
initial: GraphViewState,
|
|
84
|
+
cached: Record<string, [number, number]>,
|
|
85
|
+
callbacks: CanvasCallbacks,
|
|
86
|
+
deps: CanvasDeps,
|
|
87
|
+
): GraphCanvasHandle {
|
|
88
|
+
const graph = deps.createGraph();
|
|
89
|
+
const display = DISPLAY;
|
|
90
|
+
refreshGraphTheme(container);
|
|
91
|
+
model.nodes.forEach((node, index) => {
|
|
92
|
+
const fallback = hashPosition(node.id, index);
|
|
93
|
+
const seed = cached[node.id];
|
|
94
|
+
graph.addNode(node.id, {
|
|
95
|
+
x: isUsableCoordinate(seed?.[0]) ? seed![0] : fallback[0],
|
|
96
|
+
y: isUsableCoordinate(seed?.[1]) ? seed![1] : fallback[1],
|
|
97
|
+
size: nodeRadius(node.degree),
|
|
98
|
+
label: node.label,
|
|
99
|
+
color: nodeColor(node, model.enriched, "neutral"),
|
|
100
|
+
forceLabel: node.isGodNode,
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
model.edges.forEach((edge, index) => {
|
|
104
|
+
graph.addEdgeWithKey(`e${index}`, edge.source, edge.target, {
|
|
105
|
+
size: edge.fromFrontmatter ? 0.55 : 0.35,
|
|
106
|
+
color: edgeColor(edge, display),
|
|
107
|
+
type: edge.fromFrontmatter ? "arrow" : "line",
|
|
108
|
+
index,
|
|
109
|
+
sourceId: edge.source,
|
|
110
|
+
targetId: edge.target,
|
|
111
|
+
visibilityKey: graphEdgeVisibilityKey(edge),
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const nodeById = new Map(model.nodes.map((n) => [n.id, n]));
|
|
116
|
+
const nodeIndex = new Map(model.nodes.map((n, i) => [n.id, i]));
|
|
117
|
+
let state = initial;
|
|
118
|
+
let pathNodes = new Set<string>(state.path ?? []);
|
|
119
|
+
let pathEdges = pathEdgeKeys(state.path);
|
|
120
|
+
let neighbours = new Set<string>();
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
const sigma = deps.createSigma(graph, container, {
|
|
124
|
+
allowInvalidContainer: true,
|
|
125
|
+
labelFont: "system-ui, sans-serif",
|
|
126
|
+
labelSize: 11,
|
|
127
|
+
labelWeight: "500",
|
|
128
|
+
labelDensity: state.lod.labelDensity,
|
|
129
|
+
renderLabels: state.lod.renderLabels,
|
|
130
|
+
defaultDrawNodeLabel: drawNodeLabel,
|
|
131
|
+
defaultDrawNodeHover: drawNodeHover,
|
|
132
|
+
hideLabelsOnMove: true,
|
|
133
|
+
minCameraRatio: 0.02,
|
|
134
|
+
maxCameraRatio: 8,
|
|
135
|
+
stagePadding: 36,
|
|
136
|
+
nodeReducer: (node: string, data: Record<string, unknown>) => {
|
|
137
|
+
const s = state;
|
|
138
|
+
if (!s.derived.visibleNodeIds.has(node)) return { ...data, hidden: true };
|
|
139
|
+
const theme = graphTheme();
|
|
140
|
+
const patch: Record<string, unknown> = {};
|
|
141
|
+
const model = nodeById.get(node);
|
|
142
|
+
if (s.colorByCommunity && model?.community != null) patch.color = communityColor(model.community);
|
|
143
|
+
const dimByHover = s.hoverId !== null && node !== s.hoverId && !neighbours.has(node);
|
|
144
|
+
const dimByPath = pathNodes.size > 0 && !pathNodes.has(node);
|
|
145
|
+
const dimByChain = s.chainFocusIds.size > 0 && !s.chainFocusIds.has(node);
|
|
146
|
+
if (dimByHover || dimByPath || dimByChain) patch.color = theme.dimNode;
|
|
147
|
+
if (pathNodes.has(node) || s.chainFocusIds.has(node) || node === s.pathSourceId) { patch.forceLabel = true; patch.highlighted = true; }
|
|
148
|
+
if (node === s.selectedId || node === s.focusId || node === s.hoverId) {
|
|
149
|
+
patch.forceLabel = true;
|
|
150
|
+
patch.highlighted = true;
|
|
151
|
+
patch.size = (data.size as number) * 1.18;
|
|
152
|
+
if (node === s.selectedId) patch.color = theme.accent;
|
|
153
|
+
}
|
|
154
|
+
if (s.pinned.has(node)) patch.forceLabel = true;
|
|
155
|
+
return { ...data, ...patch };
|
|
156
|
+
},
|
|
157
|
+
edgeReducer: (_edge: string, data: Record<string, unknown>) => {
|
|
158
|
+
const s = state;
|
|
159
|
+
const src = data.sourceId as string, dst = data.targetId as string;
|
|
160
|
+
if (!s.derived.visibleNodeIds.has(src) || !s.derived.visibleNodeIds.has(dst)) return { ...data, hidden: true };
|
|
161
|
+
if (!s.derived.visibleEdgeKeys.has(data.visibilityKey as string)) return { ...data, hidden: true };
|
|
162
|
+
const theme = graphTheme();
|
|
163
|
+
const key = src < dst ? `${src}\u0000${dst}` : `${dst}\u0000${src}`;
|
|
164
|
+
const onPath = pathEdges.has(key);
|
|
165
|
+
const onChain = s.chainFocusIds.has(src) && s.chainFocusIds.has(dst) && s.mode === "chains";
|
|
166
|
+
const hovered = s.hoverId !== null && (src === s.hoverId || dst === s.hoverId);
|
|
167
|
+
const focus = s.selectedId;
|
|
168
|
+
const touchesFocus = focus !== null && (src === focus || dst === focus);
|
|
169
|
+
// LOD: on a reduced view keep a stride sample, but never drop edges the person is looking at.
|
|
170
|
+
if (s.mode !== "chains" && s.lod.edgeStride > 1 && !onPath && !hovered && !touchesFocus && (data.index as number) % s.lod.edgeStride !== 0) {
|
|
171
|
+
return { ...data, hidden: true };
|
|
172
|
+
}
|
|
173
|
+
if (onPath || onChain || hovered || touchesFocus) return { ...data, color: theme.accent, size: Math.max(1.4, data.size as number) };
|
|
174
|
+
if (pathEdges.size > 0 || s.chainFocusIds.size > 0 || s.hoverId !== null) return { ...data, color: theme.edgeDim };
|
|
175
|
+
return data;
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
sigma.on("enterNode", ({ node }) => callbacks.onHover(node ?? null));
|
|
180
|
+
sigma.on("leaveNode", () => callbacks.onHover(null));
|
|
181
|
+
sigma.on("clickNode", ({ node }) => callbacks.onClick(node ?? null));
|
|
182
|
+
sigma.on("clickStage", () => callbacks.onClick(null));
|
|
183
|
+
sigma.getCamera().on("updated", (s) => callbacks.onCamera(s.ratio));
|
|
184
|
+
|
|
185
|
+
let lastLod = state.lod;
|
|
186
|
+
// Reducer-only repaint: re-run reducers and reprocess the programs for every node and edge without re-indexing
|
|
187
|
+
// (Sigma's skipIndexation needs an explicit partialGraph; a bare refresh() always re-indexes everything).
|
|
188
|
+
const everything = { nodes: model.nodes.map((n) => n.id), edges: model.edges.map((_, i) => `e${i}`) };
|
|
189
|
+
const repaint = () => {
|
|
190
|
+
// A scheduled full refresh (window resize, setSetting) empties the edge program index until its frame runs, and
|
|
191
|
+
// skipIndexation throws on the first edge then. Rebuild in the same call instead of waiting for that frame.
|
|
192
|
+
if (!sigma.hasProgramIndices()) { sigma.refresh(); return; }
|
|
193
|
+
sigma.refresh({ partialGraph: everything, skipIndexation: true, schedule: true });
|
|
194
|
+
};
|
|
195
|
+
return {
|
|
196
|
+
update(next) {
|
|
197
|
+
const prev = state;
|
|
198
|
+
state = next;
|
|
199
|
+
const lodChanged = next.lod !== lastLod;
|
|
200
|
+
const reducersChanged = prev.selectedId !== next.selectedId || prev.hoverId !== next.hoverId || prev.focusId !== next.focusId
|
|
201
|
+
|| prev.path !== next.path || prev.pathSourceId !== next.pathSourceId || prev.pinned !== next.pinned
|
|
202
|
+
|| prev.colorByCommunity !== next.colorByCommunity || prev.chainFocusIds !== next.chainFocusIds;
|
|
203
|
+
const visibilityChanged = prev.derived !== next.derived;
|
|
204
|
+
// A camera move, a layout iteration count or a pause only changes what the reducers read when LOD flips.
|
|
205
|
+
if (!lodChanged && !reducersChanged && !visibilityChanged) return;
|
|
206
|
+
pathNodes = new Set(next.path ?? []);
|
|
207
|
+
pathEdges = pathEdgeKeys(next.path);
|
|
208
|
+
neighbours = new Set();
|
|
209
|
+
if (next.hoverId) for (const edge of next.derived.visibleModel.edges) {
|
|
210
|
+
if (edge.source === next.hoverId) neighbours.add(edge.target);
|
|
211
|
+
if (edge.target === next.hoverId) neighbours.add(edge.source);
|
|
212
|
+
}
|
|
213
|
+
let settingsChanged = false;
|
|
214
|
+
if (lodChanged) {
|
|
215
|
+
if (next.lod.labelDensity !== lastLod.labelDensity) { sigma.setSetting("labelDensity", next.lod.labelDensity); settingsChanged = true; }
|
|
216
|
+
if (next.lod.renderLabels !== lastLod.renderLabels) { sigma.setSetting("renderLabels", next.lod.renderLabels); settingsChanged = true; }
|
|
217
|
+
lastLod = next.lod;
|
|
218
|
+
}
|
|
219
|
+
// setSetting schedules a full refresh, which leaves the program index empty until its frame. Run that
|
|
220
|
+
// refresh synchronously so the reducers below (and the labels for the new LOD) are applied in this update.
|
|
221
|
+
if (settingsChanged) { sigma.refresh(); return; }
|
|
222
|
+
// Hiding or showing nodes (local view) changes the label grid, which only a full refresh rebuilds.
|
|
223
|
+
if (visibilityChanged) sigma.refresh();
|
|
224
|
+
else repaint();
|
|
225
|
+
},
|
|
226
|
+
applyPositions(positions) {
|
|
227
|
+
if (positions.length !== model.nodes.length * 2) return;
|
|
228
|
+
const index = nodeIndex;
|
|
229
|
+
graph.updateEachNodeAttributes((node, attrs) => {
|
|
230
|
+
const i = index.get(node);
|
|
231
|
+
if (i === undefined) return attrs;
|
|
232
|
+
const x = positions[i * 2]!, y = positions[i * 2 + 1]!;
|
|
233
|
+
if (isUsableCoordinate(x) && isUsableCoordinate(y)) { attrs.x = x; attrs.y = y; }
|
|
234
|
+
return attrs;
|
|
235
|
+
}, { attributes: ["x", "y"] });
|
|
236
|
+
},
|
|
237
|
+
focusNode(id) {
|
|
238
|
+
const d = sigma.getNodeDisplayData(id);
|
|
239
|
+
if (!d) return;
|
|
240
|
+
sigma.getCamera().animate({ x: d.x, y: d.y, ratio: Math.min(sigma.getCamera().getState().ratio, 0.5) }, { duration: prefersReducedMotion() ? 0 : 300 });
|
|
241
|
+
},
|
|
242
|
+
focusNodes(ids) {
|
|
243
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
244
|
+
for (const id of ids) {
|
|
245
|
+
const point = sigma.getNodeDisplayData(id);
|
|
246
|
+
if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) continue;
|
|
247
|
+
minX = Math.min(minX, point.x); minY = Math.min(minY, point.y);
|
|
248
|
+
maxX = Math.max(maxX, point.x); maxY = Math.max(maxY, point.y);
|
|
249
|
+
}
|
|
250
|
+
if (!Number.isFinite(minX)) return;
|
|
251
|
+
const span = Math.max(maxX - minX, maxY - minY);
|
|
252
|
+
sigma.getCamera().animate({ x: (minX + maxX) / 2, y: (minY + maxY) / 2, ratio: span ? Math.max(0.1, Math.min(8, span * 1.5)) : 0.5 }, { duration: prefersReducedMotion() ? 0 : 300 });
|
|
253
|
+
},
|
|
254
|
+
refreshTheme() {
|
|
255
|
+
refreshGraphTheme(container);
|
|
256
|
+
// Sigma's own graph listeners repaint an attributes batch with skipIndexation; rebuild first when a
|
|
257
|
+
// scheduled full refresh emptied the edge program index, or those repaints throw.
|
|
258
|
+
if (!sigma.hasProgramIndices()) sigma.refresh();
|
|
259
|
+
// One pass per kind: graphology emits one each*AttributesUpdated, and Sigma's own listener already recomputes
|
|
260
|
+
// the reducers and rewrites the programs for it. A refresh() after these passes would be a third one.
|
|
261
|
+
graph.updateEachNodeAttributes((node, attrs) => {
|
|
262
|
+
const n = nodeById.get(node);
|
|
263
|
+
return n ? { ...attrs, color: nodeColor(n, model.enriched, "neutral") } : attrs;
|
|
264
|
+
}, { attributes: ["color"] });
|
|
265
|
+
graph.updateEachEdgeAttributes((_key, attrs) => {
|
|
266
|
+
const edge = model.edges[attrs.index as number];
|
|
267
|
+
return edge ? { ...attrs, color: edgeColor(edge, display) } : attrs;
|
|
268
|
+
}, { attributes: ["color"] });
|
|
269
|
+
},
|
|
270
|
+
positionOf(id) {
|
|
271
|
+
if (!graph.hasNode(id)) return null;
|
|
272
|
+
const x = graph.getNodeAttribute(id, "x"), y = graph.getNodeAttribute(id, "y");
|
|
273
|
+
return typeof x === "number" && typeof y === "number" && Number.isFinite(x) && Number.isFinite(y) ? [x, y] : null;
|
|
274
|
+
},
|
|
275
|
+
destroy() { sigma.kill(); },
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Sigma 3.0.3 keeps its program index in private fields and exposes no accessor. A full refresh empties it all at
|
|
281
|
+
* once (`clearEdgeIndices`, and `clearNodeIndices`, which resets the *edge* index) and `process()` refills it all at
|
|
282
|
+
* once, one entry per edge, on the frame a scheduled refresh defers. The rebuild is therefore all-or-nothing, so one
|
|
283
|
+
* key answers for the whole index in O(1): this canvas names its edges `e0..e{size-1}`, and a graph without edges
|
|
284
|
+
* needs no entry. A Sigma without the field answers false, which only costs a full refresh.
|
|
285
|
+
*
|
|
286
|
+
* `nodeProgramIndex` needs no probe: nothing in 3.0.3 empties it (only `removeNode` deletes an entry, and this canvas
|
|
287
|
+
* never removes a node), so once `process()` has run it stays complete.
|
|
288
|
+
*/
|
|
289
|
+
export function programIndicesCover(sigma: object, graph: object): boolean {
|
|
290
|
+
const s = sigma as { edgeProgramIndex?: Record<string, unknown> };
|
|
291
|
+
const g = graph as { size?: number };
|
|
292
|
+
if (!s.edgeProgramIndex || g.size === undefined) return false;
|
|
293
|
+
return g.size === 0 || `e${g.size - 1}` in s.edgeProgramIndex;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Real Sigma and graphology, loaded on first use so module evaluation stays WebGL- and DOM-free. */
|
|
297
|
+
export async function loadCanvasDeps(): Promise<CanvasDeps> {
|
|
298
|
+
const [{ default: Sigma }, { MultiDirectedGraph }] = await Promise.all([import("sigma"), import("graphology")]);
|
|
299
|
+
return {
|
|
300
|
+
createGraph: () => new MultiDirectedGraph() as unknown as GraphLike,
|
|
301
|
+
createSigma: (g, c, s) => {
|
|
302
|
+
const sigma = new Sigma(g as never, c, s as never);
|
|
303
|
+
const like = sigma as unknown as SigmaLike;
|
|
304
|
+
// Sigma's constructor refreshes synchronously, so the index is populated by the time this returns.
|
|
305
|
+
like.hasProgramIndices = () => programIndicesCover(sigma, g);
|
|
306
|
+
return like;
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/** Decode the provider's revision-bound columnar pages without reading vault files. */
|
|
2
|
+
import type { GraphSnapshotPage, GraphPanelPage, GraphNodeColumns, GraphEdgeColumns } from "@staix/vault-mem/ui-plugin";
|
|
3
|
+
import type { Host, SnapshotReply } from "../../client/host.ts";
|
|
4
|
+
import type { GraphInput } from "../types";
|
|
5
|
+
|
|
6
|
+
const CHANGED = /restart from the first page/i;
|
|
7
|
+
const MAX_NODES = 10_000, MAX_EDGES = 100_000;
|
|
8
|
+
|
|
9
|
+
/** Assemble one revision. Never expose partial pages; retry an expired revision once. */
|
|
10
|
+
export async function assembleGraphPages(snapshot: Host["snapshot"], initial: SnapshotReply, params: Record<string, string>, active: () => boolean = () => true): Promise<SnapshotReply> {
|
|
11
|
+
let first = initial;
|
|
12
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
13
|
+
const result = await assemble(first, snapshot, params, active);
|
|
14
|
+
if (!active() || typeof result.error !== "string" || !CHANGED.test(result.error) || attempt === 1) return result;
|
|
15
|
+
first = await snapshot({ panel: "graph", ...params, ...(typeof first.vault === "string" ? { vault: first.vault } : {}) });
|
|
16
|
+
}
|
|
17
|
+
return first;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function assemble(first: SnapshotReply, snapshot: Host["snapshot"], params: Record<string, string>, active: () => boolean): Promise<SnapshotReply> {
|
|
21
|
+
if (first.error || first.unavailable || first.changed === false || first.schema !== 1) return first;
|
|
22
|
+
const start = first as unknown as GraphPanelPage;
|
|
23
|
+
if (typeof start.revision !== "string" || !start.revision.trim())
|
|
24
|
+
return { error: "Graph provider returned a missing or invalid revision; update @staix/vault-mem or report its version." };
|
|
25
|
+
if (!start.totals || !Number.isSafeInteger(start.totals.nodes) || !Number.isSafeInteger(start.totals.edges) || start.totals.nodes < 0 || start.totals.edges < 0)
|
|
26
|
+
return { error: "Graph provider returned malformed totals; update @staix/vault-mem or report its version." };
|
|
27
|
+
if (start.totals.nodes > MAX_NODES || start.totals.edges > MAX_EDGES)
|
|
28
|
+
return { error: `Graphs larger than ${MAX_NODES.toLocaleString("en-US")} notes or ${MAX_EDGES.toLocaleString("en-US")} links are not supported in this panel yet; use Search instead.` };
|
|
29
|
+
const nodes: GraphInput["nodes"] = [], edges: GraphInput["edges"] = [];
|
|
30
|
+
const communities: Record<string, number> = Object.create(null);
|
|
31
|
+
const seen = new Set<string>();
|
|
32
|
+
let page: GraphSnapshotPage = start, bytes = 0, pages = 0, edgesStarted = false;
|
|
33
|
+
for (;;) {
|
|
34
|
+
if (!active()) return { cancelled: true };
|
|
35
|
+
if (page.schema !== 1 || page.vault !== start.vault || page.revision !== start.revision || page.totals?.nodes !== start.totals.nodes || page.totals?.edges !== start.totals.edges || !Number.isSafeInteger(page.count) || page.count < 0)
|
|
36
|
+
return { error: "Graph pages changed or are invalid; restart from the first page." };
|
|
37
|
+
pages++; bytes += new TextEncoder().encode(JSON.stringify(page)).length;
|
|
38
|
+
if (page.kind === "nodes") {
|
|
39
|
+
if (edgesStarted || page.offset !== nodes.length) return { error: "Graph node pages are out of order; restart from the first page." };
|
|
40
|
+
const c = page.columns as GraphNodeColumns;
|
|
41
|
+
if (!c || ![c.id, c.label, c.type, c.domain, c.source_file, c.community, c.updated, c.date, c.placeholder].every((a) => Array.isArray(a) && a.length === page.count)) return { error: "Graph node columns are invalid; restart from the first page." };
|
|
42
|
+
for (let i = 0; i < page.count; i++) {
|
|
43
|
+
if (typeof c.id[i] !== "string" || typeof c.label[i] !== "string" || typeof c.placeholder[i] !== "boolean") return { error: "Graph node columns are invalid; restart from the first page." };
|
|
44
|
+
const id = c.id[i]!;
|
|
45
|
+
nodes.push({ id, label: c.label[i]!, relPath: c.placeholder[i] ? null : c.source_file[i] ?? null, type: c.type[i], domain: c.domain[i], date: c.date[i], updatedAt: c.updated[i] });
|
|
46
|
+
if (typeof c.community[i] === "number" && Number.isFinite(c.community[i])) communities[id] = c.community[i]!;
|
|
47
|
+
}
|
|
48
|
+
} else if (page.kind === "edges") {
|
|
49
|
+
edgesStarted = true;
|
|
50
|
+
if (nodes.length !== start.totals.nodes || page.offset !== edges.length) return { error: "Graph edge pages are out of order; restart from the first page." };
|
|
51
|
+
const c = page.columns as GraphEdgeColumns;
|
|
52
|
+
if (!c || !Array.isArray(c.relations) || ![c.source, c.target, c.relation, c.field, c.rel].every((a) => Array.isArray(a) && a.length === page.count)) return { error: "Graph edge columns are invalid; restart from the first page." };
|
|
53
|
+
for (let i = 0; i < page.count; i++) {
|
|
54
|
+
const source = c.source[i]!, target = c.target[i]!, relationIndex = c.relation[i]!;
|
|
55
|
+
if (!Number.isSafeInteger(source) || !Number.isSafeInteger(target) || !Number.isSafeInteger(relationIndex) || !nodes[source] || !nodes[target] || typeof c.relations[relationIndex] !== "string") return { error: "Graph edge references are invalid; restart from the first page." };
|
|
56
|
+
const kind = c.relations[relationIndex]!;
|
|
57
|
+
// Both declarations describe newer superseding older; normalize before the model deduplicates reciprocal edges.
|
|
58
|
+
const reverse = kind === "supersedes" && c.field[i] === "superseded_by";
|
|
59
|
+
edges.push({ source: nodes[reverse ? target : source]!.id, target: nodes[reverse ? source : target]!.id, relation: kind === "wiki_link" ? c.rel[i] || "wiki_link" : kind === "supersedes" ? "supersedes" : c.field[i] || kind, fromFrontmatter: kind !== "wiki_link" });
|
|
60
|
+
}
|
|
61
|
+
} else return { error: "Graph page kind is invalid; restart from the first page." };
|
|
62
|
+
if (nodes.length > start.totals.nodes || edges.length > start.totals.edges) return { error: "Graph page totals are invalid; restart from the first page." };
|
|
63
|
+
if (page.next === null) break;
|
|
64
|
+
if (typeof page.next !== "string" || !page.next || seen.has(page.next) || page.count === 0) return { error: "Graph page cursor is invalid; restart from the first page." };
|
|
65
|
+
seen.add(page.next);
|
|
66
|
+
const next = await snapshot({ panel: "graph", ...params, vault: start.vault, page: page.next });
|
|
67
|
+
if (next.error) return next;
|
|
68
|
+
page = next as unknown as GraphSnapshotPage;
|
|
69
|
+
}
|
|
70
|
+
if (nodes.length !== start.totals.nodes || edges.length !== start.totals.edges) return { error: "Graph pages are incomplete; restart from the first page." };
|
|
71
|
+
// The reply is rebuilt from its pages, so a field the host put on the first page that is not page data has to be
|
|
72
|
+
// carried over explicitly: the provider's declared actions are what the link control reads.
|
|
73
|
+
const capabilities = first.capabilities;
|
|
74
|
+
return { graph: { nodes, edges, ...(Object.keys(communities).length ? { communities } : {}) }, graphStats: { pages, bytes, revision: start.revision, cursor: start.cursor, vault: start.vault, placeholdersOmitted: start.totals.placeholdersOmitted }, ...(capabilities !== null && typeof capabilities === "object" ? { capabilities } : {}) };
|
|
75
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Level of detail for large graphs (issue #1 "Supported size"). Above LOD_EDGE_THRESHOLD edges LOD is mandatory:
|
|
2
|
+
// while the layout runs, or when zoomed out past LOD_ZOOMED_OUT_RATIO, the canvas draws a sample of the edges and
|
|
3
|
+
// fewer labels; zoomed in or settled it draws everything. The view tunes these constants.
|
|
4
|
+
|
|
5
|
+
import { LARGE_GRAPH_EDGES } from "../layout/protocol";
|
|
6
|
+
|
|
7
|
+
export const LOD_EDGE_THRESHOLD = LARGE_GRAPH_EDGES;
|
|
8
|
+
/** Sigma camera ratio above which the view counts as zoomed out (1 = fitted, larger = further out). */
|
|
9
|
+
export const LOD_ZOOMED_OUT_RATIO = 0.6;
|
|
10
|
+
/** While reduced, keep roughly one edge in this many. */
|
|
11
|
+
export const LOD_EDGE_STRIDE = 8;
|
|
12
|
+
/** Label density while reduced, and in full detail (Sigma's labelDensity setting). */
|
|
13
|
+
export const LOD_LABEL_DENSITY_REDUCED = 0.15;
|
|
14
|
+
export const LOD_LABEL_DENSITY_FULL = 0.55;
|
|
15
|
+
|
|
16
|
+
export interface Lod {
|
|
17
|
+
reduced: boolean;
|
|
18
|
+
/** Draw edge i only when i % edgeStride === 0; 1 draws all. */
|
|
19
|
+
edgeStride: number;
|
|
20
|
+
labelDensity: number;
|
|
21
|
+
/** Hide all labels while the layout moves nodes on a reduced graph. */
|
|
22
|
+
renderLabels: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function lodFor(edgeCount: number, view: { ratio: number; layoutRunning: boolean }): Lod {
|
|
26
|
+
const reduced = edgeCount > LOD_EDGE_THRESHOLD && (view.layoutRunning || view.ratio > LOD_ZOOMED_OUT_RATIO);
|
|
27
|
+
return reduced
|
|
28
|
+
? { reduced, edgeStride: LOD_EDGE_STRIDE, labelDensity: LOD_LABEL_DENSITY_REDUCED, renderLabels: !view.layoutRunning }
|
|
29
|
+
: { reduced, edgeStride: 1, labelDensity: LOD_LABEL_DENSITY_FULL, renderLabels: true };
|
|
30
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** prefers-reduced-motion, or false where there is no window (tests, the layout worker). */
|
|
2
|
+
export function prefersReducedMotion(): boolean {
|
|
3
|
+
return typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
4
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Graph view state, independent of Sigma and React so it is testable on its own.
|
|
2
|
+
// Rewritten for this package; behaviour follows STAIxBWLB/maru@b33341df src/components/graph/GraphView.tsx (mode,
|
|
3
|
+
// focus, selection, hover, path, pins and layout status), without app state, i18n or export.
|
|
4
|
+
|
|
5
|
+
import { applyGraphSearch, deriveGraphView, type DerivedGraph } from "../derive";
|
|
6
|
+
import { shortestPath } from "../insights";
|
|
7
|
+
import { buildAdjacency, graphEdgeVisibilityKey, withGraphDegrees, type GraphModel } from "../model";
|
|
8
|
+
import { graphTopologySignature } from "../style";
|
|
9
|
+
import type { GraphFilterProfile } from "../types";
|
|
10
|
+
import type { LayoutGraph } from "../layout/protocol";
|
|
11
|
+
import { readLayoutCache, writeLayoutCache, type CacheStorage } from "./cache";
|
|
12
|
+
import { lodFor, type Lod } from "./lod";
|
|
13
|
+
|
|
14
|
+
export type ViewMode = "global" | "local" | "chains";
|
|
15
|
+
export type LayoutStatus =
|
|
16
|
+
| { kind: "idle" }
|
|
17
|
+
| { kind: "running"; iterations: number }
|
|
18
|
+
| { kind: "paused"; iterations: number }
|
|
19
|
+
| { kind: "settled"; iterations: number }
|
|
20
|
+
| { kind: "cached-only"; reason: string }
|
|
21
|
+
| { kind: "error"; message: string };
|
|
22
|
+
|
|
23
|
+
export interface GraphViewState {
|
|
24
|
+
mode: ViewMode;
|
|
25
|
+
/** Local view centre; also the node the keyboard moves from. */
|
|
26
|
+
focusId: string | null;
|
|
27
|
+
/** Fixed centre of the local view, independent of keyboard selection. */
|
|
28
|
+
localCenterId: string | null;
|
|
29
|
+
localDepth: 1 | 2 | 3;
|
|
30
|
+
selectedId: string | null;
|
|
31
|
+
hoverId: string | null;
|
|
32
|
+
/** First endpoint chosen for a shortest path, then the found path (inclusive) or null when none exists. */
|
|
33
|
+
pathSourceId: string | null;
|
|
34
|
+
pathTargetId: string | null;
|
|
35
|
+
path: string[] | null;
|
|
36
|
+
pathMissing: boolean;
|
|
37
|
+
chainFocusIds: Set<string>;
|
|
38
|
+
colorByCommunity: boolean;
|
|
39
|
+
pinned: Set<string>;
|
|
40
|
+
layout: LayoutStatus;
|
|
41
|
+
cameraRatio: number;
|
|
42
|
+
derived: DerivedGraph;
|
|
43
|
+
profile: GraphFilterProfile;
|
|
44
|
+
search: string;
|
|
45
|
+
lod: Lod;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const OPEN_PROFILE: GraphFilterProfile = {
|
|
49
|
+
domains: [], origins: [], types: [], relations: [], community: null,
|
|
50
|
+
showUnresolved: true, showGenerated: true, minVisibleNeighbors: 0,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export interface GraphViewStore {
|
|
54
|
+
getState(): GraphViewState;
|
|
55
|
+
subscribe(listener: () => void): () => void;
|
|
56
|
+
readonly model: GraphModel;
|
|
57
|
+
/** Cache key for this graph's positions and pins. */
|
|
58
|
+
readonly cacheKey: string;
|
|
59
|
+
select(id: string | null): void;
|
|
60
|
+
hover(id: string | null): void;
|
|
61
|
+
/** Local view around a node; null goes back to the global view. */
|
|
62
|
+
openLocal(id: string | null, depth?: 1 | 2 | 3): void;
|
|
63
|
+
setMode(mode: "global" | "chains"): void;
|
|
64
|
+
focusChain(ids: string[]): void;
|
|
65
|
+
clearChainFocus(): void;
|
|
66
|
+
/** First call picks the source, second finds the path; a call with null clears it. */
|
|
67
|
+
pathTo(id: string | null): void;
|
|
68
|
+
togglePin(id: string): void;
|
|
69
|
+
setColorByCommunity(on: boolean): void;
|
|
70
|
+
setProfile(profile: GraphFilterProfile): void;
|
|
71
|
+
setSearch(search: string): void;
|
|
72
|
+
setCamera(ratio: number): void;
|
|
73
|
+
setLayout(status: LayoutStatus): void;
|
|
74
|
+
/** Moves the selection to the next/previous visible neighbour (keyboard). */
|
|
75
|
+
step(direction: 1 | -1): void;
|
|
76
|
+
/** Layout input in model node order, seeded from the cache, with pins fixed. */
|
|
77
|
+
layoutGraph(fallback: (id: string, index: number) => [number, number]): LayoutGraph;
|
|
78
|
+
/** Stores the layout's latest positions (model order) and pins. */
|
|
79
|
+
savePositions(positions: ArrayLike<number>): boolean;
|
|
80
|
+
cachedPositions(): Record<string, [number, number]>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function createGraphViewStore(model: GraphModel, options: { storage?: CacheStorage } = {}): GraphViewStore {
|
|
84
|
+
const listeners = new Set<() => void>();
|
|
85
|
+
const cacheKey = graphTopologySignature(model.nodes, model.edges);
|
|
86
|
+
const cached = readLayoutCache(options.storage, cacheKey);
|
|
87
|
+
const ids = new Set(model.nodes.map((n) => n.id));
|
|
88
|
+
const derive = (mode: ViewMode, focusId: string | null, depth: 1 | 2 | 3, profile: GraphFilterProfile): DerivedGraph => {
|
|
89
|
+
const base = deriveGraphView({ model, profile, generatedPatterns: [], mode: mode === "chains" ? "global" : mode, focusNodeId: focusId,
|
|
90
|
+
localDepth: depth, localDirection: "both", search: "", searchAsFilter: false });
|
|
91
|
+
if (mode !== "chains") return base;
|
|
92
|
+
const nodes = base.analysisModel.nodes.filter((node) => node.type === "decision");
|
|
93
|
+
const ids = new Set(nodes.map((node) => node.id));
|
|
94
|
+
const edges = base.analysisModel.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target) && (edge.relation === "supersedes" || edge.relation === "superseded_by"));
|
|
95
|
+
const graph = withGraphDegrees({ ...base.analysisModel, nodes, edges });
|
|
96
|
+
const neighbors = buildAdjacency(graph);
|
|
97
|
+
return { ...base, analysisModel: graph, visibleModel: graph, visibleNodeIds: ids, visibleEdgeKeys: new Set(edges.map(graphEdgeVisibilityKey)),
|
|
98
|
+
visibleNeighborCounts: new Map([...neighbors].map(([id, adjacent]) => [id, adjacent.size])), emptyReason: nodes.length ? null : "filtered-empty" };
|
|
99
|
+
};
|
|
100
|
+
let analysis = derive("global", null, 2, OPEN_PROFILE);
|
|
101
|
+
let state: GraphViewState = {
|
|
102
|
+
mode: "global", focusId: null, localCenterId: null, localDepth: 2, selectedId: null, hoverId: null,
|
|
103
|
+
pathSourceId: null, pathTargetId: null, path: null, pathMissing: false, chainFocusIds: new Set(), colorByCommunity: model.enriched,
|
|
104
|
+
pinned: new Set(cached.pinned.filter((id) => ids.has(id))),
|
|
105
|
+
layout: { kind: "idle" }, cameraRatio: 1,
|
|
106
|
+
profile: { ...OPEN_PROFILE }, search: "",
|
|
107
|
+
derived: analysis,
|
|
108
|
+
lod: lodFor(model.edges.length, { ratio: 1, layoutRunning: false }),
|
|
109
|
+
};
|
|
110
|
+
let positions = cached.positions;
|
|
111
|
+
|
|
112
|
+
const set = (patch: Partial<GraphViewState>) => {
|
|
113
|
+
const next = { ...state, ...patch };
|
|
114
|
+
if ("cameraRatio" in patch || "layout" in patch) {
|
|
115
|
+
const lod = lodFor(model.edges.length, { ratio: next.cameraRatio, layoutRunning: next.layout.kind === "running" });
|
|
116
|
+
// Keep the same object while the result is unchanged, so the canvas can skip camera-only updates by identity.
|
|
117
|
+
const same = lod.reduced === state.lod.reduced && lod.edgeStride === state.lod.edgeStride
|
|
118
|
+
&& lod.labelDensity === state.lod.labelDensity && lod.renderLabels === state.lod.renderLabels;
|
|
119
|
+
next.lod = same ? state.lod : lod;
|
|
120
|
+
}
|
|
121
|
+
state = next;
|
|
122
|
+
for (const l of listeners) l();
|
|
123
|
+
};
|
|
124
|
+
const known = (id: string | null) => id === null || ids.has(id);
|
|
125
|
+
const visible = (id: string | null) => id === null || state.derived.visibleNodeIds.has(id);
|
|
126
|
+
// Filtering changes which nodes and edges can be acted on. A path must remain valid in the visible graph.
|
|
127
|
+
const reconcile = (derived: DerivedGraph): Partial<GraphViewState> => {
|
|
128
|
+
const has = (id: string | null) => id !== null && derived.visibleNodeIds.has(id);
|
|
129
|
+
const selectedId = has(state.selectedId) ? state.selectedId : null;
|
|
130
|
+
const hoverId = has(state.hoverId) ? state.hoverId : null;
|
|
131
|
+
const focusId = has(state.focusId) ? state.focusId : null;
|
|
132
|
+
const chainFocusIds = [...state.chainFocusIds].every(has) ? state.chainFocusIds : new Set([...state.chainFocusIds].filter(has));
|
|
133
|
+
const source = state.pathSourceId, target = state.pathTargetId;
|
|
134
|
+
if (!has(source) || (target !== null && !has(target))) {
|
|
135
|
+
return { derived, selectedId, hoverId, focusId, chainFocusIds, pathSourceId: null, pathTargetId: null, path: null, pathMissing: false };
|
|
136
|
+
}
|
|
137
|
+
const path = source && target ? shortestPath(derived.visibleModel, source, target) : null;
|
|
138
|
+
return { derived, selectedId, hoverId, focusId, chainFocusIds, pathSourceId: source, pathTargetId: target,
|
|
139
|
+
path, pathMissing: target !== null && path === null };
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
model,
|
|
144
|
+
cacheKey,
|
|
145
|
+
getState: () => state,
|
|
146
|
+
subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
147
|
+
select(id) { if (known(id) && visible(id)) set({ selectedId: id, focusId: id ?? state.focusId }); },
|
|
148
|
+
hover(id) { if (known(id) && visible(id) && id !== state.hoverId) set({ hoverId: id }); },
|
|
149
|
+
openLocal(id, depth = state.localDepth) {
|
|
150
|
+
if (!known(id) || !visible(id)) return;
|
|
151
|
+
const mode: ViewMode = id === null ? "global" : "local";
|
|
152
|
+
analysis = derive(mode, id, depth, state.profile);
|
|
153
|
+
const derived = applyGraphSearch(analysis, state.search);
|
|
154
|
+
set({ ...reconcile(derived), mode, focusId: id, localCenterId: id, localDepth: depth, chainFocusIds: new Set(), selectedId: id ?? (state.selectedId && derived.visibleNodeIds.has(state.selectedId) ? state.selectedId : null) });
|
|
155
|
+
},
|
|
156
|
+
setMode(mode) {
|
|
157
|
+
analysis = derive(mode, null, state.localDepth, state.profile);
|
|
158
|
+
set({ ...reconcile(applyGraphSearch(analysis, state.search)), mode, localCenterId: null, chainFocusIds: new Set() });
|
|
159
|
+
},
|
|
160
|
+
focusChain(ids) {
|
|
161
|
+
const visibleIds = ids.filter((id) => state.derived.visibleNodeIds.has(id));
|
|
162
|
+
if (!visibleIds.length) return;
|
|
163
|
+
set({ chainFocusIds: new Set(visibleIds), selectedId: visibleIds[0]!, focusId: visibleIds[0]! });
|
|
164
|
+
},
|
|
165
|
+
clearChainFocus() { set({ chainFocusIds: state.chainFocusIds.size ? new Set() : state.chainFocusIds, selectedId: null, focusId: null }); },
|
|
166
|
+
pathTo(id) {
|
|
167
|
+
if (id === null) return set({ pathSourceId: null, pathTargetId: null, path: null, pathMissing: false });
|
|
168
|
+
if (!known(id) || !visible(id)) return;
|
|
169
|
+
if (state.pathSourceId === null || state.path) return set({ pathSourceId: id, pathTargetId: null, path: null, pathMissing: false });
|
|
170
|
+
const path = shortestPath(state.derived.visibleModel, state.pathSourceId, id);
|
|
171
|
+
set({ pathTargetId: id, path, pathMissing: path === null });
|
|
172
|
+
},
|
|
173
|
+
togglePin(id) {
|
|
174
|
+
if (!known(id)) return;
|
|
175
|
+
const pinned = new Set(state.pinned);
|
|
176
|
+
if (pinned.has(id)) pinned.delete(id); else pinned.add(id);
|
|
177
|
+
set({ pinned });
|
|
178
|
+
writeLayoutCache(options.storage, cacheKey, { positions, pinned: [...pinned] });
|
|
179
|
+
},
|
|
180
|
+
setColorByCommunity(on) { set({ colorByCommunity: on && model.enriched }); },
|
|
181
|
+
setProfile(profile) {
|
|
182
|
+
analysis = derive(state.mode, state.localCenterId, state.localDepth, profile);
|
|
183
|
+
set({ profile, ...reconcile(applyGraphSearch(analysis, state.search)) });
|
|
184
|
+
},
|
|
185
|
+
setSearch(search) {
|
|
186
|
+
set({ search, ...reconcile(applyGraphSearch(analysis, search)) });
|
|
187
|
+
},
|
|
188
|
+
setCamera(ratio) { if (Number.isFinite(ratio) && ratio > 0 && ratio !== state.cameraRatio) set({ cameraRatio: ratio }); },
|
|
189
|
+
setLayout(layout) { set({ layout }); },
|
|
190
|
+
step(direction) {
|
|
191
|
+
const visible = state.derived.visibleModel.nodes;
|
|
192
|
+
if (visible.length === 0) return;
|
|
193
|
+
// The anchor (focus) stays put while the selection cycles through its neighbours; with no anchor, or one
|
|
194
|
+
// without neighbours, the selection cycles through every visible node.
|
|
195
|
+
const anchor = state.focusId;
|
|
196
|
+
const neighbours = anchor ? buildAdjacency(state.derived.visibleModel).get(anchor) : undefined;
|
|
197
|
+
const pool = neighbours && neighbours.size > 0 ? [...neighbours].sort() : visible.map((n) => n.id).sort();
|
|
198
|
+
const at = state.selectedId ? pool.indexOf(state.selectedId) : -1;
|
|
199
|
+
const next = at < 0 && direction < 0 ? pool[pool.length - 1]! : pool[(at + direction + pool.length) % pool.length]!;
|
|
200
|
+
set({ selectedId: next });
|
|
201
|
+
},
|
|
202
|
+
layoutGraph(fallback) {
|
|
203
|
+
const n = model.nodes.length;
|
|
204
|
+
const index = new Map(model.nodes.map((node, i) => [node.id, i]));
|
|
205
|
+
const pos = new Float32Array(n * 2);
|
|
206
|
+
const fixed = new Uint8Array(n);
|
|
207
|
+
model.nodes.forEach((node, i) => {
|
|
208
|
+
const p = positions[node.id] ?? fallback(node.id, i);
|
|
209
|
+
pos[i * 2] = p[0];
|
|
210
|
+
pos[i * 2 + 1] = p[1];
|
|
211
|
+
fixed[i] = state.pinned.has(node.id) ? 1 : 0;
|
|
212
|
+
});
|
|
213
|
+
const sources = new Uint32Array(model.edges.length);
|
|
214
|
+
const targets = new Uint32Array(model.edges.length);
|
|
215
|
+
model.edges.forEach((e, i) => { sources[i] = index.get(e.source)!; targets[i] = index.get(e.target)!; });
|
|
216
|
+
return { nodeCount: n, positions: pos, sources, targets, fixed };
|
|
217
|
+
},
|
|
218
|
+
savePositions(flat) {
|
|
219
|
+
if (flat.length !== model.nodes.length * 2) return false;
|
|
220
|
+
const next: Record<string, [number, number]> = {};
|
|
221
|
+
model.nodes.forEach((node, i) => { next[node.id] = [flat[i * 2]!, flat[i * 2 + 1]!]; });
|
|
222
|
+
positions = next;
|
|
223
|
+
return writeLayoutCache(options.storage, cacheKey, { positions, pinned: [...state.pinned] });
|
|
224
|
+
},
|
|
225
|
+
cachedPositions: () => positions,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Edge keys on the current path, for highlighting (undirected, NUL-joined like style.edgeKey). */
|
|
230
|
+
export function pathEdgeKeys(path: string[] | null): Set<string> {
|
|
231
|
+
const keys = new Set<string>();
|
|
232
|
+
if (!path) return keys;
|
|
233
|
+
for (let i = 0; i + 1 < path.length; i += 1) {
|
|
234
|
+
const [a, b] = [path[i]!, path[i + 1]!];
|
|
235
|
+
keys.add(a < b ? `${a}\u0000${b}` : `${b}\u0000${a}`);
|
|
236
|
+
}
|
|
237
|
+
return keys;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export { graphEdgeVisibilityKey };
|