Elffuss BraidHub

kikocis/utopia public

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