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