| 1 | import { |
| 2 | useCallback, |
| 3 | useEffect, |
| 4 | useMemo, |
| 5 | useRef, |
| 6 | useState, |
| 7 | type MutableRefObject, |
| 8 | } from "react"; |
| 9 | import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; |
| 10 | import { Link, useNavigate, useSearch } from "@tanstack/react-router"; |
| 11 | import Graphology from "graphology"; |
| 12 | import { circular, circlepack } from "graphology-layout"; |
| 13 | import forceAtlas2 from "graphology-layout-forceatlas2"; |
| 14 | import FA2Layout from "graphology-layout-forceatlas2/worker"; |
| 15 | import Sigma from "sigma"; |
| 16 | import { createNodeBorderProgram } from "@sigma/node-border"; |
| 17 | import EdgeCurveProgram from "@sigma/edge-curve"; |
| 18 | import { NodeSquareShellProgram } from "./squareShellProgram"; |
| 19 | import { EntityHistory } from "./EntityHistory"; |
| 20 | import { |
| 21 | ArrowLeft, |
| 22 | ArrowRight, |
| 23 | ChevronRight, |
| 24 | CircleDashed, |
| 25 | Grape, |
| 26 | Loader2, |
| 27 | Maximize2, |
| 28 | Orbit, |
| 29 | Pause, |
| 30 | Pencil, |
| 31 | Play, |
| 32 | Waypoints, |
| 33 | X, |
| 34 | ZoomIn, |
| 35 | ZoomOut, |
| 36 | } from "lucide-react"; |
| 37 | import { |
| 38 | api, |
| 39 | type DerivedFact, |
| 40 | type EntityFact, |
| 41 | type Evidence, |
| 42 | type GraphEdge, |
| 43 | type GraphNode, |
| 44 | type BlockedDerivation, |
| 45 | type ProofStep, |
| 46 | } from "../api"; |
| 47 | import { S } from "../i18n"; |
| 48 | import { usePopoverFlip } from "../ui/popoverFlip"; |
| 49 | import { useKb, useKbId } from "../kb"; |
| 50 | import { toast } from "../toast"; |
| 51 | |
| 52 | /* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化: |
| 53 | Semantica 原版是钢蓝系(#0B1320/#5A7A9E/#7A92AE),按"chrome 零色偏、 |
| 54 | 彩色只属于数据"的既定原则换成同明度纯灰,类型色混入比例不变 */ |
| 55 | const NODE_SHELL_BASE = "#121212"; // 节点外壳深底(原 #0B1320 的中性化) |
| 56 | const NODE_CORE_BASE = "#767676"; // 节点核心灰(原 #5A7A9E 的中性化) |
| 57 | const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化) |
| 58 | const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键) |
| 59 | const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例 |
| 60 | /* 状态环取**节点自己的类型色**,不是两个写死的色相。 |
| 61 | |
| 62 | 换掉的直接原因是一次撞色:原来的选中金环 `#E7C57C` 就是 |
| 63 | `rgb(231,197,124)`,与 `EDGE_COLOR_DERIVED` 逐位相同——「这个节点被选中了」 |
| 64 | 和「这条边是推出来的」用同一个颜色说话,而这两件事毫无关系。 |
| 65 | 金色现在专属于「推出来的」。 |
| 66 | |
| 67 | 往白里混而不是直接用原色:环画在节点自己身上,同色同亮度就看不出是个环。 |
| 68 | **悬停混得更白、选中混得更少**——悬停时全图不压暗,环要在一片乱线里 |
| 69 | 立刻跳出来;选中时其余都压暗了,节点本来就孤立着,这时候环该说的是 |
| 70 | 「它是谁」,所以更贴近它自己的颜色。 */ |
| 71 | const RING_HOVER_MIX = 0.7; // 悬停:偏白,为的是跳出来 |
| 72 | const RING_SELECT_MIX = 0.35; // 选中:偏本色,为的是认得出 |
| 73 | const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝) |
| 74 | // 本体没认下的关系:同色更淡。名字来自原文,不该跟词表里的关系看着一样重 |
| 75 | const EDGE_COLOR_INFERRED = "rgba(163,163,163,0.1)"; |
| 76 | // 推出来的边(R1)。**跟上面两者说的不是一件事**:那两个说「这条边的名字从哪来」, |
| 77 | // 这个说「这条边根本不是谁说的,是引擎推的」。所以给它自己的色相而不是再淡一档灰—— |
| 78 | // 用户要在余光里就分得出「文档里写的」和「推出来的」 |
| 79 | const EDGE_COLOR_DERIVED = "rgba(231,197,124,0.42)"; |
| 80 | const EDGE_COLOR_DERIVED_DIM = "rgba(231,197,124,0.14)"; |
| 81 | /* 争议(0017 §3):珊瑚橙 `--u-contest`。金是派生、琥珀是警告、粉是危险, |
| 82 | 它得跟三个都拉开。**整条边换色**——环在节点上、边还是灰的,余光分不出来 */ |
| 83 | const EDGE_COLOR_CONTEST = "rgba(255,106,61,0.55)"; |
| 84 | const EDGE_FOCUS_CONTEST = "rgba(255,106,61,1)"; |
| 85 | |
| 86 | /** 相邻两条弧之间的曲率差。太小仍然糊,太大在长边上会甩得离节点很远 */ |
| 87 | const EDGE_CURVATURE_STEP = 0.18; |
| 88 | |
| 89 | /** 一条边画在哪条弧上;`curvature === 0` = 直线。 */ |
| 90 | interface PlacedEdge { |
| 91 | edge: GraphEdge; |
| 92 | curvature: number; |
| 93 | /** 并进这条边的别的说法(逆关系),悬停时一并显示 */ |
| 94 | alsoLabels: string[]; |
| 95 | } |
| 96 | |
| 97 | /** 同一对节点之间的边,画在各自的弧上;逆关系推出来的那些先并掉。 |
| 98 | * |
| 99 | * **两件事,顺序有讲究:先减后分。** |
| 100 | * |
| 101 | * 一、`A works_at B` 与它推出的 `B employs A` 是**同一件事的两种说法**, |
| 102 | * 不是两条知识。画成两条弧只是把冗余画得好看一点。所以逆关系推出来的边 |
| 103 | * 并进它的来源边,说法挂在那条边上。`sub_property`(`ceo_of ⊑ works_at`) |
| 104 | * 不并——那是两条粒度不同的事实,各自成立。 |
| 105 | * |
| 106 | * 二、剩下的按**无向对**分组扇开。无向是要点:一条边和它的反向边起终点相反, |
| 107 | * 按有向对分组会各自成组、各自以为自己是独苗,于是又叠回同一条直线上。 |
| 108 | * 分组用 min/max,而落到弧上时按边自己的方向翻符号——sigma 的曲率是相对 |
| 109 | * source→target 的,不翻的话反向的弧会绕到同一侧。 */ |
| 110 | function layOutParallelEdges(edges: GraphEdge[]): { |
| 111 | edges: PlacedEdge[]; |
| 112 | folded: number; |
| 113 | } { |
| 114 | const pairKey = (a: string, b: string) => (a < b ? `${a} ${b}` : `${b} ${a}`); |
| 115 | const push = (m: Map<string, GraphEdge[]>, k: string, e: GraphEdge) => { |
| 116 | const list = m.get(k); |
| 117 | if (list) list.push(e); |
| 118 | else m.set(k, [e]); |
| 119 | }; |
| 120 | |
| 121 | // ---- 一、并掉逆关系推出来的边 |
| 122 | const survivors: GraphEdge[] = []; |
| 123 | const inverses: GraphEdge[] = []; |
| 124 | for (const e of edges) { |
| 125 | if (e.derived && e.rule === "inverse") inverses.push(e); |
| 126 | else survivors.push(e); |
| 127 | } |
| 128 | /* **按前提找来源边,不是按节点对。** |
| 129 | 一度写成「取那一对节点上的第一条边」,于是 `contains` 挂到了恰好也连着 |
| 130 | 那两点的 `allied_with` 上——而 `contains` 属于 `part_of`。挂错之后 |
| 131 | 界面上看着完全正常,是最难发现的那一种。前提是服务端算出来的,用它。 */ |
| 132 | const onScreen = new Map<string, GraphEdge>(); |
| 133 | for (const e of survivors) onScreen.set(e.id, e); |
| 134 | |
| 135 | const also = new Map<string, string[]>(); |
| 136 | let folded = 0; |
| 137 | for (const e of inverses) { |
| 138 | const host = (e.premises ?? []).map((p) => onScreen.get(p)).find(Boolean); |
| 139 | if (!host) { |
| 140 | // 来源边不在这一屏(时间轴筛掉了,或它自己也是推出来的而被过滤了)。 |
| 141 | // **那就留着它**——并进一条不存在的边等于把这条知识删了 |
| 142 | survivors.push(e); |
| 143 | continue; |
| 144 | } |
| 145 | const list = also.get(host.id) ?? []; |
| 146 | // 去重:传递推出来的几条 `part_of` 各有各的逆,而前提链都回到同一条边上, |
| 147 | // 于是同一个说法会被挂三遍。**说法是名字,不是计数** |
| 148 | const name = e.label ?? e.predicate ?? ""; |
| 149 | if (!list.includes(name)) list.push(name); |
| 150 | also.set(host.id, list); |
| 151 | folded++; |
| 152 | } |
| 153 | |
| 154 | // ---- 二、剩下的按无向对扇开 |
| 155 | const groups = new Map<string, GraphEdge[]>(); |
| 156 | for (const e of survivors) push(groups, pairKey(e.source, e.target), e); |
| 157 | |
| 158 | const placed: PlacedEdge[] = []; |
| 159 | for (const group of groups.values()) { |
| 160 | const n = group.length; |
| 161 | group.forEach((e, i) => { |
| 162 | // 围绕直线对称铺开:n=1 → [0];n=2 → [-0.5, 0.5];n=3 → [-1, 0, 1] |
| 163 | const offset = n === 1 ? 0 : i - (n - 1) / 2; |
| 164 | const sign = e.source < e.target ? 1 : -1; |
| 165 | placed.push({ |
| 166 | edge: e, |
| 167 | curvature: offset === 0 ? 0 : sign * offset * EDGE_CURVATURE_STEP, |
| 168 | alsoLabels: also.get(e.id) ?? [], |
| 169 | }); |
| 170 | }); |
| 171 | } |
| 172 | return { edges: placed, folded }; |
| 173 | } |
| 174 | // 呼吸周期。动画不是为了好看,是因为静态的一个色差在几百条边里根本注意不到 |
| 175 | const DERIVED_PULSE_MS = 2200; |
| 176 | // 超过这个数就只上色不动画。**写出来而不是悄悄降级**:每帧重算几千条边的颜色, |
| 177 | // 换来的是拖不动图,而那时候用户要的是能拖得动 |
| 178 | const DERIVED_ANIMATE_MAX = 400; |
| 179 | // 开关的淡入淡出时长。**比 FADE_MS(320) 略长**:播放淡入是一批边陆续到位, |
| 180 | // 这个是一整批边同时进出,走慢一点才看得清「那批金线是一起退场的」 |
| 181 | const DERIVED_TOGGLE_MS = 420; |
| 182 | /* 推出来的边**比事实晚一点进来**,然后整体淡入。 |
| 183 | |
| 184 | 试过把推导过程演出来:前提按顺序点亮、最后点亮结论。做了两版都读不懂—— |
| 185 | 第一版前提闪一下就灭,等结论出现时前提早暗了;第二版改成整组同亮同收, |
| 186 | 仍然是几十组在图上此起彼伏,谁属于谁根本分不出。 |
| 187 | **一张几百条边的图不是讲因果链的地方**——那件事侧栏的 Derived 页 |
| 188 | 一条一条写着,看得清楚得多。这里只需要交代一件事:这些边是后来的、 |
| 189 | 跟别人写下的不是一回事。晚一点进来 + 自己的颜色,已经说完了。 */ |
| 190 | const DERIVE_SETTLE_MS = 500; // 事实落位之后,隔多久轮到推出来的 |
| 191 | const DERIVE_FADE_MS = 620; // 整体淡入的时长,比开关那一档慢,是"入场"不是"切换" |
| 192 | // 图例最多摆几个胶囊,其余收进「+N 个类」。**这一排是横向排布的, |
| 193 | // 类一多就会换行、把画布顶到下面去**;而且十几个同样的胶囊排开, |
| 194 | // 谁也读不出哪个重要。收起来的那些从「+N」里搜得到 |
| 195 | const LEGEND_MAX = 6; |
| 196 | /* 画多少个节点的可选档位。**给档位而不是给输入框**:这个数没有「精确」可言 |
| 197 | ——它只影响看得清还是拖得动,用户要的是「多点/少点」,不是 237 这个数。 |
| 198 | 最大值与后端 GRAPH_NODE_CAP_MAX 对齐;再高先垮的是拖动,不是清晰度 */ |
| 199 | const NODE_BUDGETS: number[] = [150, 300, 600, 1000]; |
| 200 | // 注意:sigma 边着色器在预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB, |
| 201 | // alpha 无法压暗边——暗度必须编码进 RGB(不透明近背景色) |
| 202 | const EDGE_DIM = "#141414"; |
| 203 | /* 幽灵边:没落地的派生。同一个色相往 EDGE_DIM 混(预乘混合下 alpha 压不暗边), |
| 204 | 更细。sigma 默认的边程序画不了虚线,也不为此另写一个 */ |
| 205 | const EDGE_GHOST = lerpColor("rgba(255,106,61,1)", EDGE_DIM, 0.55); |
| 206 | const EDGE_GHOST_FOCUS = lerpColor("rgba(255,106,61,1)", EDGE_DIM, 0.2); |
| 207 | const EDGE_FOCUS = "rgba(255,255,255,0.55)"; |
| 208 | // 选中/悬停时的派生边。**不能跟着走白**:选中恰恰是看得最仔细的时候, |
| 209 | // 而这时候「这条边是推出来的、没人写过」比任何时候都该说清楚。 |
| 210 | // 从前一律 EDGE_FOCUS,一选中金线就变白,等于把来历抹掉了。 |
| 211 | // 比常态的金更亮更实——它同样要表达「被选中了」 |
| 212 | const EDGE_FOCUS_DERIVED = "rgba(255,214,140,0.95)"; |
| 213 | const MUTED_SHELL = "#151515"; |
| 214 | /* 悬停时其余的压暗程度。**比选中轻**(选中是压到底): |
| 215 | 悬停是随鼠标走的、每划过一个节点就换一次,压到底会让整张画布不停明灭; |
| 216 | 而且两者压得一样重的话,"我只是路过"和"我选中了它"就成了同一个画面。 |
| 217 | 所以留一档差:压得深,但不到底——看得出焦点,也看得出这只是路过。 |
| 218 | (试过 0.55,太浅,焦点不够跳)*/ |
| 219 | const HOVER_MUTE = 0.78; |
| 220 | const PILL_BG = "rgba(12,12,12,0.9)"; |
| 221 | const PILL_BORDER = "rgba(255,255,255,0.14)"; |
| 222 | const PILL_TEXT = "#ededed"; |
| 223 | const TRANSPARENT = "rgba(0,0,0,0)"; |
| 224 | const DAY_MS = 24 * 3600 * 1000; |
| 225 | |
| 226 | function hexToRgb(hex: string): [number, number, number] { |
| 227 | const m = /^#?([0-9a-f]{6})$/i.exec(hex); |
| 228 | if (!m) return [128, 128, 128]; |
| 229 | const v = parseInt(m[1], 16); |
| 230 | return [(v >> 16) & 255, (v >> 8) & 255, v & 255]; |
| 231 | } |
| 232 | |
| 233 | /** c1 向 c2 按 t 比例混色 */ |
| 234 | function mix(c1: string, c2: string, t: number): string { |
| 235 | const [r1, g1, b1] = hexToRgb(c1); |
| 236 | const [r2, g2, b2] = hexToRgb(c2); |
| 237 | const f = (a: number, b: number) => Math.round(a + (b - a) * t); |
| 238 | return `rgb(${f(r1, r2)},${f(g1, g2)},${f(b1, b2)})`; |
| 239 | } |
| 240 | |
| 241 | /* 播放淡入:解析 hex / rgb / rgba(含 alpha)并线性插值 */ |
| 242 | function parseRgba(c: string): [number, number, number, number] { |
| 243 | if (c.startsWith("#")) { |
| 244 | const [r, g, b] = hexToRgb(c); |
| 245 | return [r, g, b, 1]; |
| 246 | } |
| 247 | const m = c.match( |
| 248 | /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?/, |
| 249 | ); |
| 250 | if (!m) return [128, 128, 128, 1]; |
| 251 | return [+m[1], +m[2], +m[3], m[4] !== undefined ? +m[4] : 1]; |
| 252 | } |
| 253 | function lerpColor(from: string, to: string, t: number): string { |
| 254 | const a = parseRgba(from); |
| 255 | const b = parseRgba(to); |
| 256 | const f = (i: number) => a[i] + (b[i] - a[i]) * t; |
| 257 | return `rgba(${Math.round(f(0))},${Math.round(f(1))},${Math.round(f(2))},${f(3).toFixed(3)})`; |
| 258 | } |
| 259 | /** 播放中新元素的淡入时长 */ |
| 260 | const FADE_MS = 320; |
| 261 | |
| 262 | /* 世界坐标网格:随相机平移/缩放(Figma/tldraw 式无限画布惯例)。 |
| 263 | 4 倍细分 LOD:每层 alpha 随其屏幕间距连续淡入(13px 进场 → 52px 满亮 5.5%), |
| 264 | 粗层与细层线重合处自然叠亮,形成"大小格"层次;无任何跳变。 */ |
| 265 | const GRID_BASE_WORLD = 24; // 基准世界格距(匹配 ~300 尺度的布局) |
| 266 | const GRID_FADE_IN_PX = 13; |
| 267 | const GRID_FULL_PX = 52; |
| 268 | const GRID_MAX_LEVEL_PX = 480; |
| 269 | const GRID_MAX_ALPHA = 0.055; |
| 270 | |
| 271 | function drawWorldGrid(canvas: HTMLCanvasElement, sigma: Sigma): void { |
| 272 | const ctx = canvas.getContext("2d"); |
| 273 | if (!ctx) return; |
| 274 | const { width, height } = sigma.getDimensions(); |
| 275 | const dpr = window.devicePixelRatio || 1; |
| 276 | const pw = Math.round(width * dpr); |
| 277 | const ph = Math.round(height * dpr); |
| 278 | if (canvas.width !== pw || canvas.height !== ph) { |
| 279 | canvas.width = pw; |
| 280 | canvas.height = ph; |
| 281 | } |
| 282 | ctx.setTransform(dpr, 0, 0, dpr, 0, 0); |
| 283 | ctx.clearRect(0, 0, width, height); |
| 284 | if (width <= 0 || height <= 0) return; |
| 285 | |
| 286 | // 世界→屏幕:两个探针点求每世界单位像素数与原点位置(无相机旋转场景) |
| 287 | const p0 = sigma.graphToViewport({ x: 0, y: 0 }); |
| 288 | const p1 = sigma.graphToViewport({ x: 1, y: 0 }); |
| 289 | const ppw = p1.x - p0.x; |
| 290 | if (!Number.isFinite(ppw) || ppw <= 0) return; |
| 291 | |
| 292 | // 最细可见层级:屏幕间距 ≥ 淡入阈值的最小 4 幂格距 |
| 293 | let spacing = GRID_BASE_WORLD; |
| 294 | while (spacing * ppw < GRID_FADE_IN_PX) spacing *= 4; |
| 295 | while (spacing * ppw >= GRID_FADE_IN_PX * 4) spacing /= 4; |
| 296 | |
| 297 | for (let sp = spacing; sp * ppw < GRID_MAX_LEVEL_PX; sp *= 4) { |
| 298 | const ss = sp * ppw; |
| 299 | const t = Math.min( |
| 300 | 1, |
| 301 | (ss - GRID_FADE_IN_PX) / (GRID_FULL_PX - GRID_FADE_IN_PX), |
| 302 | ); |
| 303 | if (t <= 0) continue; |
| 304 | ctx.strokeStyle = `rgba(255,255,255,${(GRID_MAX_ALPHA * t).toFixed(4)})`; |
| 305 | ctx.lineWidth = 1; |
| 306 | ctx.beginPath(); |
| 307 | const startX = ((p0.x % ss) + ss) % ss; |
| 308 | for (let x = startX; x <= width; x += ss) { |
| 309 | const px = Math.round(x) + 0.5; |
| 310 | ctx.moveTo(px, 0); |
| 311 | ctx.lineTo(px, height); |
| 312 | } |
| 313 | const startY = ((p0.y % ss) + ss) % ss; |
| 314 | for (let y = startY; y <= height; y += ss) { |
| 315 | const py = Math.round(y) + 0.5; |
| 316 | ctx.moveTo(0, py); |
| 317 | ctx.lineTo(width, py); |
| 318 | } |
| 319 | ctx.stroke(); |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /* 胶囊标签:深色圆角底 + 柔和文字(学 Semantica 的浮签风格) */ |
| 324 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 325 | function drawPillLabel( |
| 326 | ctx: CanvasRenderingContext2D, |
| 327 | data: any, |
| 328 | settings: any, |
| 329 | ): void { |
| 330 | if (!data.label) return; |
| 331 | // hover 时悬浮卡(drawHoverCard)接管展示,底层 pill 隐去,避免双层标签 |
| 332 | if (data.hideBaseLabel) return; |
| 333 | // Semantica chip: fontSize=clamp(10, size*0.25, 11), pad 6/3, radius 6, 位于节点上方,投影 blur 12 |
| 334 | const size = Math.max(10, Math.min(11, data.size * 0.25)); |
| 335 | ctx.font = `500 ${size}px Geist, Inter, "Noto Sans SC", sans-serif`; |
| 336 | ctx.textBaseline = "middle"; |
| 337 | const padX = 6; |
| 338 | const padY = 3; |
| 339 | const w = ctx.measureText(data.label).width + padX * 2; |
| 340 | const h = size + padY * 2; |
| 341 | const x = data.x + Math.max(data.size * 0.7, 12); |
| 342 | const y = data.y - Math.max(data.size * 0.9, 10) - h; |
| 343 | ctx.save(); |
| 344 | ctx.shadowColor = "rgba(0,0,0,0.6)"; |
| 345 | ctx.shadowBlur = 12; |
| 346 | ctx.beginPath(); |
| 347 | ctx.roundRect(x, y, w, h, 6); |
| 348 | ctx.fillStyle = PILL_BG; |
| 349 | ctx.fill(); |
| 350 | ctx.shadowBlur = 0; |
| 351 | ctx.strokeStyle = PILL_BORDER; |
| 352 | ctx.lineWidth = 1; |
| 353 | ctx.stroke(); |
| 354 | ctx.fillStyle = PILL_TEXT; |
| 355 | ctx.fillText(data.label, x + padX, y + h / 2); |
| 356 | ctx.restore(); |
| 357 | } |
| 358 | |
| 359 | /* Hover 悬浮卡(Semantica hoverCard 规格):径向柔光 + 名称 + 类型行 */ |
| 360 | // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 361 | function drawHoverCard( |
| 362 | ctx: CanvasRenderingContext2D, |
| 363 | data: any, |
| 364 | _settings: any, |
| 365 | ): void { |
| 366 | if (!data.label) return; |
| 367 | ctx.save(); |
| 368 | |
| 369 | // 柔光: 半径 max(size*4.8, 16), 类型色 alpha 0.18 → 0 |
| 370 | const glowR = Math.max(data.size * 4.8, 16); |
| 371 | const [r, g, b] = hexToRgb((data.typeColor as string) ?? "#888888"); |
| 372 | const grad = ctx.createRadialGradient( |
| 373 | data.x, |
| 374 | data.y, |
| 375 | 0, |
| 376 | data.x, |
| 377 | data.y, |
| 378 | glowR, |
| 379 | ); |
| 380 | grad.addColorStop(0, `rgba(${r},${g},${b},0.18)`); |
| 381 | grad.addColorStop(1, `rgba(${r},${g},${b},0)`); |
| 382 | ctx.fillStyle = grad; |
| 383 | ctx.beginPath(); |
| 384 | ctx.arc(data.x, data.y, glowR, 0, Math.PI * 2); |
| 385 | ctx.fill(); |
| 386 | |
| 387 | // 卡片: 标题 700/13 + 类型行 500/10 大写 |
| 388 | const titleSize = 13; |
| 389 | const metaSize = 10; |
| 390 | const padX = 10; |
| 391 | const padY = 7; |
| 392 | const metaGap = 5; |
| 393 | const meta = String(data.typeLabel ?? "NODE").toUpperCase(); |
| 394 | ctx.textBaseline = "top"; |
| 395 | ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`; |
| 396 | const titleW = ctx.measureText(data.label).width; |
| 397 | ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`; |
| 398 | const metaW = ctx.measureText(meta).width; |
| 399 | const w = Math.max(titleW, metaW) + padX * 2; |
| 400 | const h = padY * 2 + titleSize + metaGap + metaSize; |
| 401 | const x = data.x + Math.max(data.size * 0.9, 16); |
| 402 | const y = data.y - Math.max(data.size * 1.1, 16) - h; |
| 403 | |
| 404 | ctx.shadowColor = "rgba(0,0,0,0.62)"; |
| 405 | ctx.shadowBlur = 15; |
| 406 | ctx.beginPath(); |
| 407 | ctx.roundRect(x, y, w, h, 8); |
| 408 | ctx.fillStyle = "rgba(12,12,12,0.94)"; |
| 409 | ctx.fill(); |
| 410 | ctx.shadowBlur = 0; |
| 411 | ctx.strokeStyle = "rgba(255,255,255,0.16)"; |
| 412 | ctx.lineWidth = 1; |
| 413 | ctx.stroke(); |
| 414 | |
| 415 | ctx.fillStyle = "#f5f5f5"; |
| 416 | ctx.font = `700 ${titleSize}px Geist, Inter, "Noto Sans SC", sans-serif`; |
| 417 | ctx.fillText(data.label, x + padX, y + padY); |
| 418 | ctx.fillStyle = "rgba(255,255,255,0.5)"; |
| 419 | ctx.font = `500 ${metaSize}px Geist, Inter, sans-serif`; |
| 420 | ctx.fillText(meta, x + padX, y + padY + titleSize + metaGap); |
| 421 | ctx.restore(); |
| 422 | } |
| 423 | |
| 424 | export function Graph() { |
| 425 | const kbId = useKbId(); |
| 426 | const { kb } = useKb(); |
| 427 | /* 地址栏与画面**双向**同步。 |
| 428 | 从前只有"进"这一半:`?entity=` 在挂载时读一次就再不管了—— |
| 429 | 别人给的链接能用,而你自己看到的东西却没法分享,因为地址栏一直停在 |
| 430 | 光秃秃的 /graph。 */ |
| 431 | const search = useSearch({ from: "/app/kb/$kbId/graph" }); |
| 432 | const navigate = useNavigate(); |
| 433 | const entityParam = search.entity; |
| 434 | const [focusEntity, setFocusEntity] = useState<string | null>( |
| 435 | search.focus ?? entityParam ?? null, |
| 436 | ); |
| 437 | const [selected, setSelected] = useState<string | null>(entityParam ?? null); |
| 438 | const [searchInput, setSearchInput] = useState(""); |
| 439 | const [searchQ, setSearchQ] = useState(""); |
| 440 | const [hiddenTypes, setHiddenTypes] = useState<Set<string>>(new Set()); |
| 441 | // 推出来的边显不显示。默认显示——推理默认关着,有派生就意味着用户开过开关 |
| 442 | const [showDerived, setShowDerived] = useState(true); |
| 443 | // 信息窗默认收起:它答的是「什么时候推的」,那是偶尔才问的问题 |
| 444 | /* Inference 也用原地展开,与「+N 个类」、通知、用户菜单同一套。 |
| 445 | **贴左下角**:塔在画布左下,面板要从那个 ⋯ 按钮往右上长开 */ |
| 446 | const derivedPop = usePopoverFlip<HTMLButtonElement, HTMLDivElement>( |
| 447 | "bottom left", |
| 448 | ); |
| 449 | /* 「+N 个类」用与通知/用户卡片同一套原地展开:面板压到 chip 的真实边界 |
| 450 | (圆角 999px)再长成卡片。**贴左边,所以锚点角是 top left** */ |
| 451 | const legendPop = usePopoverFlip<HTMLButtonElement, HTMLDivElement>( |
| 452 | "top left", |
| 453 | ); |
| 454 | const [legendQ, setLegendQ] = useState(""); |
| 455 | /* 正在退场的实体。**面板不能一取消选中就卸载**——那样它是瞬间消失的。 |
| 456 | 先留在原地演完退场,再真的移除。用 selectedRef 取当前值而不是把 |
| 457 | setState 写成带副作用的 updater:那种写法在 StrictMode 下会跑两遍 */ |
| 458 | const [exiting, setExiting] = useState<string | null>(null); |
| 459 | // 打开面板时想停在哪一档、展开哪一行——幽灵边点进来时用 |
| 460 | const panelIntentRef = useRef<{ view: "derived"; open: string } | null>(null); |
| 461 | const deselect = useCallback(() => { |
| 462 | const cur = selectedRef.current; |
| 463 | if (!cur) return; |
| 464 | setExiting(cur); |
| 465 | setSelected(null); |
| 466 | window.setTimeout(() => setExiting(null), 170); |
| 467 | }, []); |
| 468 | /** null = 全时段;数值 = as-of 时刻(ms)。 |
| 469 | 默认 as-of 今天:时态平台的图谱默认呈现"现在的世界", |
| 470 | 已闭合的事实不该与现行事实无差别并列(All time 是显式选择) */ |
| 471 | /* 时间轴。URL 里带了就用它:`all` = 全时段,否则按 YYYY-MM-DD 解析 |
| 472 | (与数据的 day 级精度一致,也比一串毫秒好读) */ |
| 473 | const [timeT, setTimeT] = useState<number | null>(() => { |
| 474 | if (search.at === "all") return null; |
| 475 | if (search.at) { |
| 476 | const t = Date.parse(search.at); |
| 477 | if (!Number.isNaN(t)) return t; |
| 478 | } |
| 479 | return Date.now(); |
| 480 | }); |
| 481 | const [activeCount, setActiveCount] = useState(0); |
| 482 | const [stabilizing, setStabilizing] = useState(false); |
| 483 | /* 播放态提升到此层:reducer 需区分"播放推进"(淡入)与"手动拖动"(瞬切) */ |
| 484 | const [playing, setPlaying] = useState(false); |
| 485 | |
| 486 | /* 画面 → 地址栏。**replace 不是 push**:点节点是浏览不是导航, |
| 487 | 堆进历史会把「后退」变成逐个撤销点击。 |
| 488 | 播放中整段跳过——每帧写一次 URL 是灾难 */ |
| 489 | useEffect(() => { |
| 490 | if (playing) return; |
| 491 | const at = |
| 492 | timeT === null |
| 493 | ? "all" |
| 494 | : // 停在「现在」就不写。否则每次打开都在地址栏拖一串今天的日期, |
| 495 | // 而那本来就是默认值 |
| 496 | Math.abs(timeT - Date.now()) < DAY_MS |
| 497 | ? undefined |
| 498 | : new Date(timeT).toISOString().slice(0, 10); |
| 499 | const next = { |
| 500 | entity: selected ?? undefined, |
| 501 | // **与 entity 相同就不写**:点搜索结果会同时设这两个, |
| 502 | // 照直写出来地址栏里就是同一串 UUID 出现两遍。 |
| 503 | // 只有"聚焦在 A 的邻域、却选中了 B"时它才带信息 |
| 504 | focus: |
| 505 | focusEntity && focusEntity !== selected ? focusEntity : undefined, |
| 506 | at, |
| 507 | }; |
| 508 | if ( |
| 509 | next.entity === search.entity && |
| 510 | next.focus === search.focus && |
| 511 | next.at === search.at |
| 512 | ) |
| 513 | return; |
| 514 | navigate({ |
| 515 | to: "/kb/$kbId/graph", |
| 516 | params: { kbId }, |
| 517 | search: next, |
| 518 | replace: true, |
| 519 | }); |
| 520 | }, [ |
| 521 | selected, |
| 522 | focusEntity, |
| 523 | timeT, |
| 524 | playing, |
| 525 | search.entity, |
| 526 | search.focus, |
| 527 | search.at, |
| 528 | navigate, |
| 529 | ]); |
| 530 | |
| 531 | /* 地址栏 → 画面。**这一半是给后退/前进用的**:没有它,浏览器回退 |
| 532 | 只改地址不改画面,看起来像后退失灵。两个方向都先比较再动手,所以不会打架 */ |
| 533 | useEffect(() => { |
| 534 | const e = search.entity ?? null; |
| 535 | const f = search.focus ?? null; |
| 536 | setSelected((cur) => (cur === e ? cur : e)); |
| 537 | setFocusEntity((cur) => (cur === f ? cur : f)); |
| 538 | }, [search.entity, search.focus]); |
| 539 | /* 布局模式:force = FA2 斥力;circular = 圆环;pack = 按类型圆填充聚簇 */ |
| 540 | type LayoutMode = "force" | "circular" | "pack"; |
| 541 | const [layoutMode, setLayoutMode] = useState<LayoutMode>("force"); |
| 542 | const layoutModeRef = useRef<LayoutMode>("force"); |
| 543 | const layoutCtlRef = useRef<{ apply: (m: LayoutMode) => void } | null>(null); |
| 544 | |
| 545 | /* 画多少个。**进 queryKey**——不进的话调了档位不会重新取数, |
| 546 | 界面看着变了实际还是老数据 */ |
| 547 | const [nodeBudget, setNodeBudget] = useState<number>(NODE_BUDGETS[0]); |
| 548 | |
| 549 | const data = useQuery({ |
| 550 | queryKey: ["graph", kb?.id, focusEntity, nodeBudget], |
| 551 | queryFn: () => |
| 552 | focusEntity |
| 553 | ? api.graphNeighborhood(kb!.id, focusEntity) |
| 554 | : api.graphOverview(kb!.id, nodeBudget), |
| 555 | enabled: !!kb, |
| 556 | }); |
| 557 | |
| 558 | // 全图模式走全库实体搜索;子图模式只在已加载的子图内客户端过滤 |
| 559 | const inSubgraph = !!focusEntity; |
| 560 | // 搜到的条数上限。**「加载更多」而不是翻页**:这是个下拉建议框, |
| 561 | // 用户在找一个具体的实体,翻页会让他丢掉刚才扫过的那几条 |
| 562 | const [searchLimit, setSearchLimit] = useState(10); |
| 563 | useEffect(() => setSearchLimit(10), [searchQ]); |
| 564 | const candidates = useQuery({ |
| 565 | queryKey: ["entitySearch", kb?.id, searchQ, searchLimit], |
| 566 | queryFn: () => api.searchEntities(kb!.id, searchQ, searchLimit), |
| 567 | enabled: !!kb && searchQ.length > 0 && !inSubgraph, |
| 568 | placeholderData: (prev) => prev, |
| 569 | }); |
| 570 | const subgraphHits = useMemo(() => { |
| 571 | if (!inSubgraph || !searchQ || !data.data) return []; |
| 572 | const q = searchQ.toLowerCase(); |
| 573 | return data.data.nodes |
| 574 | .filter( |
| 575 | (n) => |
| 576 | n.name.toLowerCase().includes(q) || |
| 577 | n.disambiguator?.toLowerCase().includes(q), |
| 578 | ) |
| 579 | .slice(0, 10); |
| 580 | }, [inSubgraph, searchQ, data.data]); |
| 581 | const searchHits = inSubgraph |
| 582 | ? subgraphHits |
| 583 | : (candidates.data?.entities ?? []); |
| 584 | |
| 585 | const containerRef = useRef<HTMLDivElement>(null); |
| 586 | const gridRef = useRef<HTMLCanvasElement>(null); |
| 587 | const sigmaRef = useRef<Sigma | null>(null); |
| 588 | /* 焦点 = hover 优先于选中;样式在 reducer 里统一处理 */ |
| 589 | const selectedRef = useRef<string | null>(null); |
| 590 | const hoverRef = useRef<string | null>(null); |
| 591 | /** 鼠标停在哪条边上。用来把并进它的逆关系说法亮出来 */ |
| 592 | const hoverEdgeRef = useRef<string | null>(null); |
| 593 | const filterRef = useRef<{ |
| 594 | hiddenTypes: Set<string>; |
| 595 | activeNodes: Set<string> | null; |
| 596 | activeEdges: Set<string> | null; |
| 597 | /** 推出来的边显不显示。**默认显示**——推理默认是关的,所以有派生边就意味着 |
| 598 | * 用户主动开过开关;但要能一键藏起来,看「只有人说过的那张图」长什么样 */ |
| 599 | showDerived: boolean; |
| 600 | }>({ |
| 601 | hiddenTypes: new Set(), |
| 602 | activeNodes: null, |
| 603 | activeEdges: null, |
| 604 | showDerived: true, |
| 605 | }); |
| 606 | const playingRef = useRef(false); |
| 607 | /* 播放淡入表:本轮新激活的节点/边 id → 激活时刻(rAF 循环驱动至到位) */ |
| 608 | const fadeRef = useRef<Map<string, number>>(new Map()); |
| 609 | const fadeRafRef = useRef(0); |
| 610 | |
| 611 | const kickFade = useCallback(() => { |
| 612 | if (fadeRafRef.current) return; |
| 613 | const step = () => { |
| 614 | const now = performance.now(); |
| 615 | for (const [id, start] of fadeRef.current) |
| 616 | if (now - start >= FADE_MS) fadeRef.current.delete(id); |
| 617 | sigmaRef.current?.refresh(); |
| 618 | fadeRafRef.current = fadeRef.current.size |
| 619 | ? requestAnimationFrame(step) |
| 620 | : 0; |
| 621 | }; |
| 622 | fadeRafRef.current = requestAnimationFrame(step); |
| 623 | }, []); |
| 624 | |
| 625 | useEffect(() => { |
| 626 | playingRef.current = playing; |
| 627 | if (!playing) { |
| 628 | // 停止播放:未完成的淡入直接到位 |
| 629 | fadeRef.current.clear(); |
| 630 | sigmaRef.current?.refresh(); |
| 631 | } |
| 632 | }, [playing]); |
| 633 | |
| 634 | useEffect(() => () => cancelAnimationFrame(fadeRafRef.current), []); |
| 635 | |
| 636 | const types = useMemo(() => { |
| 637 | const map = new Map< |
| 638 | string, |
| 639 | { label: string; color: string; shape: string; count: number } |
| 640 | >(); |
| 641 | for (const n of data.data?.nodes ?? []) { |
| 642 | // 没判出类型的归到空 key 一档(0009)。真实 key 由 IRI 派生,不可能为空, |
| 643 | // 所以它撞不着任何一个类;标签走 i18n,别把 null 画到图例上 |
| 644 | const key = n.type_key ?? ""; |
| 645 | const cur = map.get(key); |
| 646 | if (cur) cur.count++; |
| 647 | else |
| 648 | map.set(key, { |
| 649 | label: n.type_label ?? S.graph.untyped, |
| 650 | color: n.color, |
| 651 | shape: n.shape, |
| 652 | count: 1, |
| 653 | }); |
| 654 | } |
| 655 | // **按出现次数排,不是按遇到的先后**。图例只摆得下几个,那几个位置该给 |
| 656 | // 画面上最多的类;从前是节点到达顺序,等于随机。次数相同按标签排—— |
| 657 | // 否则同样的数据每次刷新顺序都在抖 |
| 658 | return [...map.entries()].sort( |
| 659 | (a, b) => b[1].count - a[1].count || a[1].label.localeCompare(b[1].label), |
| 660 | ); |
| 661 | }, [data.data]); |
| 662 | |
| 663 | /* 摆得下的 / 收起来的。收起来的那些仍然可以在「+N」里搜到并切换 */ |
| 664 | const legendShown = types.slice(0, LEGEND_MAX); |
| 665 | const legendRest = types.slice(LEGEND_MAX); |
| 666 | // 被收起来的类里有没有正被隐藏的。**没有这个标记就是无声过滤**—— |
| 667 | // 在面板里关掉一个类、把面板一收,界面上再没有任何东西说它被关了 |
| 668 | const hiddenInRest = legendRest.filter(([k]) => hiddenTypes.has(k)).length; |
| 669 | |
| 670 | // 有几条推出来的边。**为零时那个开关整个不出现**——一个没开推理的库不该 |
| 671 | // 看到一个永远切换不出任何变化的按钮 |
| 672 | const derivedCount = useMemo( |
| 673 | () => (data.data?.edges ?? []).filter((e) => e.derived).length, |
| 674 | [data.data], |
| 675 | ); |
| 676 | |
| 677 | /* 时间过滤:计算 T 时刻的活跃边/节点集合 */ |
| 678 | const recomputeActive = useCallback( |
| 679 | (t: number | null) => { |
| 680 | const d = data.data; |
| 681 | if (!d) return; |
| 682 | if (t === null) { |
| 683 | filterRef.current.activeNodes = null; |
| 684 | filterRef.current.activeEdges = null; |
| 685 | setActiveCount(d.edges.length); |
| 686 | } else { |
| 687 | const prevNodes = filterRef.current.activeNodes; |
| 688 | const prevEdges = filterRef.current.activeEdges; |
| 689 | const edges = new Set<string>(); |
| 690 | const nodes = new Set<string>(); |
| 691 | const touched = new Set<string>(); |
| 692 | for (const e of d.edges) { |
| 693 | const vf = e.valid_from ? Date.parse(e.valid_from) : null; |
| 694 | const vt = e.valid_to ? Date.parse(e.valid_to) : null; |
| 695 | touched.add(e.source); |
| 696 | touched.add(e.target); |
| 697 | const active = |
| 698 | vf === null ? true : vf <= t && (vt === null || vt > t); |
| 699 | if (active) { |
| 700 | edges.add(e.id); |
| 701 | nodes.add(e.source); |
| 702 | nodes.add(e.target); |
| 703 | } |
| 704 | } |
| 705 | // 没有任何边的孤立节点保持可见 |
| 706 | for (const n of d.nodes) if (!touched.has(n.id)) nodes.add(n.id); |
| 707 | // 播放推进时新出现的元素淡入登场;手动拖动保持瞬时切换 |
| 708 | if (playingRef.current) { |
| 709 | const now = performance.now(); |
| 710 | for (const id of edges) |
| 711 | if (prevEdges && !prevEdges.has(id)) fadeRef.current.set(id, now); |
| 712 | for (const id of nodes) |
| 713 | if (prevNodes && !prevNodes.has(id)) fadeRef.current.set(id, now); |
| 714 | if (fadeRef.current.size) kickFade(); |
| 715 | } |
| 716 | filterRef.current.activeNodes = nodes; |
| 717 | filterRef.current.activeEdges = edges; |
| 718 | setActiveCount(edges.size); |
| 719 | } |
| 720 | sigmaRef.current?.refresh(); |
| 721 | }, |
| 722 | [data.data, kickFade], |
| 723 | ); |
| 724 | |
| 725 | useEffect(() => { |
| 726 | filterRef.current.hiddenTypes = hiddenTypes; |
| 727 | filterRef.current.showDerived = showDerived; |
| 728 | sigmaRef.current?.refresh(); |
| 729 | }, [hiddenTypes, showDerived]); |
| 730 | |
| 731 | const deriveRafRef = useRef(0); |
| 732 | /* 演完之前派生边不出现。**开关是"要不要显示",这个是"演到了没有"**—— |
| 733 | 两件事,混成一个会让关掉再打开时少演一遍 */ |
| 734 | const [derivedRevealed, setDerivedRevealed] = useState(false); |
| 735 | /* reducer 是每帧跑的闭包,读 state 会读到旧值——它只认 ref */ |
| 736 | const derivedRevealedRef = useRef(false); |
| 737 | useEffect(() => { |
| 738 | derivedRevealedRef.current = derivedRevealed; |
| 739 | sigmaRef.current?.refresh(); |
| 740 | }, [derivedRevealed]); |
| 741 | |
| 742 | const revealDerived = useCallback(() => { |
| 743 | setDerivedRevealed(true); |
| 744 | // 复用开关那套淡入:方向为"开",从近背景色亮到常态 |
| 745 | derivedToggleRef.current = { at: performance.now(), on: true }; |
| 746 | const step = () => { |
| 747 | const tr = derivedToggleRef.current; |
| 748 | const done = !tr || performance.now() - tr.at >= DERIVE_FADE_MS; |
| 749 | if (done) derivedToggleRef.current = null; |
| 750 | sigmaRef.current?.refresh(); |
| 751 | deriveRafRef.current = done ? 0 : requestAnimationFrame(step); |
| 752 | }; |
| 753 | cancelAnimationFrame(deriveRafRef.current); |
| 754 | deriveRafRef.current = requestAnimationFrame(step); |
| 755 | }, []); |
| 756 | |
| 757 | useEffect(() => () => cancelAnimationFrame(deriveRafRef.current), []); |
| 758 | |
| 759 | /* 开关的淡入淡出:{ 起始时刻, 朝哪个方向 };null = 没有过渡在飞 */ |
| 760 | const derivedToggleRef = useRef<{ at: number; on: boolean } | null>(null); |
| 761 | const derivedRafRef = useRef(0); |
| 762 | /* 上一次的开关值。**判「是不是真的切换了」只能靠它**——effect 的依赖里 |
| 763 | 还有 derivedCount,而「Run now 推出新边」会改 count 却没碰开关; |
| 764 | 只看 effect 触发就淡一次,那是一次没人要求的动画 */ |
| 765 | const prevShowDerived = useRef(showDerived); |
| 766 | |
| 767 | // 切换时走一段渐变,而不是瞬间消失。**得自己驱动重绘**——关掉时下面那个 |
| 768 | // 呼吸定时器不转了,没人推 sigma 重画,淡出就会卡在第一帧 |
| 769 | useEffect(() => { |
| 770 | const changed = prevShowDerived.current !== showDerived; |
| 771 | prevShowDerived.current = showDerived; |
| 772 | // 首次挂载与「只有 count 变了」都不是切换: |
| 773 | // 进页面时、以及推理跑完刷新计数时,都不该看到一段莫名其妙的淡入 |
| 774 | if (!changed) return; |
| 775 | // 数量太多时不淡:与呼吸同一条线——每帧重算几千条边的颜色换来的是卡顿。 |
| 776 | // **写出来而不是悄悄降级** |
| 777 | if (derivedCount > DERIVED_ANIMATE_MAX) return; |
| 778 | |
| 779 | const now = performance.now(); |
| 780 | const prev = derivedToggleRef.current; |
| 781 | // 半途反向(用户连点两下):从当前进度接着走,而不是从头开始—— |
| 782 | // 否则会看见一次亮度的跳变 |
| 783 | const at = |
| 784 | prev && prev.on !== showDerived |
| 785 | ? now - Math.max(0, DERIVED_TOGGLE_MS - (now - prev.at)) |
| 786 | : now; |
| 787 | derivedToggleRef.current = { at, on: showDerived }; |
| 788 | |
| 789 | const step = () => { |
| 790 | const tr = derivedToggleRef.current; |
| 791 | const done = !tr || performance.now() - tr.at >= DERIVED_TOGGLE_MS; |
| 792 | if (done) derivedToggleRef.current = null; |
| 793 | sigmaRef.current?.refresh(); |
| 794 | derivedRafRef.current = done ? 0 : requestAnimationFrame(step); |
| 795 | }; |
| 796 | cancelAnimationFrame(derivedRafRef.current); |
| 797 | derivedRafRef.current = requestAnimationFrame(step); |
| 798 | // **不在这里挂清理**:清理会在依赖变化时也跑一遍,而依赖里有 derivedCount |
| 799 | // ——推理恰好在这 420ms 中途跑完,动画就被掐在半路(画面停在一半亮度, |
| 800 | // 要等下一次任意重绘才归位)。循环自己会终止;取消只该发生在卸载时 |
| 801 | }, [showDerived, derivedCount]); |
| 802 | |
| 803 | // 卸载时收掉可能在飞的那一帧 |
| 804 | useEffect(() => () => cancelAnimationFrame(derivedRafRef.current), []); |
| 805 | |
| 806 | /* 什么时候进场。两个入口共用一段延时:进页面、以及手动打开开关。 |
| 807 | **不等布局收敛**——收敛要 2.5 秒,等完人早就在看别处了。 |
| 808 | |
| 809 | **顺序本身是内容**:先落位的是人写下的边,然后才轮到推出来的。 |
| 810 | 一起出现就分不清谁在前 */ |
| 811 | useEffect(() => { |
| 812 | if (!showDerived || !data.data) { |
| 813 | if (!showDerived) setDerivedRevealed(false); |
| 814 | return; |
| 815 | } |
| 816 | if (derivedRevealed) return; |
| 817 | const t = window.setTimeout(revealDerived, DERIVE_SETTLE_MS); |
| 818 | return () => window.clearTimeout(t); |
| 819 | }, [showDerived, data.data, derivedRevealed, revealDerived]); |
| 820 | |
| 821 | // 派生边的呼吸。**只在有派生边、且开着显示、且数量不多时才转**—— |
| 822 | // 一个没开推理的库不该为这件事每两秒重画一次 |
| 823 | useEffect(() => { |
| 824 | const n = derivedCount; |
| 825 | if (!showDerived || n === 0 || n > DERIVED_ANIMATE_MAX) return; |
| 826 | // 与 sigma 的重绘同频即可,不必每帧:呼吸是慢动作,30 fps 看不出差别 |
| 827 | const timer = setInterval(() => sigmaRef.current?.refresh(), 1000 / 30); |
| 828 | return () => clearInterval(timer); |
| 829 | }, [showDerived, derivedCount]); |
| 830 | |
| 831 | useEffect(() => { |
| 832 | selectedRef.current = selected; |
| 833 | sigmaRef.current?.refresh(); |
| 834 | }, [selected]); |
| 835 | |
| 836 | useEffect(() => { |
| 837 | recomputeActive(timeT); |
| 838 | }, [timeT, recomputeActive]); |
| 839 | |
| 840 | useEffect(() => { |
| 841 | if (!containerRef.current || !data.data) return; |
| 842 | const g = new Graphology({ multi: true }); |
| 843 | for (const n of data.data.nodes) { |
| 844 | if (!g.hasNode(n.id)) { |
| 845 | g.addNode(n.id, { |
| 846 | label: n.name, |
| 847 | // Semantica 配方:深壳 + 14% 类型 tint,核心 50% tint,钢灰描边微 tint |
| 848 | color: mix(NODE_CORE_BASE, n.color, NODE_CORE_MIX), |
| 849 | shellColor: mix(NODE_SHELL_BASE, n.color, NODE_TINT_MIX), |
| 850 | borderColor: mix(NODE_BORDER_BASE, n.color, 0.3), |
| 851 | ringColor: TRANSPARENT, |
| 852 | typeColor: n.color, |
| 853 | typeLabel: n.type_label ?? S.graph.untyped, |
| 854 | typeKey: n.type_key ?? "", |
| 855 | type: n.shape === "square" ? "square" : "shell", |
| 856 | size: 5 + Math.min(8, Math.sqrt(Number(n.degree)) * 1.6), |
| 857 | }); |
| 858 | } |
| 859 | } |
| 860 | const placed = layOutParallelEdges( |
| 861 | data.data.edges.filter((e) => g.hasNode(e.source) && g.hasNode(e.target)), |
| 862 | ); |
| 863 | for (const { edge: e, curvature, alsoLabels } of placed.edges) { |
| 864 | g.addEdgeWithKey(e.id, e.source, e.target, { |
| 865 | // 争议的边标签前置 ⚠:颜色之外再给一个不靠色觉的记号 |
| 866 | label: (e.contested ? "⚠ " : "") + (e.label?.toUpperCase() ?? ""), |
| 867 | size: e.blocked ? 0.7 : 1, |
| 868 | color: e.blocked |
| 869 | ? EDGE_GHOST |
| 870 | : e.contested |
| 871 | ? EDGE_COLOR_CONTEST |
| 872 | : e.derived |
| 873 | ? EDGE_COLOR_DERIVED |
| 874 | : e.inferred |
| 875 | ? EDGE_COLOR_INFERRED |
| 876 | : EDGE_COLOR, |
| 877 | contested: e.contested, |
| 878 | blocked: e.blocked, |
| 879 | // 独一条就走直线:曲线是为了把重叠分开,没有重叠就不必弯 |
| 880 | type: curvature === 0 ? "line" : "curved", |
| 881 | curvature, |
| 882 | // 并进来的逆关系说法,悬停时连着本名一起显示 |
| 883 | alsoLabels, |
| 884 | // reducer 每帧读它:决定要不要藏、要不要呼吸 |
| 885 | derived: e.derived, |
| 886 | }); |
| 887 | } |
| 888 | // 布局:先静态铺开,再用 worker 动画稳定 ~2.5s(Semantica 式 stabilizing) |
| 889 | let fa2: InstanceType<typeof FA2Layout> | null = null; |
| 890 | let stabilizeTimer: ReturnType<typeof setTimeout> | null = null; |
| 891 | // 拖拽状态先于 fa2 声明:outputReducer 闭包引用它们 |
| 892 | let dragged: string | null = null; |
| 893 | let dragPos: { x: number; y: number } | null = null; |
| 894 | let fa2Settings: ReturnType<typeof forceAtlas2.inferSettings> | null = null; |
| 895 | if (g.order > 0) { |
| 896 | circular.assign(g, { scale: 300 }); |
| 897 | /* 试过按规模缩放(gravity 0.12–0.22 / scalingRatio 11–16 + 加大阻尼), |
| 898 | 拿真实的图一看就否了:散是散开了,但那种"被推开"的张力没了, |
| 899 | 整张图显得瘫。**这一组是既有的、刻意偏大的**——要的是节点之间 |
| 900 | 互相顶着的感觉,不是最省力的排布 */ |
| 901 | const settings = { |
| 902 | ...forceAtlas2.inferSettings(g), |
| 903 | gravity: 0.35, |
| 904 | scalingRatio: 22, |
| 905 | outboundAttractionDistribution: true, |
| 906 | }; |
| 907 | fa2Settings = settings; |
| 908 | forceAtlas2.assign(g, { iterations: 60, settings }); |
| 909 | fa2 = new FA2Layout(g, { |
| 910 | settings, |
| 911 | // 关键:回写时把被拖节点钉回光标(不闪);且提供 outputReducer 后 |
| 912 | // supervisor 每帧 readGraphPositions —— 光标位置持续进入力模拟 |
| 913 | outputReducer: (node, attr) => { |
| 914 | if (dragged && node === dragged && dragPos) { |
| 915 | attr.x = dragPos.x; |
| 916 | attr.y = dragPos.y; |
| 917 | } |
| 918 | return attr; |
| 919 | }, |
| 920 | }); |
| 921 | fa2.start(); |
| 922 | setStabilizing(true); |
| 923 | stabilizeTimer = setTimeout(() => { |
| 924 | fa2?.stop(); |
| 925 | setStabilizing(false); |
| 926 | }, 2500); |
| 927 | } |
| 928 | |
| 929 | // 数据重建后布局回到 force(世界重新长出来) |
| 930 | setLayoutMode("force"); |
| 931 | layoutModeRef.current = "force"; |
| 932 | |
| 933 | // 任意布局结果统一缩放到 FA2 同量级世界(±target),相机 reset 观感一致 |
| 934 | const rescaleWorld = (target = 300) => { |
| 935 | let minX = Infinity, |
| 936 | maxX = -Infinity, |
| 937 | minY = Infinity, |
| 938 | maxY = -Infinity; |
| 939 | g.forEachNode((_n, a) => { |
| 940 | minX = Math.min(minX, a.x as number); |
| 941 | maxX = Math.max(maxX, a.x as number); |
| 942 | minY = Math.min(minY, a.y as number); |
| 943 | maxY = Math.max(maxY, a.y as number); |
| 944 | }); |
| 945 | const span = Math.max(maxX - minX, maxY - minY) || 1; |
| 946 | const k = (target * 2) / span; |
| 947 | const cx = (minX + maxX) / 2; |
| 948 | const cy = (minY + maxY) / 2; |
| 949 | g.updateEachNodeAttributes((_n, a) => ({ |
| 950 | ...a, |
| 951 | x: (a.x - cx) * k, |
| 952 | y: (a.y - cy) * k, |
| 953 | })); |
| 954 | }; |
| 955 | |
| 956 | // 布局切换控制(挂到 ref 供组件层按钮调用;闭包内直握 g / fa2) |
| 957 | layoutCtlRef.current = { |
| 958 | apply: (mode) => { |
| 959 | if (g.order === 0) return; |
| 960 | if (stabilizeTimer) clearTimeout(stabilizeTimer); |
| 961 | fa2?.stop(); |
| 962 | setStabilizing(false); |
| 963 | if (mode === "force") { |
| 964 | forceAtlas2.assign(g, { |
| 965 | iterations: 60, |
| 966 | settings: fa2Settings ?? undefined, |
| 967 | }); |
| 968 | fa2?.start(); |
| 969 | setStabilizing(true); |
| 970 | stabilizeTimer = setTimeout(() => { |
| 971 | fa2?.stop(); |
| 972 | setStabilizing(false); |
| 973 | }, 2500); |
| 974 | } else if (mode === "circular") { |
| 975 | circular.assign(g, { scale: 300 }); |
| 976 | } else { |
| 977 | // 按实体类型聚簇:同类型挤进同一个圆 |
| 978 | circlepack.assign(g, { hierarchyAttributes: ["typeKey"] }); |
| 979 | rescaleWorld(300); |
| 980 | } |
| 981 | sigma.setCustomBBox(null); |
| 982 | sigma.refresh(); |
| 983 | sigma.getCamera().animatedReset({ duration: 300 }); |
| 984 | }, |
| 985 | }; |
| 986 | |
| 987 | sigmaRef.current?.kill(); |
| 988 | const sigma = new Sigma(g, containerRef.current, { |
| 989 | allowInvalidContainer: true, |
| 990 | defaultNodeType: "shell", |
| 991 | nodeProgramClasses: { |
| 992 | // Semantica 节点解剖:状态环 → 描边 → 深色壳 → 微彩核心 |
| 993 | shell: createNodeBorderProgram({ |
| 994 | borders: [ |
| 995 | { size: { value: 0.1 }, color: { attribute: "ringColor" } }, |
| 996 | { size: { value: 0.07 }, color: { attribute: "borderColor" } }, |
| 997 | { size: { value: 0.3 }, color: { attribute: "shellColor" } }, |
| 998 | { size: { fill: true }, color: { attribute: "color" } }, |
| 999 | ], |
| 1000 | }), |
| 1001 | square: NodeSquareShellProgram, |
| 1002 | }, |
| 1003 | renderEdgeLabels: true, |
| 1004 | defaultEdgeType: "line", |
| 1005 | /* 平行边扇成弧(见 `layOutParallelEdges`)。直线那一版把同一对节点之间 |
| 1006 | 的每条边画在同一条线段上,于是几个标签逐字符叠成乱码——实测一对节点 |
| 1007 | 之间最多压着六条 */ |
| 1008 | edgeProgramClasses: { curved: EdgeCurveProgram }, |
| 1009 | // 边的悬停事件默认是关的。开它是为了 `enterEdge`:并进去的那些说法 |
| 1010 | // 要有地方看得见(见 edgeReducer) |
| 1011 | enableEdgeEvents: true, |
| 1012 | labelFont: '"Geist", "Inter", "Noto Sans SC", sans-serif', |
| 1013 | labelSize: 11, |
| 1014 | labelColor: { color: "#e5e5e5" }, |
| 1015 | labelRenderedSizeThreshold: 6, |
| 1016 | labelDensity: 0.7, |
| 1017 | labelGridCellSize: 140, |
| 1018 | minCameraRatio: 0.04, |
| 1019 | maxCameraRatio: 8, |
| 1020 | edgeLabelSize: 9, |
| 1021 | edgeLabelColor: { color: "#a1a1a1" }, |
| 1022 | edgeLabelFont: '"Geist", "Inter", sans-serif', |
| 1023 | defaultDrawNodeLabel: drawPillLabel, |
| 1024 | defaultDrawNodeHover: drawHoverCard, |
| 1025 | nodeReducer: (node, attrs) => { |
| 1026 | const f = filterRef.current; |
| 1027 | const res = { ...attrs }; |
| 1028 | const base = attrs.size as number; |
| 1029 | // 状态环取节点自己的类型色(见 RING_*_MIX 处的理由) |
| 1030 | const ownColor = (attrs.typeColor as string) ?? NODE_CORE_BASE; |
| 1031 | if (f.hiddenTypes.has(attrs.typeKey as string)) { |
| 1032 | res.hidden = true; |
| 1033 | return res; |
| 1034 | } |
| 1035 | // Semantica 状态表: muted { ×0.52, 全层压暗 } |
| 1036 | const muteNode = () => { |
| 1037 | res.size = base * 0.52; |
| 1038 | res.color = mix(MUTED_SHELL, NODE_CORE_BASE, 0.3); |
| 1039 | res.shellColor = MUTED_SHELL; |
| 1040 | res.borderColor = TRANSPARENT; |
| 1041 | res.ringColor = TRANSPARENT; |
| 1042 | res.label = ""; |
| 1043 | res.zIndex = 0; |
| 1044 | }; |
| 1045 | /* 悬停时其余的按 HOVER_MUTE 压一档(选中是压到底)。 |
| 1046 | 邻居不压——悬停要回答的是"它连着谁",把邻居也压掉就等于没回答 */ |
| 1047 | const softMute = () => { |
| 1048 | res.size = base * (1 - 0.48 * HOVER_MUTE); |
| 1049 | res.color = lerpColor( |
| 1050 | String(attrs.color ?? NODE_CORE_BASE), |
| 1051 | mix(MUTED_SHELL, NODE_CORE_BASE, 0.3), |
| 1052 | HOVER_MUTE, |
| 1053 | ); |
| 1054 | res.shellColor = lerpColor( |
| 1055 | String(attrs.shellColor ?? NODE_SHELL_BASE), |
| 1056 | MUTED_SHELL, |
| 1057 | HOVER_MUTE, |
| 1058 | ); |
| 1059 | res.borderColor = TRANSPARENT; |
| 1060 | res.ringColor = TRANSPARENT; |
| 1061 | res.label = ""; |
| 1062 | res.zIndex = 0; |
| 1063 | }; |
| 1064 | if (hoverRef.current === node) { |
| 1065 | res.size = Math.max(base * 1.08, 10.4); |
| 1066 | res.ringColor = mix(ownColor, "#ffffff", RING_HOVER_MIX); |
| 1067 | // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题) |
| 1068 | res.hideBaseLabel = true; |
| 1069 | res.zIndex = 4; |
| 1070 | return res; |
| 1071 | } |
| 1072 | const hov = hoverRef.current; |
| 1073 | // 选中实体可能不在当前画布(侧栏跳转/邻域重载间隙)——不在则跳过聚焦压暗逻辑 |
| 1074 | const sel = |
| 1075 | selectedRef.current && g.hasNode(selectedRef.current) |
| 1076 | ? selectedRef.current |
| 1077 | : null; |
| 1078 | if (sel) { |
| 1079 | if (node === sel) { |
| 1080 | res.size = Math.max(base * 1.02, 9.2); |
| 1081 | res.ringColor = mix(ownColor, "#ffffff", RING_SELECT_MIX); |
| 1082 | res.forceLabel = true; |
| 1083 | res.zIndex = 3; |
| 1084 | return res; |
| 1085 | } |
| 1086 | if (g.areNeighbors(sel, node)) { |
| 1087 | // neighbor {×0.76, min 4, zIndex 2} |
| 1088 | res.size = Math.max(base * 0.76, 4); |
| 1089 | res.zIndex = 2; |
| 1090 | } else { |
| 1091 | muteNode(); |
| 1092 | return res; |
| 1093 | } |
| 1094 | } else if (hov && hov !== node && !g.areNeighbors(hov, node)) { |
| 1095 | // **悬停也压暗其余**,只是比选中轻一档(见 HOVER_MUTE)。 |
| 1096 | // 邻居留着:悬停要回答的正是"它连着谁"。 |
| 1097 | // **此刻还不存在的节点直接压到底**:这个分支会提前 return, |
| 1098 | // 绕过下面那道时间过滤,只压一半的话它反而比不 hover 时更亮 |
| 1099 | if (f.activeNodes && !f.activeNodes.has(node)) muteNode(); |
| 1100 | else softMute(); |
| 1101 | return res; |
| 1102 | } else { |
| 1103 | // default {×0.7} |
| 1104 | res.size = base * 0.7; |
| 1105 | } |
| 1106 | if (f.activeNodes && !f.activeNodes.has(node)) { |
| 1107 | muteNode(); |
| 1108 | return res; |
| 1109 | } |
| 1110 | // 播放淡入:从 muted 形态渐变到本帧算出的正常形态 |
| 1111 | const fs = fadeRef.current.get(node); |
| 1112 | if (fs !== undefined) { |
| 1113 | const t = Math.min(1, (performance.now() - fs) / FADE_MS); |
| 1114 | res.size = (res.size as number) * (0.55 + 0.45 * t); |
| 1115 | res.color = lerpColor( |
| 1116 | MUTED_SHELL, |
| 1117 | String(res.color ?? NODE_CORE_BASE), |
| 1118 | t, |
| 1119 | ); |
| 1120 | res.shellColor = lerpColor( |
| 1121 | MUTED_SHELL, |
| 1122 | String(res.shellColor ?? NODE_SHELL_BASE), |
| 1123 | t, |
| 1124 | ); |
| 1125 | res.borderColor = lerpColor( |
| 1126 | "rgba(0,0,0,0)", |
| 1127 | String(res.borderColor ?? NODE_BORDER_BASE), |
| 1128 | t, |
| 1129 | ); |
| 1130 | if (t < 0.7) res.label = ""; |
| 1131 | } |
| 1132 | return res; |
| 1133 | }, |
| 1134 | edgeReducer: (edge, attrs) => { |
| 1135 | const f = filterRef.current; |
| 1136 | const res = { ...attrs }; |
| 1137 | const [s, t] = g.extremities(edge); |
| 1138 | /* 并进这条边的逆关系说法,接在本名后面:`PART OF ⁻¹ CONTAINS`。 |
| 1139 | **只在关注它的时候显示**——常驻会把标签拉长一倍,而标签太长 |
| 1140 | 正是这次要治的毛病。 |
| 1141 | 两个触发点,因为**边只有一像素宽,精确悬停对人也很难命中**: |
| 1142 | 鼠标压在这条边上,或者压在它两端任一个节点上。后者才是实际 |
| 1143 | 用得上的那个,前者留着是因为有时人就是要指那一条。 |
| 1144 | 放在隐藏/压暗逻辑之前:说法是显示的事,不是可见性的事 */ |
| 1145 | const also = attrs.alsoLabels as string[] | undefined; |
| 1146 | if (also && also.length > 0) { |
| 1147 | const focused = |
| 1148 | edge === hoverEdgeRef.current || |
| 1149 | hoverRef.current === s || |
| 1150 | hoverRef.current === t || |
| 1151 | selectedRef.current === s || |
| 1152 | selectedRef.current === t; |
| 1153 | if (focused) { |
| 1154 | res.label = `${attrs.label} ⁻¹ ${also |
| 1155 | .map((l) => l.toUpperCase()) |
| 1156 | .join(" / ")}`; |
| 1157 | } |
| 1158 | } |
| 1159 | const sk = g.getNodeAttribute(s, "typeKey") as string; |
| 1160 | const tk = g.getNodeAttribute(t, "typeKey") as string; |
| 1161 | if (f.hiddenTypes.has(sk) || f.hiddenTypes.has(tk)) { |
| 1162 | res.hidden = true; |
| 1163 | return res; |
| 1164 | } |
| 1165 | // 推出来的边:先看藏不藏,再决定呼吸到哪一档。 |
| 1166 | // **放在最前面**——藏起来的边不必再算后面那些提亮/压暗 |
| 1167 | const isDerived = attrs.derived === true; |
| 1168 | |
| 1169 | if (isDerived) { |
| 1170 | // 还没轮到它进场:先不画。**事实先落位,推出来的后到** |
| 1171 | if (!derivedRevealedRef.current) { |
| 1172 | res.hidden = true; |
| 1173 | return res; |
| 1174 | } |
| 1175 | const tr = derivedToggleRef.current; |
| 1176 | const k = tr |
| 1177 | ? Math.min(1, (performance.now() - tr.at) / DERIVED_TOGGLE_MS) |
| 1178 | : 1; |
| 1179 | // 关掉了:只有「淡出尚未走完」这一种情况还留着不藏 |
| 1180 | if (!f.showDerived) { |
| 1181 | if (!tr || tr.on || k >= 1) { |
| 1182 | res.hidden = true; |
| 1183 | return res; |
| 1184 | } |
| 1185 | /* 由当前颜色渐灭到近背景色。**暗度必须编码进 RGB** |
| 1186 | (见 EDGE_DIM 处的注释:预乘混合下 alpha 压不暗边), |
| 1187 | 所以是往 EDGE_DIM 混而不是降 alpha。 |
| 1188 | |
| 1189 | **起点不能一律写死成满亮的金**:这个分支在悬停/选中的压暗逻辑 |
| 1190 | 之前就 return 了,于是一条本来被压成暗色的无关派生边, |
| 1191 | 会先跳回满亮再淡出——那一跳就是"关派生时无关的边闪一下"。 |
| 1192 | 起点得取它此刻本来的样子 */ |
| 1193 | const selNow = |
| 1194 | selectedRef.current && g.hasNode(selectedRef.current) |
| 1195 | ? selectedRef.current |
| 1196 | : null; |
| 1197 | const hovNow = hoverRef.current; |
| 1198 | const focused = selNow ?? hovNow; |
| 1199 | const ghost = attrs.blocked === true; |
| 1200 | const from = !focused |
| 1201 | ? ghost |
| 1202 | ? EDGE_GHOST |
| 1203 | : EDGE_COLOR_DERIVED |
| 1204 | : s === focused || t === focused |
| 1205 | ? ghost |
| 1206 | ? EDGE_GHOST_FOCUS |
| 1207 | : EDGE_FOCUS_DERIVED |
| 1208 | : EDGE_DIM; |
| 1209 | res.color = lerpColor(from, EDGE_DIM, k); |
| 1210 | res.label = ""; |
| 1211 | return res; |
| 1212 | } |
| 1213 | // 幽灵边不呼吸:它不是知识,是一条没走通的路 |
| 1214 | const pulse = attrs.blocked === true |
| 1215 | ? EDGE_GHOST |
| 1216 | : lerpColor( |
| 1217 | EDGE_COLOR_DERIVED_DIM, |
| 1218 | EDGE_COLOR_DERIVED, |
| 1219 | // 三角波而不是正弦:两端各停一瞬,看起来是「呼吸」不是「闪」 |
| 1220 | Math.abs( |
| 1221 | ((performance.now() % DERIVED_PULSE_MS) / DERIVED_PULSE_MS) * 2 - |
| 1222 | 1, |
| 1223 | ), |
| 1224 | ); |
| 1225 | // 打开:从近背景色亮起来,接上呼吸 |
| 1226 | res.color = |
| 1227 | tr && tr.on && k < 1 ? lerpColor(EDGE_DIM, pulse, k) : pulse; |
| 1228 | } |
| 1229 | // hover: 只提亮关联边;selected: 提亮关联边 + 压暗其余 |
| 1230 | const hov = hoverRef.current; |
| 1231 | const sel = |
| 1232 | selectedRef.current && g.hasNode(selectedRef.current) |
| 1233 | ? selectedRef.current |
| 1234 | : null; |
| 1235 | const boost = () => { |
| 1236 | res.color = |
| 1237 | attrs.blocked === true |
| 1238 | ? EDGE_GHOST_FOCUS |
| 1239 | : attrs.contested === true |
| 1240 | ? EDGE_FOCUS_CONTEST |
| 1241 | : isDerived |
| 1242 | ? EDGE_FOCUS_DERIVED |
| 1243 | : EDGE_FOCUS; |
| 1244 | res.size = Math.max((attrs.size as number) * 1.42, 1.85); |
| 1245 | res.zIndex = 5; |
| 1246 | }; |
| 1247 | /* **时间轴停在某一刻时,这条边此刻存不存在**。 |
| 1248 | 悬停的两条分支都会提前 return,绕过下面那道时间过滤—— |
| 1249 | 不带上它的话,一 hover,所有"还没长出来"的边会从近背景色 |
| 1250 | 跳到常态色的 45%,看起来是被点亮了。实测就是这么亮的 */ |
| 1251 | const liveNow = !f.activeEdges || f.activeEdges.has(edge); |
| 1252 | if (hov && (s === hov || t === hov) && liveNow) { |
| 1253 | boost(); |
| 1254 | } else if (hov && !sel) { |
| 1255 | // 悬停时其余的边也退下去,但**只退一半**——与节点那边同一个 HOVER_MUTE。 |
| 1256 | // 压到底是选中才有的待遇。此刻不存在的边**本来就该是暗的**, |
| 1257 | // 从 EDGE_DIM 起混等于原地不动 |
| 1258 | const from = liveNow ? String(res.color) : EDGE_DIM; |
| 1259 | res.color = lerpColor(from, EDGE_DIM, HOVER_MUTE); |
| 1260 | res.size = (attrs.size as number) * (1 - 0.4 * HOVER_MUTE); |
| 1261 | res.label = ""; |
| 1262 | return res; |
| 1263 | } else if (sel) { |
| 1264 | if (s === sel || t === sel) { |
| 1265 | boost(); |
| 1266 | } else { |
| 1267 | res.color = EDGE_DIM; |
| 1268 | res.size = (attrs.size as number) * 0.6; |
| 1269 | res.label = ""; |
| 1270 | return res; |
| 1271 | } |
| 1272 | } |
| 1273 | if (f.activeEdges && !f.activeEdges.has(edge)) { |
| 1274 | res.color = EDGE_DIM; |
| 1275 | res.label = ""; |
| 1276 | return res; |
| 1277 | } |
| 1278 | // 播放淡入:边从近背景色渐亮到常规色(alpha 同步插值) |
| 1279 | const fs = fadeRef.current.get(edge); |
| 1280 | if (fs !== undefined) { |
| 1281 | const t = Math.min(1, (performance.now() - fs) / FADE_MS); |
| 1282 | res.color = lerpColor(EDGE_DIM, String(res.color), t); |
| 1283 | if (t < 0.8) res.label = ""; |
| 1284 | } |
| 1285 | return res; |
| 1286 | }, |
| 1287 | }); |
| 1288 | sigma.on("clickNode", ({ node }) => setSelected(node)); |
| 1289 | // 幽灵边点一下:打开它主语的面板,停在「推出来的」那一档、展开那一行(0017 §3) |
| 1290 | sigma.on("clickEdge", ({ edge }) => { |
| 1291 | if (g.getEdgeAttribute(edge, "blocked") !== true) return; |
| 1292 | const [s] = g.extremities(edge); |
| 1293 | panelIntentRef.current = { view: "derived", open: edge }; |
| 1294 | setSelected(s); |
| 1295 | }); |
| 1296 | sigma.on("doubleClickNode", ({ node, event }) => { |
| 1297 | event.preventSigmaDefault(); |
| 1298 | setFocusEntity(node); |
| 1299 | setSelected(node); |
| 1300 | }); |
| 1301 | sigma.on("clickStage", () => deselect()); |
| 1302 | sigma.on("enterNode", ({ node }) => { |
| 1303 | hoverRef.current = node; |
| 1304 | sigma.refresh(); |
| 1305 | }); |
| 1306 | sigma.on("leaveNode", () => { |
| 1307 | hoverRef.current = null; |
| 1308 | sigma.refresh(); |
| 1309 | }); |
| 1310 | /* 悬停一条边,把并进来的说法亮出来。 |
| 1311 | 逆关系的边被并掉了(见 `layOutParallelEdges`),少画一条是对的, |
| 1312 | 但那个名字不该就此消失:`part_of` 反过来叫 `contains` 是本体里 |
| 1313 | 写着的东西,人有权看见。**只在悬停时显示**——常驻会把标签拉长一倍, |
| 1314 | 而拉长标签正是这次要治的毛病 */ |
| 1315 | sigma.on("enterEdge", ({ edge }) => { |
| 1316 | hoverEdgeRef.current = edge; |
| 1317 | sigma.refresh(); |
| 1318 | }); |
| 1319 | sigma.on("leaveEdge", () => { |
| 1320 | hoverEdgeRef.current = null; |
| 1321 | sigma.refresh(); |
| 1322 | }); |
| 1323 | // 边标签只在放大后出现(默认视距下太密,Semantica 同样克制) |
| 1324 | const updateEdgeLabels = () => |
| 1325 | sigma.setSetting("renderEdgeLabels", sigma.getCamera().ratio < 0.7); |
| 1326 | sigma.getCamera().on("updated", updateEdgeLabels); |
| 1327 | updateEdgeLabels(); |
| 1328 | |
| 1329 | // 世界坐标网格:相机变动/容器尺寸变动时重绘 |
| 1330 | const renderGrid = () => { |
| 1331 | if (gridRef.current) drawWorldGrid(gridRef.current, sigma); |
| 1332 | }; |
| 1333 | sigma.getCamera().on("updated", renderGrid); |
| 1334 | sigma.on("resize", renderGrid); |
| 1335 | renderGrid(); |
| 1336 | |
| 1337 | // 节点拖拽 + 活的力导反馈。按下只记候选:视口位移 >4px 才升格为拖拽 |
| 1338 | //(否则纯点选也会误启 FA2);被拖节点由 fa2 的 outputReducer 钉在光标上(见上), |
| 1339 | // 松手后稳定 ~1.2s 停机 |
| 1340 | let settleTimer: ReturnType<typeof setTimeout> | null = null; |
| 1341 | let dragCandidate: string | null = null; |
| 1342 | let downPoint: { x: number; y: number } | null = null; |
| 1343 | sigma.on("downNode", (e) => { |
| 1344 | dragCandidate = e.node; |
| 1345 | downPoint = { x: e.event.x, y: e.event.y }; |
| 1346 | }); |
| 1347 | sigma.getMouseCaptor().on("mousemovebody", (e) => { |
| 1348 | if (!dragCandidate) return; |
| 1349 | if (!dragged) { |
| 1350 | if (!downPoint || Math.hypot(e.x - downPoint.x, e.y - downPoint.y) < 4) |
| 1351 | return; |
| 1352 | // 升格为拖拽 |
| 1353 | dragged = dragCandidate; |
| 1354 | if (settleTimer) clearTimeout(settleTimer); |
| 1355 | // 静态布局(circular/pack)下拖拽不唤醒力模拟——否则一碰就散架 |
| 1356 | if (layoutModeRef.current === "force" && fa2 && !fa2.isRunning()) |
| 1357 | fa2.start(); |
| 1358 | // 固定当前包围盒,避免拖拽时相机自动跟随缩放 |
| 1359 | if (!sigma.getCustomBBox()) sigma.setCustomBBox(sigma.getBBox()); |
| 1360 | } |
| 1361 | const pos = sigma.viewportToGraph(e); |
| 1362 | dragPos = pos; |
| 1363 | g.setNodeAttribute(dragged, "x", pos.x); |
| 1364 | g.setNodeAttribute(dragged, "y", pos.y); |
| 1365 | // 阻止相机平移 |
| 1366 | e.preventSigmaDefault(); |
| 1367 | e.original.preventDefault(); |
| 1368 | e.original.stopPropagation(); |
| 1369 | }); |
| 1370 | const endDrag = () => { |
| 1371 | dragCandidate = null; |
| 1372 | downPoint = null; |
| 1373 | if (!dragged) return; |
| 1374 | dragged = null; |
| 1375 | dragPos = null; |
| 1376 | settleTimer = setTimeout(() => fa2?.stop(), 1200); |
| 1377 | }; |
| 1378 | sigma.getMouseCaptor().on("mouseup", endDrag); |
| 1379 | sigmaRef.current = sigma; |
| 1380 | if (import.meta.env.DEV) { |
| 1381 | // 调试句柄(仅 dev):无头环境下检查 reducer 输出 |
| 1382 | (window as unknown as Record<string, unknown>).__g = g; |
| 1383 | (window as unknown as Record<string, unknown>).__sigma = sigma; |
| 1384 | (window as unknown as Record<string, unknown>).__sel = selectedRef; |
| 1385 | } |
| 1386 | recomputeActive(timeT); |
| 1387 | return () => { |
| 1388 | if (stabilizeTimer) clearTimeout(stabilizeTimer); |
| 1389 | if (settleTimer) clearTimeout(settleTimer); |
| 1390 | fa2?.kill(); |
| 1391 | setStabilizing(false); |
| 1392 | sigma.kill(); |
| 1393 | sigmaRef.current = null; |
| 1394 | }; |
| 1395 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 1396 | }, [data.data]); |
| 1397 | |
| 1398 | if (!kb) |
| 1399 | return <div className="p-8 text-sm text-neutral-500">{S.nav.loading}</div>; |
| 1400 | |
| 1401 | const empty = data.isSuccess && data.data.nodes.length === 0; |
| 1402 | const nodeCount = data.data?.nodes.length ?? 0; |
| 1403 | const edgeCount = data.data?.edges.length ?? 0; |
| 1404 | // 库里一共有多少。**与画上去的不是一回事**——邻域视图没有总数(它本来就只 |
| 1405 | // 是一小片),所以缺省回落到画上去的那个数,不会显示成「共 0 个」 |
| 1406 | const totalNodes = data.data?.total_nodes ?? nodeCount; |
| 1407 | const totalEdges = data.data?.total_edges ?? edgeCount; |
| 1408 | const capped = totalNodes > nodeCount; |
| 1409 | |
| 1410 | return ( |
| 1411 | <div className="h-full relative"> |
| 1412 | {/* 顶部悬浮条:搜索 + 图例 + 状态 */} |
| 1413 | <div className="absolute top-3 left-3 right-3 z-10 flex items-start gap-2 pointer-events-none"> |
| 1414 | <div className="relative pointer-events-auto"> |
| 1415 | <input |
| 1416 | className="input-dark w-60 px-3 py-1.5 text-sm shadow-lg" |
| 1417 | placeholder={ |
| 1418 | inSubgraph ? S.graph.searchInSubgraph : S.graph.searchEntity |
| 1419 | } |
| 1420 | value={searchInput} |
| 1421 | onChange={(e) => { |
| 1422 | setSearchInput(e.target.value); |
| 1423 | setSearchQ(e.target.value.trim()); |
| 1424 | }} |
| 1425 | /> |
| 1426 | {searchQ && searchHits.length > 0 && ( |
| 1427 | <div className="glass-strong absolute mt-1 w-full rounded-lg shadow-xl overflow-hidden"> |
| 1428 | {searchHits.map((c) => ( |
| 1429 | <button |
| 1430 | key={c.id} |
| 1431 | onClick={() => { |
| 1432 | // 子图内命中:只选中(已在视野里);全图搜索:跳到该实体邻域 |
| 1433 | if (!inSubgraph) setFocusEntity(c.id); |
| 1434 | setSelected(c.id); |
| 1435 | setSearchInput(""); |
| 1436 | setSearchQ(""); |
| 1437 | }} |
| 1438 | className="w-full px-3 py-1.5 text-left text-sm text-neutral-200 hover:bg-white/5 flex items-center gap-2" |
| 1439 | > |
| 1440 | <span |
| 1441 | className="h-2.5 w-2.5 rounded-full shrink-0" |
| 1442 | style={{ background: c.color }} |
| 1443 | /> |
| 1444 | <span className="truncate">{c.name}</span> |
| 1445 | {c.disambiguator && ( |
| 1446 | <span className="text-xs text-neutral-500 truncate"> |
| 1447 | · {c.disambiguator} |
| 1448 | </span> |
| 1449 | )} |
| 1450 | <span className="ml-auto text-xs text-neutral-500"> |
| 1451 | {c.type_label} |
| 1452 | </span> |
| 1453 | </button> |
| 1454 | ))} |
| 1455 | {/* 还有更多没显示。**说清剩多少**——从前固定十条,想找的那个 |
| 1456 | 不在这十条里的时候,界面上一点线索都没有。子图内搜索是客户端 |
| 1457 | 过滤,没有「更多」这回事 */} |
| 1458 | {!inSubgraph && |
| 1459 | (candidates.data?.total ?? 0) > searchHits.length && ( |
| 1460 | <button |
| 1461 | onClick={() => setSearchLimit((n) => n + 20)} |
| 1462 | 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" |
| 1463 | > |
| 1464 | {S.graph.searchMore( |
| 1465 | candidates.data!.total - searchHits.length, |
| 1466 | )} |
| 1467 | </button> |
| 1468 | )} |
| 1469 | </div> |
| 1470 | )} |
| 1471 | </div> |
| 1472 | {focusEntity && ( |
| 1473 | <button |
| 1474 | onClick={() => setFocusEntity(null)} |
| 1475 | className="u-btn u-btn-ghost glass-strong pointer-events-auto px-3 py-1.5 text-sm shadow-lg" |
| 1476 | > |
| 1477 | {S.graph.backToOverview} |
| 1478 | </button> |
| 1479 | )} |
| 1480 | |
| 1481 | {/* 图例(点击切换类型显隐)。**只摆前 LEGEND_MAX 个**,其余收进 |
| 1482 | 「+N 个类」——那一排横着长,类一多就换行把画布顶下去;而且十几个 |
| 1483 | 一模一样的胶囊排开,谁重要也读不出来 */} |
| 1484 | <div className="pointer-events-auto flex flex-wrap gap-1.5 pt-0.5"> |
| 1485 | {legendShown.map(([key, t]) => ( |
| 1486 | <button |
| 1487 | key={key} |
| 1488 | onClick={() => |
| 1489 | setHiddenTypes((prev) => { |
| 1490 | const next = new Set(prev); |
| 1491 | if (next.has(key)) next.delete(key); |
| 1492 | else next.add(key); |
| 1493 | return next; |
| 1494 | }) |
| 1495 | } |
| 1496 | className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-opacity ${ |
| 1497 | hiddenTypes.has(key) ? "opacity-35" : "" |
| 1498 | }`} |
| 1499 | > |
| 1500 | <span |
| 1501 | className={`h-2 w-2 ${t.shape === "square" ? "" : "rounded-full"}`} |
| 1502 | style={{ background: t.color }} |
| 1503 | /> |
| 1504 | <span className="text-neutral-300">{t.label}</span> |
| 1505 | </button> |
| 1506 | ))} |
| 1507 | |
| 1508 | {/* chip 上的数是**全部类**,不是被收起来的那几个—— |
| 1509 | 点开看到的就是全部(搜得到任何一个),写「+3」等于承诺了另一件事 */} |
| 1510 | {/* 复位。**只要存在隐藏就给一步到位的出口**——「只看」很容易把 |
| 1511 | 画面收得很窄,没有这个就得挨个点回来 */} |
| 1512 | {hiddenTypes.size > 0 && ( |
| 1513 | <button |
| 1514 | onClick={() => setHiddenTypes(new Set())} |
| 1515 | className="glass rounded-full px-2.5 py-1 text-[11px] text-neutral-400 transition-colors hover:text-neutral-100" |
| 1516 | > |
| 1517 | {S.graph.legendShowAll(hiddenTypes.size)} |
| 1518 | </button> |
| 1519 | )} |
| 1520 | |
| 1521 | {legendRest.length > 0 && ( |
| 1522 | <div className="relative" ref={legendPop.rootRef}> |
| 1523 | <button |
| 1524 | ref={legendPop.anchorRef} |
| 1525 | onClick={() => |
| 1526 | legendPop.open ? legendPop.close() : legendPop.setOpen(true) |
| 1527 | } |
| 1528 | title={S.graph.legendAllHint} |
| 1529 | aria-expanded={legendPop.open} |
| 1530 | className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-colors ${ |
| 1531 | legendPop.open ? "text-neutral-100" : "text-neutral-400" |
| 1532 | } hover:text-neutral-100`} |
| 1533 | > |
| 1534 | {S.graph.legendMore(types.length)} |
| 1535 | {/* 收起来的类里有正被隐藏的就点一下。**不点就是无声过滤**: |
| 1536 | 在面板里关掉一个类、把面板一收,界面上再没有任何东西说它被关了 */} |
| 1537 | {hiddenInRest > 0 && ( |
| 1538 | <span className="h-1.5 w-1.5 rounded-full bg-neutral-300" /> |
| 1539 | )} |
| 1540 | </button> |
| 1541 | {legendPop.open && ( |
| 1542 | <div |
| 1543 | ref={legendPop.panelRef} |
| 1544 | className="u-menu-glass absolute left-0 top-0 z-50 w-64 overflow-hidden rounded-xl p-2 shadow-2xl" |
| 1545 | > |
| 1546 | {/* 面板盖在 chip 原位,所以**第一行就长成那个 chip 的样子**, |
| 1547 | 点它收回去——「哪儿展开的就从哪儿收回去」, |
| 1548 | 与通知/用户卡片的关闭键跟触发键原位重合是同一个道理 */} |
| 1549 | <button |
| 1550 | onClick={() => legendPop.close()} |
| 1551 | className="mb-1.5 flex w-full items-center gap-1.5 rounded-full px-1.5 py-0.5 text-[11px] text-neutral-300 transition-colors hover:text-neutral-100" |
| 1552 | > |
| 1553 | {S.graph.legendMore(types.length)} |
| 1554 | <X size={11} className="ml-auto text-neutral-500" /> |
| 1555 | </button> |
| 1556 | <input |
| 1557 | autoFocus |
| 1558 | value={legendQ} |
| 1559 | onChange={(e) => setLegendQ(e.target.value)} |
| 1560 | placeholder={S.graph.legendSearch} |
| 1561 | className="input-dark mb-1.5 w-full px-2 py-1 text-[12px]" |
| 1562 | /> |
| 1563 | {/* **列的是全部类,不只是收起来的那些**:想找一个类的时候, |
| 1564 | 没人记得它是不是恰好排进了前几个 */} |
| 1565 | <div className="flex max-h-64 flex-col overflow-y-auto"> |
| 1566 | {types |
| 1567 | .filter(([, t]) => |
| 1568 | t.label.toLowerCase().includes(legendQ.toLowerCase()), |
| 1569 | ) |
| 1570 | .map(([key, t]) => ( |
| 1571 | /* **一行两个按钮,不是一个按钮循环三态。** |
| 1572 | 单键循环的代价是:不看当前状态就不知道下一次点击 |
| 1573 | 会发生什么,而且从「只看」回到正常必须路过「排除」 |
| 1574 | ——想清空却得先让画面变成另一个错的样子。 |
| 1575 | 拆开之后每个手势含义固定 */ |
| 1576 | <div |
| 1577 | key={key} |
| 1578 | className="group flex items-center gap-2 rounded px-1.5 py-1 hover:bg-white/5" |
| 1579 | > |
| 1580 | <button |
| 1581 | onClick={() => |
| 1582 | setHiddenTypes((prev) => { |
| 1583 | const next = new Set(prev); |
| 1584 | if (next.has(key)) next.delete(key); |
| 1585 | else next.add(key); |
| 1586 | return next; |
| 1587 | }) |
| 1588 | } |
| 1589 | className="flex min-w-0 flex-1 items-center gap-2 text-left" |
| 1590 | > |
| 1591 | <span |
| 1592 | className={`h-2 w-2 shrink-0 ${t.shape === "square" ? "" : "rounded-full"}`} |
| 1593 | style={{ |
| 1594 | background: t.color, |
| 1595 | opacity: hiddenTypes.has(key) ? 0.35 : 1, |
| 1596 | }} |
| 1597 | /> |
| 1598 | <span |
| 1599 | className={`truncate text-[12px] ${ |
| 1600 | hiddenTypes.has(key) |
| 1601 | ? "text-neutral-500 line-through" |
| 1602 | : "text-neutral-200" |
| 1603 | }`} |
| 1604 | > |
| 1605 | {t.label} |
| 1606 | </span> |
| 1607 | </button> |
| 1608 | {/* 「只看这个」:类一多时最想要的动作。**给显式按钮而不是 |
| 1609 | 修饰键**——alt+点击没人猜得到,这里横向有地方 */} |
| 1610 | <button |
| 1611 | onClick={() => |
| 1612 | setHiddenTypes( |
| 1613 | new Set( |
| 1614 | types.map(([k]) => k).filter((k) => k !== key), |
| 1615 | ), |
| 1616 | ) |
| 1617 | } |
| 1618 | className="shrink-0 rounded px-1 text-[10px] text-neutral-500 opacity-0 transition-opacity hover:text-white focus:opacity-100 group-hover:opacity-100" |
| 1619 | > |
| 1620 | {S.graph.legendOnly} |
| 1621 | </button> |
| 1622 | <span className="u-num shrink-0 text-[11px] text-neutral-500"> |
| 1623 | {t.count} |
| 1624 | </span> |
| 1625 | </div> |
| 1626 | ))} |
| 1627 | {types.every( |
| 1628 | ([, t]) => |
| 1629 | !t.label.toLowerCase().includes(legendQ.toLowerCase()), |
| 1630 | ) && ( |
| 1631 | <div className="px-1.5 py-2 text-[12px] text-neutral-500"> |
| 1632 | {S.graph.legendNone} |
| 1633 | </div> |
| 1634 | )} |
| 1635 | </div> |
| 1636 | </div> |
| 1637 | )} |
| 1638 | </div> |
| 1639 | )} |
| 1640 | </div> |
| 1641 | |
| 1642 | {/* 右上:能调「画多少个」+ 统计。**统计说的正是这个数** |
| 1643 | (「画了 150 个,共 548 个」),把调节放在它旁边,改的是谁一目了然。 |
| 1644 | 外壳保持中性——这一片是 chrome,彩色只属于数据 */} |
| 1645 | <div className="ml-auto flex flex-col items-end gap-1"> |
| 1646 | <div className="flex items-start gap-2"> |
| 1647 | <div className="pointer-events-auto flex items-center overflow-hidden rounded-md border border-white/10"> |
| 1648 | <button |
| 1649 | title={S.graph.nodeBudgetLess} |
| 1650 | disabled={nodeBudget <= NODE_BUDGETS[0]} |
| 1651 | onClick={() => |
| 1652 | setNodeBudget( |
| 1653 | (b) => NODE_BUDGETS[Math.max(0, NODE_BUDGETS.indexOf(b) - 1)], |
| 1654 | ) |
| 1655 | } |
| 1656 | className="px-1.5 py-[3px] text-[11px] leading-none text-neutral-400 transition-colors hover:bg-white/[0.06] hover:text-white disabled:opacity-25 disabled:hover:bg-transparent disabled:hover:text-neutral-400" |
| 1657 | > |
| 1658 | − |
| 1659 | </button> |
| 1660 | {/* **画满了就别再给「多画」**:库里一共就这么多,再调高什么也不会变, |
| 1661 | 而一个点了没反应的按钮比没有这个按钮更糟 */} |
| 1662 | <button |
| 1663 | title={S.graph.nodeBudgetMore} |
| 1664 | disabled={ |
| 1665 | !capped || nodeBudget >= NODE_BUDGETS[NODE_BUDGETS.length - 1] |
| 1666 | } |
| 1667 | onClick={() => |
| 1668 | setNodeBudget( |
| 1669 | (b) => |
| 1670 | NODE_BUDGETS[ |
| 1671 | Math.min(NODE_BUDGETS.length - 1, NODE_BUDGETS.indexOf(b) + 1) |
| 1672 | ], |
| 1673 | ) |
| 1674 | } |
| 1675 | className="px-1.5 py-[3px] text-[11px] leading-none text-neutral-400 transition-colors hover:bg-white/[0.06] hover:text-white disabled:opacity-25 disabled:hover:bg-transparent disabled:hover:text-neutral-400" |
| 1676 | > |
| 1677 | + |
| 1678 | </button> |
| 1679 | </div> |
| 1680 | <div className="pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500"> |
| 1681 | {/* 画满上限时说清「画了多少 / 共多少」。**这个数从前是上限冒充规模**—— |
| 1682 | 一个上万实体的库右上角永远写着 150 */} |
| 1683 | {capped ? ( |
| 1684 | <span title={S.graph.cappedHint(nodeCount, totalNodes)}> |
| 1685 | {/* **事实也用「已画 / 共」的口径**:从前这里给的是库里的总数, |
| 1686 | 而实体给的是「画了多少 / 共多少」——同一句话里两套口径, |
| 1687 | 于是调档位时实体数在变、事实数纹丝不动,看着像坏了。 |
| 1688 | 没有时间筛选时 active 恒等于已画条数,那就不说 */} |
| 1689 | {S.graph.statsCapped( |
| 1690 | nodeCount, |
| 1691 | totalNodes, |
| 1692 | edgeCount, |
| 1693 | totalEdges, |
| 1694 | timeT === null ? null : activeCount, |
| 1695 | )} |
| 1696 | </span> |
| 1697 | ) : ( |
| 1698 | S.graph.stats( |
| 1699 | nodeCount, |
| 1700 | edgeCount, |
| 1701 | timeT === null ? null : activeCount, |
| 1702 | ) |
| 1703 | )} |
| 1704 | </div> |
| 1705 | </div> |
| 1706 | {/* **单独一行,不做统计文字的前缀。** |
| 1707 | 当前缀时它一出现就把整块撑宽,而这一块是靠右的—— |
| 1708 | 于是每次重新布局,左边的档位按钮都会被挤着跳一下。 |
| 1709 | 自己占一行,第一行的宽度就不再随它变 */} |
| 1710 | {stabilizing && ( |
| 1711 | <div className="flex items-center gap-1.5 text-[11px] text-neutral-400"> |
| 1712 | <Loader2 size={11} className="animate-spin" /> |
| 1713 | {S.graph.stabilizing} |
| 1714 | </div> |
| 1715 | )} |
| 1716 | </div> |
| 1717 | </div> |
| 1718 | |
| 1719 | {/* 画布:世界坐标网格层(随相机动)垫在 sigma WebGL 层下(全出血,时间岛悬浮其上) */} |
| 1720 | <div className="absolute inset-0"> |
| 1721 | <canvas ref={gridRef} className="absolute inset-0 h-full w-full" /> |
| 1722 | <div ref={containerRef} className="absolute inset-0" /> |
| 1723 | </div> |
| 1724 | |
| 1725 | {/* 左下控件塔:推出来的边 + 布局切换 + 相机(右下归实体侧栏,底部中央归时间岛) */} |
| 1726 | {/* **items-start**:列内项目默认 stretch,一组展开就会把其余几组 |
| 1727 | 一起拉到同宽——那几组的字还收着,于是看着是几个莫名其妙的空白长条。 |
| 1728 | 各自按内容收放,才是「一组一组展开,不牵连别人」 */} |
| 1729 | <div className="absolute bottom-4 left-3 z-10 flex flex-col items-start gap-2"> |
| 1730 | {/* 推出来的边:**自成一组,也不进类型图例。** |
| 1731 | 图例回答「显示哪些类」,一排全是本体里的类;这个回答的是 |
| 1732 | 「显不显示推出来的边」——不是同一个问题。为零时整组不出现。 |
| 1733 | |
| 1734 | **摆到这座塔上,是绕开一对矛盾走的**:放在顶栏图例旁边,它长得 |
| 1735 | 像第 10 个类;想靠颜色把它区分开,又撞上这文件开头那条既定原则 |
| 1736 | ——「chrome 零色偏、彩色只属于数据」(见调色板那段注释)。 |
| 1737 | 往框架里塞一块高饱和金底,是整个界面唯一的彩色色块,扎眼且不成体系。 |
| 1738 | |
| 1739 | 这座塔本来就是「视图怎么看」的地盘(布局、缩放), |
| 1740 | 「显不显示推出来的边」正是同一族问题。外壳保持中性, |
| 1741 | 金色只出现在图标本身——与色点用在类胶囊上是同一个做法。 */} |
| 1742 | {derivedCount > 0 && ( |
| 1743 | /* **两层**:外层只负责定位,内层才有 overflow-hidden。 |
| 1744 | 那个类是给按钮堆裁圆角的,可面板是同一个盒子的子元素—— |
| 1745 | 合成一层的话面板会被一起裁掉,实测只剩塔本身那 32px 宽 */ |
| 1746 | <div className="relative" ref={derivedPop.rootRef}> |
| 1747 | <div className="u-tower group glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden"> |
| 1748 | <button |
| 1749 | onClick={() => setShowDerived((v) => !v)} |
| 1750 | role="switch" |
| 1751 | aria-checked={showDerived} |
| 1752 | title={`${S.graph.derivedEdges(derivedCount)} · ${S.graph.derivedHint}`} |
| 1753 | className={`flex items-center p-2 transition-colors ${ |
| 1754 | showDerived |
| 1755 | ? "bg-white/[0.1]" |
| 1756 | : "text-neutral-500 hover:bg-white/[0.06]" |
| 1757 | }`} |
| 1758 | style={ |
| 1759 | showDerived ? { color: "rgba(231,197,124,0.95)" } : undefined |
| 1760 | } |
| 1761 | > |
| 1762 | <Waypoints size={15} /> |
| 1763 | <span className="u-tower-label">{S.graph.viewDerived}</span> |
| 1764 | </button> |
| 1765 | <div className="h-px bg-white/10 mx-1.5" /> |
| 1766 | {/* 展开成一个小窗:这批边是什么时候推的、现在还推不推、手动再跑一次。 |
| 1767 | **与开关分成两个按钮**——「藏起来」是每天要点的,「什么时候推的」 |
| 1768 | 是偶尔才问的,合成一个会让常用动作多一步 */} |
| 1769 | <button |
| 1770 | ref={derivedPop.anchorRef} |
| 1771 | onClick={() => |
| 1772 | derivedPop.open ? derivedPop.close() : derivedPop.setOpen(true) |
| 1773 | } |
| 1774 | title={S.graph.derivedPanel} |
| 1775 | aria-expanded={derivedPop.open} |
| 1776 | className={`flex items-center p-2 text-[11px] leading-none transition-colors ${ |
| 1777 | derivedPop.open |
| 1778 | ? "text-white bg-white/[0.1]" |
| 1779 | : "text-neutral-400 hover:text-white hover:bg-white/[0.06]" |
| 1780 | }`} |
| 1781 | > |
| 1782 | <span className="grid h-[15px] w-[15px] shrink-0 place-items-center leading-none"> |
| 1783 | ⋯ |
| 1784 | </span> |
| 1785 | <span className="u-tower-label">{S.graph.derivedPanel}</span> |
| 1786 | </button> |
| 1787 | </div> |
| 1788 | {derivedPop.open && kb && ( |
| 1789 | <DerivedPanel |
| 1790 | panelRef={derivedPop.panelRef} |
| 1791 | kbId={kb.id} |
| 1792 | count={derivedCount} |
| 1793 | onClose={() => derivedPop.close()} |
| 1794 | /> |
| 1795 | )} |
| 1796 | </div> |
| 1797 | )} |
| 1798 | <div className="u-tower group glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden"> |
| 1799 | {( |
| 1800 | [ |
| 1801 | { key: "force", Icon: Orbit, label: S.graph.layoutForce }, |
| 1802 | { |
| 1803 | key: "circular", |
| 1804 | Icon: CircleDashed, |
| 1805 | label: S.graph.layoutCircular, |
| 1806 | }, |
| 1807 | { key: "pack", Icon: Grape, label: S.graph.layoutPack }, |
| 1808 | ] as const |
| 1809 | ).map(({ key, Icon, label }) => ( |
| 1810 | <button |
| 1811 | key={key} |
| 1812 | title={label} |
| 1813 | onClick={() => { |
| 1814 | setLayoutMode(key); |
| 1815 | layoutModeRef.current = key; |
| 1816 | layoutCtlRef.current?.apply(key); |
| 1817 | }} |
| 1818 | className={`flex items-center p-2 transition-colors ${ |
| 1819 | layoutMode === key |
| 1820 | ? "text-white bg-white/[0.1]" |
| 1821 | : "text-neutral-400 hover:text-white hover:bg-white/[0.06]" |
| 1822 | }`} |
| 1823 | > |
| 1824 | <Icon size={15} /> |
| 1825 | <span className="u-tower-label">{label}</span> |
| 1826 | </button> |
| 1827 | ))} |
| 1828 | </div> |
| 1829 | <div className="u-tower group glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden"> |
| 1830 | <button |
| 1831 | title={S.graph.zoomIn} |
| 1832 | onClick={() => |
| 1833 | sigmaRef.current?.getCamera().animatedZoom({ duration: 220 }) |
| 1834 | } |
| 1835 | className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors" |
| 1836 | > |
| 1837 | <ZoomIn size={15} /> |
| 1838 | <span className="u-tower-label">{S.graph.zoomIn}</span> |
| 1839 | </button> |
| 1840 | <button |
| 1841 | title={S.graph.zoomOut} |
| 1842 | onClick={() => |
| 1843 | sigmaRef.current?.getCamera().animatedUnzoom({ duration: 220 }) |
| 1844 | } |
| 1845 | className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors" |
| 1846 | > |
| 1847 | <ZoomOut size={15} /> |
| 1848 | <span className="u-tower-label">{S.graph.zoomOut}</span> |
| 1849 | </button> |
| 1850 | <div className="h-px bg-white/10 mx-1.5" /> |
| 1851 | <button |
| 1852 | title={S.graph.fitView} |
| 1853 | onClick={() => |
| 1854 | sigmaRef.current?.getCamera().animatedReset({ duration: 300 }) |
| 1855 | } |
| 1856 | className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors" |
| 1857 | > |
| 1858 | <Maximize2 size={15} /> |
| 1859 | <span className="u-tower-label">{S.graph.fitView}</span> |
| 1860 | </button> |
| 1861 | </div> |
| 1862 | </div> |
| 1863 | |
| 1864 | {empty && ( |
| 1865 | <div className="absolute inset-0 grid place-items-center pointer-events-none"> |
| 1866 | {/* 不放标题方块:页面本身就是图谱页,tab 条上也写着, |
| 1867 | 第三遍写"图谱"两个字不带任何信息。空状态该说的是下一步做什么 */} |
| 1868 | <div className="text-center text-sm text-neutral-500 max-w-xs"> |
| 1869 | {S.graph.emptyBody} |
| 1870 | </div> |
| 1871 | </div> |
| 1872 | )} |
| 1873 | |
| 1874 | {/* 底部居中悬浮时间岛 */} |
| 1875 | {edgeCount > 0 && ( |
| 1876 | <TimeScrubber |
| 1877 | edges={data.data!.edges} |
| 1878 | value={timeT} |
| 1879 | onChange={setTimeT} |
| 1880 | playing={playing} |
| 1881 | onPlayingChange={setPlaying} |
| 1882 | /> |
| 1883 | )} |
| 1884 | |
| 1885 | {/* 实体侧栏。**取消选中之后还要多留 170ms**:那段时间它在演退场 */} |
| 1886 | {(selected || exiting) && kb && ( |
| 1887 | <EntityPanel |
| 1888 | kbId={kb.id} |
| 1889 | entityId={(selected ?? exiting)!} |
| 1890 | exiting={!selected} |
| 1891 | intent={panelIntentRef} |
| 1892 | onClose={deselect} |
| 1893 | onNavigate={(id) => { |
| 1894 | // 跳转目标可能不在当前画布:同时把图 refocus 到它的邻域(与搜索选择一致) |
| 1895 | setFocusEntity(id); |
| 1896 | setSelected(id); |
| 1897 | }} |
| 1898 | /> |
| 1899 | )} |
| 1900 | </div> |
| 1901 | ); |
| 1902 | } |
| 1903 | |
| 1904 | /* ============ 时间轴(底部居中悬浮岛:播放 + 密度带 + 拖动) ============ */ |
| 1905 | |
| 1906 | /** 轨道 clientX → 对齐天步进的时间值(数据精度即 day,拖动求精细;播放仍按月推进求节奏)。 */ |
| 1907 | function scrubValueAt( |
| 1908 | clientX: number, |
| 1909 | track: HTMLDivElement | null, |
| 1910 | minTs: number, |
| 1911 | maxTs: number, |
| 1912 | ): number { |
| 1913 | if (!track) return maxTs; |
| 1914 | const rect = track.getBoundingClientRect(); |
| 1915 | // 布局未成形(宽度 0)时避免除零产出 NaN |
| 1916 | if (rect.width < 1) return maxTs; |
| 1917 | const frac = Math.min(1, Math.max(0, (clientX - rect.left) / rect.width)); |
| 1918 | const raw = minTs + frac * (maxTs - minTs); |
| 1919 | return Math.min(maxTs, minTs + Math.round((raw - minTs) / DAY_MS) * DAY_MS); |
| 1920 | } |
| 1921 | |
| 1922 | /** 播放/柱子的步长。**这两件事本来就该是同一个单位**——从前柱子按年、 |
| 1923 | * 播放按天,界面上没有任何地方说得出「一格是多久」。 */ |
| 1924 | type ScrubUnit = "year" | "month" | "day"; |
| 1925 | |
| 1926 | /** 一根柱子最多画多少根。超过就把相邻的桶并起来画——**只影响画,不影响 |
| 1927 | * 播放步长**:日单位下 15 年有五千多个桶,一根一像素也画不下, |
| 1928 | * 但播放仍然是一天一步。并了几个会在提示里说出来,不闷着 */ |
| 1929 | const SCRUB_MAX_BARS = 220; |
| 1930 | /** 整条轨走完的目标时长。**与单位无关**——单位换的是颗粒度与密度, |
| 1931 | * 不该顺带把「等多久」也换掉:日单位若按「一天一拍」走,15 年要放二十分钟 */ |
| 1932 | const SCRUB_PLAY_MS = 18000; |
| 1933 | |
| 1934 | function bucketStart(ts: number, unit: ScrubUnit): number { |
| 1935 | const d = new Date(ts); |
| 1936 | if (unit === "year") return Date.UTC(d.getUTCFullYear(), 0, 1); |
| 1937 | if (unit === "month") |
| 1938 | return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1); |
| 1939 | return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); |
| 1940 | } |
| 1941 | function bucketNext(ts: number, unit: ScrubUnit): number { |
| 1942 | const d = new Date(ts); |
| 1943 | if (unit === "year") return Date.UTC(d.getUTCFullYear() + 1, 0, 1); |
| 1944 | if (unit === "month") |
| 1945 | return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1); |
| 1946 | return ts + DAY_MS; |
| 1947 | } |
| 1948 | |
| 1949 | function TimeScrubber({ |
| 1950 | edges, |
| 1951 | value, |
| 1952 | onChange, |
| 1953 | playing, |
| 1954 | onPlayingChange, |
| 1955 | }: { |
| 1956 | edges: GraphEdge[]; |
| 1957 | value: number | null; |
| 1958 | onChange: (v: number | null) => void; |
| 1959 | /* 播放态由 Graph 持有:渲染层要区分播放推进与手动拖动 */ |
| 1960 | playing: boolean; |
| 1961 | onPlayingChange: (v: boolean) => void; |
| 1962 | }) { |
| 1963 | const setPlaying = onPlayingChange; |
| 1964 | /* 默认年:**大多数库跨度都以年计**,一进来先给能一眼看全的那一档 */ |
| 1965 | const [unit, setUnit] = useState<ScrubUnit>("year"); |
| 1966 | /* 走完整条的次数。**拿它当 key**——同一个元素上重复触发同一个动画不会重播, |
| 1967 | 换 key 让它重新挂载才会 */ |
| 1968 | const [sweep, setSweep] = useState(0); |
| 1969 | /* 指针在轨道上时,已走过的那段提亮。**它回答的是"我走到哪了"**—— |
| 1970 | 不播的时候整条都是同一档灰,看不出进度停在哪;而这正是人把指针 |
| 1971 | 移上来想知道的事 */ |
| 1972 | const [trackHover, setTrackHover] = useState(false); |
| 1973 | const trackRef = useRef<HTMLDivElement>(null); |
| 1974 | const draggingRef = useRef(false); |
| 1975 | /* 拖动落点。**播放循环有自己的浮点累加器**,不读 value——否则每帧的取整 |
| 1976 | 误差会积起来。所以光改 value 是没用的,下一帧就被原样覆盖回去。 |
| 1977 | 拖动把落点放进这里,循环下一帧接手,从新位置继续走 */ |
| 1978 | const seekRef = useRef<number | null>(null); |
| 1979 | const seek = (v: number) => { |
| 1980 | seekRef.current = v; |
| 1981 | onChange(v); |
| 1982 | }; |
| 1983 | |
| 1984 | const { minTs, maxTs, bars, merged, trackW } = useMemo(() => { |
| 1985 | const now = Date.now(); |
| 1986 | const froms = edges |
| 1987 | .map((e) => (e.valid_from ? Date.parse(e.valid_from) : NaN)) |
| 1988 | .filter((t) => !Number.isNaN(t)); |
| 1989 | const min = froms.length |
| 1990 | ? Math.min(...froms) |
| 1991 | : now - 5 * 365 * 24 * 3600 * 1000; |
| 1992 | // 起点对齐到单位边界:否则第一根柱子是半格,读起来像数据缺了一块 |
| 1993 | const start = bucketStart(min, unit); |
| 1994 | |
| 1995 | const counts = new Map<number, number>(); |
| 1996 | for (const t of froms) { |
| 1997 | const k = bucketStart(t, unit); |
| 1998 | counts.set(k, (counts.get(k) ?? 0) + 1); |
| 1999 | } |
| 2000 | const raw: { ts: number; n: number }[] = []; |
| 2001 | for (let t = start; t <= now; t = bucketNext(t, unit)) |
| 2002 | raw.push({ ts: t, n: counts.get(t) ?? 0 }); |
| 2003 | |
| 2004 | // 画不下就并桶。**并的是画,不是步长** |
| 2005 | const group = Math.max(1, Math.ceil(raw.length / SCRUB_MAX_BARS)); |
| 2006 | const cells: { ts: number; n: number }[] = []; |
| 2007 | for (let i = 0; i < raw.length; i += group) { |
| 2008 | const slice = raw.slice(i, i + group); |
| 2009 | cells.push({ |
| 2010 | ts: slice[0].ts, |
| 2011 | n: slice.reduce((a, b) => a + b.n, 0), |
| 2012 | }); |
| 2013 | } |
| 2014 | const peak = Math.max(1, ...cells.map((c) => c.n)); |
| 2015 | |
| 2016 | // 单位越大 → 桶越少 → 岛越短;越小 → 越长。**但下限要抬得够高**: |
| 2017 | // 岛里那排固定控件(播放键 + 单位选择器 + 两个年份 + 日期 + All time/Now) |
| 2018 | // 本身就要四百多像素,岛只有 320 时 flex-1 的轨道被压成 0—— |
| 2019 | // 实测柱子一根都看不见,整条是空的。 |
| 2020 | // |
| 2021 | // 抬高之后单位主要改变的是**每根柱子的粗细**:同一条轨道, |
| 2022 | // 年是十几根粗块,日是两百多根细线。这比整条伸缩更说明问题 |
| 2023 | const w = Math.min(780, Math.max(660, 380 + cells.length * 2)); |
| 2024 | |
| 2025 | return { |
| 2026 | minTs: start, |
| 2027 | maxTs: now, |
| 2028 | bars: cells.map((c) => ({ ts: c.ts, h: c.n / peak, n: c.n })), |
| 2029 | merged: group, |
| 2030 | trackW: w, |
| 2031 | }; |
| 2032 | }, [edges, unit]); |
| 2033 | |
| 2034 | // 播放按日推进(数据即 day 精度),日子快速翻过;整体节奏仍 ≈ 一个月/260ms。 |
| 2035 | // rAF 时间驱动:帧率无关,内部浮点累加避免取整漂移,值只在跨天时才下发 |
| 2036 | useEffect(() => { |
| 2037 | if (!playing) return; |
| 2038 | // 整条走完约 SCRUB_PLAY_MS,与单位无关;单位只决定落点取整到哪一格 |
| 2039 | const SPEED = (maxTs - minTs) / SCRUB_PLAY_MS; |
| 2040 | let raf = 0; |
| 2041 | let last = performance.now(); |
| 2042 | let acc = value ?? minTs; |
| 2043 | let lastPushed = 0; |
| 2044 | const step = (now: number) => { |
| 2045 | // 有人拖过了:从落点接着走,而不是沿原来的轨迹 |
| 2046 | if (seekRef.current !== null) { |
| 2047 | acc = seekRef.current; |
| 2048 | seekRef.current = null; |
| 2049 | } |
| 2050 | acc += (now - last) * SPEED; |
| 2051 | last = now; |
| 2052 | if (acc >= maxTs) { |
| 2053 | setPlaying(false); |
| 2054 | onChange(null); |
| 2055 | // 走到头了扫一道光。**这是个收尾**——播放停下、时间跳回全时段, |
| 2056 | // 没有交代的话看着像中途断了;一道光扫过说明"这条走完了" |
| 2057 | setSweep((n) => n + 1); |
| 2058 | return; |
| 2059 | } |
| 2060 | // **连续推进,不按桶跳。** 从前按 `bucketStart` 取整下发,年单位下 |
| 2061 | // 一次就是一年——播放头一格一格蹦,看着像卡顿而不是在走。 |
| 2062 | // 单位现在只管**显示**(标签精度、柱子跨度),不再管推进的步长。 |
| 2063 | // |
| 2064 | // 代价是下发变密(每帧一次),而每次下发都要重算全图的现行边, |
| 2065 | // 所以限到 ~30fps:肉眼看不出与 60fps 的差别,重算量减半 |
| 2066 | if (now - lastPushed >= 33) { |
| 2067 | lastPushed = now; |
| 2068 | onChange(Math.round(acc)); |
| 2069 | } |
| 2070 | raf = requestAnimationFrame(step); |
| 2071 | }; |
| 2072 | raf = requestAnimationFrame(step); |
| 2073 | return () => cancelAnimationFrame(raf); |
| 2074 | // 只随播放开关重启:acc 在循环内自持,value 帧帧变不应重建循环 |
| 2075 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 2076 | }, [playing, minTs, maxTs, unit]); |
| 2077 | |
| 2078 | // 展示到日:与数据的 day 级 valid_precision 对齐 |
| 2079 | const label = (() => { |
| 2080 | if (value === null) return S.graph.allTime; |
| 2081 | const d = new Date(value); |
| 2082 | const mm = String(d.getUTCMonth() + 1).padStart(2, "0"); |
| 2083 | const dd = String(d.getUTCDate()).padStart(2, "0"); |
| 2084 | // 精度跟着单位:年单位下写出「2019-01-01」是假精确 |
| 2085 | if (unit === "year") return `${d.getUTCFullYear()}`; |
| 2086 | if (unit === "month") return `${d.getUTCFullYear()}-${mm}`; |
| 2087 | return `${d.getUTCFullYear()}-${mm}-${dd}`; |
| 2088 | })(); |
| 2089 | |
| 2090 | const minYear = bars.length |
| 2091 | ? new Date(bars[0].ts).getUTCFullYear() |
| 2092 | : undefined; |
| 2093 | const maxYear = bars.length |
| 2094 | ? new Date(bars[bars.length - 1].ts).getUTCFullYear() |
| 2095 | : undefined; |
| 2096 | |
| 2097 | return ( |
| 2098 | /* 宽度随单位变:单位大 → 桶少 → 短;单位小 → 桶多 → 长而密。 |
| 2099 | 仍夹在视口内(calc 那一项),窄屏不会顶出去。 |
| 2100 | 实测宽度:年 320 / 月 648 / 日 760。 */ |
| 2101 | <div |
| 2102 | className={`glass-strong absolute bottom-4 left-1/2 -translate-x-1/2 z-10 rounded-2xl px-3 py-2 flex items-center gap-2.5 shadow-[0_12px_40px_rgba(0,0,0,0.5)] u-scrub-island${playing ? " u-solid" : ""}`} |
| 2103 | style={{ width: `min(${trackW}px, calc(100vw - 4rem))` }} |
| 2104 | > |
| 2105 | <button |
| 2106 | onClick={() => { |
| 2107 | // 已经在末端(`Now`)时按播放要从头来。**否则第一下等于没反应**: |
| 2108 | // acc 起点就是终点,循环第一帧就判定播完,只把位置清成 All time |
| 2109 | if ( |
| 2110 | !playing && |
| 2111 | (value === null || value >= maxTs - (maxTs - minTs) * 0.02) |
| 2112 | ) |
| 2113 | onChange(minTs); |
| 2114 | setPlaying(!playing); |
| 2115 | }} |
| 2116 | title={playing ? S.graph.pause : S.graph.play} |
| 2117 | className="u-btn u-btn-ghost h-8 w-8 shrink-0 grid place-items-center rounded-lg" |
| 2118 | > |
| 2119 | {playing ? <Pause size={13} /> : <Play size={13} />} |
| 2120 | </button> |
| 2121 | |
| 2122 | {/* 步长。**播放与柱子共用它**——从前柱子按年、播放按天, |
| 2123 | 界面上没有一处说得出「一格是多久」 */} |
| 2124 | <div |
| 2125 | title={S.graph.scrubUnitHint} |
| 2126 | /* **与播放键同高同圆角**:那个键是 h-8 / rounded-lg, |
| 2127 | 而这里从前是 py-[3px] 撑出来的 20px 高、rounded-md—— |
| 2128 | 并排放着两个尺寸和圆角都不一样的东西,看着不像一套 */ |
| 2129 | className="flex h-8 shrink-0 items-center overflow-hidden rounded-lg border border-white/10" |
| 2130 | > |
| 2131 | {(["year", "month", "day"] as const).map((u) => ( |
| 2132 | <button |
| 2133 | key={u} |
| 2134 | onClick={() => setUnit(u)} |
| 2135 | className={`grid h-full place-items-center px-2 text-[10px] leading-none transition-colors ${ |
| 2136 | unit === u |
| 2137 | ? "bg-white/[0.08] text-neutral-100" |
| 2138 | : "text-neutral-500 hover:bg-white/[0.04] hover:text-neutral-300" |
| 2139 | }`} |
| 2140 | > |
| 2141 | {u === "year" |
| 2142 | ? S.graph.scrubUnitYear |
| 2143 | : u === "month" |
| 2144 | ? S.graph.scrubUnitMonth |
| 2145 | : S.graph.scrubUnitDay} |
| 2146 | </button> |
| 2147 | ))} |
| 2148 | </div> |
| 2149 | |
| 2150 | <span className="shrink-0 u-num text-[10px] text-neutral-600"> |
| 2151 | {minYear} |
| 2152 | </span> |
| 2153 | |
| 2154 | {/* 密度带轨道:内嵌浅色井 + 每年事实量柱 */} |
| 2155 | <div |
| 2156 | ref={trackRef} |
| 2157 | onMouseEnter={() => setTrackHover(true)} |
| 2158 | onMouseLeave={() => setTrackHover(false)} |
| 2159 | className="relative h-9 min-w-[150px] flex-1 overflow-hidden rounded-lg bg-white/[0.04]" |
| 2160 | > |
| 2161 | {/* 演完由 **React** 卸载,**别自己 `remove()`**。 |
| 2162 | 从前是 `onAnimationEnd={(e) => e.currentTarget.remove()}`—— |
| 2163 | 把 React 管着的节点从 DOM 里抠走,它自己并不知道。下一次扫光时 |
| 2164 | key 变了,React 去移除"旧节点",而那个节点已经不在父节点里, |
| 2165 | removeChild 抛 NotFoundError,未捕获的错误让整棵树卸载重挂: |
| 2166 | 现象就是**连播两轮之后界面像刷新了一次** */} |
| 2167 | {sweep > 0 && ( |
| 2168 | <span |
| 2169 | key={sweep} |
| 2170 | className="u-sweep" |
| 2171 | onAnimationEnd={() => setSweep(0)} |
| 2172 | /> |
| 2173 | )} |
| 2174 | {/* **间隙必须随密度收**:写死 2px 时,日单位下 216 根柱子有 215 个间隙 |
| 2175 | ≈ 430px,而轨道内宽才 ~455px——柱子被挤成 0.1px,整条看起来是空的。 |
| 2176 | 实测就是这么丢的。柱子稀疏时留 2px 好数,密了就贴在一起当密度带看 */} |
| 2177 | <div |
| 2178 | className="absolute inset-x-1.5 top-1.5 bottom-1.5 flex items-end" |
| 2179 | style={{ gap: bars.length > 120 ? 0 : bars.length > 40 ? 1 : 2 }} |
| 2180 | > |
| 2181 | {bars.map((b) => { |
| 2182 | // 进入即亮(桶起点为判据):播放头脚下的柱子即已覆盖——进度条通用语义 |
| 2183 | const past = value !== null && b.ts <= value; |
| 2184 | const d = new Date(b.ts); |
| 2185 | const stamp = |
| 2186 | unit === "year" |
| 2187 | ? `${d.getUTCFullYear()}` |
| 2188 | : unit === "month" |
| 2189 | ? `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}` |
| 2190 | : d.toISOString().slice(0, 10); |
| 2191 | return ( |
| 2192 | <div |
| 2193 | key={b.ts} |
| 2194 | className="flex-1 flex items-end h-full" |
| 2195 | title={`${stamp} · ${b.n}${merged > 1 ? ` · ${S.graph.scrubBarMerged(merged)}` : ""}`} |
| 2196 | > |
| 2197 | <div |
| 2198 | className="w-full rounded-[1px] transition-colors" |
| 2199 | style={{ |
| 2200 | height: `${Math.max(10, b.h * 100)}%`, |
| 2201 | // 播放中已扫过的提亮,停止后回到常规亮度。 |
| 2202 | // **还没走到的压到近乎不可见**:它们本来是 0.09, |
| 2203 | // 在这个底色上仍看得清,于是播放头右边跟左边一样"亮着", |
| 2204 | // 走到哪儿就看不出来了。留一点点而不是归零—— |
| 2205 | // 归零等于假装那段没有数据,而它只是还没到 |
| 2206 | background: |
| 2207 | value !== null && past && (playing || trackHover) |
| 2208 | ? "rgba(255,255,255,0.62)" |
| 2209 | : value === null || past |
| 2210 | ? "rgba(255,255,255,0.32)" |
| 2211 | : "rgba(255,255,255,0.04)", |
| 2212 | }} |
| 2213 | /> |
| 2214 | </div> |
| 2215 | ); |
| 2216 | })} |
| 2217 | </div> |
| 2218 | <input |
| 2219 | type="range" |
| 2220 | className="scrubber-range" |
| 2221 | min={minTs} |
| 2222 | max={maxTs} |
| 2223 | step={DAY_MS} |
| 2224 | value={value ?? maxTs} |
| 2225 | /* **拖动不停播**:拖是"我要看那一段",不是"我要停下"—— |
| 2226 | 松手之后应该从新位置继续走到底。 |
| 2227 | (`All time` / `Now` 那两个按钮仍然停:那是明确的跳转,不是擦洗) */ |
| 2228 | onChange={(e) => seek(Number(e.target.value))} |
| 2229 | // 原生 range 的拖拽手势会被页面级鼠标监听(如图上拖节点)干扰—— |
| 2230 | // 自己用 pointer capture 驱动拖动,点击与拖拽都走同一条计算路径 |
| 2231 | onPointerDown={(e) => { |
| 2232 | draggingRef.current = true; |
| 2233 | try { |
| 2234 | e.currentTarget.setPointerCapture(e.pointerId); |
| 2235 | } catch { |
| 2236 | /* 合成事件的 pointerId 可能无效,忽略 */ |
| 2237 | } |
| 2238 | seek(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs)); |
| 2239 | }} |
| 2240 | onPointerMove={(e) => { |
| 2241 | if (draggingRef.current) |
| 2242 | seek(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs)); |
| 2243 | }} |
| 2244 | onPointerUp={() => { |
| 2245 | draggingRef.current = false; |
| 2246 | }} |
| 2247 | onPointerCancel={() => { |
| 2248 | draggingRef.current = false; |
| 2249 | }} |
| 2250 | /> |
| 2251 | </div> |
| 2252 | |
| 2253 | <span className="shrink-0 u-num text-[10px] text-neutral-600"> |
| 2254 | {maxYear} |
| 2255 | </span> |
| 2256 | |
| 2257 | <div className="w-[5.6rem] shrink-0 text-center u-num text-xs text-neutral-200"> |
| 2258 | {label} |
| 2259 | </div> |
| 2260 | |
| 2261 | <div className="h-5 w-px shrink-0 bg-white/10" /> |
| 2262 | |
| 2263 | {/* 双锚点分段:所处锚点高亮、点击即跳;拖在中间某天时两者皆不亮 */} |
| 2264 | <div className="flex shrink-0 rounded-lg overflow-hidden border border-white/10"> |
| 2265 | {( |
| 2266 | [ |
| 2267 | { |
| 2268 | key: "all", |
| 2269 | label: S.graph.allTime, |
| 2270 | active: value === null, |
| 2271 | to: null, |
| 2272 | }, |
| 2273 | { |
| 2274 | key: "now", |
| 2275 | label: S.graph.nowBtn, |
| 2276 | active: value !== null && maxTs - value < DAY_MS, |
| 2277 | to: maxTs, |
| 2278 | }, |
| 2279 | ] as const |
| 2280 | ).map((a) => ( |
| 2281 | <button |
| 2282 | key={a.key} |
| 2283 | onClick={() => { |
| 2284 | setPlaying(false); |
| 2285 | onChange(a.to); |
| 2286 | }} |
| 2287 | className={`px-2.5 py-1.5 text-xs transition-colors ${ |
| 2288 | a.active |
| 2289 | ? "bg-white/10 text-neutral-100" |
| 2290 | : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300" |
| 2291 | }`} |
| 2292 | > |
| 2293 | {a.label} |
| 2294 | </button> |
| 2295 | ))} |
| 2296 | </div> |
| 2297 | </div> |
| 2298 | ); |
| 2299 | } |
| 2300 | |
| 2301 | /* ============ 实体侧栏 ============ */ |
| 2302 | |
| 2303 | /** 世界时间(这件事何时成立)→ 文本。**一律按 UTC 读,不转本地。** |
| 2304 | * |
| 2305 | * `valid_from` / `valid_to` 来自文档里的陈述("2019 年 5 月 2 日就任"), |
| 2306 | * 是**日历日期不是时刻**,本来就没有时区;存的是那一天的 UTC 午夜。 |
| 2307 | * 按本地渲染会让 UTC-5 的读者看到 2019-05-01——凭空差一天,而且差的方向 |
| 2308 | * 还随读者所在地变。记录时间(我们何时这么认为)是另一回事,那个该按本地, |
| 2309 | * 见 EntityHistory 里 ymd 的注释。 */ |
| 2310 | function fmtTime(iso: string | null, precision: string | null): string | null { |
| 2311 | if (!iso) return null; |
| 2312 | const d = new Date(iso); |
| 2313 | const y = d.getUTCFullYear(); |
| 2314 | const m = String(d.getUTCMonth() + 1).padStart(2, "0"); |
| 2315 | const day = String(d.getUTCDate()).padStart(2, "0"); |
| 2316 | if (precision === "year") return `${y}`; |
| 2317 | if (precision === "month") return `${y}-${m}`; |
| 2318 | return `${y}-${m}-${day}`; |
| 2319 | } |
| 2320 | |
| 2321 | function fmtInterval(f: EntityFact): string { |
| 2322 | if (f.temporal === "eternal") return ""; |
| 2323 | const from = fmtTime(f.valid_from, f.valid_from_precision); |
| 2324 | const to = fmtTime(f.valid_to, f.valid_to_precision); |
| 2325 | // **「结束了但不知哪天」绝不能显示成「至今」。** 那是这条改动要修的正脸: |
| 2326 | // 原文明说 "former CEO of Weta Digital",界面却告诉读者他还在任 |
| 2327 | const endedUnknown = !f.valid_to && f.valid_to_precision === "unknown"; |
| 2328 | if (!from && !to && !endedUnknown) return ""; |
| 2329 | const end = to ?? (endedUnknown ? S.graph.endedUnknown : S.graph.ongoing); |
| 2330 | return from ? `${from} ~ ${end}` : `~ ${end}`; |
| 2331 | } |
| 2332 | |
| 2333 | /** 一条推出来的事实,**证明摊开在下面**。 |
| 2334 | * |
| 2335 | * 不做折叠:这一档存在的全部理由就是「这条边不是谁说的,是这么来的」, |
| 2336 | * 把前提藏在一次点击后面等于把理由藏起来。链最长十二条,摊开也不长。 */ |
| 2337 | /** 派生开关旁边那个小窗:**这批边是什么时候、按什么推出来的,以及现在还准不准**。 |
| 2338 | * |
| 2339 | * 存在的理由是「新鲜度看不见」。派生每小时重推一次,而事实每篇文档进来都在变—— |
| 2340 | * 一条派生边看上去和它刚推出来的时候一模一样,可它依据的前提可能三分钟前刚被撤掉。 |
| 2341 | * 光有开关答不了「我现在看到的是什么时候的结论」。 |
| 2342 | * |
| 2343 | * 手动按钮留在这里而不是别处:想重推的人正是刚看完这三行、觉得数字太旧的那个人。 |
| 2344 | */ |
| 2345 | function DerivedPanel({ |
| 2346 | panelRef, |
| 2347 | kbId, |
| 2348 | count, |
| 2349 | onClose, |
| 2350 | }: { |
| 2351 | panelRef: React.Ref<HTMLDivElement>; |
| 2352 | kbId: string; |
| 2353 | count: number; |
| 2354 | onClose: () => void; |
| 2355 | }) { |
| 2356 | const qc = useQueryClient(); |
| 2357 | const kb = useQuery({ |
| 2358 | queryKey: ["kbOne", kbId], |
| 2359 | queryFn: () => api.kbDetail(kbId), |
| 2360 | }); |
| 2361 | /* 重跑要确认,但**确认的第二下必须落在另一个按钮上**。 |
| 2362 | 这产品的手势约定是「同一个控件连点两下 = 收回去」——开关、⋯、图例胶囊 |
| 2363 | 都是这么用的。把「再点一次就执行」压在同一个按钮上,等于让同一个手势 |
| 2364 | 在这里意外地变成了「执行」,而别处它一直是「取消」。 |
| 2365 | 所以点一下只是**问一句**,问句下面给 取消 / 跑 两个目标。 |
| 2366 | |
| 2367 | 也没有用全站的 DangerConfirm:那是红标题、可要求逐字输入的危险级, |
| 2368 | 留给删库那类不可逆操作。重跑推理重但可重复,够不上那一档 */ |
| 2369 | const [armed, setArmed] = useState(false); |
| 2370 | const run = useMutation({ |
| 2371 | mutationFn: () => api.runInference(kbId), |
| 2372 | onSuccess: () => { |
| 2373 | qc.invalidateQueries({ queryKey: ["graph"] }); |
| 2374 | qc.invalidateQueries({ queryKey: ["kbOne", kbId] }); |
| 2375 | }, |
| 2376 | onError: (e: Error) => toast.error(e.message), |
| 2377 | }); |
| 2378 | |
| 2379 | const on = kb.data?.materialize_inferences ?? false; |
| 2380 | const last = kb.data?.last_inference_at; |
| 2381 | // 「多久以前」比一个时间戳好读——问题是「新不新」,不是「几点」 |
| 2382 | const age = last |
| 2383 | ? Math.round((Date.now() - new Date(last).getTime()) / 60000) |
| 2384 | : null; |
| 2385 | |
| 2386 | // **盖在触发器原位往右上长开**(bottom-0 left-0),而不是在旁边挂一扇窗。 |
| 2387 | // 面与圆角跟通知/用户卡片对齐:u-menu-glass + rounded-xl |
| 2388 | return ( |
| 2389 | <div |
| 2390 | ref={panelRef} |
| 2391 | className="u-menu-glass pointer-events-auto absolute bottom-0 left-0 z-50 w-72 overflow-hidden rounded-xl px-3 pb-3 pt-2.5 shadow-2xl" |
| 2392 | > |
| 2393 | {/* items-center 而不是 baseline:标题旁边站着一个按钮和一个关闭键, |
| 2394 | 按基线对齐会让那两个看着往上飘 */} |
| 2395 | <div className="flex items-center gap-2"> |
| 2396 | <span className="text-[13px] text-neutral-100"> |
| 2397 | {S.graph.derivedPanel} |
| 2398 | </span> |
| 2399 | {!armed && ( |
| 2400 | <button |
| 2401 | /* **要长得像个按钮**:从前是一段灰色幽灵文字夹在标题与 × 之间, |
| 2402 | 读起来像第三个标题而不是一个动作。加边框 + 内距, |
| 2403 | 与右上角那个档位加减器同一档次要控件的样子 */ |
| 2404 | className="ml-auto rounded-md border border-white/10 px-2 py-0.5 text-[11px] text-neutral-400 transition-colors hover:border-white/20 hover:text-neutral-100" |
| 2405 | disabled={!on || run.isPending} |
| 2406 | title={on ? undefined : S.err.inference_off} |
| 2407 | onClick={() => setArmed(true)} |
| 2408 | > |
| 2409 | {run.isPending ? S.graph.derivedRunning : S.graph.derivedRun} |
| 2410 | </button> |
| 2411 | )} |
| 2412 | {/* 固定 18px 方格:**别让关闭键撑起标题行的高**——一撑高, |
| 2413 | 行里最矮的标题就被居中挤出上下空当,看着像上边距过大 */} |
| 2414 | <button |
| 2415 | className={`${armed ? "ml-auto " : ""}grid h-[18px] w-[18px] place-items-center rounded text-neutral-500 transition-colors hover:bg-white/[0.06] hover:text-neutral-200`} |
| 2416 | onClick={onClose} |
| 2417 | aria-label={S.graph.close} |
| 2418 | > |
| 2419 | × |
| 2420 | </button> |
| 2421 | </div> |
| 2422 | |
| 2423 | {/* 问句 + 两个目标。**取消排在前面**:从「跑」那一下移过来最先碰到的 |
| 2424 | 是取消,误触的代价小的那个该更近 */} |
| 2425 | {armed && ( |
| 2426 | <div className="mt-2 rounded-lg bg-white/[0.04] p-2"> |
| 2427 | <p className="text-[11px] leading-relaxed text-neutral-300"> |
| 2428 | {S.graph.derivedRunAsk} |
| 2429 | </p> |
| 2430 | <div className="mt-1.5 flex gap-1.5"> |
| 2431 | <button |
| 2432 | className="rounded px-2 py-0.5 text-[11px] text-neutral-400 transition-colors hover:bg-white/[0.06] hover:text-neutral-100" |
| 2433 | onClick={() => setArmed(false)} |
| 2434 | > |
| 2435 | {S.graph.derivedRunCancel} |
| 2436 | </button> |
| 2437 | <button |
| 2438 | className="rounded bg-white/10 px-2 py-0.5 text-[11px] text-neutral-100 transition-colors hover:bg-white/[0.16]" |
| 2439 | disabled={run.isPending} |
| 2440 | onClick={() => { |
| 2441 | setArmed(false); |
| 2442 | run.mutate(); |
| 2443 | }} |
| 2444 | > |
| 2445 | {S.graph.derivedRunGo} |
| 2446 | </button> |
| 2447 | </div> |
| 2448 | </div> |
| 2449 | )} |
| 2450 | |
| 2451 | <dl className="mt-2 space-y-1 text-[11px]"> |
| 2452 | <div className="flex justify-between gap-3"> |
| 2453 | <dt className="text-neutral-500">{S.graph.derivedCountLabel}</dt> |
| 2454 | <dd className="u-num text-neutral-200">{count}</dd> |
| 2455 | </div> |
| 2456 | <div className="flex justify-between gap-3"> |
| 2457 | <dt className="text-neutral-500">{S.graph.derivedStateLabel}</dt> |
| 2458 | <dd className={on ? "text-neutral-200" : "text-[var(--u-warn)]"}> |
| 2459 | {on |
| 2460 | ? S.graph.derivedOn(kb.data!.inference_interval_minutes) |
| 2461 | : S.graph.derivedOff} |
| 2462 | </dd> |
| 2463 | </div> |
| 2464 | <div className="flex justify-between gap-3"> |
| 2465 | <dt className="text-neutral-500">{S.graph.derivedLastLabel}</dt> |
| 2466 | <dd className="u-num text-neutral-200"> |
| 2467 | {age === null ? S.graph.derivedNever : S.graph.derivedAgo(age)} |
| 2468 | </dd> |
| 2469 | </div> |
| 2470 | </dl> |
| 2471 | |
| 2472 | {/* 上一次手动跑的结果留在这儿。**推出多少、作废多少要分开说**—— |
| 2473 | 「什么都没变」和「换掉了三十条」是两件很不一样的事 */} |
| 2474 | {run.data && ( |
| 2475 | <p className="mt-2 text-[11px] text-neutral-400"> |
| 2476 | {run.data.inserted === 0 && run.data.invalidated === 0 |
| 2477 | ? S.graph.derivedNoChange |
| 2478 | : S.graph.derivedChanged(run.data.inserted, run.data.invalidated)} |
| 2479 | {run.data.capped > 0 && |
| 2480 | ` · ${S.graph.derivedCapped(run.data.capped)}`} |
| 2481 | </p> |
| 2482 | )} |
| 2483 | |
| 2484 | </div> |
| 2485 | ); |
| 2486 | } |
| 2487 | |
| 2488 | /** 推出来的一条边。**行式样与 FactRow 对齐**:同样的圆角行、同样的 |
| 2489 | * chevron 展开、同样的 role="link" 跳转(避免按钮套按钮)。 |
| 2490 | * |
| 2491 | * 从前这里是一张 `glass rounded-xl p-3` 卡片、证明常驻展开——在一列 |
| 2492 | * Relations/Timeline/History 的紧凑行里显得是另一个产品的东西,而且十几条 |
| 2493 | * 推导堆起来是一面墙。证明是「问了才看」的东西,收进展开区正合适。 */ |
| 2494 | function DerivedRow({ |
| 2495 | kbId, |
| 2496 | d, |
| 2497 | otherId, |
| 2498 | otherName, |
| 2499 | open, |
| 2500 | onToggle, |
| 2501 | onNavigate, |
| 2502 | }: { |
| 2503 | kbId: string; |
| 2504 | d: DerivedFact; |
| 2505 | otherId: string; |
| 2506 | otherName: string; |
| 2507 | open: boolean; |
| 2508 | onToggle: () => void; |
| 2509 | onNavigate: (entityId: string) => void; |
| 2510 | }) { |
| 2511 | return ( |
| 2512 | <div |
| 2513 | className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"}`} |
| 2514 | > |
| 2515 | <button |
| 2516 | onClick={onToggle} |
| 2517 | className="w-full text-left px-2 py-1.5 flex items-center gap-1.5" |
| 2518 | > |
| 2519 | <ChevronRight |
| 2520 | size={11} |
| 2521 | className={`shrink-0 text-neutral-600 transition-transform ${open ? "rotate-90" : ""}`} |
| 2522 | /> |
| 2523 | <span |
| 2524 | role="link" |
| 2525 | tabIndex={0} |
| 2526 | onClick={(ev) => { |
| 2527 | ev.stopPropagation(); |
| 2528 | onNavigate(otherId); |
| 2529 | }} |
| 2530 | onKeyDown={(ev) => { |
| 2531 | if (ev.key === "Enter") { |
| 2532 | ev.stopPropagation(); |
| 2533 | onNavigate(otherId); |
| 2534 | } |
| 2535 | }} |
| 2536 | className="truncate text-[13px] text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30" |
| 2537 | > |
| 2538 | {otherName} |
| 2539 | </span> |
| 2540 | <span className="ml-auto shrink-0 pl-2 text-[10.5px] text-neutral-600"> |
| 2541 | {d.premises.length} |
| 2542 | </span> |
| 2543 | </button> |
| 2544 | {/* 证明:前提按推导顺序,每条展开到原句(0002 R2)。**边框与 EvidenceList |
| 2545 | 同一档**——两者是同一件事的两种形态:一个给出处,一个给推理链 */} |
| 2546 | {open && <ProofChain kbId={kbId} d={d} />} |
| 2547 | </div> |
| 2548 | ); |
| 2549 | } |
| 2550 | |
| 2551 | /** 一条派生的证明链。展开时才取——证明是「问了才看」的东西。 |
| 2552 | * |
| 2553 | * 每一步是一条断言前提:三元组在上,它的原句在下,原句可点进文档。 |
| 2554 | * 前提被撤过的打标记但不藏:派生随之失效,而「当时靠的是什么」正是记录轴要答的。 |
| 2555 | * 取不到(派生已失效)就退回列表里带来的那几行文本,不空着。 */ |
| 2556 | function ProofChain({ kbId, d }: { kbId: string; d: DerivedFact }) { |
| 2557 | const proof = useQuery({ |
| 2558 | queryKey: ["proof", d.id], |
| 2559 | queryFn: () => api.derivedProof(kbId, d.id), |
| 2560 | }); |
| 2561 | const steps = proof.data?.proof?.steps; |
| 2562 | return ( |
| 2563 | <div className="mx-2 mb-2 mt-0.5 border-l border-white/15 pl-2.5"> |
| 2564 | {proof.isPending && ( |
| 2565 | <p className="text-[11px] text-neutral-600">{S.graph.proofLoading}</p> |
| 2566 | )} |
| 2567 | {steps && <ProofSteps kbId={kbId} steps={steps} />} |
| 2568 | {/* 派生已失效、证明取不到:退回列表里带来的那几行文本 */} |
| 2569 | {!proof.isPending && !steps && ( |
| 2570 | <ol className="space-y-0.5"> |
| 2571 | {d.premises.map((p, i) => ( |
| 2572 | <li key={i} className="text-[11px] text-neutral-400"> |
| 2573 | {p} |
| 2574 | </li> |
| 2575 | ))} |
| 2576 | {d.premises.length === 0 && ( |
| 2577 | <li className="text-[11px] text-neutral-600">{S.graph.derivedNoProof}</li> |
| 2578 | )} |
| 2579 | </ol> |
| 2580 | )} |
| 2581 | </div> |
| 2582 | ); |
| 2583 | } |
| 2584 | |
| 2585 | /** 证明的步,落了地的与没落地的派生共用:前提是同一种东西 */ |
| 2586 | function ProofSteps({ kbId, steps }: { kbId: string; steps: ProofStep[] }) { |
| 2587 | return ( |
| 2588 | <ol className="space-y-2"> |
| 2589 | {steps.map((st) => ( |
| 2590 | <li key={st.fact_id} className="text-[11px]"> |
| 2591 | <div className="flex items-baseline gap-1.5 flex-wrap"> |
| 2592 | <span className="u-num text-[10px] text-neutral-600 shrink-0"> |
| 2593 | {S.graph.proofStep(st.seq + 1)} |
| 2594 | </span> |
| 2595 | <span className={st.retracted ? "text-neutral-600 line-through" : "text-neutral-300"}> |
| 2596 | {st.subject} |
| 2597 | <span className="text-neutral-500"> — {st.predicate ?? "?"} → </span> |
| 2598 | {st.object ?? "?"} |
| 2599 | </span> |
| 2600 | {st.retracted && ( |
| 2601 | <span className="u-chip u-chip-warn text-[10px]">{S.graph.proofRetracted}</span> |
| 2602 | )} |
| 2603 | </div> |
| 2604 | <div className="mt-0.5 space-y-1 pl-2"> |
| 2605 | {st.evidence.map((ev) => ( |
| 2606 | <Link |
| 2607 | key={ev.chunk_id} |
| 2608 | to="/kb/$kbId/doc/$docId" |
| 2609 | params={{ kbId, docId: ev.document_id }} |
| 2610 | search={{ chunk: ev.chunk_id }} |
| 2611 | className="block text-neutral-500 hover:text-neutral-300" |
| 2612 | > |
| 2613 | <div className="line-clamp-2 italic"> |
| 2614 | {ev.quote ? `“${ev.quote}”` : S.graph.noQuote} |
| 2615 | </div> |
| 2616 | <div className="mt-0.5 text-neutral-400"> |
| 2617 | {S.graph.sectionRef(ev.filename, ev.seq + 1)} |
| 2618 | {ev.stale && ( |
| 2619 | <span |
| 2620 | className="ml-1.5 u-num text-[10px] text-neutral-600" |
| 2621 | title={S.graph.staleEvidenceHint} |
| 2622 | > |
| 2623 | {S.graph.fromVersion(ev.doc_version)} |
| 2624 | </span> |
| 2625 | )} |
| 2626 | </div> |
| 2627 | </Link> |
| 2628 | ))} |
| 2629 | {st.evidence.length === 0 && ( |
| 2630 | <p className="text-neutral-600">{S.graph.noEvidence}</p> |
| 2631 | )} |
| 2632 | </div> |
| 2633 | </li> |
| 2634 | ))} |
| 2635 | </ol> |
| 2636 | ); |
| 2637 | } |
| 2638 | |
| 2639 | /** 没落地的派生(0017 §3):像 DerivedRow 一样的一行,多一句「挡住它的是谁」, |
| 2640 | * 展开是它的证明链——人在这里看到「引擎本可以画这条边,是什么拦住了它」 */ |
| 2641 | function BlockedRow({ |
| 2642 | kbId, |
| 2643 | b, |
| 2644 | entityId, |
| 2645 | open, |
| 2646 | onToggle, |
| 2647 | onNavigate, |
| 2648 | }: { |
| 2649 | kbId: string; |
| 2650 | b: BlockedDerivation; |
| 2651 | entityId: string; |
| 2652 | open: boolean; |
| 2653 | onToggle: () => void; |
| 2654 | onNavigate: (entityId: string) => void; |
| 2655 | }) { |
| 2656 | const navigate = useNavigate(); |
| 2657 | const out = b.subject_id === entityId; |
| 2658 | const otherId = out ? b.object_id : b.subject_id; |
| 2659 | const otherName = out ? b.object : b.subject; |
| 2660 | const proof = useQuery({ |
| 2661 | queryKey: ["blocked-proof", b.violation_id], |
| 2662 | queryFn: () => api.blockedProof(kbId, b.violation_id), |
| 2663 | enabled: open, |
| 2664 | }); |
| 2665 | return ( |
| 2666 | <div |
| 2667 | className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"}`} |
| 2668 | > |
| 2669 | <button |
| 2670 | onClick={onToggle} |
| 2671 | className="w-full text-left px-2 py-1.5 flex items-center gap-1.5" |
| 2672 | > |
| 2673 | <ChevronRight |
| 2674 | size={11} |
| 2675 | className={`shrink-0 text-neutral-600 transition-transform ${open ? "rotate-90" : ""}`} |
| 2676 | /> |
| 2677 | {out ? <ArrowRight size={10} className="shrink-0 text-neutral-600" /> : <ArrowLeft size={10} className="shrink-0 text-neutral-600" />} |
| 2678 | <span className="shrink-0 text-[11px] text-neutral-500">{b.predicate}</span> |
| 2679 | <span |
| 2680 | role="link" |
| 2681 | tabIndex={0} |
| 2682 | onClick={(ev) => { |
| 2683 | ev.stopPropagation(); |
| 2684 | onNavigate(otherId); |
| 2685 | }} |
| 2686 | onKeyDown={(ev) => { |
| 2687 | if (ev.key === "Enter") { |
| 2688 | ev.stopPropagation(); |
| 2689 | onNavigate(otherId); |
| 2690 | } |
| 2691 | }} |
| 2692 | className="truncate text-[13px] text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30" |
| 2693 | > |
| 2694 | {otherName} |
| 2695 | </span> |
| 2696 | <span className="ml-auto shrink-0 pl-2 text-[10.5px] text-neutral-600"> |
| 2697 | {S.graph.ruleNames[b.rule] ?? b.rule} |
| 2698 | </span> |
| 2699 | </button> |
| 2700 | <div className="flex items-center gap-1.5 px-2 pb-1.5 pl-[26px] text-[11px]"> |
| 2701 | <span className="truncate text-[var(--u-contest)]"> |
| 2702 | {S.graph.blockedBy(b.against_text)} |
| 2703 | </span> |
| 2704 | <span |
| 2705 | role="link" |
| 2706 | tabIndex={0} |
| 2707 | onClick={() => |
| 2708 | navigate({ |
| 2709 | to: "/kb/$kbId/review", |
| 2710 | params: { kbId }, |
| 2711 | search: { queue: "violations", item: b.violation_id }, |
| 2712 | }) |
| 2713 | } |
| 2714 | className="ml-auto shrink-0 text-neutral-500 hover:text-neutral-300 hover:underline underline-offset-2" |
| 2715 | > |
| 2716 | {S.graph.blockedReview} → |
| 2717 | </span> |
| 2718 | </div> |
| 2719 | {open && ( |
| 2720 | <div className="mx-2 mb-2 mt-0.5 border-l border-white/15 pl-2.5"> |
| 2721 | {proof.isPending && ( |
| 2722 | <p className="text-[11px] text-neutral-600">{S.graph.proofLoading}</p> |
| 2723 | )} |
| 2724 | {proof.data?.steps && ( |
| 2725 | <ProofSteps kbId={kbId} steps={proof.data.steps} /> |
| 2726 | )} |
| 2727 | </div> |
| 2728 | )} |
| 2729 | </div> |
| 2730 | ); |
| 2731 | } |
| 2732 | |
| 2733 | /** 争议 chip(0017 §3):有一条 open 的违规或冲突指着这条断言。行不压暗—— |
| 2734 | * 它仍然活着。点它去 Review 对应那一档,并把那张卡点亮 */ |
| 2735 | function ContestedChip({ |
| 2736 | kbId, |
| 2737 | c, |
| 2738 | }: { |
| 2739 | kbId: string; |
| 2740 | c: NonNullable<EntityFact["contested"]>; |
| 2741 | }) { |
| 2742 | const navigate = useNavigate(); |
| 2743 | const queue = c.kind === "temporal_conflict" ? "conflicts" : "violations"; |
| 2744 | return ( |
| 2745 | <span |
| 2746 | role="link" |
| 2747 | tabIndex={0} |
| 2748 | onClick={(ev) => { |
| 2749 | ev.stopPropagation(); |
| 2750 | navigate({ |
| 2751 | to: "/kb/$kbId/review", |
| 2752 | params: { kbId }, |
| 2753 | search: { queue, item: c.ref_id }, |
| 2754 | }); |
| 2755 | }} |
| 2756 | onKeyDown={(ev) => { |
| 2757 | if (ev.key === "Enter") { |
| 2758 | ev.stopPropagation(); |
| 2759 | navigate({ |
| 2760 | to: "/kb/$kbId/review", |
| 2761 | params: { kbId }, |
| 2762 | search: { queue, item: c.ref_id }, |
| 2763 | }); |
| 2764 | } |
| 2765 | }} |
| 2766 | className="u-chip u-chip-contest shrink-0 !text-[10px] !px-1.5 cursor-pointer" |
| 2767 | title={S.graph.contestedHint(c.kind, c.derived ?? null)} |
| 2768 | > |
| 2769 | {S.graph.contestedChip} |
| 2770 | </span> |
| 2771 | ); |
| 2772 | } |
| 2773 | |
| 2774 | function EntityPanel({ |
| 2775 | kbId, |
| 2776 | entityId, |
| 2777 | exiting, |
| 2778 | intent, |
| 2779 | onClose, |
| 2780 | onNavigate, |
| 2781 | }: { |
| 2782 | kbId: string; |
| 2783 | entityId: string; |
| 2784 | /** 正在演退场:还挂在 DOM 上,但已经不接受点击 */ |
| 2785 | exiting: boolean; |
| 2786 | /** 打开时停在哪一档、展开哪一行;读一次就清掉 */ |
| 2787 | intent?: MutableRefObject<{ view: "derived"; open: string } | null>; |
| 2788 | onClose: () => void; |
| 2789 | onNavigate: (entityId: string) => void; |
| 2790 | }) { |
| 2791 | const detail = useQuery({ |
| 2792 | queryKey: ["entity", kbId, entityId], |
| 2793 | queryFn: () => api.entityDetail(kbId, entityId), |
| 2794 | }); |
| 2795 | const [openFact, setOpenFact] = useState<string | null>(null); |
| 2796 | // 推出来的那些。**单独一个键,不掺进 facts**——混在一个列表里,用户看不出 |
| 2797 | // 「文档里写的」和「引擎推的」的区别 |
| 2798 | const derived = detail.data?.derived ?? []; |
| 2799 | // 没落地的(0017 §3):推出来了,撞上一条断言 |
| 2800 | const blocked = detail.data?.blocked ?? []; |
| 2801 | /* 按「方向 + 谓词 + 规则」分组,骨架与 Relations 的 groups 一致。 |
| 2802 | 规则挂在组上而不是每一行:它对整组都成立,逐行重复既冗余, |
| 2803 | 那个琥珀色小字还会跟派生边抢色相 */ |
| 2804 | const derivedGroups = useMemo(() => { |
| 2805 | const map = new Map< |
| 2806 | string, |
| 2807 | { |
| 2808 | key: string; |
| 2809 | direction: "in" | "out"; |
| 2810 | predicate: string; |
| 2811 | rule: string; |
| 2812 | rows: DerivedFact[]; |
| 2813 | } |
| 2814 | >(); |
| 2815 | for (const d of derived) { |
| 2816 | const direction = d.subject_id === entityId ? "out" : "in"; |
| 2817 | // 四条规则各有名字。**查不到就退回原始 kind 串**——那对读的人没有 |
| 2818 | // 意义,但比显示成另一条规则的名字诚实 |
| 2819 | const rule = S.graph.ruleNames[d.rule] ?? d.rule; |
| 2820 | const key = `${direction}|${d.predicate}|${d.rule}`; |
| 2821 | const cur = map.get(key); |
| 2822 | if (cur) cur.rows.push(d); |
| 2823 | else map.set(key, { key, direction, predicate: d.predicate, rule, rows: [d] }); |
| 2824 | } |
| 2825 | return [...map.values()]; |
| 2826 | }, [derived, entityId]); |
| 2827 | // Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立); |
| 2828 | // History = 记录时间轴(我们何时这么认为、又何时改了主意) |
| 2829 | const [view, setView] = useState< |
| 2830 | "relations" | "timeline" | "history" | "derived" |
| 2831 | >("relations"); |
| 2832 | useEffect(() => { |
| 2833 | const it = intent?.current; |
| 2834 | if (!it) return; |
| 2835 | intent.current = null; |
| 2836 | setView(it.view); |
| 2837 | setOpenFact(it.open); |
| 2838 | }, [entityId, intent]); |
| 2839 | |
| 2840 | const e: GraphNode | undefined = detail.data?.entity; |
| 2841 | |
| 2842 | // 实体修正:抽取给的是初判,判错此前只能整库重抽 |
| 2843 | const qc = useQueryClient(); |
| 2844 | const [editing, setEditing] = useState(false); |
| 2845 | const [draftName, setDraftName] = useState(""); |
| 2846 | const [draftType, setDraftType] = useState(""); |
| 2847 | // 同名的其他实体:详情接口打开就给。改名之后再用响应里的那份覆盖—— |
| 2848 | // 改完名可能撞上一批新的同名,那时候的答案比打开时的新 |
| 2849 | const [renamedPeers, setRenamedPeers] = useState<GraphNode[] | null>(null); |
| 2850 | const sameName = renamedPeers ?? detail.data?.same_name ?? []; |
| 2851 | const setSameName = setRenamedPeers; |
| 2852 | // 手动合并:把同名的那个并进**当前这个**。方向写死是有意的—— |
| 2853 | // 用户正在看的就是他判断为「主」的那一个 |
| 2854 | const merge = useMutation({ |
| 2855 | mutationFn: (source: string) => api.mergeEntities(kbId, source, entityId), |
| 2856 | onSuccess: () => { |
| 2857 | toast.success(S.toast.saved); |
| 2858 | // 本地把并掉的那个摘掉,别等重取——它已经不存在了,留着会让人再点一次 |
| 2859 | setSameName((prev) => |
| 2860 | (prev ?? sameName).filter((p) => p.id !== merge.variables), |
| 2861 | ); |
| 2862 | qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] }); |
| 2863 | qc.invalidateQueries({ queryKey: ["graph"] }); |
| 2864 | qc.invalidateQueries({ queryKey: ["review", kbId] }); |
| 2865 | }, |
| 2866 | onError: (err: Error) => toast.error(err.message), |
| 2867 | }); |
| 2868 | // 类型下拉要的是全量本体,不是当前视图里出现过的那几个 |
| 2869 | const ontology = useQuery({ |
| 2870 | queryKey: ["ontology", kbId], |
| 2871 | queryFn: () => api.ontology(kbId), |
| 2872 | enabled: editing, |
| 2873 | }); |
| 2874 | const types = ontology.data?.entity_types ?? []; |
| 2875 | |
| 2876 | const openEdit = () => { |
| 2877 | if (!e) return; |
| 2878 | setDraftName(e.name); |
| 2879 | setDraftType(types.find((t) => t.key === e.type_key)?.id ?? ""); |
| 2880 | setSameName([]); |
| 2881 | setEditing(true); |
| 2882 | }; |
| 2883 | // 本体是异步来的:它到齐时把类型下拉对到当前类型上 |
| 2884 | useEffect(() => { |
| 2885 | if (editing && !draftType && e) |
| 2886 | setDraftType(types.find((t) => t.key === e.type_key)?.id ?? ""); |
| 2887 | }, [editing, draftType, e, types]); |
| 2888 | |
| 2889 | const save = useMutation({ |
| 2890 | mutationFn: () => { |
| 2891 | const body: { type_id?: string; canonical_name?: string } = {}; |
| 2892 | if (draftName.trim() && draftName.trim() !== e?.name) |
| 2893 | body.canonical_name = draftName.trim(); |
| 2894 | const curId = types.find((t) => t.key === e?.type_key)?.id; |
| 2895 | if (draftType && draftType !== curId) body.type_id = draftType; |
| 2896 | return api.updateEntity(kbId, entityId, body); |
| 2897 | }, |
| 2898 | onSuccess: (r) => { |
| 2899 | setEditing(false); |
| 2900 | setSameName(r.same_name); |
| 2901 | toast.success(S.graph.editSaved); |
| 2902 | // 改了类型/名字,图谱节点与本体计数都要跟着动 |
| 2903 | qc.invalidateQueries({ queryKey: ["entity", kbId, entityId] }); |
| 2904 | qc.invalidateQueries({ queryKey: ["graph", kbId] }); |
| 2905 | qc.invalidateQueries({ queryKey: ["ontology", kbId] }); |
| 2906 | }, |
| 2907 | onError: (err: Error) => toast.error(err.message), |
| 2908 | }); |
| 2909 | |
| 2910 | const dirty = |
| 2911 | !!e && |
| 2912 | (draftName.trim() !== e.name || |
| 2913 | draftType !== (types.find((t) => t.key === e.type_key)?.id ?? "")); |
| 2914 | |
| 2915 | // Relations = 当下有效的快照(as-of now);已闭合的历史只出现在 Timeline。 |
| 2916 | // 按「方向 + 谓词」分组:实体自身名不再逐行重复,谓词只出现在小节标题里 |
| 2917 | const { groups, historicalCount } = useMemo(() => { |
| 2918 | const all = detail.data?.facts ?? []; |
| 2919 | const nowIso = new Date().toISOString(); |
| 2920 | const current = all.filter( |
| 2921 | (f) => |
| 2922 | (!f.valid_from || f.valid_from <= nowIso) && |
| 2923 | (!f.valid_to || f.valid_to > nowIso), |
| 2924 | ); |
| 2925 | const map = new Map< |
| 2926 | string, |
| 2927 | { |
| 2928 | key: string; |
| 2929 | label: string | null; |
| 2930 | inferred: boolean; |
| 2931 | direction: string; |
| 2932 | rows: EntityFact[]; |
| 2933 | } |
| 2934 | >(); |
| 2935 | for (const f of current) { |
| 2936 | // 谓词为空的事实归到同一组:它们的共同点就是「说不出是什么关系」 |
| 2937 | const k = `${f.direction}:${f.predicate_key ?? ""}`; |
| 2938 | if (!map.has(k)) |
| 2939 | map.set(k, { |
| 2940 | key: k, |
| 2941 | label: f.predicate_label, |
| 2942 | inferred: f.inferred, |
| 2943 | direction: f.direction, |
| 2944 | rows: [], |
| 2945 | }); |
| 2946 | map.get(k)!.rows.push(f); |
| 2947 | } |
| 2948 | const arr = [...map.values()]; |
| 2949 | for (const gr of arr) |
| 2950 | gr.rows.sort((a, b) => |
| 2951 | (a.valid_from ?? "9999") < (b.valid_from ?? "9999") ? -1 : 1, |
| 2952 | ); |
| 2953 | arr.sort( |
| 2954 | (a, b) => |
| 2955 | b.rows.length - a.rows.length || |
| 2956 | (a.label ?? "").localeCompare(b.label ?? ""), |
| 2957 | ); |
| 2958 | return { groups: arr, historicalCount: all.length - current.length }; |
| 2959 | }, [detail.data]); |
| 2960 | |
| 2961 | return ( |
| 2962 | <div |
| 2963 | className={`${exiting ? "u-dock-out" : "u-dock-in"} glass-strong absolute top-14 right-3 bottom-20 w-80 z-10 rounded-xl shadow-2xl flex flex-col`} |
| 2964 | > |
| 2965 | <div className="flex items-start justify-between px-4 py-3.5 border-b border-white/10"> |
| 2966 | <div> |
| 2967 | {e && ( |
| 2968 | <> |
| 2969 | <div className="flex items-center gap-2"> |
| 2970 | <span |
| 2971 | className="h-2.5 w-2.5 rounded-full shrink-0" |
| 2972 | style={{ |
| 2973 | background: e.color, |
| 2974 | boxShadow: `0 0 8px ${e.color}55`, |
| 2975 | }} |
| 2976 | /> |
| 2977 | <span |
| 2978 | className="text-[15px] font-semibold tracking-tight text-white" |
| 2979 | style={{ fontFamily: "var(--font-display)" }} |
| 2980 | > |
| 2981 | {e.name} |
| 2982 | </span> |
| 2983 | </div> |
| 2984 | {/* 消歧后缀找不到关联事实时兜底成类型标签,那就与后面的类型重复了 */} |
| 2985 | <div className="mt-1 text-xs text-neutral-500"> |
| 2986 | {e.disambiguator && e.disambiguator !== e.type_label |
| 2987 | ? `${e.disambiguator} · ` |
| 2988 | : ""} |
| 2989 | {e.type_label ?? S.graph.untyped} ·{" "} |
| 2990 | {detail.data?.facts.length ?? 0} {S.graph.facts} |
| 2991 | </div> |
| 2992 | </> |
| 2993 | )} |
| 2994 | </div> |
| 2995 | <div className="flex items-center gap-1.5 mt-0.5"> |
| 2996 | {e && !editing && ( |
| 2997 | <button |
| 2998 | onClick={openEdit} |
| 2999 | title={S.graph.edit} |
| 3000 | className="text-neutral-500 hover:text-neutral-200" |
| 3001 | > |
| 3002 | <Pencil size={13} /> |
| 3003 | </button> |
| 3004 | )} |
| 3005 | <button |
| 3006 | onClick={onClose} |
| 3007 | className="text-neutral-500 hover:text-neutral-200" |
| 3008 | > |
| 3009 | <X size={15} /> |
| 3010 | </button> |
| 3011 | </div> |
| 3012 | </div> |
| 3013 | |
| 3014 | {editing && e && ( |
| 3015 | <div className="px-4 py-3 border-b border-white/10 space-y-2.5"> |
| 3016 | <label className="block"> |
| 3017 | <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500"> |
| 3018 | {S.graph.editName} |
| 3019 | </span> |
| 3020 | <input |
| 3021 | autoFocus |
| 3022 | value={draftName} |
| 3023 | onChange={(ev) => setDraftName(ev.target.value)} |
| 3024 | onKeyDown={(ev) => { |
| 3025 | if (ev.key === "Enter" && dirty && draftName.trim()) |
| 3026 | save.mutate(); |
| 3027 | if (ev.key === "Escape") setEditing(false); |
| 3028 | }} |
| 3029 | 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" |
| 3030 | /> |
| 3031 | </label> |
| 3032 | <label className="block"> |
| 3033 | <span className="text-[10px] uppercase tracking-[0.08em] text-neutral-500"> |
| 3034 | {S.graph.editType} |
| 3035 | </span> |
| 3036 | <select |
| 3037 | value={draftType} |
| 3038 | onChange={(ev) => setDraftType(ev.target.value)} |
| 3039 | 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" |
| 3040 | > |
| 3041 | {types.map((t) => ( |
| 3042 | <option key={t.id} value={t.id} className="bg-neutral-900"> |
| 3043 | {t.label} |
| 3044 | </option> |
| 3045 | ))} |
| 3046 | </select> |
| 3047 | </label> |
| 3048 | <div className="flex items-center gap-2 pt-0.5"> |
| 3049 | <button |
| 3050 | disabled={!dirty || !draftName.trim() || save.isPending} |
| 3051 | onClick={() => save.mutate()} |
| 3052 | 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" |
| 3053 | > |
| 3054 | {S.graph.editSave} |
| 3055 | </button> |
| 3056 | <button |
| 3057 | onClick={() => setEditing(false)} |
| 3058 | className="px-2.5 py-1 text-xs rounded text-neutral-500 hover:text-neutral-300" |
| 3059 | > |
| 3060 | {S.graph.editCancel} |
| 3061 | </button> |
| 3062 | {!draftName.trim() && ( |
| 3063 | <span className="text-[11px] text-[var(--u-danger)]"> |
| 3064 | {S.graph.editEmptyName} |
| 3065 | </span> |
| 3066 | )} |
| 3067 | </div> |
| 3068 | </div> |
| 3069 | )} |
| 3070 | |
| 3071 | {/* 同名不是错误——两个张伟可以并存。只提示,判定是不是同一个是人的事 */} |
| 3072 | {sameName.length > 0 && !editing && ( |
| 3073 | <div className="mx-4 mt-2.5 rounded border border-white/10 bg-white/[0.03] px-2.5 py-2"> |
| 3074 | <div className="flex items-start justify-between gap-2"> |
| 3075 | <p className="text-[11px] text-neutral-400"> |
| 3076 | {S.graph.sameNameNote(sameName.length)}{" "} |
| 3077 | <span className="text-neutral-500">{S.graph.sameNameHint}</span> |
| 3078 | </p> |
| 3079 | <button |
| 3080 | onClick={() => setSameName([])} |
| 3081 | className="text-neutral-600 hover:text-neutral-300 shrink-0" |
| 3082 | > |
| 3083 | <X size={11} /> |
| 3084 | </button> |
| 3085 | </div> |
| 3086 | {/* 每个同名的给两个动作:去看它,或者把它并进来。 |
| 3087 | **方向写死成「并进当前这个」**——合并有方向(源消失、事实搬到目标上), |
| 3088 | 而当前打开的这个就是用户正在看、正在判断的那一个 */} |
| 3089 | <div className="mt-1.5 space-y-1"> |
| 3090 | {sameName.map((p) => ( |
| 3091 | <div key={p.id} className="flex items-center gap-1"> |
| 3092 | <button |
| 3093 | onClick={() => onNavigate(p.id)} |
| 3094 | 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" |
| 3095 | > |
| 3096 | {p.type_label ?? S.graph.untyped} |
| 3097 | {p.disambiguator && p.disambiguator !== p.type_label |
| 3098 | ? ` · ${p.disambiguator}` |
| 3099 | : ""} |
| 3100 | </button> |
| 3101 | <button |
| 3102 | className="shrink-0 text-[11px] px-1.5 py-0.5 rounded text-neutral-400 hover:bg-white/10 hover:text-neutral-100" |
| 3103 | disabled={merge.isPending} |
| 3104 | title={S.graph.mergeIntoHint} |
| 3105 | onClick={() => { |
| 3106 | if (confirm(S.graph.mergeConfirm(p.name, e?.name ?? ""))) |
| 3107 | merge.mutate(p.id); |
| 3108 | }} |
| 3109 | > |
| 3110 | {S.graph.mergeInto} |
| 3111 | </button> |
| 3112 | </div> |
| 3113 | ))} |
| 3114 | </div> |
| 3115 | </div> |
| 3116 | )} |
| 3117 | |
| 3118 | {/* 视图切换:Relations(分组)| Timeline(年表) */} |
| 3119 | <div className="px-4 pt-2.5"> |
| 3120 | <div className="flex rounded-lg overflow-hidden border border-white/10 w-fit"> |
| 3121 | {(["relations", "timeline", "history", "derived"] as const) |
| 3122 | // 推出来的那一档:**没有派生就不出现**。一个没开推理的库不该看到 |
| 3123 | // 一个永远是空的标签页。没落地的也算——那正是这一档要说的事 |
| 3124 | .filter( |
| 3125 | (v) => v !== "derived" || derived.length > 0 || blocked.length > 0, |
| 3126 | ) |
| 3127 | .map((v) => ( |
| 3128 | <button |
| 3129 | key={v} |
| 3130 | onClick={() => setView(v)} |
| 3131 | className={`px-3 py-1 text-[11px] transition-colors ${ |
| 3132 | view === v |
| 3133 | ? "bg-white/10 text-neutral-100" |
| 3134 | : "text-neutral-500 hover:bg-white/[0.05] hover:text-neutral-300" |
| 3135 | }`} |
| 3136 | > |
| 3137 | {v === "relations" |
| 3138 | ? S.graph.viewRelations |
| 3139 | : v === "timeline" |
| 3140 | ? S.graph.viewTimeline |
| 3141 | : v === "history" |
| 3142 | ? S.graph.viewHistory |
| 3143 | : S.graph.viewDerived} |
| 3144 | </button> |
| 3145 | ))} |
| 3146 | </div> |
| 3147 | </div> |
| 3148 | |
| 3149 | <div className="u-scroll flex-1 overflow-y-auto px-2 py-2"> |
| 3150 | {view === "relations" && historicalCount > 0 && ( |
| 3151 | <button |
| 3152 | onClick={() => setView("timeline")} |
| 3153 | className="mx-2 mb-2 mt-0.5 text-[11px] text-neutral-500 hover:text-neutral-300 underline-offset-2 hover:underline" |
| 3154 | > |
| 3155 | {S.graph.historicalNote(historicalCount)} |
| 3156 | </button> |
| 3157 | )} |
| 3158 | {view === "relations" && |
| 3159 | groups.map((gr) => ( |
| 3160 | <div key={gr.key} className="mb-3 last:mb-1"> |
| 3161 | <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"> |
| 3162 | {gr.direction === "in" ? ( |
| 3163 | <ArrowLeft size={10} /> |
| 3164 | ) : ( |
| 3165 | <ArrowRight size={10} /> |
| 3166 | )} |
| 3167 | <span |
| 3168 | className={ |
| 3169 | gr.label === null ? "italic text-neutral-600" : undefined |
| 3170 | } |
| 3171 | title={ |
| 3172 | gr.label && gr.inferred |
| 3173 | ? S.graph.inferredPredicate |
| 3174 | : undefined |
| 3175 | } |
| 3176 | > |
| 3177 | {gr.label ?? S.graph.unknownPredicate} |
| 3178 | </span> |
| 3179 | {gr.rows.length > 1 && ( |
| 3180 | <span className="text-neutral-600">{gr.rows.length}</span> |
| 3181 | )} |
| 3182 | </div> |
| 3183 | <div> |
| 3184 | {gr.rows.map((f) => ( |
| 3185 | <FactRow |
| 3186 | key={f.id} |
| 3187 | kbId={kbId} |
| 3188 | fact={f} |
| 3189 | open={openFact === f.id} |
| 3190 | onToggle={() => |
| 3191 | setOpenFact(openFact === f.id ? null : f.id) |
| 3192 | } |
| 3193 | onNavigate={onNavigate} |
| 3194 | /> |
| 3195 | ))} |
| 3196 | </div> |
| 3197 | </div> |
| 3198 | ))} |
| 3199 | {view === "timeline" && ( |
| 3200 | <TimelineView |
| 3201 | kbId={kbId} |
| 3202 | facts={detail.data?.facts ?? []} |
| 3203 | openFact={openFact} |
| 3204 | onToggle={(id) => setOpenFact(openFact === id ? null : id)} |
| 3205 | onNavigate={onNavigate} |
| 3206 | /> |
| 3207 | )} |
| 3208 | {view === "history" && ( |
| 3209 | <EntityHistory kbId={kbId} entityId={entityId} /> |
| 3210 | )} |
| 3211 | {view === "derived" && ( |
| 3212 | <> |
| 3213 | <p className="px-2 pb-1.5 pt-0.5 text-[11px] leading-relaxed text-neutral-500"> |
| 3214 | {S.graph.derivedHint} |
| 3215 | </p> |
| 3216 | {/* **与 Relations 同一个骨架**:方向箭头 + 谓词 + 条数的小标题, |
| 3217 | 底下是紧凑行。规则(传递/对称)并进标题——它对整组都成立, |
| 3218 | 挂在每一行上是重复,而且那个 `--u-warn` 琥珀色又是一处 |
| 3219 | 与派生边抢色相的地方 */} |
| 3220 | {derivedGroups.map((gr) => ( |
| 3221 | <div key={gr.key} className="mb-3 last:mb-1"> |
| 3222 | <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"> |
| 3223 | {gr.direction === "in" ? ( |
| 3224 | <ArrowLeft size={10} /> |
| 3225 | ) : ( |
| 3226 | <ArrowRight size={10} /> |
| 3227 | )} |
| 3228 | <span>{gr.predicate}</span> |
| 3229 | <span className="text-neutral-600">{gr.rule}</span> |
| 3230 | {gr.rows.length > 1 && ( |
| 3231 | <span className="ml-auto text-neutral-600"> |
| 3232 | {gr.rows.length} |
| 3233 | </span> |
| 3234 | )} |
| 3235 | </div> |
| 3236 | <div> |
| 3237 | {gr.rows.map((d) => { |
| 3238 | const out = d.subject_id === entityId; |
| 3239 | return ( |
| 3240 | <DerivedRow |
| 3241 | key={d.id} |
| 3242 | kbId={kbId} |
| 3243 | d={d} |
| 3244 | otherId={out ? d.object_id : d.subject_id} |
| 3245 | otherName={out ? d.object : d.subject} |
| 3246 | open={openFact === d.id} |
| 3247 | onToggle={() => |
| 3248 | setOpenFact(openFact === d.id ? null : d.id) |
| 3249 | } |
| 3250 | onNavigate={onNavigate} |
| 3251 | /> |
| 3252 | ); |
| 3253 | })} |
| 3254 | </div> |
| 3255 | </div> |
| 3256 | ))} |
| 3257 | {blocked.length > 0 && ( |
| 3258 | <div className="mb-3 last:mb-1"> |
| 3259 | <div className="flex items-center gap-1.5 px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-[var(--u-contest)]"> |
| 3260 | <span>{S.graph.blockedTitle}</span> |
| 3261 | <span className="ml-auto text-neutral-600"> |
| 3262 | {blocked.length} |
| 3263 | </span> |
| 3264 | </div> |
| 3265 | <p className="px-2 pb-1.5 text-[11px] leading-relaxed text-neutral-500"> |
| 3266 | {S.graph.blockedHint} |
| 3267 | </p> |
| 3268 | {blocked.map((b) => ( |
| 3269 | <BlockedRow |
| 3270 | key={b.violation_id} |
| 3271 | kbId={kbId} |
| 3272 | b={b} |
| 3273 | entityId={entityId} |
| 3274 | open={openFact === b.violation_id} |
| 3275 | onToggle={() => |
| 3276 | setOpenFact( |
| 3277 | openFact === b.violation_id ? null : b.violation_id, |
| 3278 | ) |
| 3279 | } |
| 3280 | onNavigate={onNavigate} |
| 3281 | /> |
| 3282 | ))} |
| 3283 | </div> |
| 3284 | )} |
| 3285 | </> |
| 3286 | )} |
| 3287 | {view !== "history" && |
| 3288 | view !== "derived" && |
| 3289 | detail.data?.facts.length === 0 && ( |
| 3290 | <p className="text-sm text-neutral-500 p-2">{S.graph.noFacts}</p> |
| 3291 | )} |
| 3292 | </div> |
| 3293 | </div> |
| 3294 | ); |
| 3295 | } |
| 3296 | |
| 3297 | /** 年表视图:带区间的事实按起点摊开成竖直时间线;无时间的沉到底部 undated。 */ |
| 3298 | function TimelineView({ |
| 3299 | kbId, |
| 3300 | facts, |
| 3301 | openFact, |
| 3302 | onToggle, |
| 3303 | onNavigate, |
| 3304 | }: { |
| 3305 | kbId: string; |
| 3306 | facts: EntityFact[]; |
| 3307 | openFact: string | null; |
| 3308 | onToggle: (id: string) => void; |
| 3309 | onNavigate: (entityId: string) => void; |
| 3310 | }) { |
| 3311 | const dated = facts |
| 3312 | .filter((f) => f.temporal !== "eternal" && (f.valid_from || f.valid_to)) |
| 3313 | .sort((a, b) => |
| 3314 | (a.valid_from ?? a.valid_to ?? "") < (b.valid_from ?? b.valid_to ?? "") |
| 3315 | ? -1 |
| 3316 | : 1, |
| 3317 | ); |
| 3318 | const undated = facts.filter((f) => !dated.includes(f)); |
| 3319 | |
| 3320 | return ( |
| 3321 | <div className="px-2 pt-1"> |
| 3322 | <div className="relative ml-1.5 border-l border-white/15 pl-3 space-y-0.5"> |
| 3323 | {dated.map((f) => ( |
| 3324 | <div key={f.id} className="relative"> |
| 3325 | <span className="absolute -left-[17.5px] top-2.5 h-2 w-2 rounded-full bg-neutral-600 ring-2 ring-[#0f0f0f]" /> |
| 3326 | <TimelineRow |
| 3327 | kbId={kbId} |
| 3328 | fact={f} |
| 3329 | open={openFact === f.id} |
| 3330 | onToggle={() => onToggle(f.id)} |
| 3331 | onNavigate={onNavigate} |
| 3332 | /> |
| 3333 | </div> |
| 3334 | ))} |
| 3335 | {dated.length === 0 && ( |
| 3336 | <p className="py-2 text-xs text-neutral-500"> |
| 3337 | {S.graph.timelineEmpty} |
| 3338 | </p> |
| 3339 | )} |
| 3340 | </div> |
| 3341 | {undated.length > 0 && ( |
| 3342 | <div className="mt-3"> |
| 3343 | <div className="px-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600"> |
| 3344 | {S.graph.undated} |
| 3345 | </div> |
| 3346 | {undated.map((f) => ( |
| 3347 | <FactRow |
| 3348 | key={f.id} |
| 3349 | kbId={kbId} |
| 3350 | fact={f} |
| 3351 | open={openFact === f.id} |
| 3352 | onToggle={() => onToggle(f.id)} |
| 3353 | onNavigate={onNavigate} |
| 3354 | /> |
| 3355 | ))} |
| 3356 | </div> |
| 3357 | )} |
| 3358 | </div> |
| 3359 | ); |
| 3360 | } |
| 3361 | |
| 3362 | /** 年表条目:区间 + 闭合方式标记 + 开放事实的最后确认时间;点击展开证据。 */ |
| 3363 | function TimelineRow({ |
| 3364 | kbId, |
| 3365 | fact, |
| 3366 | open, |
| 3367 | onToggle, |
| 3368 | onNavigate, |
| 3369 | }: { |
| 3370 | kbId: string; |
| 3371 | fact: EntityFact; |
| 3372 | open: boolean; |
| 3373 | onToggle: () => void; |
| 3374 | onNavigate: (entityId: string) => void; |
| 3375 | }) { |
| 3376 | const interval = fmtInterval(fact); |
| 3377 | const isOpenEnded = !fact.valid_to; |
| 3378 | const literal = fmtObjectValue(fact.object_value); |
| 3379 | return ( |
| 3380 | <div |
| 3381 | className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${ |
| 3382 | fact.stale ? "opacity-55" : "" |
| 3383 | }`} |
| 3384 | title={fact.stale ? S.graph.staleFactHint : undefined} |
| 3385 | > |
| 3386 | <button onClick={onToggle} className="w-full text-left px-2 py-1.5"> |
| 3387 | <div className="flex items-center gap-1.5 u-num text-[10.5px] text-neutral-500"> |
| 3388 | {interval || "—"} |
| 3389 | {fact.corrected && ( |
| 3390 | <span className="text-neutral-600" title={S.graph.correctedHint}> |
| 3391 | ⟲ |
| 3392 | </span> |
| 3393 | )} |
| 3394 | {isOpenEnded && fact.last_evidence_time && ( |
| 3395 | <span className="ml-auto text-neutral-600"> |
| 3396 | {S.graph.lastConfirmed(fact.last_evidence_time.slice(0, 10))} |
| 3397 | </span> |
| 3398 | )} |
| 3399 | </div> |
| 3400 | <div className="mt-0.5 flex items-center gap-1.5 text-[13px] text-neutral-200"> |
| 3401 | <span className="text-neutral-500 text-xs"> |
| 3402 | {fact.direction === "in" ? "←" : "→"}{" "} |
| 3403 | <span |
| 3404 | className={ |
| 3405 | fact.predicate_label === null |
| 3406 | ? "italic text-neutral-600" |
| 3407 | : undefined |
| 3408 | } |
| 3409 | title={ |
| 3410 | fact.predicate_label && fact.inferred |
| 3411 | ? S.graph.inferredPredicate |
| 3412 | : undefined |
| 3413 | } |
| 3414 | > |
| 3415 | {fact.predicate_label ?? S.graph.unknownPredicate} |
| 3416 | </span> |
| 3417 | </span> |
| 3418 | {fact.other_id ? ( |
| 3419 | <span |
| 3420 | role="link" |
| 3421 | tabIndex={0} |
| 3422 | onClick={(ev) => { |
| 3423 | ev.stopPropagation(); |
| 3424 | onNavigate(fact.other_id!); |
| 3425 | }} |
| 3426 | onKeyDown={(ev) => { |
| 3427 | if (ev.key === "Enter") { |
| 3428 | ev.stopPropagation(); |
| 3429 | onNavigate(fact.other_id!); |
| 3430 | } |
| 3431 | }} |
| 3432 | className="truncate hover:text-white hover:underline underline-offset-2 decoration-white/30" |
| 3433 | > |
| 3434 | {fact.other_name ?? "?"} |
| 3435 | </span> |
| 3436 | ) : ( |
| 3437 | <span className="truncate"> |
| 3438 | {fact.other_name ?? literal ?? "?"} |
| 3439 | </span> |
| 3440 | )} |
| 3441 | {fact.stale && ( |
| 3442 | <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5"> |
| 3443 | {S.graph.staleFactChip} |
| 3444 | </span> |
| 3445 | )} |
| 3446 | {fact.contested && ( |
| 3447 | <ContestedChip kbId={kbId} c={fact.contested} /> |
| 3448 | )} |
| 3449 | </div> |
| 3450 | </button> |
| 3451 | {open && <EvidenceList kbId={kbId} fact={fact} />} |
| 3452 | </div> |
| 3453 | ); |
| 3454 | } |
| 3455 | |
| 3456 | /** 字面值宾语的显示:属性 {value,unit} / 问数映射 {summary} / 其他 JSON 兜底。 */ |
| 3457 | function fmtObjectValue(v: Record<string, unknown> | null): string | null { |
| 3458 | if (!v) return null; |
| 3459 | if (v.value !== undefined) { |
| 3460 | const val = |
| 3461 | typeof v.value === "boolean" ? (v.value ? "✓" : "✗") : String(v.value); |
| 3462 | return typeof v.unit === "string" && v.unit ? `${val} ${v.unit}` : val; |
| 3463 | } |
| 3464 | if (typeof v.summary === "string") return v.summary; |
| 3465 | return JSON.stringify(v); |
| 3466 | } |
| 3467 | |
| 3468 | function FactRow({ |
| 3469 | kbId, |
| 3470 | fact, |
| 3471 | open, |
| 3472 | onToggle, |
| 3473 | onNavigate, |
| 3474 | }: { |
| 3475 | kbId: string; |
| 3476 | fact: EntityFact; |
| 3477 | open: boolean; |
| 3478 | onToggle: () => void; |
| 3479 | onNavigate: (entityId: string) => void; |
| 3480 | }) { |
| 3481 | const interval = fmtInterval(fact); |
| 3482 | // 与 Review 的低置信口径一致:只有低到需要怀疑才挂 chip,常规置信保持沉默 |
| 3483 | const lowConfidence = fact.confidence < 0.75; |
| 3484 | |
| 3485 | return ( |
| 3486 | <div |
| 3487 | className={`rounded-lg transition-colors ${open ? "bg-white/[0.05]" : "hover:bg-white/[0.04]"} ${ |
| 3488 | fact.stale ? "opacity-55" : "" |
| 3489 | }`} |
| 3490 | title={fact.stale ? S.graph.staleFactHint : undefined} |
| 3491 | > |
| 3492 | <button |
| 3493 | onClick={onToggle} |
| 3494 | className="w-full text-left px-2 py-1.5 flex items-center gap-1.5" |
| 3495 | > |
| 3496 | <ChevronRight |
| 3497 | size={11} |
| 3498 | className={`shrink-0 text-neutral-600 transition-transform ${open ? "rotate-90" : ""}`} |
| 3499 | /> |
| 3500 | {fact.other_id ? ( |
| 3501 | <span |
| 3502 | role="link" |
| 3503 | tabIndex={0} |
| 3504 | onClick={(ev) => { |
| 3505 | ev.stopPropagation(); |
| 3506 | onNavigate(fact.other_id!); |
| 3507 | }} |
| 3508 | onKeyDown={(ev) => { |
| 3509 | if (ev.key === "Enter") { |
| 3510 | ev.stopPropagation(); |
| 3511 | onNavigate(fact.other_id!); |
| 3512 | } |
| 3513 | }} |
| 3514 | className="truncate text-[13px] text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30" |
| 3515 | > |
| 3516 | {fact.other_name ?? "?"} |
| 3517 | </span> |
| 3518 | ) : ( |
| 3519 | <span className="truncate text-[13px] text-neutral-200"> |
| 3520 | {fact.other_name ?? fmtObjectValue(fact.object_value) ?? "?"} |
| 3521 | </span> |
| 3522 | )} |
| 3523 | {lowConfidence && ( |
| 3524 | <span className="shrink-0 u-num u-meta-warn text-[10.5px]"> |
| 3525 | {Math.round(fact.confidence * 100)}% |
| 3526 | </span> |
| 3527 | )} |
| 3528 | {fact.stale && ( |
| 3529 | <span className="u-chip u-chip-neutral shrink-0 !text-[10px] !px-1.5"> |
| 3530 | {S.graph.staleFactChip} |
| 3531 | </span> |
| 3532 | )} |
| 3533 | {fact.contested && <ContestedChip kbId={kbId} c={fact.contested} />} |
| 3534 | {interval && ( |
| 3535 | <span className="ml-auto shrink-0 pl-2 u-num text-[10.5px] text-neutral-500"> |
| 3536 | {interval} |
| 3537 | </span> |
| 3538 | )} |
| 3539 | </button> |
| 3540 | {open && <EvidenceList kbId={kbId} fact={fact} />} |
| 3541 | </div> |
| 3542 | ); |
| 3543 | } |
| 3544 | |
| 3545 | /** 证据展开区(FactRow 与 TimelineRow 共用):quote + 跳原文 + 版本角标 + 置信。 */ |
| 3546 | function EvidenceList({ kbId, fact }: { kbId: string; fact: EntityFact }) { |
| 3547 | const evidence = useQuery({ |
| 3548 | queryKey: ["evidence", fact.id], |
| 3549 | queryFn: () => api.factEvidence(kbId, fact.id), |
| 3550 | }); |
| 3551 | return ( |
| 3552 | <div className="mx-2 mb-2 mt-0.5 space-y-2 border-l border-white/15 pl-2.5"> |
| 3553 | {evidence.data?.evidence.map((ev: Evidence) => ( |
| 3554 | <Link |
| 3555 | key={ev.chunk_id} |
| 3556 | to="/kb/$kbId/doc/$docId" |
| 3557 | params={{ kbId, docId: ev.document_id }} |
| 3558 | search={{ chunk: ev.chunk_id }} |
| 3559 | className="block text-xs text-neutral-500 hover:text-neutral-300" |
| 3560 | > |
| 3561 | {/* 原文说的谓词,只在它与事实行上显示的不同时才写出来。本体外的谓词 |
| 3562 | 事实行上已经显示原文说法(0052),相同的话再写一遍是噪声; |
| 3563 | 一条事实有多种说法时(占 3%)这里才有话说 */} |
| 3564 | {ev.proposed_predicate && |
| 3565 | ev.proposed_predicate !== fact.predicate_key && ( |
| 3566 | <div className="mb-0.5 text-[11px] text-neutral-400"> |
| 3567 | {S.graph.proposedPredicate(ev.proposed_predicate)} |
| 3568 | </div> |
| 3569 | )} |
| 3570 | <div className="line-clamp-2 italic"> |
| 3571 | {ev.quote ? `“${ev.quote}”` : S.graph.noQuote} |
| 3572 | </div> |
| 3573 | <div className="mt-0.5 text-neutral-400"> |
| 3574 | {S.graph.sectionRef(ev.filename, ev.seq + 1)} |
| 3575 | {ev.stale && ( |
| 3576 | <span |
| 3577 | className="ml-1.5 u-num text-[10px] text-neutral-600" |
| 3578 | title={S.graph.staleEvidenceHint} |
| 3579 | > |
| 3580 | {S.graph.fromVersion(ev.doc_version)} |
| 3581 | </span> |
| 3582 | )} |
| 3583 | </div> |
| 3584 | </Link> |
| 3585 | ))} |
| 3586 | {evidence.data?.evidence.length === 0 && ( |
| 3587 | <p className="text-xs text-neutral-500">{S.graph.noEvidence}</p> |
| 3588 | )} |
| 3589 | {/* 置信度只在低到值得怀疑时说话(与 Review 低置信口径一致),常规不标 */} |
| 3590 | {fact.confidence < 0.75 && ( |
| 3591 | <p className="text-[10px] text-[var(--u-warn)]"> |
| 3592 | {Math.round(fact.confidence * 100)}% {S.graph.confidence} |
| 3593 | </p> |
| 3594 | )} |
| 3595 | </div> |
| 3596 | ); |
| 3597 | } |