Elffuss BraidHub

kikocis/utopia public

b7cca7fa81d9 · 7.8 KiBRawPermalink
1import { useEffect, useMemo, useRef, useState } from "react";
2import { useQuery } from "@tanstack/react-query";
3import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
4import { api, type ChunkFact } from "../api";
5import { S } from "../i18n";
6import { Pager, pageSlice } from "../ui";
7import { SourcesRail } from "./SourcesRail";
8
9const DOC_PAGE = 12;
10
11const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
12
13function factRange(f: ChunkFact): string | null {
14 if (!f.valid_from && !f.valid_to) return null;
15 return `${ym(f.valid_from) ?? "…"} → ${ym(f.valid_to) ?? S.doc.ongoing}`;
16}
17
18export function DocViewer() {
19 const { docId } = useParams({ from: "/app/doc/$docId" });
20 const { chunk } = useSearch({ from: "/app/doc/$docId" });
21 const navigate = useNavigate();
22
23 const detail = useQuery({
24 queryKey: ["docDetail", docId],
25 queryFn: () => api.documentDetail(docId),
26 });
27 // 反向证据链:各分块抽出的事实(一次取整文档,按 chunk 分组)
28 const extractions = useQuery({
29 queryKey: ["docExtractions", docId],
30 queryFn: () => api.documentExtractions(docId),
31 });
32 const factsByChunk = useMemo(() => {
33 const map = new Map<string, ChunkFact[]>();
34 for (const f of extractions.data?.facts ?? []) {
35 if (!map.has(f.chunk_id)) map.set(f.chunk_id, []);
36 map.get(f.chunk_id)!.push(f);
37 }
38 return map;
39 }, [extractions.data]);
40
41 // null = 自动定位:有引用跳转时翻到目标分块所在页
42 const [page, setPage] = useState<number | null>(null);
43 useEffect(() => setPage(null), [chunk, docId]);
44
45 const highlightRef = useRef<HTMLDivElement>(null);
46 // 引用跳转:滚动到目标分块点亮一下,稍候淡出恢复普通状态(不常驻高亮)
47 const [flash, setFlash] = useState(false);
48 useEffect(() => {
49 if (detail.data && highlightRef.current) {
50 highlightRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
51 setFlash(true);
52 // 平滑滚动本身耗几百毫秒,点亮窗口要留足滚动后的可视时间
53 const t = setTimeout(() => setFlash(false), 2600);
54 return () => clearTimeout(t);
55 }
56 }, [detail.data, chunk]);
57
58 if (detail.isPending)
59 return <div className="p-8 text-sm text-neutral-500">{S.doc.loading}</div>;
60 if (detail.isError)
61 return (
62 <div className="p-8 text-sm text-rose-400">
63 {(detail.error as Error).message}
64 </div>
65 );
66
67 const { document: doc, chunks } = detail.data;
68 const targetIdx = chunk ? chunks.findIndex((c) => c.id === chunk) : -1;
69 const curPage = page ?? (targetIdx >= 0 ? Math.floor(targetIdx / DOC_PAGE) : 0);
70 const { rows: pagedChunks, safe: safePage } = pageSlice(chunks, curPage, DOC_PAGE);
71
72 return (
73 <div className="h-full flex">
74 {/* 来源栏常驻:当前文档所属文件夹高亮,点其他文件夹跳回 Library 对应视图 */}
75 <SourcesRail
76 kbId={doc.kb_id}
77 active={doc.source_id ?? "uploads"}
78 onSelect={(sel) => navigate({ to: "/library", search: { src: sel } })}
79 />
80 <div className="flex-1 min-w-0 overflow-y-auto u-scroll">
81 <div className="max-w-4xl mx-auto p-6">
82 <div className="mb-4 flex items-baseline justify-between gap-4">
83 <div>
84 <h2 className="text-lg font-bold text-neutral-100 break-all">{doc.filename}</h2>
85 <p className="mt-0.5 text-xs text-neutral-500">
86 {chunks.length} {S.doc.sections} · {(doc.size_bytes / 1024).toFixed(0)} KB ·{" "}
87 {new Date(doc.created_at).toLocaleDateString()}
88 </p>
89 </div>
90 <Link to="/library" className="shrink-0 text-sm text-[var(--u-accent)] hover:underline">
91 {S.doc.backToLibrary}
92 </Link>
93 </div>
94
95 <div className="space-y-3">
96 {pagedChunks.map((c) => {
97 const hit = c.id === chunk;
98 const facts = factsByChunk.get(c.id) ?? [];
99 return (
100 <div key={c.id} ref={hit ? highlightRef : undefined} className="flex gap-3">
101 <div
102 className={`flex-1 min-w-0 rounded-xl border p-4 text-sm leading-relaxed whitespace-pre-wrap border-white/10 transition-[border-color,background-color,box-shadow] duration-700 ${
103 hit && flash ? "u-flash" : "bg-white/[0.04]"
104 }`}
105 >
106 <div className="mb-1.5 text-xs text-neutral-500">
107 {S.doc.section} {c.seq + 1}
108 {hit && (
109 <span
110 className={`ml-2 text-[var(--u-accent)] transition-opacity duration-700 ${
111 flash ? "opacity-100" : "opacity-0"
112 }`}
113 >
114 {S.doc.citedHere}
115 </span>
116 )}
117 </div>
118 {c.text}
119 </div>
120
121 {/* 抽取对照栏:这个分块产出了哪些事实(实体可跳图谱) */}
122 {facts.length > 0 && (
123 <aside className="w-64 shrink-0 rounded-xl border border-white/10 bg-white/[0.02] p-3">
124 <div className="mb-2 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-600">
125 {S.doc.extracted} · {facts.length}
126 </div>
127 <div className="space-y-2">
128 {facts.map((f) => {
129 const range = factRange(f);
130 return (
131 <div key={f.fact_id} className="text-xs leading-snug">
132 <div>
133 <Link
134 to="/graph"
135 search={{ entity: f.subject_id }}
136 className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
137 >
138 {f.subject}
139 </Link>
140 <span
141 className={
142 f.predicate === null
143 ? "italic text-neutral-700"
144 : "text-neutral-600"
145 }
146 title={
147 f.predicate && f.inferred
148 ? S.graph.inferredPredicate
149 : undefined
150 }
151 >
152 {" "}
153 {f.predicate ?? S.graph.unknownPredicate}{" "}
154 </span>
155 {f.object_id ? (
156 <Link
157 to="/graph"
158 search={{ entity: f.object_id }}
159 className="text-neutral-200 hover:text-white hover:underline underline-offset-2 decoration-white/30"
160 >
161 {f.object}
162 </Link>
163 ) : (
164 <span className="text-neutral-300">{f.object ?? ""}</span>
165 )}
166 </div>
167 {range && <div className="u-num text-[10.5px] text-neutral-500">{range}</div>}
168 </div>
169 );
170 })}
171 </div>
172 </aside>
173 )}
174 </div>
175 );
176 })}
177 </div>
178 <Pager total={chunks.length} pageSize={DOC_PAGE} page={safePage} onPage={setPage} />
179 </div>
180 </div>
181 </div>
182 );
183}