Elffuss BraidHub

kikocis/utopia public

Make the graph page read correctly (#149)
Changeset74eba708a4a32565a769eccb862cf2b2a397e1b17b8bd1d6f684e4cb5c686c0f
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-01 03:53 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-01 03:53 +08:00
Parentsfc2336f545ac

Browse the files at this changeset

28 files changed

modified README.md +1 −0
@@ -97,6 +97,7 @@
9797 - [ ] **Execution gate**: every downstream call an agent makes passes ontology rules and symbolic logic first; what fails does not land
9898 - [ ] **Lakehouse**: Iceberg / Delta Lake, plus Databricks, Snowflake and MaxCompute
9999 - [ ] **More sources**: MySQL, ClickHouse and Doris drivers; S3, WebDAV, Notion and Feishu connectors
100+- [ ] **Time to the moment**: an `instant` precision beside year / month / day, for sources that carry a real timestamp — today a connector rounds it to a UTC day, which can shift an event across midnight by one day
100101 - [ ] **Agent memory over MCP**: episode writes, the retrieve endpoint, and the MCP server
101102 - [ ] **Enterprise**: OIDC SSO, backup and restore commands, benchmarks at 100k documents
102103
modified README.zh-CN.md +1 −0
@@ -98,6 +98,7 @@
9898 - [ ] **执行校验层**:Agent 的每一次调用先过本体规则与符号逻辑,通不过不落地
9999 - [ ] **数据湖仓**:Iceberg / Delta Lake,以及 Databricks、Snowflake、MaxCompute
100100 - [ ] **更多数据源**:MySQL、ClickHouse、Doris 驱动,S3、WebDAV、Notion、飞书连接器
101+- [ ] **精确到时刻**:在年 / 月 / 日之外加一档 `instant` 精度,给那些本来就带时间戳的来源——现在连接器按 UTC 截到天,跨午夜的事件会差一天
101102 - [ ] **MCP 上的 Agent 记忆**:补齐 episodes 写入、retrieve 端点与 MCP 服务器
102103 - [ ] **企业化**:OIDC SSO、备份恢复命令、10 万文档级别的性能基准
103104
modified crates/utopia-server/src/api/graph_routes.rs +14 −2
@@ -32,14 +32,22 @@
3232 .map_err(|_| AppError::Validation("Invalid `at` (expected YYYY-MM-DD or RFC3339)".into()))
3333 }
3434
35-/// 总览一次画多少个节点。**上限本身是合理的**——画一万个点没人看得懂;
35+/// 总览一次画多少个节点的**默认值**。上限本身是合理的——画一万个点没人看得懂;
3636 /// 骗人的是把它当成规模显示,所以接口同时回总数
3737 const GRAPH_NODE_CAP: i64 = 150;
38+/// 调得再高也得有个天花板。**这个数不是拍的**:节点按度数降序取,越往后越是
39+/// 边缘节点,而力导布局是 O(n²) 量级的——超过这个数,先垮的是「拖得动」
40+/// 而不是「看得清」。要真看上万个点,那是另一种视图,不是把这个调大
41+const GRAPH_NODE_CAP_MAX: i64 = 1000;
3842
3943 #[derive(Deserialize)]
4044 pub struct OverviewQuery {
4145 #[serde(default)]
4246 pub at: Option<String>,
47+ /// 画多少个。不给就用默认值;给了也钳在 [10, GRAPH_NODE_CAP_MAX]——
48+ /// 界面上的按钮只给几档,但接口是公开的,别让一个 `limit=999999` 把库拖垮
49+ #[serde(default)]
50+ pub limit: Option<i64>,
4351 }
4452
4553 pub async fn overview(
@@ -52,8 +60,12 @@
5260 let at = parse_at(q.at.as_deref())?;
5361 // 画多少个是渲染的事,库里有多少是知识库的事——两个数都回,界面才说得出
5462 // 「画了 150 个,共 325 个」而不是把上限说成规模
63+ let limit = q
64+ .limit
65+ .unwrap_or(GRAPH_NODE_CAP)
66+ .clamp(10, GRAPH_NODE_CAP_MAX);
5567 let (nodes, edges, total_nodes, total_edges) =
56- utopia_store::graph::overview(&state.pool, kb_id, GRAPH_NODE_CAP, at).await?;
68+ utopia_store::graph::overview(&state.pool, kb_id, limit, at).await?;
5769 Ok(Json(json!({
5870 "nodes": nodes, "edges": edges,
5971 "total_nodes": total_nodes, "total_edges": total_edges,
modified docs/decisions/0013-a-source-should-hand-over-its-history.md +26 −0
@@ -101,6 +101,32 @@
101101 与 #108「部分抽取报告成完成」、#127「一条坏记录不该毁掉一整块」同一条原则:
102102 **限了覆盖面就要说出来**。
103103
104+## 已知取舍:时刻被截成了日期
105+
106+连接器把时间戳写进正文时是 `created_at.format("%Y-%m-%d")`——**按 UTC 截到天**。
107+抽取器从 "Opened by X on 2026-08-18." 这句话里读出的 `valid_from` 因此是
108+day 精度,时刻在入库前就没了。
109+
110+**代价说清楚**:跨 UTC 午夜的事件会差一天。一个 UTC+8 的人在 8 月 19 日
111+早上七点开的 issue,GitHub 界面上写着 8-19,我们的文档里写的是 8-18。
112+
113+**为什么仍然接受**:
114+
115+- 它没有真的丢。源头原样还在,而两个连接器都是**幂等可重同步**的——
116+ 真要精确到时刻,重同步一次就能拿回来。这与"不可逆丢失"差一个量级。
117+- 精度模型本来就在说实话。`precision = day` 的含义正是"知道哪天、不知哪刻",
118+ day 精度的日期存成 UTC 午夜、按 UTC 渲染,是自洽的。**真正的错是假装知道**。
119+- 这产品目前不问"几点"。它回答"某个时刻世界是什么样",粒度到天。
120+
121+**什么时候该回头做**:有人要按"当地营业日"统计,或者接了一个事件天然聚在
122+午夜附近的源(交接班、开盘收盘)。那时 day 精度不够,才值得加一档 `instant`
123+精度——连带 CHECK 约束、抽取提示词、渲染分支一起改。
124+
125+顺带记一条同源的规矩,它已经落在代码里:**世界时间与记录时间的时区待遇相反**。
126+`valid_from`/`valid_to` 来自文档里的陈述,是日历日期不是时刻,一律按 UTC 渲染
127+(转本地会让 UTC-5 的读者看到前一天);`recorded_at` 这类"我们何时这么认为"
128+是真实时刻,按看的人的时区渲染。这两处**故意不一样,别统一**。
129+
104130 ## 为什么没有抽象成 `issues` + provider
105131
106132 接第二个供应商正是为了看清该不该抽象。答案是**暂时不该**:取法根本不同
modified web/src/api.ts +4 −2
@@ -1174,7 +1174,7 @@
11741174 method: "PUT",
11751175 body: JSON.stringify(body),
11761176 }),
1177- graphOverview: (kbId: string) =>
1177+ graphOverview: (kbId: string, limit?: number) =>
11781178 request<{
11791179 nodes: GraphNode[];
11801180 edges: GraphEdge[];
@@ -1182,7 +1182,9 @@
11821182 * 那一批,把上限当成规模显示是这个接口从前最误导人的地方 */
11831183 total_nodes?: number;
11841184 total_edges?: number;
1185- }>(`/api/v1/kbs/${kbId}/graph/overview`),
1185+ }>(
1186+ `/api/v1/kbs/${kbId}/graph/overview${limit ? `?limit=${limit}` : ""}`,
1187+ ),
11861188 /** 邻域视图**没有总数**:它本来就只是一小片,说「共 325 个」没有意义。
11871189 * 两个字段声明成可选,好让调用方与总览共用一个类型 */
11881190 graphNeighborhood: (kbId: string, entityId: string) =>
modified web/src/i18n/en.ts +37 −4
@@ -163,6 +163,15 @@
163163 unknownKind: (kind: string) => kind,
164164 },
165165
166+ kbScope: {
167+ deniedTitle: "You don't have access to this knowledge base",
168+ deniedBody:
169+ "The link points at a base you can't open. Ask whoever shared it to grant you access, or pick one of your own.",
170+ missingTitle: "This knowledge base is gone",
171+ missingBody:
172+ "It was deleted, or the link was mistyped. Your own bases are listed below.",
173+ myKbs: "My knowledge bases",
174+ },
166175 nav: {
167176 workspaceLabel: "Workspace",
168177 kbLabel: "Knowledge base",
@@ -547,6 +556,16 @@
547556 graph: {
548557 // 还没判出类型的实体(0009)。不是一个类,是"这一格还空着"
549558 untyped: "Untyped",
559+ legendMore: (n: number) => `All ${n} classes`,
560+ nodeBudget: "How many entities to draw",
561+ nodeBudgetMore: "Draw more",
562+ nodeBudgetLess: "Draw fewer",
563+ legendSearch: "Filter classes",
564+ legendNone: "No class matches",
565+ legendOnly: "Only",
566+ legendShowAll: (n: number) => `Show all (${n} hidden)`,
567+ legendAllHint:
568+ "Every class on screen, most common first. Click to show or hide.",
550569 searchMore: (n: number) => `${n} more — load 20`,
551570 zoomIn: "Zoom in",
552571 zoomOut: "Zoom out",
@@ -615,6 +634,9 @@
615634 "Edges no one asserted — the engine worked them out from axioms your ontology declares. Each one shows the premises it came from.",
616635 derivedNoProof: "The premises are gone.",
617636 derivedPanel: "Inference",
637+ derivedRunAsk: "Re-run inference for the whole base?",
638+ derivedRunGo: "Run",
639+ derivedRunCancel: "Cancel",
618640 derivedCountLabel: "Edges derived",
619641 derivedStateLabel: "Schedule",
620642 derivedLastLabel: "Last run",
@@ -665,15 +687,26 @@
665687 /* 必须跟 ongoing 看得出区别:混淆这两个正是迁移 0046 要修的东西——
666688 原文说 "former CEO",界面却显示 now */
667689 endedUnknown: "ended, date unknown",
668- stats: (n: number, e: number, active: number) =>
669- `${n} entities · ${e} facts · ${active} active`,
690+ stats: (n: number, e: number, active: number | null) =>
691+ `${n} entities · ${e} facts${active === null ? "" : ` · ${active} active`}`,
670692 /** 画布只画度数最高的一批。**说清楚画了多少、共多少**——从前这里写的是
671693 * 上限,一个上万实体的库右上角永远是 150 */
672- statsCapped: (shown: number, total: number, e: number, active: number) =>
673- `showing ${shown} of ${total} entities · ${e} facts · ${active} active`,
694+ statsCapped: (
695+ shown: number,
696+ total: number,
697+ shownE: number,
698+ totalE: number,
699+ active: number | null,
700+ ) =>
701+ `showing ${shown} of ${total} entities · ${shownE} of ${totalE} facts${active === null ? "" : ` · ${active} active`}`,
674702 cappedHint: (shown: number, total: number) =>
675703 `The canvas draws the ${shown} best-connected entities of ${total}. Search to reach the rest.`,
676704 stabilizing: "Stabilizing layout",
705+ scrubUnitHint: "Step size for playback and for each bar",
706+ scrubUnitYear: "Yr",
707+ scrubUnitMonth: "Mo",
708+ scrubUnitDay: "Dy",
709+ scrubBarMerged: (n: number) => `each bar covers ${n} steps`,
677710 allTime: "All time",
678711 nowBtn: "Now",
679712 play: "Play timeline",
modified web/src/i18n/zh.ts +35 −4
@@ -144,6 +144,14 @@
144144 unknownKind: (kind: string) => kind,
145145 },
146146
147+ kbScope: {
148+ deniedTitle: "你没有这个知识库的权限",
149+ deniedBody:
150+ "链接指向的库你打不开。找分享给你的人开通权限,或者回到自己的库。",
151+ missingTitle: "这个知识库不在了",
152+ missingBody: "它已被删除,或者链接抄错了。下面是你自己的库。",
153+ myKbs: "我的知识库",
154+ },
147155 nav: {
148156 workspaceLabel: "工作区",
149157 kbLabel: "知识库",
@@ -512,6 +520,15 @@
512520 },
513521 graph: {
514522 untyped: "未分类",
523+ legendMore: (n: number) => `全部 ${n} 个类`,
524+ nodeBudget: "画多少个实体",
525+ nodeBudgetMore: "多画一些",
526+ nodeBudgetLess: "少画一些",
527+ legendSearch: "筛选类",
528+ legendNone: "没有匹配的类",
529+ legendOnly: "只看",
530+ legendShowAll: (n: number) => `显示全部(隐藏了 ${n} 个)`,
531+ legendAllHint: "画面上的全部类,按出现次数排。点一下显示或隐藏。",
515532 searchMore: (n: number) => `还有 ${n} 个——再加载 20`,
516533 zoomIn: "放大",
517534 zoomOut: "缩小",
@@ -566,6 +583,9 @@
566583 "没有人断言过的边——引擎按本体声明的公理推出来的。每一条都附着它用到的前提。",
567584 derivedNoProof: "前提已经不在了。",
568585 derivedPanel: "推理",
586+ derivedRunAsk: "对整个库重跑一遍推理?",
587+ derivedRunGo: "跑",
588+ derivedRunCancel: "取消",
569589 derivedCountLabel: "推出来的边",
570590 derivedStateLabel: "定时",
571591 derivedLastLabel: "上次推理",
@@ -610,13 +630,24 @@
610630 "被取代的那条断言仍留在台账里。",
611631 ongoing: "至今",
612632 endedUnknown: "已结束(时间不详)",
613- stats: (n: number, e: number, active: number) =>
614- `${n} 个实体 · ${e} 条事实 · ${active} 条现行`,
615- statsCapped: (shown: number, total: number, e: number, active: number) =>
616- `已画 ${shown} / 共 ${total} 个实体 · ${e} 条事实 · ${active} 条现行`,
633+ stats: (n: number, e: number, active: number | null) =>
634+ `${n} 个实体 · ${e} 条事实${active === null ? "" : ` · ${active} 条现行`}`,
635+ statsCapped: (
636+ shown: number,
637+ total: number,
638+ shownE: number,
639+ totalE: number,
640+ active: number | null,
641+ ) =>
642+ `已画 ${shown} / 共 ${total} 个实体 · ${shownE} / 共 ${totalE} 条事实${active === null ? "" : ` · ${active} 条现行`}`,
617643 cappedHint: (shown: number, total: number) =>
618644 `画布只画连接最密的 ${shown} 个,库里共 ${total} 个。其余的用搜索找。`,
619645 stabilizing: "布局收敛中",
646+ scrubUnitHint: "播放的步长,也是每根柱子的跨度",
647+ scrubUnitYear: "年",
648+ scrubUnitMonth: "月",
649+ scrubUnitDay: "日",
650+ scrubBarMerged: (n: number) => `每根柱子含 ${n} 步`,
620651 allTime: "全部时间",
621652 nowBtn: "现在",
622653 play: "播放时间线",
modified web/src/kb.tsx +17 −1
@@ -1,9 +1,19 @@
11 // 当前工作区/知识库上下文:均可切换且 localStorage 记忆;工作区无 KB 时自动创建 "General"。
22 import { useSyncExternalStore } from "react";
3+import { useParams } from "@tanstack/react-router";
34 import { useQuery, useQueryClient } from "@tanstack/react-query";
45 import { api, type Kb, type Workspace } from "./api";
56 import { kbStore, wsStore } from "./wsStore";
67
8+/** 当前路径里的知识库 id。**页面都在 /kb/$kbId 之下,所以直接从路径取**——
9+ * 不必等库列表加载完,链接里写的是谁就是谁。不在作用域内(账户页等)时
10+ * 回落到记忆里的那个。 */
11+export function useKbId(): string {
12+ const params = useParams({ strict: false }) as { kbId?: string };
13+ const { kb } = useKb();
14+ return params.kbId ?? kb?.id ?? "";
15+}
16+
717 export function useKb(): {
818 kb: Kb | null;
919 kbs: Kb[];
@@ -39,7 +49,13 @@
3949 });
4050
4151 const kbList = kbs.data ?? [];
42- const kb = kbList.find((k) => k.id === selectedKbId) ?? kbList[0] ?? null;
52+ /* **URL 里有就以 URL 为准**:两者回答的不是同一个问题——地址栏说的是
53+ "这个链接指向什么",localStorage 说的是"我上次在看什么"。
54+ 别人分享的链接必须赢过我自己的记忆,否则打开看到的是我的库、
55+ 数据不同而界面一模一样 */
56+ const routeParams = useParams({ strict: false }) as { kbId?: string };
57+ const wantedKbId = routeParams.kbId ?? selectedKbId;
58+ const kb = kbList.find((k) => k.id === wantedKbId) ?? kbList[0] ?? null;
4359
4460 return {
4561 kb,
modified web/src/pages/AccountShell.tsx +1 −1
@@ -43,7 +43,7 @@
4343 <SectionMark text={S.account.brand} title={S.docs.backTitle} />
4444 <div className="ml-auto flex items-center gap-1.5">
4545 <Link
46- to="/graph"
46+ to="/"
4747 className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
4848 >
4949 {S.account.backToApp}
modified web/src/pages/Chat.tsx +16 −11
@@ -33,7 +33,7 @@
3333 } from "../api";
3434 import { S } from "../i18n";
3535 import { toast } from "../toast";
36-import { useKb } from "../kb";
36+import { useKb, useKbId } from "../kb";
3737 import { DangerConfirm, RAIL_CLS } from "../ui";
3838
3939 interface Turn {
@@ -49,6 +49,7 @@
4949 const DRAFT_KEY = "chat:draft";
5050
5151 export function Chat() {
52+ const kbId = useKbId();
5253 const { kb, kbs, setKb } = useKb();
5354 const queryClient = useQueryClient();
5455 const navigate = useNavigate();
@@ -126,7 +127,7 @@
126127 activeIdRef.current = null;
127128 setActiveId(null);
128129 setTurns([]);
129- navigate({ to: "/chat", replace: true });
130+ navigate({ to: "/kb/$kbId/chat", params: { kbId }, replace: true });
130131 }
131132 // eslint-disable-next-line react-hooks/exhaustive-deps
132133 }, [kb?.id]);
@@ -138,8 +139,8 @@
138139 const last = sessionStorage.getItem(lastKey(kb.id));
139140 if (last) {
140141 navigate({
141- to: "/chat/$conversationId",
142- params: { conversationId: last },
142+ to: "/kb/$kbId/chat/$conversationId",
143+ params: { kbId, conversationId: last },
143144 replace: true,
144145 });
145146 }
@@ -164,7 +165,10 @@
164165
165166 /** 列表点击只改 URL,装载由路由同步 effect 负责 */
166167 const openConversation = (id: string) =>
167- navigate({ to: "/chat/$conversationId", params: { conversationId: id } });
168+ navigate({
169+ to: "/kb/$kbId/chat/$conversationId",
170+ params: { kbId, conversationId: id },
171+ });
168172
169173 const loadConversation = async (id: string) => {
170174 if (streaming) abortRef.current?.();
@@ -188,7 +192,7 @@
188192 activeIdRef.current = null;
189193 setActiveId(null);
190194 setTurns([]);
191- navigate({ to: "/chat", replace: true });
195+ navigate({ to: "/kb/$kbId/chat", params: { kbId }, replace: true });
192196 }
193197 };
194198
@@ -199,7 +203,7 @@
199203 activeIdRef.current = null;
200204 setActiveId(null);
201205 setTurns([]);
202- navigate({ to: "/chat" });
206+ navigate({ to: "/kb/$kbId/chat", params: { kbId } });
203207 inputRef.current?.focus();
204208 };
205209
@@ -231,8 +235,8 @@
231235 setActiveId(id);
232236 sessionStorage.setItem(lastKey(kb.id), id);
233237 navigate({
234- to: "/chat/$conversationId",
235- params: { conversationId: id },
238+ to: "/kb/$kbId/chat/$conversationId",
239+ params: { kbId, conversationId: id },
236240 replace: true,
237241 });
238242 invalidateList();
@@ -580,6 +584,7 @@
580584 }
581585
582586 function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
587+ const kbId = useKbId();
583588 if (turn.role === "user") {
584589 return (
585590 <div className="flex justify-end">
@@ -646,8 +651,8 @@
646651 ) : (
647652 <Link
648653 key={s.n}
649- to="/doc/$docId"
650- params={{ docId: s.document_id! }}
654+ to="/kb/$kbId/doc/$docId"
655+ params={{ kbId, docId: s.document_id! }}
651656 search={{ chunk: s.chunk_id }}
652657 title={s.excerpt}
653658 className="block text-xs text-neutral-500 glass rounded-lg px-3 py-1.5 glass-hover hover:text-neutral-300"
modified web/src/pages/DocViewer.tsx +10 −6
@@ -3,6 +3,7 @@
33 import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
44 import { api, type ChunkFact } from "../api";
55 import { S } from "../i18n";
6+import { useKbId } from "../kb";
67 import { Pager, pageSlice } from "../ui";
78 import { SourcesRail } from "./SourcesRail";
89
@@ -16,8 +17,9 @@
1617 }
1718
1819 export function DocViewer() {
19- const { docId } = useParams({ from: "/app/doc/$docId" });
20- const { chunk } = useSearch({ from: "/app/doc/$docId" });
20+ const kbId = useKbId();
21+ const { docId } = useParams({ from: "/app/kb/$kbId/doc/$docId" });
22+ const { chunk } = useSearch({ from: "/app/kb/$kbId/doc/$docId" });
2123 const navigate = useNavigate();
2224
2325 const detail = useQuery({
@@ -75,7 +77,7 @@
7577 <SourcesRail
7678 kbId={doc.kb_id}
7779 active={doc.source_id ?? "uploads"}
78- onSelect={(sel) => navigate({ to: "/library", search: { src: sel } })}
80+ onSelect={(sel) => navigate({ to: "/kb/$kbId/library", params: { kbId }, search: { src: sel } })}
7981 />
8082 <div className="flex-1 min-w-0 overflow-y-auto u-scroll">
8183 <div className="max-w-4xl mx-auto p-6">
@@ -87,7 +89,7 @@
8789 {new Date(doc.created_at).toLocaleDateString()}
8890 </p>
8991 </div>
90- <Link to="/library" className="shrink-0 text-sm text-[var(--u-accent)] hover:underline">
92+ <Link to="/kb/$kbId/library" params={{ kbId }} className="shrink-0 text-sm text-[var(--u-accent)] hover:underline">
9193 {S.doc.backToLibrary}
9294 </Link>
9395 </div>
@@ -131,7 +133,8 @@
131133 <div key={f.fact_id} className="text-xs leading-snug">
132134 <div>
133135 <Link
134- to="/graph"
136+ to="/kb/$kbId/graph"
137+ params={{ kbId }}
135138 search={{ entity: f.subject_id }}
136139 className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
137140 >
@@ -154,7 +157,8 @@
154157 </span>
155158 {f.object_id ? (
156159 <Link
157- to="/graph"
160+ to="/kb/$kbId/graph"
161+ params={{ kbId }}
158162 search={{ entity: f.object_id }}
159163 className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
160164 >
modified web/src/pages/Docs.tsx +1 −1
@@ -225,7 +225,7 @@
225225 {/* 右侧:显式返回(与字标双路回城)+ GitHub·版本胶囊 + 登录态 */}
226226 <div className="ml-auto flex items-center gap-1.5">
227227 <Link
228- to="/graph"
228+ to="/"
229229 className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
230230 >
231231 {S.account.backToApp}
modified web/src/pages/EntityHistory.tsx +20 −3
@@ -8,6 +8,7 @@
88 import { FileText, Merge, PencilLine, Tag, Undo2 } from "lucide-react";
99 import { api, type EntityHistoryEvent } from "../api";
1010 import { S } from "../i18n";
11+import { useKbId } from "../kb";
1112 import { Pager } from "../ui";
1213
1314 const PER = 20;
@@ -33,7 +34,22 @@
3334 retype_reverted: "text-[var(--u-warn)]",
3435 };
3536
36-const ymd = (iso: string) => iso.slice(0, 10);
37+/* 这两个函数**故意不一样**,别"统一一下"——它们渲染的是两种时间。
38+
39+ `ymd` 给的是**记录时刻**(我们何时这么认为):那是一个真实时刻,
40+ 该按看的人所在的时区显示。从前这里也是切 ISO 字符串,等于按 UTC 显示——
41+ UTC+8 的人在早上八点前做的修订,历史里会显示成前一天。
42+
43+ `ym` 给的是**世界时间**(这件事何时成立):它来自文档里的陈述
44+ ("2019 年 5 月就任"),是**日历日期不是时刻**,本来就没有时区。
45+ 切 ISO 字符串正是按 UTC 读回存进去的那一天;转成本地反而会让
46+ UTC-5 的读者看到前一个月。 */
47+const ymd = (iso: string) => {
48+ const d = new Date(iso);
49+ const m = String(d.getMonth() + 1).padStart(2, "0");
50+ const day = String(d.getDate()).padStart(2, "0");
51+ return `${d.getFullYear()}-${m}-${day}`;
52+};
3753 const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
3854
3955 /** 宾语:实体名优先,其次字面值(属性事实)的摘要/值 */
@@ -57,6 +73,7 @@
5773 }
5874
5975 function EventRow({ e }: { e: EntityHistoryEvent }) {
76+ const kbId = useKbId();
6077 const Icon = KIND_ICON[e.kind] ?? FileText;
6178 const note = intervalNote(e);
6279 return (
@@ -99,8 +116,8 @@
99116 <>
100117 <span>·</span>
101118 <Link
102- to="/doc/$docId"
103- params={{ docId: e.document_id }}
119+ to="/kb/$kbId/doc/$docId"
120+ params={{ kbId, docId: e.document_id }}
104121 search={{}}
105122 className="truncate hover:text-neutral-300"
106123 title={e.quote ?? e.filename}
modified web/src/pages/Graph.tsx +1040 −173
@@ -1,6 +1,6 @@
11 import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3-import { Link, useSearch } from "@tanstack/react-router";
3+import { Link, useNavigate, useSearch } from "@tanstack/react-router";
44 import Graphology from "graphology";
55 import { circular, circlepack } from "graphology-layout";
66 import forceAtlas2 from "graphology-layout-forceatlas2";
@@ -15,11 +15,13 @@
1515 ChevronRight,
1616 CircleDashed,
1717 Grape,
18+ Loader2,
1819 Maximize2,
1920 Orbit,
2021 Pause,
2122 Pencil,
2223 Play,
24+ Waypoints,
2325 X,
2426 ZoomIn,
2527 ZoomOut,
@@ -33,7 +35,8 @@
3335 type GraphNode,
3436 } from "../api";
3537 import { S } from "../i18n";
36-import { useKb } from "../kb";
38+import { usePopoverFlip } from "../ui/popoverFlip";
39+import { useKb, useKbId } from "../kb";
3740 import { toast } from "../toast";
3841
3942 /* 画布调色板 —— 结构取自 Semantica GraphWorkspace 源码;基色已中性化:
@@ -44,8 +47,19 @@
4447 const NODE_BORDER_BASE = "#909090"; // 节点描边(原 #7A92AE 的中性化)
4548 const NODE_TINT_MIX = 0.14; // 类型色只按 14% 混入外壳(高级感的关键)
4649 const NODE_CORE_MIX = 0.5; // 核心向类型色的混入比例
47-const RING_SELECTED = "#E7C57C"; // 选中金环
48-const RING_HOVERED = "#8FE7FF"; // 悬停冰青环
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; // 选中:偏本色,为的是认得出
4963 const EDGE_COLOR = "rgba(163,163,163,0.2)"; // 纯灰(应用户要求,不用钢蓝)
5064 // 本体没认下的关系:同色更淡。名字来自原文,不该跟词表里的关系看着一样重
5165 const EDGE_COLOR_INFERRED = "rgba(163,163,163,0.1)";
@@ -59,17 +73,48 @@
5973 // 超过这个数就只上色不动画。**写出来而不是悄悄降级**:每帧重算几千条边的颜色,
6074 // 换来的是拖不动图,而那时候用户要的是能拖得动
6175 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];
6297 // 注意:sigma 边着色器在预乘混合(ONE, ONE_MINUS_SRC_ALPHA)下不预乘 RGB,
6398 // alpha 无法压暗边——暗度必须编码进 RGB(不透明近背景色)
6499 const EDGE_DIM = "#141414";
65100 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)";
66106 const MUTED_SHELL = "#151515";
107+/* 悬停时其余的压暗程度。**比选中轻**(选中是压到底):
108+ 悬停是随鼠标走的、每划过一个节点就换一次,压到底会让整张画布不停明灭;
109+ 而且两者压得一样重的话,"我只是路过"和"我选中了它"就成了同一个画面。
110+ 所以留一档差:压得深,但不到底——看得出焦点,也看得出这只是路过。
111+ (试过 0.55,太浅,焦点不够跳)*/
112+const HOVER_MUTE = 0.78;
67113 const PILL_BG = "rgba(12,12,12,0.9)";
68114 const PILL_BORDER = "rgba(255,255,255,0.14)";
69115 const PILL_TEXT = "#ededed";
70116 const TRANSPARENT = "rgba(0,0,0,0)";
71117 const DAY_MS = 24 * 3600 * 1000;
72-const MONTH_MS = 30 * DAY_MS;
73118
74119 function hexToRgb(hex: string): [number, number, number] {
75120 const m = /^#?([0-9a-f]{6})$/i.exec(hex);
@@ -270,11 +315,17 @@
270315 }
271316
272317 export function Graph() {
318+ const kbId = useKbId();
273319 const { kb } = useKb();
274- // 深链入口:/graph?entity=… 直接聚焦并选中该实体(证据两跳可达的反向路径)
275- const { entity: entityParam } = useSearch({ from: "/app/graph" });
320+ /* 地址栏与画面**双向**同步。
321+ 从前只有"进"这一半:`?entity=` 在挂载时读一次就再不管了——
322+ 别人给的链接能用,而你自己看到的东西却没法分享,因为地址栏一直停在
323+ 光秃秃的 /graph。 */
324+ const search = useSearch({ from: "/app/kb/$kbId/graph" });
325+ const navigate = useNavigate();
326+ const entityParam = search.entity;
276327 const [focusEntity, setFocusEntity] = useState<string | null>(
277- entityParam ?? null,
328+ search.focus ?? entityParam ?? null,
278329 );
279330 const [selected, setSelected] = useState<string | null>(entityParam ?? null);
280331 const [searchInput, setSearchInput] = useState("");
@@ -283,27 +334,115 @@
283334 // 推出来的边显不显示。默认显示——推理默认关着,有派生就意味着用户开过开关
284335 const [showDerived, setShowDerived] = useState(true);
285336 // 信息窗默认收起:它答的是「什么时候推的」,那是偶尔才问的问题
286- const [derivedPanel, setDerivedPanel] = useState(false);
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+ }, []);
287359 /** null = 全时段;数值 = as-of 时刻(ms)。
288360 默认 as-of 今天:时态平台的图谱默认呈现"现在的世界",
289361 已闭合的事实不该与现行事实无差别并列(All time 是显式选择) */
290- const [timeT, setTimeT] = useState<number | null>(() => Date.now());
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+ });
291372 const [activeCount, setActiveCount] = useState(0);
292373 const [stabilizing, setStabilizing] = useState(false);
293374 /* 播放态提升到此层:reducer 需区分"播放推进"(淡入)与"手动拖动"(瞬切) */
294375 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]);
295430 /* 布局模式:force = FA2 斥力;circular = 圆环;pack = 按类型圆填充聚簇 */
296431 type LayoutMode = "force" | "circular" | "pack";
297432 const [layoutMode, setLayoutMode] = useState<LayoutMode>("force");
298433 const layoutModeRef = useRef<LayoutMode>("force");
299434 const layoutCtlRef = useRef<{ apply: (m: LayoutMode) => void } | null>(null);
300435
436+ /* 画多少个。**进 queryKey**——不进的话调了档位不会重新取数,
437+ 界面看着变了实际还是老数据 */
438+ const [nodeBudget, setNodeBudget] = useState<number>(NODE_BUDGETS[0]);
439+
301440 const data = useQuery({
302- queryKey: ["graph", kb?.id, focusEntity],
441+ queryKey: ["graph", kb?.id, focusEntity, nodeBudget],
303442 queryFn: () =>
304443 focusEntity
305444 ? api.graphNeighborhood(kb!.id, focusEntity)
306- : api.graphOverview(kb!.id),
445+ : api.graphOverview(kb!.id, nodeBudget),
307446 enabled: !!kb,
308447 });
309448
@@ -386,22 +525,37 @@
386525 const types = useMemo(() => {
387526 const map = new Map<
388527 string,
389- { label: string; color: string; shape: string }
528+ { label: string; color: string; shape: string; count: number }
390529 >();
391530 for (const n of data.data?.nodes ?? []) {
392531 // 没判出类型的归到空 key 一档(0009)。真实 key 由 IRI 派生,不可能为空,
393532 // 所以它撞不着任何一个类;标签走 i18n,别把 null 画到图例上
394533 const key = n.type_key ?? "";
395- if (!map.has(key))
534+ const cur = map.get(key);
535+ if (cur) cur.count++;
536+ else
396537 map.set(key, {
397538 label: n.type_label ?? S.graph.untyped,
398539 color: n.color,
399540 shape: n.shape,
541+ count: 1,
400542 });
401543 }
402- return [...map.entries()];
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+ );
403550 }, [data.data]);
404551
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+
405559 // 有几条推出来的边。**为零时那个开关整个不出现**——一个没开推理的库不该
406560 // 看到一个永远切换不出任何变化的按钮
407561 const derivedCount = useMemo(
@@ -463,6 +617,96 @@
463617 sigmaRef.current?.refresh();
464618 }, [hiddenTypes, showDerived]);
465619
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+
466710 // 派生边的呼吸。**只在有派生边、且开着显示、且数量不多时才转**——
467711 // 一个没开推理的库不该为这件事每两秒重画一次
468712 useEffect(() => {
@@ -527,6 +771,10 @@
527771 let fa2Settings: ReturnType<typeof forceAtlas2.inferSettings> | null = null;
528772 if (g.order > 0) {
529773 circular.assign(g, { scale: 300 });
774+ /* 试过按规模缩放(gravity 0.12–0.22 / scalingRatio 11–16 + 加大阻尼),
775+ 拿真实的图一看就否了:散是散开了,但那种"被推开"的张力没了,
776+ 整张图显得瘫。**这一组是既有的、刻意偏大的**——要的是节点之间
777+ 互相顶着的感觉,不是最省力的排布 */
530778 const settings = {
531779 ...forceAtlas2.inferSettings(g),
532780 gravity: 0.35,
@@ -648,6 +896,8 @@
648896 const f = filterRef.current;
649897 const res = { ...attrs };
650898 const base = attrs.size as number;
899+ // 状态环取节点自己的类型色(见 RING_*_MIX 处的理由)
900+ const ownColor = (attrs.typeColor as string) ?? NODE_CORE_BASE;
651901 if (f.hiddenTypes.has(attrs.typeKey as string)) {
652902 res.hidden = true;
653903 return res;
@@ -662,15 +912,34 @@
662912 res.label = "";
663913 res.zIndex = 0;
664914 };
665- // hover 只提亮自身(不压暗全图);压暗聚焦只属于点击选中
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+ };
666934 if (hoverRef.current === node) {
667935 res.size = Math.max(base * 1.08, 10.4);
668- res.ringColor = RING_HOVERED;
936+ res.ringColor = mix(ownColor, "#ffffff", RING_HOVER_MIX);
669937 // 悬浮卡接管标签展示;label 本身保留(悬浮卡靠它渲染标题)
670938 res.hideBaseLabel = true;
671939 res.zIndex = 4;
672940 return res;
673941 }
942+ const hov = hoverRef.current;
674943 // 选中实体可能不在当前画布(侧栏跳转/邻域重载间隙)——不在则跳过聚焦压暗逻辑
675944 const sel =
676945 selectedRef.current && g.hasNode(selectedRef.current)
@@ -679,7 +948,7 @@
679948 if (sel) {
680949 if (node === sel) {
681950 res.size = Math.max(base * 1.02, 9.2);
682- res.ringColor = RING_SELECTED;
951+ res.ringColor = mix(ownColor, "#ffffff", RING_SELECT_MIX);
683952 res.forceLabel = true;
684953 res.zIndex = 3;
685954 return res;
@@ -692,6 +961,14 @@
692961 muteNode();
693962 return res;
694963 }
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;
695972 } else {
696973 // default {×0.7}
697974 res.size = base * 0.7;
@@ -737,12 +1014,47 @@
7371014 // 推出来的边:先看藏不藏,再决定呼吸到哪一档。
7381015 // **放在最前面**——藏起来的边不必再算后面那些提亮/压暗
7391016 const isDerived = attrs.derived === true;
1017+
7401018 if (isDerived) {
741- if (!f.showDerived) {
1019+ // 还没轮到它进场:先不画。**事实先落位,推出来的后到**
1020+ if (!derivedRevealedRef.current) {
7421021 res.hidden = true;
7431022 return res;
7441023 }
745- res.color = lerpColor(
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(
7461058 EDGE_COLOR_DERIVED_DIM,
7471059 EDGE_COLOR_DERIVED,
7481060 // 三角波而不是正弦:两端各停一瞬,看起来是「呼吸」不是「闪」
@@ -751,6 +1063,9 @@
7511063 1,
7521064 ),
7531065 );
1066+ // 打开:从近背景色亮起来,接上呼吸
1067+ res.color =
1068+ tr && tr.on && k < 1 ? lerpColor(EDGE_DIM, pulse, k) : pulse;
7541069 }
7551070 // hover: 只提亮关联边;selected: 提亮关联边 + 压暗其余
7561071 const hov = hoverRef.current;
@@ -759,12 +1074,26 @@
7591074 ? selectedRef.current
7601075 : null;
7611076 const boost = () => {
762- res.color = EDGE_FOCUS;
1077+ res.color = isDerived ? EDGE_FOCUS_DERIVED : EDGE_FOCUS;
7631078 res.size = Math.max((attrs.size as number) * 1.42, 1.85);
7641079 res.zIndex = 5;
7651080 };
766- if (hov && (s === hov || t === hov)) {
1081+ /* **时间轴停在某一刻时,这条边此刻存不存在**。
1082+ 悬停的两条分支都会提前 return,绕过下面那道时间过滤——
1083+ 不带上它的话,一 hover,所有"还没长出来"的边会从近背景色
1084+ 跳到常态色的 45%,看起来是被点亮了。实测就是这么亮的 */
1085+ const liveNow = !f.activeEdges || f.activeEdges.has(edge);
1086+ if (hov && (s === hov || t === hov) && liveNow) {
7671087 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;
7681097 } else if (sel) {
7691098 if (s === sel || t === sel) {
7701099 boost();
@@ -796,7 +1125,7 @@
7961125 setFocusEntity(node);
7971126 setSelected(node);
7981127 });
799- sigma.on("clickStage", () => setSelected(null));
1128+ sigma.on("clickStage", () => deselect());
8001129 sigma.on("enterNode", ({ node }) => {
8011130 hoverRef.current = node;
8021131 sigma.refresh();
@@ -963,9 +1292,11 @@
9631292 </button>
9641293 )}
9651294
966- {/* 图例(点击切换类型显隐) */}
1295+ {/* 图例(点击切换类型显隐)。**只摆前 LEGEND_MAX 个**,其余收进
1296+ 「+N 个类」——那一排横着长,类一多就换行把画布顶下去;而且十几个
1297+ 一模一样的胶囊排开,谁重要也读不出来 */}
9671298 <div className="pointer-events-auto flex flex-wrap gap-1.5 pt-0.5">
968- {types.map(([key, t]) => (
1299+ {legendShown.map(([key, t]) => (
9691300 <button
9701301 key={key}
9711302 onClick={() =>
@@ -987,74 +1318,215 @@
9871318 <span className="text-neutral-300">{t.label}</span>
9881319 </button>
9891320 ))}
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+ )}
9901454 </div>
9911455
992- {/* 推出来的边:**自成一组,不进类型图例。**
993- 图例回答「显示哪些类」,一排全是本体里的类;这个回答的是
994- 「显不显示推出来的边」——不是同一个问题,混进那一排它就像是
995- 多出来的一个类。为零时整组不出现 */}
996- {derivedCount > 0 && (
997- <div className="pointer-events-auto relative flex items-center gap-1 pt-0.5 pl-1 ml-1 border-l border-white/10">
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">
9981462 <button
999- onClick={() => setShowDerived((v) => !v)}
1000- title={S.graph.derivedHint}
1001- className={`glass rounded-full px-2.5 py-1 text-[11px] flex items-center gap-1.5 transition-opacity ${
1002- showDerived ? "" : "opacity-35"
1003- }`}
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"
10041471 >
1005- <span
1006- className="h-2 w-2 rounded-full"
1007- style={{ background: "rgba(231,197,124,0.9)" }}
1008- />
1009- <span className="text-neutral-300">
1010- {S.graph.derivedEdges(derivedCount)}
1011- </span>
1472+ −
10121473 </button>
1013- {/* 展开成一个小窗:这批边是什么时候推的、现在还推不推、手动再跑一次。
1014- **与开关分成两个按钮**——「藏起来」是每天要点的,「什么时候推的」
1015- 是偶尔才问的,合成一个会让常用动作多一步 */}
1474+ {/* **画满了就别再给「多画」**:库里一共就这么多,再调高什么也不会变,
1475+ 而一个点了没反应的按钮比没有这个按钮更糟 */}
10161476 <button
1017- onClick={() => setDerivedPanel((v) => !v)}
1018- title={S.graph.derivedPanel}
1019- aria-expanded={derivedPanel}
1020- className={`glass rounded-full h-[22px] w-[22px] text-[11px] leading-none text-neutral-400 hover:text-neutral-100 transition-colors ${
1021- derivedPanel ? "text-neutral-100" : ""
1022- }`}
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"
10231490 >
1024- ⋯
1491+ +
10251492 </button>
1026- {derivedPanel && kb && (
1027- <DerivedPanel
1028- kbId={kb.id}
1029- count={derivedCount}
1030- onClose={() => setDerivedPanel(false)}
1031- />
1032- )}
10331493 </div>
1034- )}
1035-
1036- <div className="ml-auto pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500">
1037- {stabilizing && (
1038- <span className="text-neutral-400">{S.graph.stabilizing} · </span>
1039- )}
1494+ <div className="pointer-events-none pt-0.5 u-num text-[11px] text-neutral-500">
10401495 {/* 画满上限时说清「画了多少 / 共多少」。**这个数从前是上限冒充规模**——
10411496 一个上万实体的库右上角永远写着 150 */}
10421497 {capped ? (
10431498 <span title={S.graph.cappedHint(nodeCount, totalNodes)}>
1499+ {/* **事实也用「已画 / 共」的口径**:从前这里给的是库里的总数,
1500+ 而实体给的是「画了多少 / 共多少」——同一句话里两套口径,
1501+ 于是调档位时实体数在变、事实数纹丝不动,看着像坏了。
1502+ 没有时间筛选时 active 恒等于已画条数,那就不说 */}
10441503 {S.graph.statsCapped(
10451504 nodeCount,
10461505 totalNodes,
1506+ edgeCount,
10471507 totalEdges,
1048- timeT === null ? edgeCount : activeCount,
1508+ timeT === null ? null : activeCount,
10491509 )}
10501510 </span>
10511511 ) : (
10521512 S.graph.stats(
10531513 nodeCount,
10541514 edgeCount,
1055- timeT === null ? edgeCount : activeCount,
1515+ timeT === null ? null : activeCount,
10561516 )
10571517 )}
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+ )}
10581530 </div>
10591531 </div>
10601532
@@ -1064,9 +1536,80 @@
10641536 <div ref={containerRef} className="absolute inset-0" />
10651537 </div>
10661538
1067- {/* 左下控件塔:布局切换 + 相机(右下归实体侧栏,底部中央归时间岛) */}
1068- <div className="absolute bottom-4 left-3 z-10 flex flex-col gap-2">
1069- <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
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">
10701613 {(
10711614 [
10721615 { key: "force", Icon: Orbit, label: S.graph.layoutForce },
@@ -1086,34 +1629,37 @@
10861629 layoutModeRef.current = key;
10871630 layoutCtlRef.current?.apply(key);
10881631 }}
1089- className={`p-2 transition-colors ${
1632+ className={`flex items-center p-2 transition-colors ${
10901633 layoutMode === key
10911634 ? "text-white bg-white/[0.1]"
10921635 : "text-neutral-400 hover:text-white hover:bg-white/[0.06]"
10931636 }`}
10941637 >
10951638 <Icon size={15} />
1639+ <span className="u-tower-label">{label}</span>
10961640 </button>
10971641 ))}
10981642 </div>
1099- <div className="glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
1643+ <div className="u-tower group glass-strong rounded-xl shadow-xl flex flex-col overflow-hidden">
11001644 <button
11011645 title={S.graph.zoomIn}
11021646 onClick={() =>
11031647 sigmaRef.current?.getCamera().animatedZoom({ duration: 220 })
11041648 }
1105- className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
1649+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
11061650 >
11071651 <ZoomIn size={15} />
1652+ <span className="u-tower-label">{S.graph.zoomIn}</span>
11081653 </button>
11091654 <button
11101655 title={S.graph.zoomOut}
11111656 onClick={() =>
11121657 sigmaRef.current?.getCamera().animatedUnzoom({ duration: 220 })
11131658 }
1114- className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
1659+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
11151660 >
11161661 <ZoomOut size={15} />
1662+ <span className="u-tower-label">{S.graph.zoomOut}</span>
11171663 </button>
11181664 <div className="h-px bg-white/10 mx-1.5" />
11191665 <button
@@ -1121,9 +1667,10 @@
11211667 onClick={() =>
11221668 sigmaRef.current?.getCamera().animatedReset({ duration: 300 })
11231669 }
1124- className="p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
1670+ className="flex items-center p-2 text-neutral-400 hover:text-white hover:bg-white/[0.06] transition-colors"
11251671 >
11261672 <Maximize2 size={15} />
1673+ <span className="u-tower-label">{S.graph.fitView}</span>
11271674 </button>
11281675 </div>
11291676 </div>
@@ -1149,12 +1696,13 @@
11491696 />
11501697 )}
11511698
1152- {/* 实体侧栏 */}
1153- {selected && kb && (
1699+ {/* 实体侧栏。**取消选中之后还要多留 170ms**:那段时间它在演退场 */}
1700+ {(selected || exiting) && kb && (
11541701 <EntityPanel
11551702 kbId={kb.id}
1156- entityId={selected}
1157- onClose={() => setSelected(null)}
1703+ entityId={(selected ?? exiting)!}
1704+ exiting={!selected}
1705+ onClose={deselect}
11581706 onNavigate={(id) => {
11591707 // 跳转目标可能不在当前画布:同时把图 refocus 到它的邻域(与搜索选择一致)
11601708 setFocusEntity(id);
@@ -1184,6 +1732,33 @@
11841732 return Math.min(maxTs, minTs + Math.round((raw - minTs) / DAY_MS) * DAY_MS);
11851733 }
11861734
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+
11871762 function TimeScrubber({
11881763 edges,
11891764 value,
@@ -1199,10 +1774,27 @@
11991774 onPlayingChange: (v: boolean) => void;
12001775 }) {
12011776 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);
12021786 const trackRef = useRef<HTMLDivElement>(null);
12031787 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+ };
12041796
1205- const { minTs, maxTs, bars } = useMemo(() => {
1797+ const { minTs, maxTs, bars, merged, trackW } = useMemo(() => {
12061798 const now = Date.now();
12071799 const froms = edges
12081800 .map((e) => (e.valid_from ? Date.parse(e.valid_from) : NaN))
@@ -1210,42 +1802,83 @@
12101802 const min = froms.length
12111803 ? Math.min(...froms)
12121804 : now - 5 * 365 * 24 * 3600 * 1000;
1213- const minYear = new Date(min).getUTCFullYear();
1214- const maxYear = new Date(now).getUTCFullYear();
1805+ // 起点对齐到单位边界:否则第一根柱子是半格,读起来像数据缺了一块
1806+ const start = bucketStart(min, unit);
1807+
12151808 const counts = new Map<number, number>();
12161809 for (const t of froms) {
1217- const y = new Date(t).getUTCFullYear();
1218- counts.set(y, (counts.get(y) ?? 0) + 1);
1810+ const k = bucketStart(t, unit);
1811+ counts.set(k, (counts.get(k) ?? 0) + 1);
12191812 }
1220- const peak = Math.max(1, ...counts.values());
1221- const bars: { year: number; h: number }[] = [];
1222- for (let y = minYear; y <= maxYear; y++) {
1223- bars.push({ year: y, h: (counts.get(y) ?? 0) / peak });
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+ });
12241826 }
1225- return { minTs: Date.UTC(minYear, 0, 1), maxTs: now, bars };
1226- }, [edges]);
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]);
12271846
12281847 // 播放按日推进(数据即 day 精度),日子快速翻过;整体节奏仍 ≈ 一个月/260ms。
12291848 // rAF 时间驱动:帧率无关,内部浮点累加避免取整漂移,值只在跨天时才下发
12301849 useEffect(() => {
12311850 if (!playing) return;
1232- const SPEED = MONTH_MS / 260; // 每毫秒真实时间推进的时间线毫秒数
1851+ // 整条走完约 SCRUB_PLAY_MS,与单位无关;单位只决定落点取整到哪一格
1852+ const SPEED = (maxTs - minTs) / SCRUB_PLAY_MS;
12331853 let raf = 0;
12341854 let last = performance.now();
12351855 let acc = value ?? minTs;
1236- let lastSnapped = Number.NaN;
1856+ let lastPushed = 0;
12371857 const step = (now: number) => {
1858+ // 有人拖过了:从落点接着走,而不是沿原来的轨迹
1859+ if (seekRef.current !== null) {
1860+ acc = seekRef.current;
1861+ seekRef.current = null;
1862+ }
12381863 acc += (now - last) * SPEED;
12391864 last = now;
12401865 if (acc >= maxTs) {
12411866 setPlaying(false);
12421867 onChange(null);
1868+ // 走到头了扫一道光。**这是个收尾**——播放停下、时间跳回全时段,
1869+ // 没有交代的话看着像中途断了;一道光扫过说明"这条走完了"
1870+ setSweep((n) => n + 1);
12431871 return;
12441872 }
1245- const snapped = minTs + Math.round((acc - minTs) / DAY_MS) * DAY_MS;
1246- if (snapped !== lastSnapped) {
1247- lastSnapped = snapped;
1248- onChange(snapped);
1873+ // **连续推进,不按桶跳。** 从前按 `bucketStart` 取整下发,年单位下
1874+ // 一次就是一年——播放头一格一格蹦,看着像卡顿而不是在走。
1875+ // 单位现在只管**显示**(标签精度、柱子跨度),不再管推进的步长。
1876+ //
1877+ // 代价是下发变密(每帧一次),而每次下发都要重算全图的现行边,
1878+ // 所以限到 ~30fps:肉眼看不出与 60fps 的差别,重算量减半
1879+ if (now - lastPushed >= 33) {
1880+ lastPushed = now;
1881+ onChange(Math.round(acc));
12491882 }
12501883 raf = requestAnimationFrame(step);
12511884 };
@@ -1253,7 +1886,7 @@
12531886 return () => cancelAnimationFrame(raf);
12541887 // 只随播放开关重启:acc 在循环内自持,value 帧帧变不应重建循环
12551888 // eslint-disable-next-line react-hooks/exhaustive-deps
1256- }, [playing, minTs, maxTs]);
1889+ }, [playing, minTs, maxTs, unit]);
12571890
12581891 // 展示到日:与数据的 day 级 valid_precision 对齐
12591892 const label = (() => {
@@ -1261,17 +1894,36 @@
12611894 const d = new Date(value);
12621895 const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
12631896 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}`;
12641900 return `${d.getUTCFullYear()}-${mm}-${dd}`;
12651901 })();
12661902
1267- const minYear = bars[0]?.year;
1268- const maxYear = bars[bars.length - 1]?.year;
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;
12691909
12701910 return (
1271- <div className="glass-strong absolute bottom-4 left-1/2 -translate-x-1/2 z-10 w-[min(560px,calc(100%-4rem))] rounded-2xl px-3 py-2 flex items-center gap-2.5 shadow-[0_12px_40px_rgba(0,0,0,0.5)]">
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+ >
12721918 <button
12731919 onClick={() => {
1274- if (!playing && value === null) onChange(minTs);
1920+ // 已经在末端(`Now`)时按播放要从头来。**否则第一下等于没反应**:
1921+ // acc 起点就是终点,循环第一帧就判定播完,只把位置清成 All time
1922+ if (
1923+ !playing &&
1924+ (value === null || value >= maxTs - (maxTs - minTs) * 0.02)
1925+ )
1926+ onChange(minTs);
12751927 setPlaying(!playing);
12761928 }}
12771929 title={playing ? S.graph.pause : S.graph.play}
@@ -1280,6 +1932,34 @@
12801932 {playing ? <Pause size={13} /> : <Play size={13} />}
12811933 </button>
12821934
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+
12831963 <span className="shrink-0 u-num text-[10px] text-neutral-600">
12841964 {minYear}
12851965 </span>
@@ -1287,30 +1967,61 @@
12871967 {/* 密度带轨道:内嵌浅色井 + 每年事实量柱 */}
12881968 <div
12891969 ref={trackRef}
1290- className="relative flex-1 h-9 rounded-lg bg-white/[0.04]"
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]"
12911973 >
1292- <div className="absolute inset-x-1.5 top-1.5 bottom-1.5 flex items-end gap-[2px]">
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+ >
12931994 {bars.map((b) => {
1294- // 进入即亮(年初为判据):播放头脚下的柱子即已覆盖——进度条通用语义
1295- const barTs = Date.UTC(b.year, 0, 1);
1296- const past = value !== null && barTs <= value;
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);
12972004 return (
12982005 <div
1299- key={b.year}
2006+ key={b.ts}
13002007 className="flex-1 flex items-end h-full"
1301- title={`${b.year}`}
2008+ title={`${stamp} · ${b.n}${merged > 1 ? ` · ${S.graph.scrubBarMerged(merged)}` : ""}`}
13022009 >
13032010 <div
13042011 className="w-full rounded-[1px] transition-colors"
13052012 style={{
13062013 height: `${Math.max(10, b.h * 100)}%`,
1307- // 播放中已扫过的年份提亮,停止后回到常规亮度
2014+ // 播放中已扫过的提亮,停止后回到常规亮度。
2015+ // **还没走到的压到近乎不可见**:它们本来是 0.09,
2016+ // 在这个底色上仍看得清,于是播放头右边跟左边一样"亮着",
2017+ // 走到哪儿就看不出来了。留一点点而不是归零——
2018+ // 归零等于假装那段没有数据,而它只是还没到
13082019 background:
1309- value !== null && past && playing
2020+ value !== null && past && (playing || trackHover)
13102021 ? "rgba(255,255,255,0.62)"
13112022 : value === null || past
13122023 ? "rgba(255,255,255,0.32)"
1313- : "rgba(255,255,255,0.09)",
2024+ : "rgba(255,255,255,0.04)",
13142025 }}
13152026 />
13162027 </div>
@@ -1324,25 +2035,24 @@
13242035 max={maxTs}
13252036 step={DAY_MS}
13262037 value={value ?? maxTs}
1327- onChange={(e) => {
1328- setPlaying(false);
1329- onChange(Number(e.target.value));
1330- }}
2038+ /* **拖动不停播**:拖是"我要看那一段",不是"我要停下"——
2039+ 松手之后应该从新位置继续走到底。
2040+ (`All time` / `Now` 那两个按钮仍然停:那是明确的跳转,不是擦洗) */
2041+ onChange={(e) => seek(Number(e.target.value))}
13312042 // 原生 range 的拖拽手势会被页面级鼠标监听(如图上拖节点)干扰——
13322043 // 自己用 pointer capture 驱动拖动,点击与拖拽都走同一条计算路径
13332044 onPointerDown={(e) => {
1334- setPlaying(false);
13352045 draggingRef.current = true;
13362046 try {
13372047 e.currentTarget.setPointerCapture(e.pointerId);
13382048 } catch {
13392049 /* 合成事件的 pointerId 可能无效,忽略 */
13402050 }
1341- onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
2051+ seek(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
13422052 }}
13432053 onPointerMove={(e) => {
13442054 if (draggingRef.current)
1345- onChange(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
2055+ seek(scrubValueAt(e.clientX, trackRef.current, minTs, maxTs));
13462056 }}
13472057 onPointerUp={() => {
13482058 draggingRef.current = false;
@@ -1403,6 +2113,13 @@
14032113
14042114 /* ============ 实体侧栏 ============ */
14052115
2116+/** 世界时间(这件事何时成立)→ 文本。**一律按 UTC 读,不转本地。**
2117+ *
2118+ * `valid_from` / `valid_to` 来自文档里的陈述("2019 年 5 月 2 日就任"),
2119+ * 是**日历日期不是时刻**,本来就没有时区;存的是那一天的 UTC 午夜。
2120+ * 按本地渲染会让 UTC-5 的读者看到 2019-05-01——凭空差一天,而且差的方向
2121+ * 还随读者所在地变。记录时间(我们何时这么认为)是另一回事,那个该按本地,
2122+ * 见 EntityHistory 里 ymd 的注释。 */
14062123 function fmtTime(iso: string | null, precision: string | null): string | null {
14072124 if (!iso) return null;
14082125 const d = new Date(iso);
@@ -1439,10 +2156,12 @@
14392156 * 手动按钮留在这里而不是别处:想重推的人正是刚看完这三行、觉得数字太旧的那个人。
14402157 */
14412158 function DerivedPanel({
2159+ panelRef,
14422160 kbId,
14432161 count,
14442162 onClose,
14452163 }: {
2164+ panelRef: React.Ref<HTMLDivElement>;
14462165 kbId: string;
14472166 count: number;
14482167 onClose: () => void;
@@ -1452,6 +2171,15 @@
14522171 queryKey: ["kbOne", kbId],
14532172 queryFn: () => api.kbDetail(kbId),
14542173 });
2174+ /* 重跑要确认,但**确认的第二下必须落在另一个按钮上**。
2175+ 这产品的手势约定是「同一个控件连点两下 = 收回去」——开关、⋯、图例胶囊
2176+ 都是这么用的。把「再点一次就执行」压在同一个按钮上,等于让同一个手势
2177+ 在这里意外地变成了「执行」,而别处它一直是「取消」。
2178+ 所以点一下只是**问一句**,问句下面给 取消 / 跑 两个目标。
2179+
2180+ 也没有用全站的 DangerConfirm:那是红标题、可要求逐字输入的危险级,
2181+ 留给删库那类不可逆操作。重跑推理重但可重复,够不上那一档 */
2182+ const [armed, setArmed] = useState(false);
14552183 const run = useMutation({
14562184 mutationFn: () => api.runInference(kbId),
14572185 onSuccess: () => {
@@ -1468,14 +2196,36 @@
14682196 ? Math.round((Date.now() - new Date(last).getTime()) / 60000)
14692197 : null;
14702198
2199+ // **盖在触发器原位往右上长开**(bottom-0 left-0),而不是在旁边挂一扇窗。
2200+ // 面与圆角跟通知/用户卡片对齐:u-menu-glass + rounded-xl
14712201 return (
1472- <div className="glass-strong pointer-events-auto absolute left-0 top-8 z-20 w-72 rounded-xl p-3 shadow-xl">
1473- <div className="flex items-baseline gap-2">
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">
14742209 <span className="text-[13px] text-neutral-100">
14752210 {S.graph.derivedPanel}
14762211 </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+ 行里最矮的标题就被居中挤出上下空当,看着像上边距过大 */}
14772227 <button
1478- className="ml-auto text-neutral-500 hover:text-neutral-200"
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`}
14792229 onClick={onClose}
14802230 aria-label={S.graph.close}
14812231 >
@@ -1483,6 +2233,34 @@
14832233 </button>
14842234 </div>
14852235
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+
14862264 <dl className="mt-2 space-y-1 text-[11px]">
14872265 <div className="flex justify-between gap-3">
14882266 <dt className="text-neutral-500">{S.graph.derivedCountLabel}</dt>
@@ -1516,61 +2294,81 @@
15162294 </p>
15172295 )}
15182296
1519- {/* **不是实心白。** `u-btn-primary` 是全站主操作那一档,用在一个悬浮小窗里
1520- 的次要动作上,整块面板会被这一个按钮压住 */}
1521- <button
1522- className="u-btn u-btn-ghost mt-2.5 w-full py-1 text-[11px]"
1523- disabled={!on || run.isPending}
1524- title={on ? undefined : S.err.inference_off}
1525- onClick={() => run.mutate()}
1526- >
1527- {run.isPending ? S.graph.derivedRunning : S.graph.derivedRun}
1528- </button>
15292297 </div>
15302298 );
15312299 }
15322300
2301+/** 推出来的一条边。**行式样与 FactRow 对齐**:同样的圆角行、同样的
2302+ * chevron 展开、同样的 role="link" 跳转(避免按钮套按钮)。
2303+ *
2304+ * 从前这里是一张 `glass rounded-xl p-3` 卡片、证明常驻展开——在一列
2305+ * Relations/Timeline/History 的紧凑行里显得是另一个产品的东西,而且十几条
2306+ * 推导堆起来是一面墙。证明是「问了才看」的东西,收进展开区正合适。 */
15332307 function DerivedRow({
15342308 d,
2309+ otherId,
2310+ otherName,
2311+ open,
2312+ onToggle,
15352313 onNavigate,
15362314 }: {
15372315 d: DerivedFact;
2316+ otherId: string;
2317+ otherName: string;
2318+ open: boolean;
2319+ onToggle: () => void;
15382320 onNavigate: (entityId: string) => void;
15392321 }) {
15402322 return (
1541- <div className="glass rounded-xl p-3">
1542- <div className="flex items-baseline gap-1.5 flex-wrap text-sm">
1543- <button
1544- className="text-neutral-100 hover:text-white underline-offset-2 hover:underline"
1545- onClick={() => onNavigate(d.subject_id)}
1546- >
1547- {d.subject}
1548- </button>
1549- <span className="text-xs text-neutral-500">{d.predicate}</span>
1550- <button
1551- className="text-neutral-100 hover:text-white underline-offset-2 hover:underline"
1552- onClick={() => onNavigate(d.object_id)}
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"
15532348 >
1554- {d.object}
1555- </button>
1556- <span className="ml-auto text-[10px] text-[var(--u-warn)]">
1557- {d.rule === "transitive"
1558- ? S.graph.ruleTransitive
1559- : S.graph.ruleSymmetric}
2349+ {otherName}
15602350 </span>
1561- </div>
1562- {/* 证明:前提按推导顺序,缩进一格。看得出链是怎么走的 */}
1563- <ol className="mt-2 space-y-0.5 border-l border-[var(--u-line)] pl-2.5">
1564- {d.premises.map((p, i) => (
1565- <li key={i} className="text-[11px] text-neutral-400">
1566- {p}
1567- </li>
1568- ))}
1569- </ol>
1570- {d.premises.length === 0 && (
1571- <p className="mt-1 text-[11px] text-neutral-600">
1572- {S.graph.derivedNoProof}
1573- </p>
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>
15742372 )}
15752373 </div>
15762374 );
@@ -1579,11 +2377,14 @@
15792377 function EntityPanel({
15802378 kbId,
15812379 entityId,
2380+ exiting,
15822381 onClose,
15832382 onNavigate,
15842383 }: {
15852384 kbId: string;
15862385 entityId: string;
2386+ /** 正在演退场:还挂在 DOM 上,但已经不接受点击 */
2387+ exiting: boolean;
15872388 onClose: () => void;
15882389 onNavigate: (entityId: string) => void;
15892390 }) {
@@ -1595,6 +2396,33 @@
15952396 // 推出来的那些。**单独一个键,不掺进 facts**——混在一个列表里,用户看不出
15962397 // 「文档里写的」和「引擎推的」的区别
15972398 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]);
15982426 // Relations = 按关系分组(查关系);Timeline = 有效时间轴(事情何时成立);
15992427 // History = 记录时间轴(我们何时这么认为、又何时改了主意)
16002428 const [view, setView] = useState<
@@ -1723,7 +2551,9 @@
17232551 }, [detail.data]);
17242552
17252553 return (
1726- <div className="glass-strong absolute top-14 right-3 bottom-20 w-80 z-10 rounded-xl shadow-2xl flex flex-col">
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+ >
17272557 <div className="flex items-start justify-between px-4 py-3.5 border-b border-white/10">
17282558 <div>
17292559 {e && (
@@ -1968,15 +2798,52 @@
19682798 {view === "history" && (
19692799 <EntityHistory kbId={kbId} entityId={entityId} />
19702800 )}
1971- {view === "derived" && (
1972- <div className="space-y-2">
1973- <p className="px-2 pb-1 text-[11px] leading-relaxed text-neutral-500">
2801+{view === "derived" && (
2802+ <>
2803+ <p className="px-2 pb-1.5 pt-0.5 text-[11px] leading-relaxed text-neutral-500">
19742804 {S.graph.derivedHint}
19752805 </p>
1976- {derived.map((d) => (
1977- <DerivedRow key={d.id} d={d} onNavigate={onNavigate} />
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>
19782845 ))}
1979- </div>
2846+ </>
19802847 )}
19812848 {view !== "history" &&
19822849 view !== "derived" &&
@@ -2016,7 +2883,7 @@
20162883 <div className="relative ml-1.5 border-l border-white/15 pl-3 space-y-0.5">
20172884 {dated.map((f) => (
20182885 <div key={f.id} className="relative">
2019- <span className="absolute -left-[17.5px] top-2.5 h-2 w-2 rounded-full bg-neutral-600 ring-2 ring-[#0f0f10]" />
2886+ <span className="absolute -left-[17.5px] top-2.5 h-2 w-2 rounded-full bg-neutral-600 ring-2 ring-[#0f0f0f]" />
20202887 <TimelineRow
20212888 kbId={kbId}
20222889 fact={f}
@@ -2243,8 +3110,8 @@
22433110 {evidence.data?.evidence.map((ev: Evidence) => (
22443111 <Link
22453112 key={ev.chunk_id}
2246- to="/doc/$docId"
2247- params={{ docId: ev.document_id }}
3113+ to="/kb/$kbId/doc/$docId"
3114+ params={{ kbId, docId: ev.document_id }}
22483115 search={{ chunk: ev.chunk_id }}
22493116 className="block text-xs text-neutral-500 hover:text-neutral-300"
22503117 >
added web/src/pages/KbScope.tsx +99 −0
@@ -0,0 +1,99 @@
1+// KB 作用域层:`/kb/$kbId` 之下的一切都属于这个知识库。
2+//
3+// **为什么把库放进路径而不是查询参数**:库是容器不是筛选条件——图谱、搜索、
4+// 文库、本体、复核全都在它下面。路径能表达这种包含关系,而且路由器会替你兜底:
5+// `/kb/$kbId/search` 没有 id 根本构造不出来。`?kb=` 是可选的,标签页之间跳一下
6+// 就掉了,掉了还不报错——于是悄悄看的是另一个库的数据,界面一模一样。
7+//
8+// **为什么还要 localStorage**:两者回答的不是同一个问题。URL 回答"这个链接指向
9+// 什么",localStorage 回答"我上次在看什么"。所以 URL 里有就以 URL 为准,
10+// 没有才回落到记忆(见 kb.tsx 与下面的 KbRedirect)。
11+import { useEffect } from "react";
12+import { Link, Outlet, useNavigate, useParams } from "@tanstack/react-router";
13+import { useQuery } from "@tanstack/react-query";
14+
15+import { ApiError, api } from "../api";
16+import { S } from "../i18n";
17+import { useKb } from "../kb";
18+import { kbStore, wsStore } from "../wsStore";
19+
20+/** 库不存在或没权限时的落地页。**不能只给一张空图**——分享链接最常见的
21+ * 失败就是对方没权限,而空白的图谱看起来像"这个库是空的",是另一回事。 */
22+function KbNoAccess({ status }: { status: number }) {
23+ return (
24+ <div className="grid h-full place-items-center px-6">
25+ <div className="max-w-sm text-center">
26+ <h2 className="text-[15px] text-neutral-200">
27+ {status === 404 ? S.kbScope.missingTitle : S.kbScope.deniedTitle}
28+ </h2>
29+ <p className="mt-2 text-xs leading-relaxed text-neutral-500">
30+ {status === 404 ? S.kbScope.missingBody : S.kbScope.deniedBody}
31+ </p>
32+ <Link
33+ to="/account/kbs"
34+ className="u-btn u-btn-ghost mt-4 inline-block px-3 py-1.5 text-xs"
35+ >
36+ {S.kbScope.myKbs}
37+ </Link>
38+ </div>
39+ </div>
40+ );
41+}
42+
43+export function KbScope() {
44+ const { kbId } = useParams({ from: "/app/kb/$kbId" });
45+ // **直接问后端,而不是在当前工作区的列表里找**:链接可能指向另一个工作区
46+ // 里的库,那时列表里没有它,但用户其实有权限——照列表判断会错杀
47+ const kb = useQuery({
48+ queryKey: ["kbOne", kbId],
49+ queryFn: () => api.kbDetail(kbId),
50+ retry: false,
51+ });
52+
53+ // 打开哪个库,"上次看的"就跟到哪个库;工作区也一并对齐,
54+ // 否则顶栏的切换器显示的还是上一个工作区
55+ useEffect(() => {
56+ if (!kb.data) return;
57+ kbStore.set(kb.data.id);
58+ wsStore.set(kb.data.workspace_id);
59+ }, [kb.data]);
60+
61+ if (kb.isError) {
62+ const status = kb.error instanceof ApiError ? kb.error.status : 500;
63+ return <KbNoAccess status={status} />;
64+ }
65+ // 加载中什么都不画:这一层只是个作用域,闪一个 spinner 反而像页面在跳
66+ if (!kb.data) return null;
67+ return <Outlet />;
68+}
69+
70+/** 旧路径(`/graph` 这类不带库的地址)的接管:解析出该去哪个库再跳过去。
71+ *
72+ * **不能在 beforeLoad 里直接重定向**——那时候库列表还没取回来,
73+ * localStorage 里也可能什么都没有(新设备、清过缓存)。所以做成一个组件,
74+ * 等 useKb 把库解析出来再走。 */
75+export function KbRedirect({
76+ page,
77+}: {
78+ page:
79+ | "graph"
80+ | "search"
81+ | "chat"
82+ | "library"
83+ | "ontology"
84+ | "mappings"
85+ | "review"
86+ | "settings";
87+}) {
88+ const { kb } = useKb();
89+ const navigate = useNavigate();
90+ useEffect(() => {
91+ if (!kb) return;
92+ navigate({
93+ to: `/kb/$kbId/${page}`,
94+ params: { kbId: kb.id },
95+ replace: true,
96+ });
97+ }, [kb, page, navigate]);
98+ return null;
99+}
modified web/src/pages/KbSettings.tsx +5 −6
@@ -4,7 +4,7 @@
44 context)遮蔽的层级 bug。 */
55 import { useEffect, useState } from "react";
66 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
7-import { useNavigate, useSearch } from "@tanstack/react-router";
7+import { useParams, useNavigate } from "@tanstack/react-router";
88 import {
99 History as HistoryIcon,
1010 Lock,
@@ -14,7 +14,6 @@
1414 } from "lucide-react";
1515 import { api, type AuditEvent } from "../api";
1616 import { LANG_NAMES, S } from "../i18n";
17-import { useKb } from "../kb";
1817 import {
1918 DangerConfirm,
2019 Dropdown,
@@ -49,9 +48,9 @@
4948 export function KbSettings() {
5049 const navigate = useNavigate();
5150 const queryClient = useQueryClient();
52- const { kb: currentKb } = useKb();
53- const { kb: kbParam } = useSearch({ from: "/app/kb-settings" });
54- const kbId = kbParam ?? currentKb?.id;
51+ /* 库 id 来自路径。**从前是 `?kb=`**——那是这套路由改造之前唯一
52+ 带着库走的地方,现在整片都在 /kb/$kbId 之下,它就不必自成一格了 */
53+ const { kbId } = useParams({ from: "/app/kb/$kbId/settings" });
5554
5655 const kb = useQuery({
5756 queryKey: ["kbOne", kbId],
@@ -110,7 +109,7 @@
110109 mutationFn: () => api.deleteKb(kbId!),
111110 onSuccess: () => {
112111 queryClient.invalidateQueries({ queryKey: ["kbs"] });
113- navigate({ to: "/library", search: {} });
112+ navigate({ to: "/kb/$kbId/library", params: { kbId } });
114113 },
115114 onError: (e) => setError((e as Error).message),
116115 });
modified web/src/pages/Library.tsx +5 −4
@@ -14,7 +14,7 @@
1414 } from "lucide-react";
1515 import { api, type Doc, type ExtractionDrop, type SourceView } from "../api";
1616 import { S } from "../i18n";
17-import { useKb } from "../kb";
17+import { useKb, useKbId } from "../kb";
1818 import { toast } from "../toast";
1919 import { Chip, type ChipTone, DangerConfirm, Loading, Pager } from "../ui";
2020 import {
@@ -303,7 +303,7 @@
303303 const queryClient = useQueryClient();
304304 const fileInput = useRef<HTMLInputElement>(null);
305305 // 从文档查看页的来源栏跳回时带 ?src= 定位到对应文件夹
306- const { src } = useSearch({ from: "/app/library" });
306+ const { src } = useSearch({ from: "/app/kb/$kbId/library" });
307307 const [dragging, setDragging] = useState(false);
308308 const [selection, setSelection] = useState<LibrarySelection>(src ?? "all");
309309 const [adding, setAdding] = useState(false);
@@ -1879,6 +1879,7 @@
18791879 drops?: ExtractionDrop[];
18801880 onShowDrops: (rows: ExtractionDrop[]) => void;
18811881 }) {
1882+ const kbId = useKbId();
18821883 const dropTotal = drops?.reduce((n, d) => n + d.count, 0) ?? 0;
18831884 const statusText =
18841885 S.library.status[doc.status as keyof typeof S.library.status] ?? doc.status;
@@ -1890,8 +1891,8 @@
18901891 <tr className="border-b border-white/5 hover:bg-white/[0.03]">
18911892 <td className="px-4 py-2.5 max-w-xs truncate" title={doc.filename}>
18921893 <Link
1893- to="/doc/$docId"
1894- params={{ docId: doc.id }}
1894+ to="/kb/$kbId/doc/$docId"
1895+ params={{ kbId, docId: doc.id }}
18951896 search={{}}
18961897 className="text-neutral-200 hover:text-[var(--u-accent)]"
18971898 >
modified web/src/pages/Login.tsx +1 −1
@@ -39,7 +39,7 @@
3939 onSuccess: () => {
4040 // 谢幕:卡片上浮淡出、巨构放大穿越,再进入图谱首页
4141 setLeaving(true);
42- window.setTimeout(() => navigate({ to: "/graph" }), 650);
42+ window.setTimeout(() => navigate({ to: "/" }), 650);
4343 },
4444 });
4545
modified web/src/pages/MyKbs.tsx +2 −2
@@ -35,7 +35,7 @@
3535 const rows = mine.data?.kbs ?? [];
3636 const openKb = (id: string) => {
3737 setKb(id);
38- navigate({ to: "/graph" });
38+ navigate({ to: "/kb/$kbId/graph", params: { kbId: id } });
3939 };
4040
4141 return (
@@ -91,7 +91,7 @@
9191 <button
9292 onClick={() => {
9393 setKb(row.kb.id);
94- navigate({ to: "/kb-settings", search: { kb: row.kb.id } });
94+ navigate({ to: "/kb/$kbId/settings", params: { kbId: row.kb.id } });
9595 }}
9696 className="u-btn u-btn-ghost px-2.5 py-1 text-xs"
9797 >
modified web/src/pages/Ontology.tsx +2 −1
@@ -412,7 +412,8 @@
412412 {rows.map((e) => (
413413 <Link
414414 key={e.id}
415- to="/graph"
415+ to="/kb/$kbId/graph"
416+ params={{ kbId }}
416417 search={{ entity: e.id }}
417418 className="flex items-center gap-2 py-1.5 text-sm text-neutral-300 hover:text-white"
418419 >
modified web/src/pages/Review.tsx +5 −2
@@ -15,7 +15,7 @@
1515 type ReviewSide,
1616 } from "../api";
1717 import { S } from "../i18n";
18-import { useKb } from "../kb";
18+import { useKb, useKbId } from "../kb";
1919 import { Chip, type ChipTone, Pager, RAIL_CLS, cn } from "../ui";
2020
2121 const DUP_PAGE = 6;
@@ -685,6 +685,7 @@
685685 }
686686
687687 export function Review() {
688+ const kbId = useKbId();
688689 const { kb } = useKb();
689690 const queryClient = useQueryClient();
690691 const navigate = useNavigate();
@@ -929,7 +930,9 @@
929930 active={false}
930931 label={S.review.railMappings}
931932 count={counts.mappings}
932- onClick={() => navigate({ to: "/mappings" })}
933+ onClick={() =>
934+ navigate({ to: "/kb/$kbId/mappings", params: { kbId } })
935+ }
933936 external
934937 />
935938 </div>
modified web/src/pages/Search.tsx +4 −3
@@ -3,12 +3,13 @@
33 import { Link } from "@tanstack/react-router";
44 import { api } from "../api";
55 import { S } from "../i18n";
6-import { useKb } from "../kb";
6+import { useKb, useKbId } from "../kb";
77 import { Pager, pageSlice } from "../ui";
88
99 const RESULT_PAGE = 10;
1010
1111 export function Search() {
12+ const kbId = useKbId();
1213 const { kb } = useKb();
1314 const [input, setInput] = useState("");
1415 const [query, setQuery] = useState("");
@@ -60,8 +61,8 @@
6061 {pageSlice(results.data?.results ?? [], page, RESULT_PAGE).rows.map((r) => (
6162 <Link
6263 key={r.id}
63- to="/doc/$docId"
64- params={{ docId: r.document_id }}
64+ to="/kb/$kbId/doc/$docId"
65+ params={{ kbId, docId: r.document_id }}
6566 search={{ chunk: r.id }}
6667 className="block glass rounded-xl p-4 glass-hover"
6768 >
modified web/src/pages/Settings.tsx +2 −2
@@ -406,7 +406,7 @@
406406 className="u-btn u-btn-ghost px-2.5 py-1 text-xs shrink-0"
407407 onClick={() => {
408408 setKb(kb.id);
409- navigate({ to: "/kb-settings", search: { kb: kb.id } });
409+ navigate({ to: "/kb/$kbId/settings", params: { kbId: kb.id } });
410410 }}
411411 >
412412 {S.settings.kbs.openSettings}
@@ -438,7 +438,7 @@
438438 // 建完直达库设置:下一步几乎总是邀人/配置
439439 if (id) {
440440 setKb(id);
441- navigate({ to: "/kb-settings", search: { kb: id } });
441+ navigate({ to: "/kb/$kbId/settings", params: { kbId: id } });
442442 }
443443 }}
444444 />
modified web/src/pages/Shell.tsx +11 −9
@@ -19,7 +19,7 @@
1919 } from "lucide-react";
2020 import { api, ApiError } from "../api";
2121 import { S } from "../i18n";
22-import { useKb } from "../kb";
22+import { useKb, useKbId } from "../kb";
2323 import { Dropdown, GithubMark, Wordmark } from "../ui";
2424 import { AlertBell } from "./AlertBell";
2525 import { UserMenu } from "./UserMenu";
@@ -30,20 +30,21 @@
3030
3131 const TABS = [
3232 // 图谱是门面,排第一;两种查询方式(Search/Ask)随后
33- { to: "/graph", label: S.nav.graph, Icon: Waypoints },
34- { to: "/search", label: S.nav.search, Icon: SearchIcon },
35- { to: "/chat", label: S.nav.ask, Icon: MessagesSquare },
36- { to: "/library", label: S.nav.library, Icon: LibraryIcon },
37- { to: "/review", label: S.review.title, Icon: ListChecks },
38- { to: "/ontology", label: S.ontology.title, Icon: Shapes },
33+ { to: "/kb/$kbId/graph", label: S.nav.graph, Icon: Waypoints },
34+ { to: "/kb/$kbId/search", label: S.nav.search, Icon: SearchIcon },
35+ { to: "/kb/$kbId/chat", label: S.nav.ask, Icon: MessagesSquare },
36+ { to: "/kb/$kbId/library", label: S.nav.library, Icon: LibraryIcon },
37+ { to: "/kb/$kbId/review", label: S.review.title, Icon: ListChecks },
38+ { to: "/kb/$kbId/ontology", label: S.ontology.title, Icon: Shapes },
3939 // 本体说「世界上有什么」,数据映射说「这个数在库里怎么算」——挨着放
40- { to: "/mappings", label: S.mapping.title, Icon: Database },
40+ { to: "/kb/$kbId/mappings", label: S.mapping.title, Icon: Database },
4141 // 库设置与其它 tab 同为"当前知识库作用域",并列于内容导航
42- { to: "/kb-settings", label: S.nav.settings, Icon: SettingsIcon },
42+ { to: "/kb/$kbId/settings", label: S.nav.settings, Icon: SettingsIcon },
4343 ] as const;
4444
4545 export function Shell() {
4646 const navigate = useNavigate();
47+ const kbId = useKbId();
4748
4849 const me = useQuery({ queryKey: ["me"], queryFn: api.me });
4950 const health = useQuery({
@@ -154,6 +155,7 @@
154155 <Link
155156 key={to}
156157 to={to}
158+ params={{ kbId }}
157159 className="flex items-center gap-2 px-3.5 py-2.5 text-[13.5px] font-medium text-neutral-400 border-b-2 border-transparent hover:text-neutral-200"
158160 activeProps={{
159161 className:
modified web/src/router.tsx +104 −30
@@ -13,6 +13,7 @@
1313 import { Library } from "./pages/Library";
1414 import { Login } from "./pages/Login";
1515 import { Privacy, Terms } from "./pages/Legal";
16+import { KbRedirect, KbScope } from "./pages/KbScope";
1617 import { KbSettings } from "./pages/KbSettings";
1718 import { MyKbs } from "./pages/MyKbs";
1819 import { NotFound } from "./pages/ServerDown";
@@ -59,9 +60,18 @@
5960 },
6061 });
6162
62-const chatRoute = createRoute({
63+/* 知识库作用域。**库是容器不是筛选条件**——底下这些页面全都属于某一个库,
64+ 路径表达包含关系,路由器也就替我们兜住了「忘了带库」这类错误:
65+ `/kb/$kbId/search` 没有 id 根本构造不出来。理由详见 pages/KbScope.tsx */
66+const kbRoute = createRoute({
6367 getParentRoute: () => appRoute,
64- path: "/chat",
68+ path: "/kb/$kbId",
69+ component: KbScope,
70+});
71+
72+const chatRoute = createRoute({
73+ getParentRoute: () => kbRoute,
74+ path: "chat",
6575 component: Chat,
6676 });
6777
@@ -74,23 +84,34 @@
7484 });
7585
7686 const searchRoute = createRoute({
77- getParentRoute: () => appRoute,
78- path: "/search",
87+ getParentRoute: () => kbRoute,
88+ path: "search",
7989 component: Search,
8090 });
8191
8292 const graphRoute = createRoute({
83- getParentRoute: () => appRoute,
84- path: "/graph",
85- validateSearch: (search: Record<string, unknown>): { entity?: string } => ({
93+ getParentRoute: () => kbRoute,
94+ path: "graph",
95+ /* 图谱页的可分享状态。**三个都是"你在看什么",不是"你怎么看"**——
96+ 所以档位(画多少个)刻意不进 URL:那是本地观感,换台机器不该跟着走。
97+
98+ - entity:选中了谁
99+ - focus:是否处在某个实体的邻域(与"在全图里选中"是两个画面)
100+ - at:时间轴停在哪一刻。**这条最不能少**——这产品的卖点就是
101+ "看某个时刻的世界",不带时刻的链接把最有意思的那部分丢了 */
102+ validateSearch: (
103+ search: Record<string, unknown>,
104+ ): { entity?: string; focus?: string; at?: string } => ({
86105 entity: typeof search.entity === "string" ? search.entity : undefined,
106+ focus: typeof search.focus === "string" ? search.focus : undefined,
107+ at: typeof search.at === "string" ? search.at : undefined,
87108 }),
88109 component: Graph,
89110 });
90111
91112 const docRoute = createRoute({
92- getParentRoute: () => appRoute,
93- path: "/doc/$docId",
113+ getParentRoute: () => kbRoute,
114+ path: "doc/$docId",
94115 validateSearch: (search: Record<string, unknown>): { chunk?: string } => ({
95116 chunk: typeof search.chunk === "string" ? search.chunk : undefined,
96117 }),
@@ -98,8 +119,8 @@
98119 });
99120
100121 const libraryRoute = createRoute({
101- getParentRoute: () => appRoute,
102- path: "/library",
122+ getParentRoute: () => kbRoute,
123+ path: "library",
103124 validateSearch: (search: Record<string, unknown>): { src?: string } => ({
104125 src: typeof search.src === "string" ? search.src : undefined,
105126 }),
@@ -107,20 +128,20 @@
107128 });
108129
109130 const ontologyRoute = createRoute({
110- getParentRoute: () => appRoute,
111- path: "/ontology",
131+ getParentRoute: () => kbRoute,
132+ path: "ontology",
112133 component: Ontology,
113134 });
114135
115136 const mappingsRoute = createRoute({
116- getParentRoute: () => appRoute,
117- path: "/mappings",
137+ getParentRoute: () => kbRoute,
138+ path: "mappings",
118139 component: Mappings,
119140 });
120141
121142 const reviewRoute = createRoute({
122- getParentRoute: () => appRoute,
123- path: "/review",
143+ getParentRoute: () => kbRoute,
144+ path: "review",
124145 component: Review,
125146 });
126147
@@ -187,12 +208,55 @@
187208 });
188209
189210 const kbSettingsRoute = createRoute({
211+ getParentRoute: () => kbRoute,
212+ path: "settings",
213+ component: KbSettings,
214+});
215+
216+/* 旧路径兼容:`/graph` 这类不带库的地址仍然可用,解析出该去哪个库再跳。
217+ **不做成 beforeLoad 重定向**——那时候库列表还没取回来,localStorage 里
218+ 也可能什么都没有(新设备、清过缓存),只能等 useKb 解析出来 */
219+/* **逐条写出来,不用工厂函数**:工厂里的 path 是 string,类型系统认不出
220+ 字面量,别处 `redirect({ to: "/graph" })` 就通不过。啰嗦换类型安全 */
221+const legacyGraphRoute = createRoute({
222+ getParentRoute: () => appRoute,
223+ path: "/graph",
224+ component: () => <KbRedirect page="graph" />,
225+});
226+const legacySearchRoute = createRoute({
227+ getParentRoute: () => appRoute,
228+ path: "/search",
229+ component: () => <KbRedirect page="search" />,
230+});
231+const legacyChatRoute = createRoute({
232+ getParentRoute: () => appRoute,
233+ path: "/chat",
234+ component: () => <KbRedirect page="chat" />,
235+});
236+const legacyLibraryRoute = createRoute({
237+ getParentRoute: () => appRoute,
238+ path: "/library",
239+ component: () => <KbRedirect page="library" />,
240+});
241+const legacyOntologyRoute = createRoute({
242+ getParentRoute: () => appRoute,
243+ path: "/ontology",
244+ component: () => <KbRedirect page="ontology" />,
245+});
246+const legacyMappingsRoute = createRoute({
247+ getParentRoute: () => appRoute,
248+ path: "/mappings",
249+ component: () => <KbRedirect page="mappings" />,
250+});
251+const legacyReviewRoute = createRoute({
252+ getParentRoute: () => appRoute,
253+ path: "/review",
254+ component: () => <KbRedirect page="review" />,
255+});
256+const legacyKbSettingsRoute = createRoute({
190257 getParentRoute: () => appRoute,
191258 path: "/kb-settings",
192- validateSearch: (search: Record<string, unknown>): { kb?: string } => ({
193- kb: typeof search.kb === "string" ? search.kb : undefined,
194- }),
195- component: KbSettings,
259+ component: () => <KbRedirect page="settings" />,
196260 });
197261
198262 const routeTree = rootRoute.addChildren([
@@ -205,15 +269,25 @@
205269 accountShellRoute.addChildren([accountRoute, myKbsRoute, adminRoute]),
206270 appRoute.addChildren([
207271 indexRoute,
208- chatRoute.addChildren([chatConversationRoute]),
209- searchRoute,
210- graphRoute,
211- docRoute,
212- libraryRoute,
213- reviewRoute,
214- ontologyRoute,
215- mappingsRoute,
216- kbSettingsRoute,
272+ legacyGraphRoute,
273+ legacySearchRoute,
274+ legacyChatRoute,
275+ legacyLibraryRoute,
276+ legacyOntologyRoute,
277+ legacyMappingsRoute,
278+ legacyReviewRoute,
279+ legacyKbSettingsRoute,
280+ kbRoute.addChildren([
281+ chatRoute.addChildren([chatConversationRoute]),
282+ searchRoute,
283+ graphRoute,
284+ docRoute,
285+ libraryRoute,
286+ reviewRoute,
287+ ontologyRoute,
288+ mappingsRoute,
289+ kbSettingsRoute,
290+ ]),
217291 ]),
218292 ]);
219293
modified web/src/styles.css +165 −3
@@ -39,6 +39,15 @@
3939 --u-line-strong: rgba(255, 255, 255, 0.14);
4040 --u-surface: rgba(255, 255, 255, 0.04);
4141 --u-surface-strong: rgba(10, 10, 10, 0.72);
42+ /* 指针停在面上时的实底。**毛玻璃是给"没在看它"的时候用的**——
43+ 半透让浮层不至于把画布切断;可一旦人把指针移进来,他要读的就是面板本身,
44+ 这时候背后的图反而是噪声。所以这两档不是审美偏好,是同一块面在
45+ "余光里"和"正在读"两种状态下该有的样子。
46+ 统一在这里定义,改一处四处都跟着:顶栏、导航、时间岛、控件塔、
47+ 以及所有 u-menu-glass 的弹出面板 */
48+ --u-surface-strong-hover: rgba(10, 10, 10, 0.94);
49+ --u-menu-surface: rgba(14, 14, 14, 0.85);
50+ --u-menu-surface-hover: rgba(14, 14, 14, 0.97);
4251 }
4352
4453 body {
@@ -77,6 +86,36 @@
7786 backdrop-filter: blur(20px);
7887 -webkit-backdrop-filter: blur(20px);
7988 border: 1px solid var(--u-line);
89+ /* 基态上的时长是**离开**时用的:慢一点,指针擦过边缘不会闪。
90+ 进入的时长写在 :hover 里,更快,为的是跟手 */
91+ transition: background-color 260ms ease;
92+}
93+.glass-strong:hover {
94+ background: var(--u-surface-strong-hover);
95+ transition-duration: 120ms;
96+}
97+/* 正在工作时也按下去,与 hover 同一档。**这比在轨道上循环扫光更准**:
98+ 它说的是"这块面正在工作",而不是"在等一件不知道多久的事"——
99+ 循环微光是不确定进度的语言,而时间轴是确定的。
100+ 播放中人本来就盯着它看,半透的毛玻璃这时候只是噪声 */
101+/* 时间岛:宽度随单位变,所以它要**同时**过渡背景与宽度。
102+ 不能只挂 Tailwind 的 `transition-[width]`——上面 .glass-strong 用的是
103+ `transition` 简写,会把 transition-property 整个覆盖掉,而自定义 CSS
104+ 不在 utilities 层里、胜过那个工具类。实测:岛的计算过渡只剩
105+ background-color,宽度变成瞬变。要过渡两样就得写在同一条声明里 */
106+.u-scrub-island {
107+ transition:
108+ background-color 260ms ease,
109+ width 300ms ease;
110+}
111+.u-scrub-island:hover,
112+.u-scrub-island.u-solid {
113+ transition-duration: 120ms, 300ms;
114+}
115+
116+.glass-strong.u-solid {
117+ background: var(--u-surface-strong-hover);
118+ transition-duration: 120ms;
80119 }
81120
82121 /* 模态对话框的面:**近实底**。
@@ -85,7 +124,10 @@
85124 身后的回答文字清晰可辨,标题几乎读不出)。
86125 遮罩也一并加深:0.6 的黑压不住一屏白字。 */
87126 .u-modal-panel {
88- background: rgba(12, 12, 14, 0.97);
127+ /* **中性,不掺色相**:原本是 rgba(12,12,14),蓝比红绿高 2——
128+ 在大面积深底上肉眼看得出偏冷。这产品的既定原则是
129+ 「chrome 零色偏、彩色只属于数据」,这里也照办 */
130+ background: rgba(12, 12, 12, 0.97);
89131 backdrop-filter: blur(24px);
90132 -webkit-backdrop-filter: blur(24px);
91133 border: 1px solid var(--u-line-strong);
@@ -152,6 +194,72 @@
152194 .u-pop-in-tl {
153195 transform-origin: top left;
154196 }
197+/* 走到终点时扫一道光:从左到右扫过整条轨道。
198+ **它说的是"这条走完了"**——播放停下、时间跳回全时段,
199+ 没有任何交代的话看着像中途断了。方向与刚刚走过的方向一致。
200+ 只演一次,走完就卸载;轨道自身 overflow-hidden,光不会溢出圆角 */
201+@keyframes u-sweep-kf {
202+ from {
203+ transform: translateX(-100%);
204+ opacity: 0;
205+ }
206+ 18% {
207+ opacity: 1;
208+ }
209+ to {
210+ transform: translateX(100%);
211+ opacity: 0;
212+ }
213+}
214+.u-sweep {
215+ position: absolute;
216+ inset: 0;
217+ pointer-events: none;
218+ background: linear-gradient(
219+ 90deg,
220+ transparent,
221+ rgba(255, 255, 255, 0.18),
222+ transparent
223+ );
224+ animation: u-sweep-kf 720ms cubic-bezier(0.4, 0, 0.2, 1) both;
225+}
226+
227+/* 停靠面板的入场:从它停靠的那条边滑进来。
228+ **不用 u-pop-in 那种缩放**——那是给锚在某个按钮上的弹出菜单的,
229+ 它有明确的"从哪儿长出来";侧栏是贴着右边缘停的一块面,该从边缘进来。
230+ 只在打开时演一次:在实体之间切换时面板留在原地只换内容,
231+ 每点一个节点就抖一下反而吵 */
232+@keyframes u-dock-in-kf {
233+ from {
234+ opacity: 0;
235+ transform: translateX(14px);
236+ }
237+ to {
238+ opacity: 1;
239+ transform: translateX(0);
240+ }
241+}
242+.u-dock-in {
243+ animation: u-dock-in-kf 0.18s cubic-bezier(0.16, 1, 0.3, 1) both;
244+}
245+/* 退场。**比入场快、缓动相反**:进来要"落位"(减速停住),
246+ 出去要"离开"(加速甩出)。同一条曲线两头用会让关闭显得拖沓。
247+ 退场期间不再接受点击——它已经在走了,这时候点上去只会让人困惑 */
248+@keyframes u-dock-out-kf {
249+ from {
250+ opacity: 1;
251+ transform: translateX(0);
252+ }
253+ to {
254+ opacity: 0;
255+ transform: translateX(14px);
256+ }
257+}
258+.u-dock-out {
259+ animation: u-dock-out-kf 0.15s cubic-bezier(0.4, 0, 1, 1) both;
260+ pointer-events: none;
261+}
262+
155263 /* 向上弹出的变体(composer 停靠底部时菜单开口朝上) */
156264 @keyframes u-pop-up-kf {
157265 from {
@@ -172,15 +280,27 @@
172280 原地变形动画在组件内用 FLIP 实现(首帧压到胶囊真实边界再展开),
173281 CSS 只负责面板的皮 */
174282 .u-menu-glass {
175- background: rgba(14, 14, 16, 0.85);
283+ /* 中性,不掺色相:原本 rgba(14,14,16) 蓝比红绿高 2。这个面同时用在
284+ 通知、用户菜单、图例的「+N 个类」和 Inference 面板上,一处偏色四处都偏 */
285+ background: var(--u-menu-surface);
286+ /* 基态上的时长是**离开**时用的:慢一点,指针擦过边缘不会闪。
287+ 进入的时长写在 :hover 里,更快,为的是跟手 */
288+ transition: background-color 260ms ease;
176289 backdrop-filter: blur(24px);
177290 -webkit-backdrop-filter: blur(24px);
178291 border: 1px solid rgba(255, 255, 255, 0.14);
179292 }
293+.u-menu-glass:hover {
294+ background: var(--u-menu-surface-hover);
295+ transition-duration: 120ms;
296+}
180297
181298 @media (prefers-reduced-motion: reduce) {
182299 .u-pop-in,
183- .u-pop-up {
300+ .u-pop-up,
301+ .u-dock-in,
302+ .u-dock-out,
303+ .u-sweep {
184304 animation: none;
185305 }
186306 }
@@ -708,3 +828,45 @@
708828 color: var(--u-text-2);
709829 margin: 0.4em 0;
710830 }
831+
832+/* 左下控件塔:**整组一起展开**,不是逐个按钮。
833+ 一组是一个语义单元(派生 / 布局 / 相机),鼠标进了这一组,
834+ 这一组的名字就都该出来——逐个展开的话,名字会随指针跳来跳去,
835+ 而人想知道的往往正是"旁边那个是什么"。
836+
837+ 用 max-width 而不是 width 做过渡:名字长短不一,写死宽度要么截断
838+ 要么留白,max-width 让每个按钮按自己的内容收放。
839+ overflow-hidden 已经在组容器上了,收起时不会漏字。 */
840+.u-tower-label {
841+ max-width: 0;
842+ overflow: hidden;
843+ white-space: nowrap;
844+ opacity: 0;
845+ font-size: 11px;
846+ line-height: 1;
847+ /* 图标与文字之间的空当用 **margin**,既不能用按钮上的 gap,也不能用 padding:
848+ gap 对宽度为 0 的项目照样生效;而 padding 不会被 max-width 压缩
849+ (border-box 下宽度最小就等于那点 padding)——两种写法都会让收起态
850+ 凭空多出 8px,方块就不方了。实测 39x31,改成 margin 后才是 31x31 */
851+ margin-left: 0;
852+ transition:
853+ max-width 220ms ease,
854+ margin-left 220ms ease,
855+ opacity 160ms ease;
856+}
857+.u-tower:hover .u-tower-label {
858+ max-width: 9rem;
859+ margin-left: 0.5rem;
860+ opacity: 1;
861+}
862+/* 键盘走焦点时也要出来:只认 hover 的话,用键盘的人永远看不到名字 */
863+.u-tower:focus-within .u-tower-label {
864+ max-width: 9rem;
865+ margin-left: 0.5rem;
866+ opacity: 1;
867+}
868+@media (prefers-reduced-motion: reduce) {
869+ .u-tower-label {
870+ transition: none;
871+ }
872+}
modified web/src/ui/index.tsx +1 −1
@@ -885,7 +885,7 @@
885885 export function SectionMark({ text, title }: { text: string; title: string }) {
886886 return (
887887 <RouterLink
888- to="/graph"
888+ to="/"
889889 title={title}
890890 className="relative inline-flex text-white text-[17px]"
891891 style={{ fontFamily: "var(--font-brand)", letterSpacing: "0.06em" }}
modified web/src/ui/popoverFlip.ts +9 −3
@@ -18,7 +18,12 @@
1818 * `close()` 会先播收回动画再卸载;要立刻关(比如导航走了)直接 `setOpen(false)`。
1919 * 面板外点击与 Esc 已经接好,挂在 `rootRef` 上。
2020 */
21-export function usePopoverFlip<A extends HTMLElement, P extends HTMLElement>() {
21+export function usePopoverFlip<A extends HTMLElement, P extends HTMLElement>(
22+ /** 变形的锚点角。**面板贴哪边就写哪边**:顶栏右侧的面板贴右上角,
23+ * 贴左边的面板(比如图例的「+N 个类」)要写 "top left",
24+ * 否则它会从右边缘往左长出来,看着像从别处飞过来的 */
25+ origin: "top right" | "top left" | "bottom left" = "top right",
26+) {
2227 const [open, setOpen] = useState(false);
2328 const rootRef = useRef<HTMLDivElement>(null);
2429 const anchorRef = useRef<A>(null);
@@ -33,7 +38,7 @@
3338 const a = anchor.getBoundingClientRect();
3439 const p = panel.getBoundingClientRect();
3540 if (p.width < 1 || p.height < 1) return;
36- panel.style.transformOrigin = "top right";
41+ panel.style.transformOrigin = origin;
3742 panel.style.transform = `scale(${a.width / p.width}, ${a.height / p.height})`;
3843 panel.style.borderRadius = "999px";
3944 panel.style.opacity = "0.35";
@@ -61,7 +66,7 @@
6166 cancelAnimationFrame(raf);
6267 if (done !== undefined) window.clearTimeout(done);
6368 };
64- }, [open]);
69+ }, [open, origin]);
6570
6671 const close = () => {
6772 const panel = panelRef.current;
@@ -72,6 +77,7 @@
7277 return;
7378 }
7479 closingRef.current = true;
80+ panel.style.transformOrigin = origin;
7581 const a = anchor.getBoundingClientRect();
7682 // offsetWidth/Height 是布局尺寸,不受当前 transform 影响——
7783 // 用 getBoundingClientRect 会拿到已经缩过的值,越缩越小