SigmaGraph.tsx
17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import Graph from "graphology";
import circular from "graphology-layout/circular";
import circlepack from "graphology-layout/circlepack";
import noverlap from "graphology-layout-noverlap";
import forceAtlas2 from "graphology-layout-forceatlas2";
import FA2Layout from "graphology-layout-forceatlas2/worker";
import EdgeCurveProgram, { EdgeCurvedArrowProgram, indexParallelEdgesIndex } from "@sigma/edge-curve";
import { NodeBorderProgram } from "@sigma/node-border";
import Sigma from "sigma";
import { EdgeArrowProgram } from "sigma/rendering";
import { useCallback, useEffect, useImperativeHandle, useRef, forwardRef } from "react";
import { communityColor, hslToHex, typeColor } from "@/lib/colors";
import type { GraphPayload } from "@/lib/types";
export type ColorBy = "type" | "community" | "degree";
export type LayoutKind = "forceatlas2" | "circlepack" | "circular";
export interface SigmaGraphHandle {
zoomIn: () => void;
zoomOut: () => void;
reset: () => void;
focusNode: (id: string, ratio?: number) => void;
exportPNG: (filename: string) => void;
restartLayout: () => void;
order: () => number;
}
export interface SigmaGraphProps {
data: GraphPayload | null;
colorBy?: ColorBy;
layout?: LayoutKind;
layoutRunning?: boolean;
showNodeLabels?: boolean;
showEdgeLabels?: boolean;
selectedNode?: string | null;
/** 检索命中的子图:这些节点/边高亮,其余淡化 */
emphasis?: { nodes: Set<string>; edges: Set<string>; seeds?: Set<string> } | null;
onSelectNode?: (id: string | null) => void;
onSelectEdge?: (e: { source: string; target: string; relation: string }) => void;
onDoubleClickNode?: (id: string) => void;
onLayoutStateChange?: (running: boolean) => void;
className?: string;
}
const DIM_NODE = "rgba(148,163,184,0.18)";
const DIM_EDGE = "rgba(148,163,184,0.09)";
function degreeColor(deg: number, max: number): string {
const t = max > 0 ? Math.min(1, deg / max) : 0;
// 低度数偏青,高度数偏品红——比按类型着色更能一眼看出枢纽
return hslToHex(190 - t * 190, 72, 58 - t * 12);
}
/**
* 节点半径(像素)。
*
* 这里必须跟着**当前渲染的节点数**收缩,否则节点会盖住边:
* 500 个节点铺在 ~1000x700 的画布上,平均间距只有 37px 左右,
* 半径再按 13~15px 画,两点之间的连线就整条藏在两个圆底下 ——
* 这正是一开始"一条边都看不见"的原因。
*/
function nodeRadius(degree: number, maxDegree: number, order: number): number {
const crowding = Math.min(1, 240 / Math.max(order, 1)); // 节点越多越小
const base = 2.2 + 3.2 * crowding;
const span = 4 + 9 * crowding;
const t = maxDegree > 1 ? Math.sqrt(Math.min(1, degree / maxDegree)) : 0;
return base + span * t;
}
export const SigmaGraph = forwardRef<SigmaGraphHandle, SigmaGraphProps>(function SigmaGraph(
{
data, colorBy = "type", layout = "forceatlas2", layoutRunning = true,
showNodeLabels = true, showEdgeLabels = false, selectedNode = null, emphasis = null,
onSelectNode, onSelectEdge, onDoubleClickNode, onLayoutStateChange, className,
}, ref,
) {
const hostRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<Sigma | null>(null);
const graphRef = useRef<Graph | null>(null);
const fa2Ref = useRef<FA2Layout | null>(null);
const hoveredRef = useRef<string | null>(null);
const neighborsRef = useRef<Set<string>>(new Set());
const draggedRef = useRef<string | null>(null);
const emphasisRef = useRef(emphasis);
const selectedRef = useRef(selectedNode);
// colorBy / 标签开关必须走 ref:reducer 是在建渲染器那一次闭包里创建的,
// 直接读 props 会永远读到首次渲染的值,切换着色模式就没反应了。
const colorByRef = useRef(colorBy);
const showNodeLabelsRef = useRef(showNodeLabels);
const showEdgeLabelsRef = useRef(showEdgeLabels);
const lastClickRef = useRef<{ id: string; at: number } | null>(null);
emphasisRef.current = emphasis;
selectedRef.current = selectedNode;
colorByRef.current = colorBy;
showNodeLabelsRef.current = showNodeLabels;
showEdgeLabelsRef.current = showEdgeLabels;
const stopLayout = useCallback(() => {
if (fa2Ref.current?.isRunning()) {
fa2Ref.current.stop();
onLayoutStateChange?.(false);
}
}, [onLayoutStateChange]);
// ---------- 建图 + 初始化渲染器 ----------
useEffect(() => {
if (!hostRef.current || !data) return;
const g = new Graph({ multi: true, type: "directed" });
const maxDeg = data.nodes.reduce((m, n) => Math.max(m, n.attributes.degree), 1);
for (const n of data.nodes) {
if (g.hasNode(n.key)) continue;
g.addNode(n.key, {
label: n.attributes.label,
etype: n.attributes.type,
community: n.attributes.community,
degree: n.attributes.degree,
occurrence: n.attributes.occurrence,
verified: n.attributes.verified,
size: nodeRadius(n.attributes.degree, maxDeg, data.nodes.length),
x: Math.random(), y: Math.random(),
});
}
for (const e of data.edges) {
if (!g.hasNode(e.source) || !g.hasNode(e.target)) continue;
if (g.hasEdge(e.key)) continue;
try {
g.addDirectedEdgeWithKey(e.key, e.source, e.target, {
label: e.attributes.label,
relation: e.attributes.relation,
occurrence: e.attributes.occurrence,
size: Math.max(0.9, Math.min(4.5, e.attributes.size)),
});
} catch { /* 重复 key,跳过 */ }
}
// 平行边编号 → 分配不同曲率,让多重边不再完全重叠
// (v1 用直线渲染,A→B 的多条不同关系叠成一条,肉眼只看得到一条)
indexParallelEdgesIndex(g, {
edgeIndexAttribute: "parallelIndex",
edgeMinIndexAttribute: "parallelMinIndex",
edgeMaxIndexAttribute: "parallelMaxIndex",
});
g.forEachEdge((edge, attrs) => {
const idx = attrs.parallelIndex as number | undefined;
const max = attrs.parallelMaxIndex as number | undefined;
const min = attrs.parallelMinIndex as number | undefined;
if (typeof idx === "number" && typeof max === "number") {
const spread = Math.max(1, max - (min ?? 0));
g.setEdgeAttribute(edge, "type", "curved");
g.setEdgeAttribute(edge, "curvature", 0.18 + 0.22 * (idx / spread));
} else if (g.source(edge) === g.target(edge)) {
g.setEdgeAttribute(edge, "type", "curved");
g.setEdgeAttribute(edge, "curvature", 0.5);
} else {
g.setEdgeAttribute(edge, "type", "straight");
}
});
// 布局分三步:
// 1) 给一个有结构的初始位置,让 FA2 收敛得更快更稳;
// 2) 主线程同步跑一遍 FA2 —— 保证一打开就是铺开的样子,不依赖 worker 的时序;
// 3) 再交给 Web Worker 持续微调(可暂停)。
// v1 是随机初始化 + 主线程 O(n²) 手写迭代,300 个节点直接卡死,出来还是一团毛球。
if (g.order > 1) {
try {
if (layout === "circlepack") {
circlepack.assign(g, {
hierarchyAttributes: colorBy === "community" ? ["community"] : ["etype"],
});
} else {
circular.assign(g, { scale: Math.max(80, g.order * 1.6) });
}
} catch {
circular.assign(g);
}
if (layout === "forceatlas2") {
// 注意 gravity 必须配合 strongGravityMode 取 0.05 量级。
// 取 1.0 以上会把整张图吸成一个实心球,边全被节点盖住 —— 别改大。
const settings = { ...forceAtlas2.inferSettings(g), barnesHutOptimize: g.order > 300 };
forceAtlas2.assign(g, {
iterations: g.order > 800 ? 120 : g.order > 300 ? 260 : 420,
settings,
});
// 消重叠:让标签读得清,这是 LightRAG 那种"看得懂"的观感的关键一步
try {
noverlap.assign(g, {
maxIterations: 60,
settings: { margin: 2.5, ratio: 1.05, speed: 3 },
});
} catch { /* 极端退化图上可能失败,忽略 */ }
}
}
graphRef.current = g;
const renderer = new Sigma(g, hostRef.current, {
allowInvalidContainer: true,
renderEdgeLabels: showEdgeLabels,
defaultEdgeType: "straight",
edgeProgramClasses: {
straight: EdgeArrowProgram,
curved: EdgeCurvedArrowProgram,
curvedNoArrow: EdgeCurveProgram,
},
nodeProgramClasses: { border: NodeBorderProgram },
labelFont: 'Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
labelSize: 12,
labelWeight: "500",
labelDensity: 0.9,
labelGridCellSize: 70,
labelRenderedSizeThreshold: 7,
edgeLabelSize: 10,
edgeLabelFont: 'Inter, "PingFang SC", system-ui, sans-serif',
minCameraRatio: 0.03,
maxCameraRatio: 14,
zIndex: true,
nodeReducer: (node, d) => {
const res: Record<string, unknown> = { ...d };
const emp = emphasisRef.current;
const hov = hoveredRef.current;
const sel = selectedRef.current;
const mode = colorByRef.current;
res.color = mode === "community" ? communityColor(d.community)
: mode === "degree" ? degreeColor(d.degree ?? 0, maxDeg)
: typeColor(d.etype);
if (emp) {
if (emp.nodes.has(node)) {
if (emp.seeds?.has(node)) {
res.type = "border";
res.borderColor = "#ffffff";
res.size = (d.size as number) * 1.35;
}
res.zIndex = 2;
} else {
res.color = DIM_NODE;
res.label = "";
res.zIndex = 0;
}
}
// hover:只留下自己和邻居,其余淡化 —— LightRAG 的标志性交互
if (hov && node !== hov && !neighborsRef.current.has(node)) {
res.color = DIM_NODE;
res.label = "";
res.zIndex = 0;
}
if (node === sel || node === hov) {
res.type = "border";
res.borderColor = node === sel ? "#ef4444" : "#ffffff";
res.size = (d.size as number) * 1.4;
res.zIndex = 3;
res.forceLabel = true;
}
if (!showNodeLabelsRef.current && node !== sel && node !== hov) res.label = "";
return res as never;
},
edgeReducer: (edge, d) => {
const res: Record<string, unknown> = { ...d };
const g2 = graphRef.current!;
const emp = emphasisRef.current;
const hov = hoveredRef.current;
const sel = selectedRef.current;
const [s, t] = [g2.source(edge), g2.target(edge)];
res.color = "rgba(120,134,158,0.62)";
if (emp) {
if (emp.edges.has(edge) || (emp.nodes.has(s) && emp.nodes.has(t))) {
res.color = "rgba(245,158,11,0.9)";
res.size = Math.max(1.4, (d.size as number) * 1.2);
res.zIndex = 2;
} else {
res.color = DIM_EDGE;
res.hidden = false;
res.label = "";
}
}
if (hov) {
if (s === hov || t === hov) {
res.color = "rgba(99,102,241,0.85)";
res.size = Math.max(1.4, (d.size as number) * 1.3);
res.zIndex = 3;
if (showEdgeLabelsRef.current) res.forceLabel = true;
} else {
res.color = DIM_EDGE;
res.label = "";
}
}
if (sel && (s === sel || t === sel)) {
res.color = "rgba(239,68,68,0.8)";
res.zIndex = 3;
}
if (!showEdgeLabelsRef.current && !(hov && (s === hov || t === hov))) res.label = "";
return res as never;
},
});
rendererRef.current = renderer;
// ---------- 交互 ----------
renderer.on("enterNode", ({ node }) => {
hoveredRef.current = node;
const nbrs = new Set<string>([node]);
g.forEachNeighbor(node, (n) => nbrs.add(n));
neighborsRef.current = nbrs;
renderer.refresh({ skipIndexation: true });
if (hostRef.current) hostRef.current.style.cursor = "pointer";
});
renderer.on("leaveNode", () => {
hoveredRef.current = null;
neighborsRef.current = new Set();
renderer.refresh({ skipIndexation: true });
if (hostRef.current) hostRef.current.style.cursor = "";
});
renderer.on("clickNode", ({ node }) => {
const prev = lastClickRef.current;
const now = Date.now();
if (prev && prev.id === node && now - prev.at < 350) {
lastClickRef.current = null;
onDoubleClickNode?.(node); // 双击 = 展开该节点邻域
return;
}
lastClickRef.current = { id: node, at: now };
onSelectNode?.(node);
});
renderer.on("clickEdge", ({ edge }) => {
onSelectEdge?.({
source: g.source(edge), target: g.target(edge),
relation: g.getEdgeAttribute(edge, "relation") as string,
});
});
renderer.on("clickStage", () => onSelectNode?.(null));
// 节点拖拽(v1 完全没有,节点位置不可调)
renderer.on("downNode", ({ node }) => {
draggedRef.current = node;
g.setNodeAttribute(node, "highlighted", true);
if (!renderer.getCustomBBox()) renderer.setCustomBBox(renderer.getBBox());
});
const mouse = renderer.getMouseCaptor();
mouse.on("mousemovebody", (e) => {
const node = draggedRef.current;
if (!node) return;
const pos = renderer.viewportToGraph(e);
g.setNodeAttribute(node, "x", pos.x);
g.setNodeAttribute(node, "y", pos.y);
e.preventSigmaDefault();
e.original.preventDefault();
e.original.stopPropagation();
});
const drop = () => {
const node = draggedRef.current;
if (node) g.removeNodeAttribute(node, "highlighted");
draggedRef.current = null;
};
mouse.on("mouseup", drop);
renderer.on("upNode", drop);
// ---------- ForceAtlas2 持续微调(Web Worker,不占主线程)----------
if (layout === "forceatlas2" && g.order > 2) {
const fa2 = new FA2Layout(g, {
settings: { ...forceAtlas2.inferSettings(g), barnesHutOptimize: g.order > 300 },
});
fa2Ref.current = fa2;
if (layoutRunning) {
fa2.start();
onLayoutStateChange?.(true);
// 同步预跑已经收敛得差不多了,worker 只做短暂微调,避免一直烧 CPU
const ms = g.order > 600 ? 5000 : 3000;
const timer = window.setTimeout(() => {
if (fa2Ref.current?.isRunning()) {
fa2Ref.current.stop();
onLayoutStateChange?.(false);
}
}, ms);
return () => {
window.clearTimeout(timer);
fa2Ref.current?.kill();
fa2Ref.current = null;
renderer.kill();
rendererRef.current = null;
};
}
}
return () => {
fa2Ref.current?.kill();
fa2Ref.current = null;
renderer.kill();
rendererRef.current = null;
};
// colorBy / 标签开关通过 refresh 生效,不需要重建整个渲染器
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, layout]);
// 着色 / 标签 / 强调 变化时只刷新,不重建
useEffect(() => {
const r = rendererRef.current;
if (!r) return;
r.setSetting("renderEdgeLabels", showEdgeLabels);
r.refresh({ skipIndexation: true });
}, [colorBy, showNodeLabels, showEdgeLabels, emphasis, selectedNode]);
// 布局启停
useEffect(() => {
const fa2 = fa2Ref.current;
if (!fa2) return;
if (layoutRunning && !fa2.isRunning()) fa2.start();
if (!layoutRunning && fa2.isRunning()) fa2.stop();
}, [layoutRunning]);
useImperativeHandle(ref, () => ({
zoomIn: () => rendererRef.current?.getCamera().animatedZoom({ duration: 300 }),
zoomOut: () => rendererRef.current?.getCamera().animatedUnzoom({ duration: 300 }),
reset: () => rendererRef.current?.getCamera().animatedReset({ duration: 400 }),
order: () => graphRef.current?.order ?? 0,
restartLayout: () => {
fa2Ref.current?.start();
onLayoutStateChange?.(true);
window.setTimeout(() => {
if (fa2Ref.current?.isRunning()) {
fa2Ref.current.stop();
onLayoutStateChange?.(false);
}
}, 5000);
},
focusNode: (id: string, ratio = 0.35) => {
const r = rendererRef.current;
const g = graphRef.current;
if (!r || !g || !g.hasNode(id)) return;
stopLayout();
const d = r.getNodeDisplayData(id);
if (d) r.getCamera().animate({ x: d.x, y: d.y, ratio }, { duration: 500 });
},
exportPNG: (filename: string) => {
const r = rendererRef.current;
if (!r) return;
const canvases = r.getCanvases();
const { width, height } = r.getDimensions();
const dpr = window.devicePixelRatio || 1;
const out = document.createElement("canvas");
out.width = width * dpr;
out.height = height * dpr;
const ctx = out.getContext("2d");
if (!ctx) return;
const isDark = document.documentElement.classList.contains("dark");
ctx.fillStyle = isDark ? "#141822" : "#ffffff";
ctx.fillRect(0, 0, out.width, out.height);
for (const layer of ["edges", "edgeLabels", "nodes", "labels", "hovers"]) {
const c = canvases[layer];
if (c) ctx.drawImage(c, 0, 0, out.width, out.height);
}
out.toBlob((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}, "image/png");
},
}), [stopLayout, onLayoutStateChange]);
return <div ref={hostRef} className={className ?? "sigma-host"} />;
});