@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,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Graph panel: Sigma canvas, layout worker, toolbar and keyboard. Adapted from STAIxBWLB/maru@b33341df
|
|
3
|
+
* src/components/graph/GraphView.tsx (toolbar, local view, path, pins, layout status), reduced to what the
|
|
4
|
+
* vmem provider can supply. The client store assembles provider pages into `reply.graph` before rendering.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
8
|
+
import { Empty, Notice } from "../../client/components.tsx";
|
|
9
|
+
import { GraphExportButton } from "../../client/graph-export.tsx";
|
|
10
|
+
import type { GraphPositions } from "../export.ts";
|
|
11
|
+
import type { SnapshotReply } from "../../client/host.ts";
|
|
12
|
+
import { vaultParam, type ViewProps } from "../../client/views/common.ts";
|
|
13
|
+
import { linkAction } from "../../client/write.ts";
|
|
14
|
+
import { startLayout, type LayoutHandle } from "../layout/client";
|
|
15
|
+
import { buildGraphModel, type GraphModel } from "../model";
|
|
16
|
+
import type { GraphInput } from "../types";
|
|
17
|
+
import { hashPosition, loadCanvasDeps, mountGraphCanvas, type CanvasDeps, type GraphCanvasHandle } from "./canvas";
|
|
18
|
+
import type { CacheStorage } from "./cache";
|
|
19
|
+
import { LOD_EDGE_THRESHOLD } from "./lod";
|
|
20
|
+
import { GraphChainsPanel, GraphFilterPanel, GraphInspector, GraphInsightsPanel, GraphLegend, type LinkProposal } from "./SidePanels";
|
|
21
|
+
import { createGraphViewStore, type GraphViewStore, type LayoutStatus } from "./state";
|
|
22
|
+
|
|
23
|
+
/** A GraphInput when `value` has the shape; anything else is null (the panel then explains why there is no graph).
|
|
24
|
+
* Edges to absent nodes are kept: buildGraphModel turns their endpoints into unresolved ghost nodes. */
|
|
25
|
+
export function readGraphInput(value: unknown): GraphInput | null {
|
|
26
|
+
if (!value || typeof value !== "object") return null;
|
|
27
|
+
const v = value as Partial<GraphInput>;
|
|
28
|
+
if (!Array.isArray(v.nodes) || !Array.isArray(v.edges)) return null;
|
|
29
|
+
const nodes = v.nodes.filter((n) => n && typeof n.id === "string" && typeof n.label === "string");
|
|
30
|
+
const edges = v.edges.filter((e) => e && typeof e.source === "string" && typeof e.target === "string" && typeof e.relation === "string");
|
|
31
|
+
return { nodes: nodes.map((n) => ({ ...n, relPath: typeof n.relPath === "string" ? n.relPath : null })), edges: edges.map((e) => ({ ...e, fromFrontmatter: e.fromFrontmatter === true })), ...(v.communities ? { communities: v.communities } : {}) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface GraphEnv {
|
|
35
|
+
/** The panel module URL the layout worker starts from. */
|
|
36
|
+
moduleUrl?: URL | string;
|
|
37
|
+
workerAllowed?: boolean;
|
|
38
|
+
storage?: CacheStorage;
|
|
39
|
+
canvasDeps?: () => Promise<CanvasDeps>;
|
|
40
|
+
createWorker?: (url: URL | string, options: WorkerOptions) => Worker;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let env: GraphEnv = {};
|
|
44
|
+
/** Set once by the panel entry (`new URL(import.meta.url)`); tests set fakes. */
|
|
45
|
+
export function configureGraph(next: GraphEnv): void {
|
|
46
|
+
env = next;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function browserStorage(): CacheStorage | undefined {
|
|
50
|
+
try {
|
|
51
|
+
return typeof localStorage === "undefined" ? undefined : localStorage;
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function layoutLabel(status: LayoutStatus): string {
|
|
58
|
+
switch (status.kind) {
|
|
59
|
+
case "idle": return "Layout not started";
|
|
60
|
+
case "running": return `Laying out (${status.iterations} iterations)`;
|
|
61
|
+
case "paused": return `Layout paused at ${status.iterations} iterations`;
|
|
62
|
+
case "settled": return `Layout settled after ${status.iterations} iterations`;
|
|
63
|
+
case "cached-only": return status.reason;
|
|
64
|
+
// Worker and client messages already name the cause and the next step.
|
|
65
|
+
case "error": return status.message;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Exact serialized content of a graph input: equal for a resent identical graph, different for any change. */
|
|
70
|
+
export function graphContent(input: GraphInput): string {
|
|
71
|
+
return JSON.stringify(input);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The actions the provider declared for this panel, as its manifest's `capabilities.actions` reached the reply. */
|
|
75
|
+
export function declaredActions(reply: SnapshotReply): string[] {
|
|
76
|
+
const capabilities = reply.capabilities;
|
|
77
|
+
if (!capabilities || typeof capabilities !== "object") return [];
|
|
78
|
+
const actions = (capabilities as { actions?: unknown }).actions;
|
|
79
|
+
return Array.isArray(actions) ? actions.filter((action): action is string => typeof action === "string") : [];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function GraphPanel({ reply, params, navigate, theme, beginWrite }: ViewProps) {
|
|
83
|
+
// Every poll or push hands over a new reply object; only a changed graph may rebuild the view (and its worker).
|
|
84
|
+
// Content is compared exactly (no hash, so no collisions); the generation counter is the React key.
|
|
85
|
+
const parsed = useMemo(() => readGraphInput(reply.graph), [reply.graph]);
|
|
86
|
+
// Derived state (React's "store information from previous renders" pattern): a changed content bumps the
|
|
87
|
+
// generation during render; no ref is written while rendering.
|
|
88
|
+
const [seen, setSeen] = useState<{ content: string | null; generation: number }>({ content: null, generation: 0 });
|
|
89
|
+
const content = parsed ? graphContent(parsed) : null;
|
|
90
|
+
if (content !== seen.content) setSeen({ content, generation: seen.generation + 1 });
|
|
91
|
+
const generation = content !== seen.content ? seen.generation + 1 : seen.generation;
|
|
92
|
+
const model = useMemo(() => (parsed ? buildGraphModel(parsed) : null), [generation]); // keyed on content, not identity
|
|
93
|
+
if (typeof reply.error === "string") return <><Notice tone="err">{reply.error}</Notice>{/restart from the first page/i.test(reply.error) && <button type="button" className="vmem-button" onClick={() => navigate("graph", vaultParam(params))}>First page</button>}</>;
|
|
94
|
+
if (!model) {
|
|
95
|
+
const reason = typeof reply.unavailable === "string" ? reply.unavailable : "this vmem provider does not send a graph snapshot yet (vault-mem #266); update @staix/vault-mem, then reload this panel";
|
|
96
|
+
return <Empty title="Graph not available" hint={reason.charAt(0).toUpperCase() + reason.slice(1) + "."} />;
|
|
97
|
+
}
|
|
98
|
+
if (model.nodes.length === 0) return <Empty title="No notes to graph" hint="Add notes or links to the vault, then reload this panel." />;
|
|
99
|
+
return <>{Number((reply.graphStats as { placeholdersOmitted?: number } | undefined)?.placeholdersOmitted) > 0 && <Notice tone="warn">Some unresolved links were omitted by the provider because the graph reached its size limit.</Notice>}<GraphCanvasView key={generation} model={model} params={params} navigate={navigate} beginWrite={beginWrite} canLink={declaredActions(reply).includes("link")} themeKey={theme ? theme.mode + JSON.stringify(theme.tokens ?? {}) : ""} /></>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function GraphCanvasView({ model, params, navigate, beginWrite, canLink, themeKey }: { model: GraphModel; params: Record<string, string>; navigate: ViewProps["navigate"]; beginWrite: ViewProps["beginWrite"]; canLink: boolean; themeKey: string }) {
|
|
103
|
+
const store = useMemo<GraphViewStore>(() => createGraphViewStore(model, { storage: env.storage ?? browserStorage() }), [model]);
|
|
104
|
+
const hasSupersedes = useMemo(() => model.edges.some((edge) => edge.relation === "supersedes" || edge.relation === "superseded_by"), [model]);
|
|
105
|
+
const subscribe = useCallback((listener: () => void) => store.subscribe(listener), [store]);
|
|
106
|
+
const state = useSyncExternalStore(subscribe, store.getState, store.getState);
|
|
107
|
+
const selectedTextId = useId();
|
|
108
|
+
const hostRef = useRef<HTMLDivElement | null>(null);
|
|
109
|
+
const canvasRef = useRef<GraphCanvasHandle | null>(null);
|
|
110
|
+
const layoutRef = useRef<LayoutHandle | null>(null);
|
|
111
|
+
const [canvasError, setCanvasError] = useState<string | null>(null);
|
|
112
|
+
const [canvasReady, setCanvasReady] = useState(false);
|
|
113
|
+
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
let cancelled = false;
|
|
116
|
+
let lastSave = 0;
|
|
117
|
+
let initialFixed: Uint8Array = new Uint8Array(0);
|
|
118
|
+
let latest: Float32Array | null = null;
|
|
119
|
+
const save = () => { if (latest) { store.savePositions(latest); lastSave = Date.now(); } };
|
|
120
|
+
const host = hostRef.current;
|
|
121
|
+
if (!host) return;
|
|
122
|
+
let stage: "canvas" | "layout" = "canvas";
|
|
123
|
+
(env.canvasDeps ?? loadCanvasDeps)()
|
|
124
|
+
.then((deps) => {
|
|
125
|
+
if (cancelled) return;
|
|
126
|
+
canvasRef.current = mountGraphCanvas(host, model, store.getState(), store.cachedPositions(), {
|
|
127
|
+
onHover: (id) => store.hover(id),
|
|
128
|
+
onClick: (id) => store.select(id),
|
|
129
|
+
onCamera: (ratio) => store.setCamera(ratio),
|
|
130
|
+
}, deps);
|
|
131
|
+
setCanvasReady(true);
|
|
132
|
+
stage = "layout";
|
|
133
|
+
const initial = store.layoutGraph(hashPosition);
|
|
134
|
+
initialFixed = initial.fixed ?? new Uint8Array(model.nodes.length);
|
|
135
|
+
return startLayout({
|
|
136
|
+
moduleUrl: env.moduleUrl ?? "",
|
|
137
|
+
workerAllowed: env.moduleUrl ? env.workerAllowed : false,
|
|
138
|
+
createWorker: env.createWorker,
|
|
139
|
+
graph: initial,
|
|
140
|
+
onPositions(positions, iterations) {
|
|
141
|
+
canvasRef.current?.applyPositions(positions);
|
|
142
|
+
latest = positions;
|
|
143
|
+
if (Date.now() - lastSave > 2_000) save();
|
|
144
|
+
if (store.getState().layout.kind !== "paused") store.setLayout({ kind: "running", iterations });
|
|
145
|
+
},
|
|
146
|
+
onState(s) {
|
|
147
|
+
const current = store.getState().layout;
|
|
148
|
+
const iterations = "iterations" in current ? current.iterations : 0;
|
|
149
|
+
if (s === "running") store.setLayout({ kind: "running", iterations });
|
|
150
|
+
if (s === "paused") store.setLayout({ kind: "paused", iterations });
|
|
151
|
+
if (s === "done" || s === "stopped") { save(); store.setLayout({ kind: "settled", iterations }); }
|
|
152
|
+
},
|
|
153
|
+
onError: (message) => store.setLayout({ kind: "error", message }),
|
|
154
|
+
}).then((handle) => {
|
|
155
|
+
if (cancelled) { if (handle.state === "running") handle.teardown(); return; }
|
|
156
|
+
if (handle.state === "cached-only") store.setLayout({ kind: "cached-only", reason: handle.reason });
|
|
157
|
+
else {
|
|
158
|
+
layoutRef.current = handle;
|
|
159
|
+
// Pins toggled between init and ready were only in the store; bring the worker up to date now.
|
|
160
|
+
const drift = model.nodes.flatMap((node, index) => {
|
|
161
|
+
const pinned = store.getState().pinned.has(node.id);
|
|
162
|
+
if (pinned === (initialFixed[index] === 1)) return [];
|
|
163
|
+
const live = canvasRef.current?.positionOf(node.id);
|
|
164
|
+
return [{ index, fixed: pinned, ...(live ? { position: live } : {}) }];
|
|
165
|
+
});
|
|
166
|
+
if (drift.length) handle.fix(drift);
|
|
167
|
+
store.setLayout({ kind: "running", iterations: 0 });
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
})
|
|
171
|
+
.catch((error: unknown) => {
|
|
172
|
+
if (cancelled) return;
|
|
173
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
174
|
+
if (stage === "canvas") setCanvasError(`the graph canvas could not start (${detail}); this browser may lack WebGL. Try another browser or enable hardware acceleration.`);
|
|
175
|
+
else store.setLayout({ kind: "error", message: `the graph layout could not start (${detail}); the canvas keeps the cached positions. Reload the panel to try again.` });
|
|
176
|
+
});
|
|
177
|
+
return () => {
|
|
178
|
+
cancelled = true;
|
|
179
|
+
save();
|
|
180
|
+
layoutRef.current?.teardown();
|
|
181
|
+
layoutRef.current = null;
|
|
182
|
+
canvasRef.current?.destroy();
|
|
183
|
+
canvasRef.current = null;
|
|
184
|
+
};
|
|
185
|
+
}, [model, store]);
|
|
186
|
+
|
|
187
|
+
useEffect(() => { canvasRef.current?.update(state); }, [state]);
|
|
188
|
+
// The theme reaches the canvas through the container's computed tokens; re-read them after React applied the
|
|
189
|
+
// new data-theme (this effect runs after commit).
|
|
190
|
+
useEffect(() => { canvasRef.current?.refreshTheme(); }, [themeKey]);
|
|
191
|
+
|
|
192
|
+
const togglePin = (id: string) => {
|
|
193
|
+
const wasPinned = store.getState().pinned.has(id);
|
|
194
|
+
store.togglePin(id);
|
|
195
|
+
const index = model.nodes.findIndex((n) => n.id === id);
|
|
196
|
+
const live = canvasRef.current?.positionOf(id) ?? undefined;
|
|
197
|
+
layoutRef.current?.fix([{ index, fixed: !wasPinned, ...(live ? { position: live } : {}) }]);
|
|
198
|
+
if (store.getState().layout.kind === "settled" && layoutRef.current) {
|
|
199
|
+
store.setLayout({ kind: "running", iterations: (store.getState().layout as { iterations: number }).iterations });
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const selected = state.selectedId ? state.derived.visibleModel.nodes.find((n) => n.id === state.selectedId) ?? null : null;
|
|
204
|
+
const readVisiblePositions = (): GraphPositions => {
|
|
205
|
+
const positions: Record<string, [number, number]> = Object.create(null);
|
|
206
|
+
for (const node of state.derived.visibleModel.nodes) {
|
|
207
|
+
const point = canvasRef.current?.positionOf(node.id);
|
|
208
|
+
if (point) positions[node.id] = point;
|
|
209
|
+
}
|
|
210
|
+
return positions;
|
|
211
|
+
};
|
|
212
|
+
const running = state.layout.kind === "running";
|
|
213
|
+
const paused = state.layout.kind === "paused";
|
|
214
|
+
|
|
215
|
+
const onKey = (event: React.KeyboardEvent<HTMLDivElement>) => {
|
|
216
|
+
// Leave browser and host shortcuts (Ctrl/Cmd+P, Ctrl+L, Alt+arrows) alone.
|
|
217
|
+
if (event.ctrlKey || event.metaKey || event.altKey) return;
|
|
218
|
+
const key = event.key;
|
|
219
|
+
if (key === "ArrowRight" || key === "ArrowDown") store.step(1);
|
|
220
|
+
else if (key === "ArrowLeft" || key === "ArrowUp") store.step(-1);
|
|
221
|
+
else if (key === "Enter" && state.selectedId) openNote(state.selectedId);
|
|
222
|
+
else if (key === "l" && state.selectedId) store.openLocal(state.selectedId);
|
|
223
|
+
else if (key === "p" && state.selectedId) store.pathTo(state.selectedId);
|
|
224
|
+
else if (key === "Escape") { store.pathTo(null); if (state.mode === "chains") store.clearChainFocus(); else { store.openLocal(null); store.select(null); } }
|
|
225
|
+
else return;
|
|
226
|
+
event.preventDefault();
|
|
227
|
+
const id = store.getState().selectedId;
|
|
228
|
+
if (id && key.startsWith("Arrow")) canvasRef.current?.focusNode(id);
|
|
229
|
+
};
|
|
230
|
+
const openNote = useCallback((id: string) => {
|
|
231
|
+
const node = model.nodes.find((n) => n.id === id);
|
|
232
|
+
if (node?.relPath) navigate("note", { path: node.relPath, ...vaultParam(params) });
|
|
233
|
+
}, [model, navigate, params]);
|
|
234
|
+
const focusChain = useCallback((ids: string[]) => { store.focusChain(ids); canvasRef.current?.focusNodes(ids); }, [store]);
|
|
235
|
+
// A proposed link is a write like any other: the store previews it through the provider's two-step action and the
|
|
236
|
+
// shared dialog confirms it, so the control is only offered when the provider declares that action.
|
|
237
|
+
const link = useMemo<LinkProposal | undefined>(() => (canLink ? { propose: (input) => beginWrite(linkAction({ ...input, ...vaultParam(params) })) } : undefined), [canLink, beginWrite, params]);
|
|
238
|
+
|
|
239
|
+
return (
|
|
240
|
+
<section className="vmem-graph" aria-label="Vault graph">
|
|
241
|
+
<div className="vmem-graph-bar" role="toolbar" aria-label="Graph controls">
|
|
242
|
+
<span className="vmem-sub">{state.derived.visibleModel.nodes.length} notes · {state.derived.visibleModel.edges.length} links{model.edges.length > LOD_EDGE_THRESHOLD ? " · large graph, detail reduced while moving" : ""}</span>
|
|
243
|
+
<GraphExportButton model={state.derived.visibleModel} positions={readVisiblePositions} disabledReason={canvasError ? "Export unavailable: the graph canvas could not start." : !canvasReady ? "Export is available when the graph canvas is ready." : !state.derived.visibleModel.nodes.length ? "No nodes match; clear filters or search to export." : undefined} />
|
|
244
|
+
<button type="button" className="vmem-button" aria-pressed={state.mode === "global"} onClick={() => store.setMode("global")}>Global view</button>
|
|
245
|
+
<button type="button" className="vmem-button" aria-pressed={state.mode === "local"} disabled={!selected} onClick={() => selected && store.openLocal(selected.id)}>Local view</button>
|
|
246
|
+
<button type="button" className="vmem-button" aria-pressed={state.mode === "chains"} onClick={() => store.setMode("chains")}>Decision chains</button>
|
|
247
|
+
<button type="button" className="vmem-button" disabled={!selected} aria-pressed={state.pathSourceId !== null && !state.path} onClick={() => selected && store.pathTo(selected.id)}>
|
|
248
|
+
{state.pathSourceId && !state.path ? "Path to…" : "Path from"}
|
|
249
|
+
</button>
|
|
250
|
+
<button type="button" className="vmem-button" disabled={!selected} aria-pressed={selected ? state.pinned.has(selected.id) : false} onClick={() => selected && togglePin(selected.id)}>Pin</button>
|
|
251
|
+
{model.enriched ? <button type="button" className="vmem-button" aria-pressed={state.colorByCommunity} onClick={() => store.setColorByCommunity(!state.colorByCommunity)}>Communities</button> : null}
|
|
252
|
+
{running || paused ? <button type="button" className="vmem-button" onClick={() => (paused ? layoutRef.current?.resume() : layoutRef.current?.pause())}>{paused ? "Resume layout" : "Pause layout"}</button> : null}
|
|
253
|
+
</div>
|
|
254
|
+
<p className="vmem-sub vmem-graph-status" role="status">{layoutLabel(state.layout)}</p>
|
|
255
|
+
{canvasError ? <Notice tone="err">{canvasError}</Notice> : null}
|
|
256
|
+
{state.derived.focusMissing ? <Notice tone="warn">The focused note is not in this graph. Choose Global view.</Notice> : null}
|
|
257
|
+
{state.pathMissing ? <Notice tone="warn">No path connects these notes. Pick another endpoint.</Notice> : null}
|
|
258
|
+
<div
|
|
259
|
+
ref={hostRef}
|
|
260
|
+
className="vmem-graph-canvas"
|
|
261
|
+
tabIndex={0}
|
|
262
|
+
role="application"
|
|
263
|
+
aria-label="Graph canvas. Arrow keys move between linked notes, Enter opens, L opens the local view, P picks path endpoints, Escape clears."
|
|
264
|
+
aria-describedby={selectedTextId}
|
|
265
|
+
onKeyDown={onKey}
|
|
266
|
+
/>
|
|
267
|
+
<aside className="vmem-graph-sidebar" aria-label="Graph details">
|
|
268
|
+
{state.mode === "chains" && <GraphChainsPanel model={model} visibleIds={state.derived.visibleNodeIds} chainFocusIds={state.chainFocusIds} hasSupersedes={hasSupersedes} search={state.search} focus={focusChain} open={openNote} />}
|
|
269
|
+
<GraphFilterPanel state={state} store={store} />
|
|
270
|
+
<GraphLegend state={state} themeKey={themeKey} />
|
|
271
|
+
<GraphInspector node={state.derived.visibleModel.nodes.find((node) => node.id === state.selectedId) ?? null} model={state.derived.visibleModel} open={openNote} link={link} />
|
|
272
|
+
<GraphInsightsPanel model={state.derived.analysisModel} visibleIds={state.derived.visibleNodeIds} select={(id) => store.select(id)} />
|
|
273
|
+
</aside>
|
|
274
|
+
<p id={selectedTextId} className="vmem-sub" aria-live="polite">
|
|
275
|
+
{selected ? `${selected.label}${selected.relPath ? "" : " (unresolved link)"} · ${selected.degree} links${state.path ? ` · path of ${state.path.length - 1} steps` : ""}` : "No note selected"}
|
|
276
|
+
</p>
|
|
277
|
+
</section>
|
|
278
|
+
);
|
|
279
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/** Read-only controls adapted from STAIxBWLB/maru@b33341df src/components/graph/GraphFilterPanel, GraphLegend, GraphInspector and GraphInsightsPanel. */
|
|
2
|
+
import { memo, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { LINK_RELATIONS, type LinkRelation } from "../../client/write.ts";
|
|
4
|
+
import { findBridges, findHiddenLinks, findOrphans, findSurprisingConnections } from "../insights";
|
|
5
|
+
import { buildDecisionChains } from "../decisionChains";
|
|
6
|
+
import type { GraphModel, GraphNode } from "../model";
|
|
7
|
+
import { GRAPH_SEARCH_LIMIT, graphSearchRank, rankGraphSearch } from "../search";
|
|
8
|
+
import { communityColor, refreshGraphTheme } from "../style";
|
|
9
|
+
import type { GraphFilterProfile } from "../types";
|
|
10
|
+
import { LARGE_GRAPH_EDGES } from "../layout/protocol";
|
|
11
|
+
import type { GraphViewState, GraphViewStore } from "./state";
|
|
12
|
+
import { OPEN_PROFILE } from "./state";
|
|
13
|
+
|
|
14
|
+
/** Chain groups use the existing maru-derived decisionChains.ts model. */
|
|
15
|
+
const CHAIN_LIST_LIMIT = 50;
|
|
16
|
+
/** Targets the inspector lists before asking for a narrower graph, as the chain lists do. */
|
|
17
|
+
const LINK_TARGET_LIMIT = 200;
|
|
18
|
+
|
|
19
|
+
/** What the inspector may offer when the provider declares the `link` action; absent means the control is hidden. */
|
|
20
|
+
export interface LinkProposal {
|
|
21
|
+
propose(input: { from: string; to: string; relation: LinkRelation; bidirectional: boolean }): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const GraphChainsPanel = memo(function GraphChainsPanel({ model, visibleIds, chainFocusIds, hasSupersedes, search = "", focus, open }: { model: GraphModel; visibleIds: Set<string>; chainFocusIds: Set<string>; hasSupersedes: boolean; search?: string; focus(ids: string[]): void; open(id: string): void }) {
|
|
25
|
+
const layout = useMemo(() => buildDecisionChains(model), [model]);
|
|
26
|
+
const shown = useMemo(() => {
|
|
27
|
+
let chains = layout.chains.filter((chain) => chain.nodes.some((node) => visibleIds.has(node.id)));
|
|
28
|
+
let isolated = layout.isolated.filter((node) => visibleIds.has(node.id));
|
|
29
|
+
if (search.trim()) {
|
|
30
|
+
const rank = (node: GraphNode) => visibleIds.has(node.id) ? graphSearchRank(node, search) ?? Infinity : Infinity;
|
|
31
|
+
const best = (nodes: GraphNode[]) => nodes.reduce((value, node) => Math.min(value, rank(node)), Infinity);
|
|
32
|
+
chains = chains.map((chain) => ({ chain, rank: best(chain.nodes) })).sort((a, b) => a.rank - b.rank).map((item) => item.chain);
|
|
33
|
+
isolated = isolated.map((node) => ({ node, rank: rank(node) })).sort((a, b) => a.rank - b.rank).map((item) => item.node);
|
|
34
|
+
}
|
|
35
|
+
return { chains, isolated };
|
|
36
|
+
}, [layout, visibleIds, search]);
|
|
37
|
+
return <section className="vmem-card vmem-graph-panel" aria-label="Decision chains">
|
|
38
|
+
<h2 className="vmem-card-title">Decision chains</h2>
|
|
39
|
+
{!hasSupersedes && <p>This graph has no supersedes edges. Chains appear when decisions reference each other with supersedes or superseded_by.</p>}
|
|
40
|
+
{shown.chains.length === 0 && <p>No linked decision chains in the current graph.</p>}
|
|
41
|
+
{shown.chains.length > CHAIN_LIST_LIMIT && <p>Showing {CHAIN_LIST_LIMIT} of {shown.chains.length} chains; search or filter to narrow.</p>}
|
|
42
|
+
<ol>{shown.chains.slice(0, CHAIN_LIST_LIMIT).map((chain) => {
|
|
43
|
+
const ids = chain.nodes.map((node) => node.id), visible = ids.filter((id) => visibleIds.has(id));
|
|
44
|
+
const selected = visible.length > 0 && visible.length === chainFocusIds.size && visible.every((id) => chainFocusIds.has(id));
|
|
45
|
+
const label = chain.nodes.slice(0, 3).map((node) => node.label).join(" → ");
|
|
46
|
+
const members = chain.nodes.length > CHAIN_LIST_LIMIT ? [...chain.nodes.filter((node) => visibleIds.has(node.id)), ...chain.nodes.filter((node) => !visibleIds.has(node.id))] : chain.nodes;
|
|
47
|
+
return <li key={JSON.stringify(ids)}><button type="button" className="vmem-button" aria-pressed={selected} onClick={() => focus(visible)}>Focus chain: {label}{ids.length > 3 ? " ..." : ""}</button>
|
|
48
|
+
{visible.length !== ids.length && <span> {visible.length} of {ids.length} visible</span>}
|
|
49
|
+
<ul>{members.slice(0, CHAIN_LIST_LIMIT).map((node) => <li key={node.id}><button type="button" className="vmem-button" disabled={!node.relPath} onClick={() => open(node.id)}>Open {node.label}</button>{node.date ? ` (${node.date})` : ""}</li>)}</ul>
|
|
50
|
+
{ids.length > CHAIN_LIST_LIMIT && <p>Showing {CHAIN_LIST_LIMIT} of {ids.length} decisions, visible first.</p>}
|
|
51
|
+
</li>;
|
|
52
|
+
})}</ol>
|
|
53
|
+
{shown.isolated.length > 0 && <><h3>Unlinked decisions</h3>{shown.isolated.length > CHAIN_LIST_LIMIT && <p>Showing {CHAIN_LIST_LIMIT} of {shown.isolated.length} unlinked decisions; search or filter to narrow.</p>}<ul>{shown.isolated.slice(0, CHAIN_LIST_LIMIT).map((node) => <li key={node.id}><button type="button" className="vmem-button" aria-pressed={chainFocusIds.size === 1 && chainFocusIds.has(node.id)} onClick={() => focus([node.id])}>Focus {node.label}</button> <button type="button" className="vmem-button" disabled={!node.relPath} onClick={() => open(node.id)}>Open {node.label}</button></li>)}</ul></>}
|
|
54
|
+
</section>;
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
function Facet({ label, items, values, update }: { label: string; items: { value: string; count: number }[]; values: string[]; update(values: string[]): void }) {
|
|
58
|
+
return <fieldset className="vmem-graph-facet"><legend>{label}</legend>{items.map((item) => <label key={item.value} className="vmem-graph-option"><input type="checkbox" checked={values.includes(item.value)} onChange={() => update(values.includes(item.value) ? values.filter((v) => v !== item.value) : [...values, item.value])} /> {item.value} ({item.count})</label>)}</fieldset>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function GraphFilterPanel({ state, store }: { state: GraphViewState; store: GraphViewStore }) {
|
|
62
|
+
const { profile, derived } = state;
|
|
63
|
+
const update = (patch: Partial<GraphFilterProfile>) => store.setProfile({ ...profile, ...patch });
|
|
64
|
+
const results = useMemo(() => rankGraphSearch(derived.analysisModel.nodes, state.search), [derived.analysisModel, state.search]);
|
|
65
|
+
return <section className="vmem-card vmem-graph-panel" aria-label="Graph filters">
|
|
66
|
+
<h2 className="vmem-card-title">Search and filters</h2>
|
|
67
|
+
<label htmlFor="vmem-graph-search">Search notes</label>
|
|
68
|
+
<input id="vmem-graph-search" className="vmem-input" type="search" value={state.search} onChange={(e) => store.setSearch(e.currentTarget.value)} />
|
|
69
|
+
{state.search && <><p role="status">{results.length === GRAPH_SEARCH_LIMIT ? `First ${GRAPH_SEARCH_LIMIT} results` : `${results.length} search results`}</p><ul aria-label="Graph search results">{results.map((item) => <li key={item.id}><button type="button" className="vmem-button" onClick={() => store.select(item.id)}>{item.label}</button></li>)}</ul></>}
|
|
70
|
+
<Facet label="Domains" items={derived.facets.domains} values={profile.domains} update={(domains) => update({ domains })} />
|
|
71
|
+
<Facet label="Types" items={derived.facets.types} values={profile.types} update={(types) => update({ types })} />
|
|
72
|
+
<Facet label="Relations" items={derived.facets.relations} values={profile.relations} update={(relations) => update({ relations })} />
|
|
73
|
+
<label htmlFor="vmem-graph-community">Community</label>
|
|
74
|
+
<select id="vmem-graph-community" className="vmem-input" value={profile.community === null ? "" : String(profile.community)} onChange={(e) => update({ community: e.currentTarget.value === "" ? null : Number(e.currentTarget.value) })}>
|
|
75
|
+
<option value="">All communities</option>{derived.facets.communities.map((item) => <option key={item.value} value={item.value}>{item.value} ({item.count})</option>)}
|
|
76
|
+
</select>
|
|
77
|
+
{derived.pausedFilters.length > 0 && <p className="vmem-sub">Unavailable filters: {derived.pausedFilters.join(", ")}</p>}
|
|
78
|
+
<button type="button" className="vmem-button" onClick={() => { store.setProfile({ ...OPEN_PROFILE }); store.setSearch(""); }}>Reset filters</button>
|
|
79
|
+
</section>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function GraphLegend({ state, themeKey = "" }: { state: GraphViewState; themeKey?: string }) {
|
|
83
|
+
const swatches = useRef<HTMLUListElement>(null);
|
|
84
|
+
const communities = state.derived.facets.communities;
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
const list = swatches.current;
|
|
87
|
+
if (!list) return;
|
|
88
|
+
refreshGraphTheme(list.closest(".vmem-graph")?.querySelector(".vmem-graph-canvas"));
|
|
89
|
+
list.querySelectorAll<HTMLElement>("[data-community]").forEach((el) => { el.style.backgroundColor = communityColor(Number(el.dataset.community)); });
|
|
90
|
+
}, [communities, themeKey, state.colorByCommunity]);
|
|
91
|
+
return <section className="vmem-card vmem-graph-panel" aria-label="Graph legend"><h2 className="vmem-card-title">Legend</h2><p>Node size reflects link count. Unresolved notes use the canvas background. Selected and path nodes are highlighted.</p><p>Arrows represent frontmatter links; lines represent other links.</p>{state.colorByCommunity && communities.length > 0 && <ul ref={swatches} aria-label="Community colours">{communities.map((item) => <li key={item.value}><span className="vmem-community-swatch" data-community={item.value} aria-hidden="true" /> Community {item.value}</li>)}</ul>}</section>;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The link form: a second note and one of the provider's relations. It only proposes — the shared write dialog shows
|
|
96
|
+
* the provider's preview and its planned changes, and nothing reaches the vault before Confirm.
|
|
97
|
+
*/
|
|
98
|
+
function LinkForm({ node, model, propose }: { node: GraphNode; model: GraphModel; propose: LinkProposal["propose"] }) {
|
|
99
|
+
const [to, setTo] = useState("");
|
|
100
|
+
const [relation, setRelation] = useState<LinkRelation>(LINK_RELATIONS[0]);
|
|
101
|
+
const [bidirectional, setBidirectional] = useState(true);
|
|
102
|
+
// A placeholder link has no file behind it, so only notes the provider gave a path can be a target.
|
|
103
|
+
const targets = useMemo(() => model.nodes.filter((item) => item.id !== node.id && item.relPath).sort((a, b) => a.label.localeCompare(b.label)), [model, node.id]);
|
|
104
|
+
const from = node.relPath;
|
|
105
|
+
const chosen = targets.find((item) => item.id === to);
|
|
106
|
+
if (!from) return <p>This note is an unresolved link with no file, so a link cannot start here. Open the note it points at, or add it first.</p>;
|
|
107
|
+
if (!targets.length) return <p>No other note in this graph can be a link target. Clear search and filters, or add another note first.</p>;
|
|
108
|
+
return (
|
|
109
|
+
<>
|
|
110
|
+
<h3>Link this note</h3>
|
|
111
|
+
<label htmlFor="vmem-graph-link-target">Link to</label>
|
|
112
|
+
<select id="vmem-graph-link-target" className="vmem-input" value={chosen?.id ?? ""} onChange={(event) => setTo(event.currentTarget.value)}>
|
|
113
|
+
<option value="">Choose a note</option>
|
|
114
|
+
{targets.slice(0, LINK_TARGET_LIMIT).map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}
|
|
115
|
+
</select>
|
|
116
|
+
{targets.length > LINK_TARGET_LIMIT && <p className="vmem-sub">Showing the first {LINK_TARGET_LIMIT} of {targets.length} notes by label; search or filter to narrow.</p>}
|
|
117
|
+
<label htmlFor="vmem-graph-link-relation">Relation</label>
|
|
118
|
+
<select id="vmem-graph-link-relation" className="vmem-input" value={relation} onChange={(event) => setRelation(event.currentTarget.value as LinkRelation)}>
|
|
119
|
+
{LINK_RELATIONS.map((item) => <option key={item} value={item}>{item}</option>)}
|
|
120
|
+
</select>
|
|
121
|
+
<label className="vmem-graph-option"><input type="checkbox" checked={bidirectional} onChange={(event) => setBidirectional(event.currentTarget.checked)} /> Both directions</label>
|
|
122
|
+
<button type="button" className="vmem-button" disabled={!chosen?.relPath} onClick={() => { if (chosen?.relPath) propose({ from, to: chosen.relPath, relation, bidirectional }); }}>Propose link</button>
|
|
123
|
+
<p className="vmem-sub">Nothing is written until you confirm the preview.</p>
|
|
124
|
+
</>
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function GraphInspector({ node, model, open, link }: { node: GraphNode | null; model: GraphModel; open(id: string): void; link?: LinkProposal }) {
|
|
129
|
+
if (!node) return <section className="vmem-card vmem-graph-panel" aria-label="Graph inspector"><h2 className="vmem-card-title">Inspector</h2><p>Select a note to inspect it.</p></section>;
|
|
130
|
+
const labels = new Map(model.nodes.map((item) => [item.id, item.label]));
|
|
131
|
+
const related = model.edges.filter((edge) => edge.source === node.id || edge.target === node.id);
|
|
132
|
+
return <section className="vmem-card vmem-graph-panel" aria-label="Graph inspector"><h2 className="vmem-card-title">Inspector</h2><h3>{node.label}</h3><dl><dt>Type</dt><dd>{node.type}</dd><dt>Domain</dt><dd>{node.domain ?? "None"}</dd><dt>Community</dt><dd>{node.community ?? "None"}</dd><dt>Visible links</dt><dd>{node.degree}</dd><dt>Path</dt><dd>{node.relPath ?? "Unresolved"}</dd></dl>{node.relPath && <button type="button" className="vmem-button" onClick={() => open(node.id)}>Open note</button>}{link ? <LinkForm key={node.id} node={node} model={model} propose={link.propose} /> : null}<h3>Connections</h3><ul>{related.slice(0, 20).map((edge) => <li key={JSON.stringify([edge.source, edge.target, edge.relation])}>{labels.get(edge.source) ?? edge.source} → {labels.get(edge.target) ?? edge.target} ({edge.relation})</li>)}</ul>{related.length > 20 && <p>Showing 20 of {related.length} connections.</p>}</section>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function GraphInsightsPanel({ model, visibleIds, select }: { model: GraphModel; visibleIds: Set<string>; select(id: string): void }) {
|
|
136
|
+
const [open, setOpen] = useState(false);
|
|
137
|
+
const results = useMemo(() => open ? { orphans: findOrphans(model), bridges: findBridges(model), cross: findSurprisingConnections(model), hidden: model.edges.length <= LARGE_GRAPH_EDGES ? findHiddenLinks(model) : [] } : null, [model, open]);
|
|
138
|
+
const labels = useMemo(() => new Map(model.nodes.map((node) => [node.id, node.label])), [model]);
|
|
139
|
+
const label = (id: string) => labels.get(id) ?? id;
|
|
140
|
+
return <section className="vmem-card vmem-graph-panel" aria-label="Graph insights"><h2 className="vmem-card-title">Insights</h2><button type="button" className="vmem-button" aria-expanded={open} aria-controls="vmem-graph-insights-results" onClick={() => setOpen(!open)}>{open ? "Hide insights" : "Show insights"}</button><div id="vmem-graph-insights-results">{results && <><h3>Orphan notes</h3><ul>{results.orphans.map((item) => <li key={item.id}><button type="button" className="vmem-button" disabled={!visibleIds.has(item.id)} title={!visibleIds.has(item.id) ? "Hidden by search" : undefined} onClick={() => select(item.id)}>{label(item.id)}</button></li>)}</ul><h3>Community bridges</h3><ul>{results.bridges.map((item) => <li key={item.id}><button type="button" className="vmem-button" disabled={!visibleIds.has(item.id)} title={!visibleIds.has(item.id) ? "Hidden by search" : undefined} onClick={() => select(item.id)}>{label(item.id)}</button> ({item.communityCount} communities)</li>)}</ul><h3>Cross-community connections</h3><ul>{results.cross.map((item) => <li key={`${item.source}:${item.target}`}>{label(item.source)} → {label(item.target)}</li>)}</ul><h3>Possible links</h3>{model.edges.length > LARGE_GRAPH_EDGES ? <p>Possible links are unavailable for large graphs. Narrow the graph with filters first.</p> : <ul>{results.hidden.map((item) => <li key={`${item.source}:${item.target}`}>{label(item.source)} ↔ {label(item.target)} ({item.shared} shared)</li>)}</ul>}</>}</div></section>;
|
|
141
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Pin and layout cache in per-viewer browser storage. Positions are keyed by node id under a key the caller derives
|
|
2
|
+
// from the graph (graphTopologySignature), so a changed graph never reuses stale coordinates by index. Storage that
|
|
3
|
+
// is missing, full or refuses access degrades to "no cache", never an error.
|
|
4
|
+
|
|
5
|
+
import { sanitizePositions } from "../positions";
|
|
6
|
+
|
|
7
|
+
export interface CacheStorage {
|
|
8
|
+
getItem(key: string): string | null;
|
|
9
|
+
setItem(key: string, value: string): void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const PREFIX = "vmem-ui:graph:";
|
|
13
|
+
|
|
14
|
+
export interface CachedLayout {
|
|
15
|
+
positions: Record<string, [number, number]>;
|
|
16
|
+
pinned: string[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function readLayoutCache(storage: CacheStorage | undefined, key: string): CachedLayout {
|
|
20
|
+
const empty: CachedLayout = { positions: {}, pinned: [] };
|
|
21
|
+
if (!storage) return empty;
|
|
22
|
+
try {
|
|
23
|
+
const raw = JSON.parse(storage.getItem(PREFIX + key) ?? "null") as Partial<CachedLayout> | null;
|
|
24
|
+
if (!raw || typeof raw !== "object") return empty;
|
|
25
|
+
const positions = raw.positions && typeof raw.positions === "object" ? sanitizePositions(raw.positions) : {};
|
|
26
|
+
const pinned = Array.isArray(raw.pinned) ? raw.pinned.filter((id): id is string => typeof id === "string") : [];
|
|
27
|
+
return { positions, pinned };
|
|
28
|
+
} catch {
|
|
29
|
+
return empty;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Returns false when the storage refused the write (full or blocked); the view keeps working without a cache. */
|
|
34
|
+
export function writeLayoutCache(storage: CacheStorage | undefined, key: string, layout: CachedLayout): boolean {
|
|
35
|
+
if (!storage) return false;
|
|
36
|
+
try {
|
|
37
|
+
storage.setItem(PREFIX + key, JSON.stringify({ positions: sanitizePositions(layout.positions), pinned: layout.pinned }));
|
|
38
|
+
return true;
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|