Elffuss BraidHub

kikocis/utopia public

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