Elffuss BraidHub

kikocis/utopia public

834f8753ffd7 · 65.8 KiBRawPermalink
1import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3import { Link, useSearch } from "@tanstack/react-router";
4import Graphology from "graphology";
5import { circular, circlepack } from "graphology-layout";
6import forceAtlas2 from "graphology-layout-forceatlas2";
7import FA2Layout from "graphology-layout-forceatlas2/worker";
8import Sigma from "sigma";
9import { createNodeBorderProgram } from "@sigma/node-border";
10import { NodeSquareShellProgram } from "./squareShellProgram";
11import { EntityHistory } from "./EntityHistory";
12import {
13 ArrowLeft,
14 ArrowRight,
15 ChevronRight,
16 CircleDashed,
17 Grape,
18 Maximize2,
19 Orbit,
20 Pause,
21 Pencil,
22 Play,
23 X,
24 ZoomIn,
25 ZoomOut,
26} from "lucide-react";
27import { api, type EntityFact, type Evidence, type GraphEdge, type GraphNode } from "../api";
28import { S } from "../i18n";
29import { useKb } from "../kb";
30import { toast } from "../toast";
31
32/* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:
33 Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、
34 彩色只属于数据"的既定原则换成同明度纯灰,类型色混入比例不变 */
35const NODE_SHELL_BASE = "#121212"; // 节点外壳深底(原 #0B1320 的中性化)
36const NODE_CORE_BASE = "#767676"; // 节点核心灰(原 #5A7A9E 的中性化)
37const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化)
38const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键)
39const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例
40const RING_SELECTED = "#E7C57C"; // 选中金环
41const RING_HOVERED = "#8FE7FF"; // 悬停冰青环
42const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝)
43// 注意:sigma 边着色器在预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB,
44// alpha 无法压暗边——暗度必须编码进 RGB(不透明近背景色)
45const EDGE_DIM = "#141414";
46const EDGE_FOCUS = "rgba(255,255,255,0.55)";
47const MUTED_SHELL = "#151515";
48const PILL_BG = "rgba(12,12,12,0.9)";
49const PILL_BORDER = "rgba(255,255,255,0.14)";
50const PILL_TEXT = "#ededed";
51const TRANSPARENT = "rgba(0,0,0,0)";
52const DAY_MS = 24 * 3600 * 1000;
53const MONTH_MS = 30 * DAY_MS;
54
55function hexToRgb(hex: string): [number, number, number] {
56 const m = /^#?([0-9a-f]{6})$/i.exec(hex);
57 if (!m) return [128, 128, 128];
58 const v = parseInt(m[1], 16);
59 return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
60}
61
62/** c1 向 c2 按 t 比例混色 */
63function mix(c1: string, c2: string, t: number): string {
64 const [r1, g1, b1] = hexToRgb(c1);
65 const [r2, g2, b2] = hexToRgb(c2);
66 const f = (a: number, b: number) => Math.round(a + (b - a) * t);
67 return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`;
68}
69
70/* 播放淡入:解析 hex / rgb / rgba(含 alpha)并线性插值 */
71function parseRgba(c: string): [number, number, number, number] {
72 if (c.startsWith("#")) {
73 const [r, g, b] = hexToRgb(c);
74 return [r, g, b, 1];
75 }
76 const m = c.match(/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/);
77 if (!m) return [128, 128, 128, 1];
78 return [+m[1], +m[2], +m[3], m[4] !== undefined ? +m[4] : 1];
79}
80function lerpColor(from: string, to: string, t: number): string {
81 const a = parseRgba(from);
82 const b = parseRgba(to);
83 const f = (i: number) => a[i] + (b[i] - a[i]) * t;
84 return `rgba(${Math.round(f(0))},${Math.round(f(1))},${Math.round(f(2))},${f(3).toFixed(3)})`;
85}
86/** 播放中新元素的淡入时长 */
87const FADE_MS = 320;
88
89/* 世界坐标网格:随相机平移/缩放(Figma/tldraw 式无限画布惯例)。
90 4 倍细分 LOD:每层 alpha 随其屏幕间距连续淡入(13px 进场 → 52px 满亮 5.5%),
91 粗层与细层线重合处自然叠亮,形成"大小格"层次;无任何跳变。 */
92const GRID_BASE_WORLD = 24; // 基准世界格距(匹配 ~300 尺度的布局)
93const GRID_FADE_IN_PX = 13;
94const GRID_FULL_PX = 52;
95const GRID_MAX_LEVEL_PX = 480;
96const GRID_MAX_ALPHA = 0.055;
97
98function drawWorldGrid(canvas: HTMLCanvasElement, sigma: Sigma): void {
99 const ctx = canvas.getContext("2d");
100 if (!ctx) return;
101 const { width, height } = sigma.getDimensions();
102 const dpr = window.devicePixelRatio || 1;
103 const pw = Math.round(width * dpr);
104 const ph = Math.round(height * dpr);
105 if (canvas.width !== pw || canvas.height !== ph) {
106 canvas.width = pw;
107 canvas.height = ph;
108 }
109 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
110 ctx.clearRect(0, 0, width, height);
111 if (width <= 0 || height <= 0) return;
112
113 // 世界→屏幕:两个探针点求每世界单位像素数与原点位置(无相机旋转场景)
114 const p0 = sigma.graphToViewport({ x: 0, y: 0 });
115 const p1 = sigma.graphToViewport({ x: 1, y: 0 });
116 const ppw = p1.x - p0.x;
117 if (!Number.isFinite(ppw) || ppw <= 0) return;
118
119 // 最细可见层级:屏幕间距 ≥ 淡入阈值的最小 4 幂格距
120 let spacing = GRID_BASE_WORLD;
121 while (spacing * ppw < GRID_FADE_IN_PX) spacing *= 4;
122 while (spacing * ppw >= GRID_FADE_IN_PX * 4) spacing /= 4;
123
124 for (let sp = spacing; sp * ppw < GRID_MAX_LEVEL_PX; sp *= 4) {
125 const ss = sp * ppw;
126 const t = Math.min(1, (ss - GRID_FADE_IN_PX) / (GRID_FULL_PX - GRID_FADE_IN_PX));
127 if (t <= 0) continue;
128 ctx.strokeStyle = `rgba(255,255,255,${(GRID_MAX_ALPHA * t).toFixed(4)})`;
129 ctx.lineWidth = 1;
130 ctx.beginPath();
131 const startX = ((p0.x % ss) + ss) % ss;
132 for (let x = startX; x <= width; x += ss) {
133 const px = Math.round(x) + 0.5;
134 ctx.moveTo(px, 0);
135 ctx.lineTo(px, height);
136 }
137 const startY = ((p0.y % ss) + ss) % ss;
138 for (let y = startY; y <= height; y += ss) {
139 const py = Math.round(y) + 0.5;
140 ctx.moveTo(0, py);
141 ctx.lineTo(width, py);
142 }
143 ctx.stroke();
144 }
145}
146
147/* 胶囊标签:深色圆角底 + 柔和文字(学 Semantica 的浮签风格) */
148// eslint-disable-next-line @typescript-eslint/no-explicit-any
149function drawPillLabel(ctx: CanvasRenderingContext2D, data: any, settings: any): void {
150 if (!data.label) return;
151 // hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签
152 if (data.hideBaseLabel) return;
153 // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12
154 const size = Math.max(10, Math.min(11, data.size * 0.25));
155 ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`;
156 ctx.textBaseline = "middle";
157 const padX = 6;
158 const padY = 3;
159 const w = ctx.measureText(data.label).width + padX * 2;
160 const h = size + padY * 2;
161 const x = data.x + Math.max(data.size * 0.7, 12);
162 const y = data.y - Math.max(data.size * 0.9, 10) - h;
163 ctx.save();
164 ctx.shadowColor = "rgba(0,0,0,0.6)";
165 ctx.shadowBlur = 12;
166 ctx.beginPath();
167 ctx.roundRect(x, y, w, h, 6);
168 ctx.fillStyle = PILL_BG;
169 ctx.fill();
170 ctx.shadowBlur = 0;
171 ctx.strokeStyle = PILL_BORDER;
172 ctx.lineWidth = 1;
173 ctx.stroke();
174 ctx.fillStyle = PILL_TEXT;
175 ctx.fillText(data.label, x + padX, y + h / 2);
176 ctx.restore();
177}
178
179/* Hover 悬浮卡(Semantica hoverCard 规格):径向柔光 + 名称 + 类型行 */
180// eslint-disable-next-line @typescript-eslint/no-explicit-any
181function drawHoverCard(ctx: CanvasRenderingContext2D, data: any, _settings: any): void {
182 if (!data.label) return;
183 ctx.save();
184
185 // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0
186 const glowR = Math.max(data.size * 4.8, 16);
187 const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888");
188 const grad = ctx.createRadialGradient(data.x, data.y, 0, data.x, data.y, glowR);
189 grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`);
190 grad.addColorStop(1, `rgba(${r},${g},${b},0)`);
191 ctx.fillStyle = grad;
192 ctx.beginPath();
193 ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2);
194 ctx.fill();
195
196 // 卡片: 标题 700/13 + 类型行 500/10 大写
197 const titleSize = 13;
198 const metaSize = 10;
199 const padX = 10;
200 const padY = 7;
201 const metaGap = 5;
202 const meta = String(data.typeLabel ?? "NODE").toUpperCase();
203 ctx.textBaseline = "top";
204 ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
205 const titleW = ctx.measureText(data.label).width;
206 ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
207 const metaW = ctx.measureText(meta).width;
208 const w = Math.max(titleW, metaW) + padX * 2;
209 const h = padY * 2 + titleSize + metaGap + metaSize;
210 const x = data.x + Math.max(data.size * 0.9, 16);
211 const y = data.y - Math.max(data.size * 1.1, 16) - h;
212
213 ctx.shadowColor = "rgba(0,0,0,0.62)";
214 ctx.shadowBlur = 15;
215 ctx.beginPath();
216 ctx.roundRect(x, y, w, h, 8);
217 ctx.fillStyle = "rgba(12,12,12,0.94)";
218 ctx.fill();
219 ctx.shadowBlur = 0;
220 ctx.strokeStyle = "rgba(255,255,255,0.16)";
221 ctx.lineWidth = 1;
222 ctx.stroke();
223
224 ctx.fillStyle = "#f5f5f5";
225 ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`;
226 ctx.fillText(data.label, x + padX, y + padY);
227 ctx.fillStyle = "rgba(255,255,255,0.5)";
228 ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`;
229 ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap);
230 ctx.restore();
231}
232
233export function Graph() {
234 const { kb } = useKb();
235 // 深链入口:/graph?entity=… 直接聚焦并选中该实体(证据两跳可达的反向路径)
236 const { entity: entityParam } = useSearch({ from: "/app/graph" });
237 const [focusEntity, setFocusEntity] = useState<string | null>(entityParam ?? null);
238 const [selected, setSelected] = useState<string | null>(entityParam ?? null);
239 const [searchInput, setSearchInput] = useState("");
240 const [searchQ, setSearchQ] = useState("");
241 const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set());
242 /** null = 全时段;数值 = as-of 时刻(ms)。
243 默认 as-of 今天:时态平台的图谱默认呈现"现在的世界",
244 已闭合的事实不该与现行事实无差别并列(All time 是显式选择) */
245 const [timeT, setTimeT] = useState<number | null>(() => Date.now());
246 const [activeCount, setActiveCount] = useState(0);
247 const [stabilizing, setStabilizing] = useState(false);
248 /* 播放态提升到此层:reducer 需区分"播放推进"(淡入)与"手动拖动"(瞬切) */
249 const [playing, setPlaying] = useState(false);
250 /* 布局模式:force = FA2 斥力;circular = 圆环;pack = 按类型圆填充聚簇 */
251 type LayoutMode = "force" | "circular" | "pack";
252 const [layoutMode, setLayoutMode] = useState<LayoutMode>("force");
253 const layoutModeRef = useRef<LayoutMode>("force");
254 const layoutCtlRef = useRef<{ apply: (m: LayoutMode) => void } | null>(null);
255
256 const data = useQuery({
257 queryKey: ["graph", kb?.id, focusEntity],
258 queryFn: () =>
259 focusEntity ? api.graphNeighborhood(kb!.id, focusEntity) : api.graphOverview(kb!.id),
260 enabled: !!kb,
261 });
262
263 // 全图模式走全库实体搜索;子图模式只在已加载的子图内客户端过滤
264 const inSubgraph = !!focusEntity;
265 const candidates = useQuery({
266 queryKey: ["entitySearch", kb?.id, searchQ],
267 queryFn: () => api.searchEntities(kb!.id, searchQ),
268 enabled: !!kb && searchQ.length > 0 && !inSubgraph,
269 });
270 const subgraphHits = useMemo(() => {
271 if (!inSubgraph || !searchQ || !data.data) return [];
272 const q = searchQ.toLowerCase();
273 return data.data.nodes
274 .filter(
275 (n) =>
276 n.name.toLowerCase().includes(q) ||
277 n.disambiguator?.toLowerCase().includes(q),
278 )
279 .slice(0, 10);
280 }, [inSubgraph, searchQ, data.data]);
281 const searchHits = inSubgraph ? subgraphHits : (candidates.data?.entities ?? []);
282
283 const containerRef = useRef<HTMLDivElement>(null);
284 const gridRef = useRef<HTMLCanvasElement>(null);
285 const sigmaRef = useRef<Sigma | null>(null);
286 /* 焦点 = hover 优先于选中;样式在 reducer 里统一处理 */
287 const selectedRef = useRef<string | null>(null);
288 const hoverRef = useRef<string | null>(null);
289 const filterRef = useRef<{
290 hiddenTypes: Set<string>;
291 activeNodes: Set<string> | null;
292 activeEdges: Set<string> | null;
293 }>({ hiddenTypes: new Set(), activeNodes: null, activeEdges: null });
294 const playingRef = useRef(false);
295 /* 播放淡入表:本轮新激活的节点/边 id → 激活时刻(rAF 循环驱动至到位) */
296 const fadeRef = useRef<Map<string, number>>(new Map());
297 const fadeRafRef = useRef(0);
298
299 const kickFade = useCallback(() => {
300 if (fadeRafRef.current) return;
301 const step = () => {
302 const now = performance.now();
303 for (const [id, start] of fadeRef.current)
304 if (now - start >= FADE_MS) fadeRef.current.delete(id);
305 sigmaRef.current?.refresh();
306 fadeRafRef.current = fadeRef.current.size ? requestAnimationFrame(step) : 0;
307 };
308 fadeRafRef.current = requestAnimationFrame(step);
309 }, []);
310
311 useEffect(() => {
312 playingRef.current = playing;
313 if (!playing) {
314 // 停止播放:未完成的淡入直接到位
315 fadeRef.current.clear();
316 sigmaRef.current?.refresh();
317 }
318 }, [playing]);
319
320 useEffect(() => () => cancelAnimationFrame(fadeRafRef.current), []);
321
322 const types = useMemo(() => {
323 const map = new Map<string, { label: string; color: string; shape: string }>();
324 for (const n of data.data?.nodes ?? []) {
325 // 没判出类型的归到空 key 一档(0009)。真实 key 由 IRI 派生,不可能为空,
326 // 所以它撞不着任何一个类;标签走 i18n,别把 null 画到图例上
327 const key = n.type_key ?? "";
328 if (!map.has(key))
329 map.set(key, {
330 label: n.type_label ?? S.graph.untyped,
331 color: n.color,
332 shape: n.shape,
333 });
334 }
335 return [...map.entries()];
336 }, [data.data]);
337
338 /* 时间过滤:计算 T 时刻的活跃边/节点集合 */
339 const recomputeActive = useCallback(
340 (t: number | null) => {
341 const d = data.data;
342 if (!d) return;
343 if (t === null) {
344 filterRef.current.activeNodes = null;
345 filterRef.current.activeEdges = null;
346 setActiveCount(d.edges.length);
347 } else {
348 const prevNodes = filterRef.current.activeNodes;
349 const prevEdges = filterRef.current.activeEdges;
350 const edges = new Set<string>();
351 const nodes = new Set<string>();
352 const touched = new Set<string>();
353 for (const e of d.edges) {
354 const vf = e.valid_from ? Date.parse(e.valid_from) : null;
355 const vt = e.valid_to ? Date.parse(e.valid_to) : null;
356 touched.add(e.source);
357 touched.add(e.target);
358 const active = vf === null ? true : vf <= t && (vt === null || vt > t);
359 if (active) {
360 edges.add(e.id);
361 nodes.add(e.source);
362 nodes.add(e.target);
363 }
364 }
365 // 没有任何边的孤立节点保持可见
366 for (const n of d.nodes) if (!touched.has(n.id)) nodes.add(n.id);
367 // 播放推进时新出现的元素淡入登场;手动拖动保持瞬时切换
368 if (playingRef.current) {
369 const now = performance.now();
370 for (const id of edges) if (prevEdges && !prevEdges.has(id)) fadeRef.current.set(id, now);
371 for (const id of nodes) if (prevNodes && !prevNodes.has(id)) fadeRef.current.set(id, now);
372 if (fadeRef.current.size) kickFade();
373 }
374 filterRef.current.activeNodes = nodes;
375 filterRef.current.activeEdges = edges;
376 setActiveCount(edges.size);
377 }
378 sigmaRef.current?.refresh();
379 },
380 [data.data, kickFade],
381 );
382
383 useEffect(() => {
384 filterRef.current.hiddenTypes = hiddenTypes;
385 sigmaRef.current?.refresh();
386 }, [hiddenTypes]);
387
388 useEffect(() => {
389 selectedRef.current = selected;
390 sigmaRef.current?.refresh();
391 }, [selected]);
392
393 useEffect(() => {
394 recomputeActive(timeT);
395 }, [timeT, recomputeActive]);
396
397 useEffect(() => {
398 if (!containerRef.current || !data.data) return;
399 const g = new Graphology({ multi: true });
400 for (const n of data.data.nodes) {
401 if (!g.hasNode(n.id)) {
402 g.addNode(n.id, {
403 label: n.name,
404 // Semantica 配方:深壳 + 14% 类型 tint,核心 50% tint,钢灰描边微 tint
405 color: mix(NODE_CORE_BASE, n.color, NODE_CORE_MIX),
406 shellColor: mix(NODE_SHELL_BASE, n.color, NODE_TINT_MIX),
407 borderColor: mix(NODE_BORDER_BASE, n.color, 0.3),
408 ringColor: TRANSPARENT,
409 typeColor: n.color,
410 typeLabel: n.type_label ?? S.graph.untyped,
411 typeKey: n.type_key ?? "",
412 type: n.shape === "square" ? "square" : "shell",
413 size: 5 + Math.min(8, Math.sqrt(Number(n.degree)) * 1.6),
414 });
415 }
416 }
417 for (const e of data.data.edges) {
418 if (g.hasNode(e.source) && g.hasNode(e.target)) {
419 g.addEdgeWithKey(e.id, e.source, e.target, {
420 label: e.label.toUpperCase(),
421 size: 1,
422 color: EDGE_COLOR,
423 type: "line",
424 });
425 }
426 }
427 // 布局:先静态铺开,再用 worker 动画稳定 ~2.5s(Semantica 式 stabilizing)
428 let fa2: InstanceType<typeof FA2Layout> | null = null;
429 let stabilizeTimer: ReturnType<typeof setTimeout> | null = null;
430 // 拖拽状态先于 fa2 声明:outputReducer 闭包引用它们
431 let dragged: string | null = null;
432 let dragPos: { x: number; y: number } | null = null;
433 let fa2Settings: ReturnType<typeof forceAtlas2.inferSettings> | null = null;
434 if (g.order > 0) {
435 circular.assign(g, { scale: 300 });
436 const settings = {
437 ...forceAtlas2.inferSettings(g),
438 gravity: 0.35,
439 scalingRatio: 22,
440 outboundAttractionDistribution: true,
441 };
442 fa2Settings = settings;
443 forceAtlas2.assign(g, { iterations: 60, settings });
444 fa2 = new FA2Layout(g, {
445 settings,
446 // 关键:回写时把被拖节点钉回光标(不闪);且提供 outputReducer 后
447 // supervisor 每帧 readGraphPositions —— 光标位置持续进入力模拟
448 outputReducer: (node, attr) => {
449 if (dragged && node === dragged && dragPos) {
450 attr.x = dragPos.x;
451 attr.y = dragPos.y;
452 }
453 return attr;
454 },
455 });
456 fa2.start();
457 setStabilizing(true);
458 stabilizeTimer = setTimeout(() => {
459 fa2?.stop();
460 setStabilizing(false);
461 }, 2500);
462 }
463
464 // 数据重建后布局回到 force(世界重新长出来)
465 setLayoutMode("force");
466 layoutModeRef.current = "force";
467
468 // 任意布局结果统一缩放到 FA2 同量级世界(±target),相机 reset 观感一致
469 const rescaleWorld = (target = 300) => {
470 let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
471 g.forEachNode((_n, a) => {
472 minX = Math.min(minX, a.x as number);
473 maxX = Math.max(maxX, a.x as number);
474 minY = Math.min(minY, a.y as number);
475 maxY = Math.max(maxY, a.y as number);
476 });
477 const span = Math.max(maxX - minX, maxY - minY) || 1;
478 const k = (target * 2) / span;
479 const cx = (minX + maxX) / 2;
480 const cy = (minY + maxY) / 2;
481 g.updateEachNodeAttributes((_n, a) => ({ ...a, x: (a.x - cx) * k, y: (a.y - cy) * k }));
482 };
483
484 // 布局切换控制(挂到 ref 供组件层按钮调用;闭包内直握 g / fa2)
485 layoutCtlRef.current = {
486 apply: (mode) => {
487 if (g.order === 0) return;
488 if (stabilizeTimer) clearTimeout(stabilizeTimer);
489 fa2?.stop();
490 setStabilizing(false);
491 if (mode === "force") {
492 forceAtlas2.assign(g, { iterations: 60, settings: fa2Settings ?? undefined });
493 fa2?.start();
494 setStabilizing(true);
495 stabilizeTimer = setTimeout(() => {
496 fa2?.stop();
497 setStabilizing(false);
498 }, 2500);
499 } else if (mode === "circular") {
500 circular.assign(g, { scale: 300 });
501 } else {
502 // 按实体类型聚簇:同类型挤进同一个圆
503 circlepack.assign(g, { hierarchyAttributes: ["typeKey"] });
504 rescaleWorld(300);
505 }
506 sigma.setCustomBBox(null);
507 sigma.refresh();
508 sigma.getCamera().animatedReset({ duration: 300 });
509 },
510 };
511
512 sigmaRef.current?.kill();
513 const sigma = new Sigma(g, containerRef.current, {
514 allowInvalidContainer: true,
515 defaultNodeType: "shell",
516 nodeProgramClasses: {
517 // Semantica 节点解剖:状态环 → 描边 → 深色壳 → 微彩核心
518 shell: createNodeBorderProgram({
519 borders: [
520 { size: { value: 0.1 }, color: { attribute: "ringColor" } },
521 { size: { value: 0.07 }, color: { attribute: "borderColor" } },
522 { size: { value: 0.3 }, color: { attribute: "shellColor" } },
523 { size: { fill: true }, color: { attribute: "color" } },
524 ],
525 }),
526 square: NodeSquareShellProgram,
527 },
528 renderEdgeLabels: true,
529 defaultEdgeType: "line",
530 labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif',
531 labelSize: 11,
532 labelColor: { color: "#e5e5e5" },
533 labelRenderedSizeThreshold: 6,
534 labelDensity: 0.7,
535 labelGridCellSize: 140,
536 minCameraRatio: 0.04,
537 maxCameraRatio: 8,
538 edgeLabelSize: 9,
539 edgeLabelColor: { color: "#a1a1a1" },
540 edgeLabelFont: '"Geist", "Inter", sans-serif',
541 defaultDrawNodeLabel: drawPillLabel,
542 defaultDrawNodeHover: drawHoverCard,
543 nodeReducer: (node, attrs) => {
544 const f = filterRef.current;
545 const res = { ...attrs };
546 const base = attrs.size as number;
547 if (f.hiddenTypes.has(attrs.typeKey as string)) {
548 res.hidden = true;
549 return res;
550 }
551 // Semantica 状态表: muted { ×0.52, 全层压暗 }
552 const muteNode = () => {
553 res.size = base * 0.52;
554 res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3);
555 res.shellColor = MUTED_SHELL;
556 res.borderColor = TRANSPARENT;
557 res.ringColor = TRANSPARENT;
558 res.label = "";
559 res.zIndex = 0;
560 };
561 // hover 只提亮自身(不压暗全图);压暗聚焦只属于点击选中
562 if (hoverRef.current === node) {
563 res.size = Math.max(base * 1.08, 10.4);
564 res.ringColor = RING_HOVERED;
565 // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题)
566 res.hideBaseLabel = true;
567 res.zIndex = 4;
568 return res;
569 }
570 // 选中实体可能不在当前画布(侧栏跳转/邻域重载间隙)——不在则跳过聚焦压暗逻辑
571 const sel = selectedRef.current && g.hasNode(selectedRef.current) ? selectedRef.current : null;
572 if (sel) {
573 if (node === sel) {
574 res.size = Math.max(base * 1.02, 9.2);
575 res.ringColor = RING_SELECTED;
576 res.forceLabel = true;
577 res.zIndex = 3;
578 return res;
579 }
580 if (g.areNeighbors(sel, node)) {
581 // neighbor {×0.76, min 4, zIndex 2}
582 res.size = Math.max(base * 0.76, 4);
583 res.zIndex = 2;
584 } else {
585 muteNode();
586 return res;
587 }
588 } else {
589 // default {×0.7}
590 res.size = base * 0.7;
591 }
592 if (f.activeNodes && !f.activeNodes.has(node)) {
593 muteNode();
594 return res;
595 }
596 // 播放淡入:从 muted 形态渐变到本帧算出的正常形态
597 const fs = fadeRef.current.get(node);
598 if (fs !== undefined) {
599 const t = Math.min(1, (performance.now() - fs) / FADE_MS);
600 res.size = (res.size as number) * (0.55 + 0.45 * t);
601 res.color = lerpColor(MUTED_SHELL, String(res.color ?? NODE_CORE_BASE), t);
602 res.shellColor = lerpColor(MUTED_SHELL, String(res.shellColor ?? NODE_SHELL_BASE), t);
603 res.borderColor = lerpColor("rgba(0,0,0,0)", String(res.borderColor ?? NODE_BORDER_BASE), t);
604 if (t < 0.7) res.label = "";
605 }
606 return res;
607 },
608 edgeReducer: (edge, attrs) => {
609 const f = filterRef.current;
610 const res = { ...attrs };
611 const [s, t] = g.extremities(edge);
612 const sk = g.getNodeAttribute(s, "typeKey") as string;
613 const tk = g.getNodeAttribute(t, "typeKey") as string;
614 if (f.hiddenTypes.has(sk) || f.hiddenTypes.has(tk)) {
615 res.hidden = true;
616 return res;
617 }
618 // hover: 只提亮关联边;selected: 提亮关联边 + 压暗其余
619 const hov = hoverRef.current;
620 const sel =
621 selectedRef.current && g.hasNode(selectedRef.current) ? selectedRef.current : null;
622 const boost = () => {
623 res.color = EDGE_FOCUS;
624 res.size = Math.max((attrs.size as number) * 1.42, 1.85);
625 res.zIndex = 5;
626 };
627 if (hov && (s === hov || t === hov)) {
628 boost();
629 } else if (sel) {
630 if (s === sel || t === sel) {
631 boost();
632 } else {
633 res.color = EDGE_DIM;
634 res.size = (attrs.size as number) * 0.6;
635 res.label = "";
636 return res;
637 }
638 }
639 if (f.activeEdges && !f.activeEdges.has(edge)) {
640 res.color = EDGE_DIM;
641 res.label = "";
642 return res;
643 }
644 // 播放淡入:边从近背景色渐亮到常规色(alpha 同步插值)
645 const fs = fadeRef.current.get(edge);
646 if (fs !== undefined) {
647 const t = Math.min(1, (performance.now() - fs) / FADE_MS);
648 res.color = lerpColor(EDGE_DIM, String(res.color), t);
649 if (t < 0.8) res.label = "";
650 }
651 return res;
652 },
653 });
654 sigma.on("clickNode", ({ node }) => setSelected(node));
655 sigma.on("doubleClickNode", ({ node, event }) => {
656 event.preventSigmaDefault();
657 setFocusEntity(node);
658 setSelected(node);
659 });
660 sigma.on("clickStage", () => setSelected(null));
661 sigma.on("enterNode", ({ node }) => {
662 hoverRef.current = node;
663 sigma.refresh();
664 });
665 sigma.on("leaveNode", () => {
666 hoverRef.current = null;
667 sigma.refresh();
668 });
669 // 边标签只在放大后出现(默认视距下太密,Semantica 同样克制)
670 const updateEdgeLabels = () =>
671 sigma.setSetting("renderEdgeLabels", sigma.getCamera().ratio < 0.7);
672 sigma.getCamera().on("updated", updateEdgeLabels);
673 updateEdgeLabels();
674
675 // 世界坐标网格:相机变动/容器尺寸变动时重绘
676 const renderGrid = () => {
677 if (gridRef.current) drawWorldGrid(gridRef.current, sigma);
678 };
679 sigma.getCamera().on("updated", renderGrid);
680 sigma.on("resize", renderGrid);
681 renderGrid();
682
683 // 节点拖拽 + 活的力导反馈。按下只记候选:视口位移 >4px 才升格为拖拽
684 //(否则纯点选也会误启 FA2);被拖节点由 fa2 的 outputReducer 钉在光标上(见上),
685 // 松手后稳定 ~1.2s 停机
686 let settleTimer: ReturnType<typeof setTimeout> | null = null;
687 let dragCandidate: string | null = null;
688 let downPoint: { x: number; y: number } | null = null;
689 sigma.on("downNode", (e) => {
690 dragCandidate = e.node;
691 downPoint = { x: e.event.x, y: e.event.y };
692 });
693 sigma.getMouseCaptor().on("mousemovebody", (e) => {
694 if (!dragCandidate) return;
695 if (!dragged) {
696 if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4) return;
697 // 升格为拖拽
698 dragged = dragCandidate;
699 if (settleTimer) clearTimeout(settleTimer);
700 // 静态布局(circular/pack)下拖拽不唤醒力模拟——否则一碰就散架
701 if (layoutModeRef.current === "force" && fa2 && !fa2.isRunning()) fa2.start();
702 // 固定当前包围盒,避免拖拽时相机自动跟随缩放
703 if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox());
704 }
705 const pos = sigma.viewportToGraph(e);
706 dragPos = pos;
707 g.setNodeAttribute(dragged, "x", pos.x);
708 g.setNodeAttribute(dragged, "y", pos.y);
709 // 阻止相机平移
710 e.preventSigmaDefault();
711 e.original.preventDefault();
712 e.original.stopPropagation();
713 });
714 const endDrag = () => {
715 dragCandidate = null;
716 downPoint = null;
717 if (!dragged) return;
718 dragged = null;
719 dragPos = null;
720 settleTimer = setTimeout(() => fa2?.stop(), 1200);
721 };
722 sigma.getMouseCaptor().on("mouseup", endDrag);
723 sigmaRef.current = sigma;
724 if (import.meta.env.DEV) {
725 // 调试句柄(仅 dev):无头环境下检查 reducer 输出
726 (window as unknown as Record<string, unknown>).__g = g;
727 (window as unknown as Record<string, unknown>).__sigma = sigma;
728 (window as unknown as Record<string, unknown>).__sel = selectedRef;
729 }
730 recomputeActive(timeT);
731 return () => {
732 if (stabilizeTimer) clearTimeout(stabilizeTimer);
733 if (settleTimer) clearTimeout(settleTimer);
734 fa2?.kill();
735 setStabilizing(false);
736 sigma.kill();
737 sigmaRef.current = null;
738 };
739 // eslint-disable-next-line react-hooks/exhaustive-deps
740 }, [data.data]);
741
742 if (!kb) return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>;
743
744 const empty = data.isSuccess && data.data.nodes.length === 0;
745 const nodeCount = data.data?.nodes.length ?? 0;
746 const edgeCount = data.data?.edges.length ?? 0;
747
748 return (
749 <div className="h-full relative">
750 {/* 顶部悬浮条:搜索 + 图例 + 状态 */}
751 <div className="absolute top-3 left-3 right-3 z-10 flex items-start gap-2 pointer-events-none">
752 <div className="relative pointer-events-auto">
753 <input
754 className="input-dark w-60 px-3 py-1.5 text-sm shadow-lg"
755 placeholder={inSubgraph ? S.graph.searchInSubgraph : S.graph.searchEntity}
756 value={searchInput}
757 onChange={(e) => {
758 setSearchInput(e.target.value);
759 setSearchQ(e.target.value.trim());
760 }}
761 />
762 {searchQ && searchHits.length > 0 && (
763 <div className="glass-strong absolute mt-1 w-full rounded-lg shadow-xl overflow-hidden">
764 {searchHits.map((c) => (
765 <button
766 key={c.id}
767 onClick={() => {
768 // 子图内命中:只选中(已在视野里);全图搜索:跳到该实体邻域
769 if (!inSubgraph) setFocusEntity(c.id);
770 setSelected(c.id);
771 setSearchInput("");
772 setSearchQ("");
773 }}
774 className="w-full px-3 py-1.5 text-left text-sm text-neutral-200 hover:bg-white/5 flex items-center gap-2"
775 >
776 <span
777 className="h-2.5 w-2.5 rounded-full shrink-0"
778 style={{ background: c.color }}
779 />
780 <span className="truncate">{c.name}</span>
781 {c.disambiguator && (
782 <span className="text-xs text-neutral-500 truncate">· {c.disambiguator}</span>
783 )}
784 <span className="ml-auto text-xs text-neutral-500">{c.type_label}</span>
785 </button>
786 ))}
787 </div>
788 )}
789 </div>
790 {focusEntity && (
791 <button
792 onClick={() => setFocusEntity(null)}
793 className="u-btn u-btn-ghost glass-strong pointer-events-auto px-3 py-1.5 text-sm shadow-lg"
794 >
795 {S.graph.backToOverview}
796 </button>
797 )}
798
799 {/* 图例(点击切换类型显隐) */}
800 <div className="pointer-events-auto flex flex-wrap gap-1.5 pt-0.5">
801 {types.map(([key, t]) => (
802 <button
803 key={key}
804 onClick={() =>
805 setHiddenTypes((prev) => {
806 const next = new Set(prev);
807 if (next.has(key)) next.delete(key);
808 else next.add(key);
809 return next;
810 })
811 }
812 className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-opacity ${
813 hiddenTypes.has(key) ? "opacity-35" : ""
814 }`}
815 >
816 <span
817 className={`h-2 w-2 ${t.shape === "square" ? "" : "rounded-full"}`}
818 style={{ background: t.color }}
819 />
820 <span className="text-neutral-300">{t.label}</span>
821 </button>
822 ))}
823 </div>
824
825 <div className="ml-auto pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500">
826 {stabilizing && <span className="text-neutral-400">{S.graph.stabilizing} · </span>}
827 {S.graph.stats(nodeCount, edgeCount, timeT === null ? edgeCount : activeCount)}
828 </div>
829 </div>
830
831 {/* 画布:世界坐标网格层(随相机动)垫在 sigma WebGL 层下(全出血,时间岛悬浮其上) */}
832 <div className="absolute inset-0">
833 <canvas ref={gridRef} className="absolute inset-0 h-full w-full" />
834 <div ref={containerRef} className="absolute inset-0" />
835 </div>
836
837 {/* 左下控件塔:布局切换 + 相机(右下归实体侧栏,底部中央归时间岛) */}
838 <div className="absolute bottom-4 left-3 z-10 flex flex-col gap-2">
839 <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
840 {(
841 [
842 { key: "force", Icon: Orbit, label: S.graph.layoutForce },
843 { key: "circular", Icon: CircleDashed, label: S.graph.layoutCircular },
844 { key: "pack", Icon: Grape, label: S.graph.layoutPack },
845 ] as const
846 ).map(({ key, Icon, label }) => (
847 <button
848 key={key}
849 title={label}
850 onClick={() => {
851 setLayoutMode(key);
852 layoutModeRef.current = key;
853 layoutCtlRef.current?.apply(key);
854 }}
855 className={`p-2 transition-colors ${
856 layoutMode === key
857 ? "text-white bg-white/[0.1]"
858 : "text-neutral-400 hover:text-white hover:bg-white/[0.06]"
859 }`}
860 >
861 <Icon size={15} />
862 </button>
863 ))}
864 </div>
865 <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
866 <button
867 title={S.graph.zoomIn}
868 onClick={() => sigmaRef.current?.getCamera().animatedZoom({ duration: 220 })}
869 className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
870 >
871 <ZoomIn size={15} />
872 </button>
873 <button
874 title={S.graph.zoomOut}
875 onClick={() => sigmaRef.current?.getCamera().animatedUnzoom({ duration: 220 })}
876 className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
877 >
878 <ZoomOut size={15} />
879 </button>
880 <div className="h-px bg-white/10 mx-1.5" />
881 <button
882 title={S.graph.fitView}
883 onClick={() => sigmaRef.current?.getCamera().animatedReset({ duration: 300 })}
884 className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
885 >
886 <Maximize2 size={15} />
887 </button>
888 </div>
889 </div>
890
891 {empty && (
892 <div className="absolute inset-0 grid place-items-center pointer-events-none">
893 {/* 不放标题方块:页面本身就是图谱页,tab 条上也写着,
894 第三遍写"图谱"两个字不带任何信息。空状态该说的是下一步做什么 */}
895 <div className="text-center text-sm text-neutral-500 max-w-xs">
896 {S.graph.emptyBody}
897 </div>
898 </div>
899 )}
900
901 {/* 底部居中悬浮时间岛 */}
902 {edgeCount > 0 && (
903 <TimeScrubber
904 edges={data.data!.edges}
905 value={timeT}
906 onChange={setTimeT}
907 playing={playing}
908 onPlayingChange={setPlaying}
909 />
910 )}
911
912 {/* 实体侧栏 */}
913 {selected && kb && (
914 <EntityPanel
915 kbId={kb.id}
916 entityId={selected}
917 onClose={() => setSelected(null)}
918 onNavigate={(id) => {
919 // 跳转目标可能不在当前画布:同时把图 refocus 到它的邻域(与搜索选择一致)
920 setFocusEntity(id);
921 setSelected(id);
922 }}
923 />
924 )}
925 </div>
926 );
927}
928
929/* ============ 时间轴(底部居中悬浮岛:播放 + 密度带 + 拖动) ============ */
930
931/** 轨道 clientX → 对齐天步进的时间值(数据精度即 day,拖动求精细;播放仍按月推进求节奏)。 */
932function scrubValueAt(
933 clientX: number,
934 track: HTMLDivElement | null,
935 minTs: number,
936 maxTs: number,
937): number {
938 if (!track) return maxTs;
939 const rect = track.getBoundingClientRect();
940 // 布局未成形(宽度 0)时避免除零产出 NaN
941 if (rect.width < 1) return maxTs;
942 const frac = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width));
943 const raw = minTs + frac * (maxTs - minTs);
944 return Math.min(maxTs, minTs + Math.round((raw - minTs) / DAY_MS) * DAY_MS);
945}
946
947function TimeScrubber({
948 edges,
949 value,
950 onChange,
951 playing,
952 onPlayingChange,
953}: {
954 edges: GraphEdge[];
955 value: number | null;
956 onChange: (v: number | null) => void;
957 /* 播放态由 Graph 持有:渲染层要区分播放推进与手动拖动 */
958 playing: boolean;
959 onPlayingChange: (v: boolean) => void;
960}) {
961 const setPlaying = onPlayingChange;
962 const trackRef = useRef<HTMLDivElement>(null);
963 const draggingRef = useRef(false);
964
965 const { minTs, maxTs, bars } = useMemo(() => {
966 const now = Date.now();
967 const froms = edges
968 .map((e) => (e.valid_from ? Date.parse(e.valid_from) : NaN))
969 .filter((t) => !Number.isNaN(t));
970 const min = froms.length ? Math.min(...froms) : now - 5 * 365 * 24 * 3600 * 1000;
971 const minYear = new Date(min).getUTCFullYear();
972 const maxYear = new Date(now).getUTCFullYear();
973 const counts = new Map<number, number>();
974 for (const t of froms) {
975 const y = new Date(t).getUTCFullYear();
976 counts.set(y, (counts.get(y) ?? 0) + 1);
977 }
978 const peak = Math.max(1, ...counts.values());
979 const bars: { year: number; h: number }[] = [];
980 for (let y = minYear; y <= maxYear; y++) {
981 bars.push({ year: y, h: (counts.get(y) ?? 0) / peak });
982 }
983 return { minTs: Date.UTC(minYear, 0, 1), maxTs: now, bars };
984 }, [edges]);
985
986 // 播放按日推进(数据即 day 精度),日子快速翻过;整体节奏仍 ≈ 一个月/260ms。
987 // rAF 时间驱动:帧率无关,内部浮点累加避免取整漂移,值只在跨天时才下发
988 useEffect(() => {
989 if (!playing) return;
990 const SPEED = MONTH_MS / 260; // 每毫秒真实时间推进的时间线毫秒数
991 let raf = 0;
992 let last = performance.now();
993 let acc = value ?? minTs;
994 let lastSnapped = Number.NaN;
995 const step = (now: number) => {
996 acc += (now - last) * SPEED;
997 last = now;
998 if (acc >= maxTs) {
999 setPlaying(false);
1000 onChange(null);
1001 return;
1002 }
1003 const snapped = minTs + Math.round((acc - minTs) / DAY_MS) * DAY_MS;
1004 if (snapped !== lastSnapped) {
1005 lastSnapped = snapped;
1006 onChange(snapped);
1007 }
1008 raf = requestAnimationFrame(step);
1009 };
1010 raf = requestAnimationFrame(step);
1011 return () => cancelAnimationFrame(raf);
1012 // 只随播放开关重启:acc 在循环内自持,value 帧帧变不应重建循环
1013 // eslint-disable-next-line react-hooks/exhaustive-deps
1014 }, [playing, minTs, maxTs]);
1015
1016 // 展示到日:与数据的 day 级 valid_precision 对齐
1017 const label = (() => {
1018 if (value === null) return S.graph.allTime;
1019 const d = new Date(value);
1020 const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
1021 const dd = String(d.getUTCDate()).padStart(2, "0");
1022 return `${d.getUTCFullYear()}-${mm}-${dd}`;
1023 })();
1024
1025 const minYear = bars[0]?.year;
1026 const maxYear = bars[bars.length - 1]?.year;
1027
1028 return (
1029 <div className="glass-strong absolute bottom-4 left-1/2 -translate-x-1/2 z-10 w-[min(560px,calc(100%-4rem))] rounded-2xl px-3 py-2 flex items-center gap-2.5 shadow-[0_12px_40px_rgba(0,0,0,0.5)]">
1030 <button
1031 onClick={() => {
1032 if (!playing && value === null) onChange(minTs);
1033 setPlaying(!playing);
1034 }}
1035 title={playing ? S.graph.pause : S.graph.play}
1036 className="u-btn u-btn-ghost h-8 w-8 shrink-0 grid place-items-center rounded-lg"
1037 >
1038 {playing ? <Pause size={13} /> : <Play size={13} />}
1039 </button>
1040
1041 <span className="shrink-0 u-num text-[10px] text-neutral-600">
1042 {minYear}
1043 </span>
1044
1045 {/* 密度带轨道:内嵌浅色井 + 每年事实量柱 */}
1046 <div ref={trackRef} className="relative flex-1 h-9 rounded-lg bg-white/[0.04]">
1047 <div className="absolute inset-x-1.5 top-1.5 bottom-1.5 flex items-end gap-[2px]">
1048 {bars.map((b) => {
1049 // 进入即亮(年初为判据):播放头脚下的柱子即已覆盖——进度条通用语义
1050 const barTs = Date.UTC(b.year, 0, 1);
1051 const past = value !== null && barTs <= value;
1052 return (
1053 <div key={b.year} className="flex-1 flex items-end h-full" title={`${b.year}`}>
1054 <div
1055 className="w-full rounded-[1px] transition-colors"
1056 style={{
1057 height: `${Math.max(10, b.h * 100)}%`,
1058 // 播放中已扫过的年份提亮,停止后回到常规亮度
1059 background:
1060 value !== null && past && playing
1061 ? "rgba(255,255,255,0.62)"
1062 : value === null || past
1063 ? "rgba(255,255,255,0.32)"
1064 : "rgba(255,255,255,0.09)",
1065 }}
1066 />
1067 </div>
1068 );
1069 })}
1070 </div>
1071 <input
1072 type="range"
1073 className="scrubber-range"
1074 min={minTs}
1075 max={maxTs}
1076 step={DAY_MS}
1077 value={value ?? maxTs}
1078 onChange={(e) => {
1079 setPlaying(false);
1080 onChange(Number(e.target.value));
1081 }}
1082 // 原生 range 的拖拽手势会被页面级鼠标监听(如图上拖节点)干扰——
1083 // 自己用 pointer capture 驱动拖动,点击与拖拽都走同一条计算路径
1084 onPointerDown={(e) => {
1085 setPlaying(false);
1086 draggingRef.current = true;
1087 try {
1088 e.currentTarget.setPointerCapture(e.pointerId);
1089 } catch {
1090 /* 合成事件的 pointerId 可能无效,忽略 */
1091 }
1092 onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
1093 }}
1094 onPointerMove={(e) => {
1095 if (draggingRef.current)
1096 onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
1097 }}
1098 onPointerUp={() => {
1099 draggingRef.current = false;
1100 }}
1101 onPointerCancel={() => {
1102 draggingRef.current = false;
1103 }}
1104 />
1105 </div>
1106
1107 <span className="shrink-0 u-num text-[10px] text-neutral-600">
1108 {maxYear}
1109 </span>
1110
1111 <div className="w-[5.6rem] shrink-0 text-center u-num text-xs text-neutral-200">
1112 {label}
1113 </div>
1114
1115 <div className="h-5 w-px shrink-0 bg-white/10" />
1116
1117 {/* 双锚点分段:所处锚点高亮、点击即跳;拖在中间某天时两者皆不亮 */}
1118 <div className="flex shrink-0 rounded-lg overflow-hidden border border-white/10">
1119 {(
1120 [
1121 { key: "all", label: S.graph.allTime, active: value === null, to: null },
1122 {
1123 key: "now",
1124 label: S.graph.nowBtn,
1125 active: value !== null && maxTs - value < DAY_MS,
1126 to: maxTs,
1127 },
1128 ] as const
1129 ).map((a) => (
1130 <button
1131 key={a.key}
1132 onClick={() => {
1133 setPlaying(false);
1134 onChange(a.to);
1135 }}
1136 className={`px-2.5 py-1.5 text-xs transition-colors ${
1137 a.active
1138 ? "bg-white/10 text-neutral-100"
1139 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
1140 }`}
1141 >
1142 {a.label}
1143 </button>
1144 ))}
1145 </div>
1146 </div>
1147 );
1148}
1149
1150/* ============ 实体侧栏 ============ */
1151
1152function fmtTime(iso: string | null, precision: string | null): string | null {
1153 if (!iso) return null;
1154 const d = new Date(iso);
1155 const y = d.getUTCFullYear();
1156 const m = String(d.getUTCMonth() + 1).padStart(2, "0");
1157 const day = String(d.getUTCDate()).padStart(2, "0");
1158 if (precision === "year") return `${y}`;
1159 if (precision === "month") return `${y}-${m}`;
1160 return `${y}-${m}-${day}`;
1161}
1162
1163function fmtInterval(f: EntityFact): string {
1164 if (f.temporal === "eternal") return "";
1165 const from = fmtTime(f.valid_from, f.valid_from_precision);
1166 const to = fmtTime(f.valid_to, f.valid_to_precision);
1167 // **「结束了但不知哪天」绝不能显示成「至今」。** 那是这条改动要修的正脸:
1168 // 原文明说 "former CEO of Weta Digital",界面却告诉读者他还在任
1169 const endedUnknown = !f.valid_to && f.valid_to_precision === "unknown";
1170 if (!from && !to && !endedUnknown) return "";
1171 const end = to ?? (endedUnknown ? S.graph.endedUnknown : S.graph.ongoing);
1172 return from ? `${from} ~ ${end}` : `~ ${end}`;
1173}
1174
1175function EntityPanel({
1176 kbId,
1177 entityId,
1178 onClose,
1179 onNavigate,
1180}: {
1181 kbId: string;
1182 entityId: string;
1183 onClose: () => void;
1184 onNavigate: (entityId: string) => void;
1185}) {
1186 const detail = useQuery({
1187 queryKey: ["entity", kbId, entityId],
1188 queryFn: () => api.entityDetail(kbId, entityId),
1189 });
1190 const [openFact, setOpenFact] = useState<string | null>(null);
1191 // Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立);
1192 // History = 记录时间轴(我们何时这么认为、又何时改了主意)
1193 const [view, setView] = useState<"relations" | "timeline" | "history">("relations");
1194
1195 const e: GraphNode | undefined = detail.data?.entity;
1196
1197 // 实体修正:抽取给的是初判,判错此前只能整库重抽
1198 const qc = useQueryClient();
1199 const [editing, setEditing] = useState(false);
1200 const [draftName, setDraftName] = useState("");
1201 const [draftType, setDraftType] = useState("");
1202 const [sameName, setSameName] = useState<GraphNode[]>([]);
1203 // 类型下拉要的是全量本体,不是当前视图里出现过的那几个
1204 const ontology = useQuery({
1205 queryKey: ["ontology", kbId],
1206 queryFn: () => api.ontology(kbId),
1207 enabled: editing,
1208 });
1209 const types = ontology.data?.entity_types ?? [];
1210
1211 const openEdit = () => {
1212 if (!e) return;
1213 setDraftName(e.name);
1214 setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
1215 setSameName([]);
1216 setEditing(true);
1217 };
1218 // 本体是异步来的:它到齐时把类型下拉对到当前类型上
1219 useEffect(() => {
1220 if (editing && !draftType && e)
1221 setDraftType(types.find((t) => t.key === e.type_key)?.id ?? "");
1222 }, [editing, draftType, e, types]);
1223
1224 const save = useMutation({
1225 mutationFn: () => {
1226 const body: { type_id?: string; canonical_name?: string } = {};
1227 if (draftName.trim() && draftName.trim() !== e?.name) body.canonical_name = draftName.trim();
1228 const curId = types.find((t) => t.key === e?.type_key)?.id;
1229 if (draftType && draftType !== curId) body.type_id = draftType;
1230 return api.updateEntity(kbId, entityId, body);
1231 },
1232 onSuccess: (r) => {
1233 setEditing(false);
1234 setSameName(r.same_name);
1235 toast.success(S.graph.editSaved);
1236 // 改了类型/名字,图谱节点与本体计数都要跟着动
1237 qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] });
1238 qc.invalidateQueries({ queryKey: ["graph", kbId] });
1239 qc.invalidateQueries({ queryKey: ["ontology", kbId] });
1240 },
1241 onError: (err: Error) => toast.error(err.message),
1242 });
1243
1244 const dirty =
1245 !!e &&
1246 (draftName.trim() !== e.name ||
1247 draftType !== (types.find((t) => t.key === e.type_key)?.id ?? ""));
1248
1249 // Relations = 当下有效的快照(as-of now);已闭合的历史只出现在 Timeline。
1250 // 按「方向 + 谓词」分组:实体自身名不再逐行重复,谓词只出现在小节标题里
1251 const { groups, historicalCount } = useMemo(() => {
1252 const all = detail.data?.facts ?? [];
1253 const nowIso = new Date().toISOString();
1254 const current = all.filter(
1255 (f) => (!f.valid_from || f.valid_from <= nowIso) && (!f.valid_to || f.valid_to > nowIso),
1256 );
1257 const map = new Map<
1258 string,
1259 { key: string; label: string; direction: string; rows: EntityFact[] }
1260 >();
1261 for (const f of current) {
1262 const k = `${f.direction}:${f.predicate_key}`;
1263 if (!map.has(k))
1264 map.set(k, { key: k, label: f.predicate_label, direction: f.direction, rows: [] });
1265 map.get(k)!.rows.push(f);
1266 }
1267 const arr = [...map.values()];
1268 for (const gr of arr)
1269 gr.rows.sort((a, b) => ((a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1));
1270 arr.sort((a, b) => b.rows.length - a.rows.length || a.label.localeCompare(b.label));
1271 return { groups: arr, historicalCount: all.length - current.length };
1272 }, [detail.data]);
1273
1274 return (
1275 <div className="glass-strong absolute top-14 right-3 bottom-20 w-80 z-10 rounded-xl shadow-2xl flex flex-col">
1276 <div className="flex items-start justify-between px-4 py-3.5 border-b border-white/10">
1277 <div>
1278 {e && (
1279 <>
1280 <div className="flex items-center gap-2">
1281 <span
1282 className="h-2.5 w-2.5 rounded-full shrink-0"
1283 style={{ background: e.color, boxShadow: `0 0 8px ${e.color}55` }}
1284 />
1285 <span
1286 className="text-[15px] font-semibold tracking-tight text-white"
1287 style={{ fontFamily: "var(--font-display)" }}
1288 >
1289 {e.name}
1290 </span>
1291 </div>
1292 {/* 消歧后缀找不到关联事实时兜底成类型标签,那就与后面的类型重复了 */}
1293 <div className="mt-1 text-xs text-neutral-500">
1294 {e.disambiguator && e.disambiguator !== e.type_label
1295 ? `${e.disambiguator} · `
1296 : ""}
1297 {e.type_label ?? S.graph.untyped} · {detail.data?.facts.length ?? 0}{" "}
1298 {S.graph.facts}
1299 </div>
1300 </>
1301 )}
1302 </div>
1303 <div className="flex items-center gap-1.5 mt-0.5">
1304 {e && !editing && (
1305 <button
1306 onClick={openEdit}
1307 title={S.graph.edit}
1308 className="text-neutral-500 hover:text-neutral-200"
1309 >
1310 <Pencil size={13} />
1311 </button>
1312 )}
1313 <button onClick={onClose} className="text-neutral-500 hover:text-neutral-200">
1314 <X size={15} />
1315 </button>
1316 </div>
1317 </div>
1318
1319 {editing && e && (
1320 <div className="px-4 py-3 border-b border-white/10 space-y-2.5">
1321 <label className="block">
1322 <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500">
1323 {S.graph.editName}
1324 </span>
1325 <input
1326 autoFocus
1327 value={draftName}
1328 onChange={(ev) => setDraftName(ev.target.value)}
1329 onKeyDown={(ev) => {
1330 if (ev.key === "Enter" && dirty && draftName.trim()) save.mutate();
1331 if (ev.key === "Escape") setEditing(false);
1332 }}
1333 className="mt-1 w-full bg-white/[0.04] border border-white/10 rounded px-2 py-1 text-sm text-neutral-100 focus:outline-none focus:border-white/25"
1334 />
1335 </label>
1336 <label className="block">
1337 <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500">
1338 {S.graph.editType}
1339 </span>
1340 <select
1341 value={draftType}
1342 onChange={(ev) => setDraftType(ev.target.value)}
1343 className="mt-1 w-full bg-white/[0.04] border border-white/10 rounded px-2 py-1 text-sm text-neutral-100 focus:outline-none focus:border-white/25"
1344 >
1345 {types.map((t) => (
1346 <option key={t.id} value={t.id} className="bg-neutral-900">
1347 {t.label}
1348 </option>
1349 ))}
1350 </select>
1351 </label>
1352 <div className="flex items-center gap-2 pt-0.5">
1353 <button
1354 disabled={!dirty || !draftName.trim() || save.isPending}
1355 onClick={() => save.mutate()}
1356 className="u-pop px-2.5 py-1 text-xs rounded bg-white/10 text-neutral-100 hover:bg-white/15 disabled:opacity-40 disabled:cursor-not-allowed"
1357 >
1358 {S.graph.editSave}
1359 </button>
1360 <button
1361 onClick={() => setEditing(false)}
1362 className="px-2.5 py-1 text-xs rounded text-neutral-500 hover:text-neutral-300"
1363 >
1364 {S.graph.editCancel}
1365 </button>
1366 {!draftName.trim() && (
1367 <span className="text-[11px] text-[var(--u-danger)]">{S.graph.editEmptyName}</span>
1368 )}
1369 </div>
1370 </div>
1371 )}
1372
1373 {/* 同名不是错误——两个张伟可以并存。只提示,判定是不是同一个是人的事 */}
1374 {sameName.length > 0 && !editing && (
1375 <div className="mx-4 mt-2.5 rounded border border-white/10 bg-white/[0.03] px-2.5 py-2">
1376 <div className="flex items-start justify-between gap-2">
1377 <p className="text-[11px] text-neutral-400">
1378 {S.graph.sameNameNote(sameName.length)}{" "}
1379 <span className="text-neutral-500">{S.graph.sameNameHint}</span>
1380 </p>
1381 <button
1382 onClick={() => setSameName([])}
1383 className="text-neutral-600 hover:text-neutral-300 shrink-0"
1384 >
1385 <X size={11} />
1386 </button>
1387 </div>
1388 <div className="mt-1.5 flex flex-wrap gap-1">
1389 {sameName.map((p) => (
1390 <button
1391 key={p.id}
1392 onClick={() => onNavigate(p.id)}
1393 className="text-[11px] px-1.5 py-0.5 rounded bg-white/[0.06] text-neutral-300 hover:bg-white/10"
1394 >
1395 {p.type_label ?? S.graph.untyped}
1396 {p.disambiguator && p.disambiguator !== p.type_label
1397 ? ` · ${p.disambiguator}`
1398 : ""}
1399 </button>
1400 ))}
1401 </div>
1402 </div>
1403 )}
1404
1405 {/* 视图切换:Relations(分组)| Timeline(年表) */}
1406 <div className="px-4 pt-2.5">
1407 <div className="flex rounded-lg overflow-hidden border border-white/10 w-fit">
1408 {(["relations", "timeline", "history"] as const).map((v) => (
1409 <button
1410 key={v}
1411 onClick={() => setView(v)}
1412 className={`px-3 py-1 text-[11px] transition-colors ${
1413 view === v
1414 ? "bg-white/10 text-neutral-100"
1415 : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300"
1416 }`}
1417 >
1418 {v === "relations"
1419 ? S.graph.viewRelations
1420 : v === "timeline"
1421 ? S.graph.viewTimeline
1422 : S.graph.viewHistory}
1423 </button>
1424 ))}
1425 </div>
1426 </div>
1427
1428 <div className="u-scroll flex-1 overflow-y-auto px-2 py-2">
1429 {view === "relations" && historicalCount > 0 && (
1430 <button
1431 onClick={() => setView("timeline")}
1432 className="mx-2 mb-2 mt-0.5 text-[11px] text-neutral-500 hover:text-neutral-300 underline-offset-2 hover:underline"
1433 >
1434 {S.graph.historicalNote(historicalCount)}
1435 </button>
1436 )}
1437 {view === "relations" &&
1438 groups.map((gr) => (
1439 <div key={gr.key} className="mb-3 last:mb-1">
1440 <div className="flex items-center gap-1.5 px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-500">
1441 {gr.direction === "in" ? <ArrowLeft size={10} /> : <ArrowRight size={10} />}
1442 {gr.label}
1443 {gr.rows.length > 1 && <span className="text-neutral-600">{gr.rows.length}</span>}
1444 </div>
1445 <div>
1446 {gr.rows.map((f) => (
1447 <FactRow
1448 key={f.id}
1449 kbId={kbId}
1450 fact={f}
1451 open={openFact === f.id}
1452 onToggle={() => setOpenFact(openFact === f.id ? null : f.id)}
1453 onNavigate={onNavigate}
1454 />
1455 ))}
1456 </div>
1457 </div>
1458 ))}
1459 {view === "timeline" && (
1460 <TimelineView
1461 kbId={kbId}
1462 facts={detail.data?.facts ?? []}
1463 openFact={openFact}
1464 onToggle={(id) => setOpenFact(openFact === id ? null : id)}
1465 onNavigate={onNavigate}
1466 />
1467 )}
1468 {view === "history" && <EntityHistory kbId={kbId} entityId={entityId} />}
1469 {view !== "history" && detail.data?.facts.length === 0 && (
1470 <p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p>
1471 )}
1472 </div>
1473 </div>
1474 );
1475}
1476
1477/** 年表视图:带区间的事实按起点摊开成竖直时间线;无时间的沉到底部 undated。 */
1478function TimelineView({
1479 kbId,
1480 facts,
1481 openFact,
1482 onToggle,
1483 onNavigate,
1484}: {
1485 kbId: string;
1486 facts: EntityFact[];
1487 openFact: string | null;
1488 onToggle: (id: string) => void;
1489 onNavigate: (entityId: string) => void;
1490}) {
1491 const dated = facts
1492 .filter((f) => f.temporal !== "eternal" && (f.valid_from || f.valid_to))
1493 .sort((a, b) =>
1494 (a.valid_from ?? a.valid_to ?? "") < (b.valid_from ?? b.valid_to ?? "") ? -1 : 1,
1495 );
1496 const undated = facts.filter((f) => !dated.includes(f));
1497
1498 return (
1499 <div className="px-2 pt-1">
1500 <div className="relative ml-1.5 border-l border-white/15 pl-3 space-y-0.5">
1501 {dated.map((f) => (
1502 <div key={f.id} className="relative">
1503 <span className="absolute -left-[17.5px] top-2.5 h-2 w-2 rounded-full bg-neutral-600 ring-2 ring-[#0f0f10]" />
1504 <TimelineRow
1505 kbId={kbId}
1506 fact={f}
1507 open={openFact === f.id}
1508 onToggle={() => onToggle(f.id)}
1509 onNavigate={onNavigate}
1510 />
1511 </div>
1512 ))}
1513 {dated.length === 0 && (
1514 <p className="py-2 text-xs text-neutral-500">{S.graph.timelineEmpty}</p>
1515 )}
1516 </div>
1517 {undated.length > 0 && (
1518 <div className="mt-3">
1519 <div className="px-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
1520 {S.graph.undated}
1521 </div>
1522 {undated.map((f) => (
1523 <FactRow
1524 key={f.id}
1525 kbId={kbId}
1526 fact={f}
1527 open={openFact === f.id}
1528 onToggle={() => onToggle(f.id)}
1529 onNavigate={onNavigate}
1530 />
1531 ))}
1532 </div>
1533 )}
1534 </div>
1535 );
1536}
1537
1538/** 年表条目:区间 + 闭合方式标记 + 开放事实的最后确认时间;点击展开证据。 */
1539function TimelineRow({
1540 kbId,
1541 fact,
1542 open,
1543 onToggle,
1544 onNavigate,
1545}: {
1546 kbId: string;
1547 fact: EntityFact;
1548 open: boolean;
1549 onToggle: () => void;
1550 onNavigate: (entityId: string) => void;
1551}) {
1552 const interval = fmtInterval(fact);
1553 const isOpenEnded = !fact.valid_to;
1554 const literal = fmtObjectValue(fact.object_value);
1555 return (
1556 <div
1557 className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
1558 fact.stale ? "opacity-55" : ""
1559 }`}
1560 title={fact.stale ? S.graph.staleFactHint : undefined}
1561 >
1562 <button onClick={onToggle} className="w-full text-left px-2 py-1.5">
1563 <div className="flex items-center gap-1.5 u-num text-[10.5px] text-neutral-500">
1564 {interval || "—"}
1565 {fact.corrected && (
1566 <span className="text-neutral-600" title={S.graph.correctedHint}>
1567 ⟲
1568 </span>
1569 )}
1570 {isOpenEnded && fact.last_evidence_time && (
1571 <span className="ml-auto text-neutral-600">
1572 {S.graph.lastConfirmed(fact.last_evidence_time.slice(0, 10))}
1573 </span>
1574 )}
1575 </div>
1576 <div className="mt-0.5 flex items-center gap-1.5 text-[13px] text-neutral-200">
1577 <span className="text-neutral-500 text-xs">
1578 {fact.direction === "in" ? "←" : "→"} {fact.predicate_label}
1579 </span>
1580 {fact.other_id ? (
1581 <span
1582 role="link"
1583 tabIndex={0}
1584 onClick={(ev) => {
1585 ev.stopPropagation();
1586 onNavigate(fact.other_id!);
1587 }}
1588 onKeyDown={(ev) => {
1589 if (ev.key === "Enter") {
1590 ev.stopPropagation();
1591 onNavigate(fact.other_id!);
1592 }
1593 }}
1594 className="truncate hover:text-white hover:underline underline-offset-2 decoration-white/30"
1595 >
1596 {fact.other_name ?? "?"}
1597 </span>
1598 ) : (
1599 <span className="truncate">{fact.other_name ?? literal ?? "?"}</span>
1600 )}
1601 {fact.stale && (
1602 <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5">
1603 {S.graph.staleFactChip}
1604 </span>
1605 )}
1606 </div>
1607 </button>
1608 {open && <EvidenceList kbId={kbId} fact={fact} />}
1609 </div>
1610 );
1611}
1612
1613/** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */
1614function fmtObjectValue(v: Record<string, unknown> | null): string | null {
1615 if (!v) return null;
1616 if (v.value !== undefined) {
1617 const val = typeof v.value === "boolean" ? (v.value ? "✓" : "✗") : String(v.value);
1618 return typeof v.unit === "string" && v.unit ? `${val} ${v.unit}` : val;
1619 }
1620 if (typeof v.summary === "string") return v.summary;
1621 return JSON.stringify(v);
1622}
1623
1624function FactRow({
1625 kbId,
1626 fact,
1627 open,
1628 onToggle,
1629 onNavigate,
1630}: {
1631 kbId: string;
1632 fact: EntityFact;
1633 open: boolean;
1634 onToggle: () => void;
1635 onNavigate: (entityId: string) => void;
1636}) {
1637 const interval = fmtInterval(fact);
1638 // 与 Review 的低置信口径一致:只有低到需要怀疑才挂 chip,常规置信保持沉默
1639 const lowConfidence = fact.confidence < 0.75;
1640
1641 return (
1642 <div
1643 className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${
1644 fact.stale ? "opacity-55" : ""
1645 }`}
1646 title={fact.stale ? S.graph.staleFactHint : undefined}
1647 >
1648 <button onClick={onToggle} className="w-full text-left px-2 py-1.5 flex items-center gap-1.5">
1649 <ChevronRight
1650 size={11}
1651 className={`shrink-0 text-neutral-600 transition-transform ${open ? "rotate-90" : ""}`}
1652 />
1653 {fact.other_id ? (
1654 <span
1655 role="link"
1656 tabIndex={0}
1657 onClick={(ev) => {
1658 ev.stopPropagation();
1659 onNavigate(fact.other_id!);
1660 }}
1661 onKeyDown={(ev) => {
1662 if (ev.key === "Enter") {
1663 ev.stopPropagation();
1664 onNavigate(fact.other_id!);
1665 }
1666 }}
1667 className="truncate text-[13px] text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
1668 >
1669 {fact.other_name ?? "?"}
1670 </span>
1671 ) : (
1672 <span className="truncate text-[13px] text-neutral-200">
1673 {fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"}
1674 </span>
1675 )}
1676 {lowConfidence && (
1677 <span className="shrink-0 u-num u-meta-warn text-[10.5px]">
1678 {Math.round(fact.confidence * 100)}%
1679 </span>
1680 )}
1681 {fact.stale && (
1682 <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5">
1683 {S.graph.staleFactChip}
1684 </span>
1685 )}
1686 {interval && (
1687 <span className="ml-auto shrink-0 pl-2 u-num text-[10.5px] text-neutral-500">
1688 {interval}
1689 </span>
1690 )}
1691 </button>
1692 {open && <EvidenceList kbId={kbId} fact={fact} />}
1693 </div>
1694 );
1695}
1696
1697/** 证据展开区(FactRow 与 TimelineRow 共用):quote + 跳原文 + 版本角标 + 置信。 */
1698function EvidenceList({ kbId, fact }: { kbId: string; fact: EntityFact }) {
1699 const evidence = useQuery({
1700 queryKey: ["evidence", fact.id],
1701 queryFn: () => api.factEvidence(kbId, fact.id),
1702 });
1703 return (
1704 <div className="mx-2 mb-2 mt-0.5 space-y-2 border-l border-white/15 pl-2.5">
1705 {evidence.data?.evidence.map((ev: Evidence) => (
1706 <Link
1707 key={ev.chunk_id}
1708 to="/doc/$docId"
1709 params={{ docId: ev.document_id }}
1710 search={{ chunk: ev.chunk_id }}
1711 className="block text-xs text-neutral-500 hover:text-neutral-300"
1712 >
1713 {/* 原文说的谓词,只在它与本体谓词不同时显示——词表外的词被降级成
1714 "related to" 后,事实行上只剩"有关联",原意仅存于此。相同则是噪声 */}
1715 {ev.proposed_predicate && ev.proposed_predicate !== fact.predicate_key && (
1716 <div className="mb-0.5 text-[11px] text-neutral-400">
1717 {S.graph.proposedPredicate(ev.proposed_predicate)}
1718 </div>
1719 )}
1720 <div className="line-clamp-2 italic">
1721 {ev.quote ? `“${ev.quote}”` : S.graph.noQuote}
1722 </div>
1723 <div className="mt-0.5 text-neutral-400">
1724 {S.graph.sectionRef(ev.filename, ev.seq + 1)}
1725 {ev.stale && (
1726 <span
1727 className="ml-1.5 u-num text-[10px] text-neutral-600"
1728 title={S.graph.staleEvidenceHint}
1729 >
1730 {S.graph.fromVersion(ev.doc_version)}
1731 </span>
1732 )}
1733 </div>
1734 </Link>
1735 ))}
1736 {evidence.data?.evidence.length === 0 && (
1737 <p className="text-xs text-neutral-500">{S.graph.noEvidence}</p>
1738 )}
1739 {/* 置信度只在低到值得怀疑时说话(与 Review 低置信口径一致),常规不标 */}
1740 {fact.confidence < 0.75 && (
1741 <p className="text-[10px] text-[var(--u-warn)]">
1742 {Math.round(fact.confidence * 100)}% {S.graph.confidence}
1743 </p>
1744 )}
1745 </div>
1746 );
1747}