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