AskAnswer.tsx
8.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Database, FileText } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { CopyButton, Modal } from "@/components/ui";
import { DataTable, RankChart } from "./DataTable";
import type { Citation, DataRef } from "@/lib/onto";
/**
* 答案正文:把 [^d2:c17] 原文角标和 [^run:12] 数据角标换成可点的编号。
* 每个数字都能点开看到它来自哪条 SQL、哪个口径;每句结论都能点开看到原文。
*/
export function AskAnswer({ text, citations, dataRefs, streaming }: {
text: string; citations: Citation[]; dataRefs: DataRef[]; streaming?: boolean;
}) {
const [openChunk, setOpenChunk] = useState<Citation | null>(null);
const [openData, setOpenData] = useState<DataRef | null>(null);
const { md, order } = useMemo(() => {
const order: string[] = [];
const md = (text || "").replace(/\[\^([A-Za-z0-9_\-]+:[A-Za-z0-9_\-]+)\]/g, (_, id: string) => {
if (!order.includes(id)) order.push(id);
return ` [${id.startsWith("run:") ? "数" : ""}${order.indexOf(id) + 1}](#cite:${id})`;
});
return { md, order };
}, [text]);
return (
<div className="prose-answer text-body leading-relaxed">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
a: ({ href, children }) => {
if (href?.startsWith("#cite:")) {
const id = href.slice(6);
const isRun = id.startsWith("run:");
const c = isRun ? dataRefs.find((d) => `run:${d.run_id}` === id) : citations.find((x) => x.chunk_id === id);
return (
<button
className={isRun
? "mx-0.5 rounded bg-brand2/15 px-1 align-super text-caption font-semibold text-brand2 hover:bg-brand2/25"
: "mx-0.5 rounded bg-brand/15 px-1 align-super text-caption font-semibold text-brand hover:bg-brand/25"}
title={isRun ? "查看数据来源" : "查看原文"}
onClick={() => {
if (!c) return;
if (isRun) setOpenData(c as DataRef); else setOpenChunk(c as Citation);
}}>
{children}
</button>
);
}
return <a href={href} target="_blank" rel="noreferrer" className="text-brand underline">{children}</a>;
},
table: ({ children }) => (
<div className="my-2 overflow-x-auto"><table className="w-full border-collapse text-label">{children}</table></div>
),
th: ({ children }) => <th className="border border-line bg-ink/5 px-2 py-1 text-left font-medium">{children}</th>,
td: ({ children }) => <td className="border border-line px-2 py-1">{children}</td>,
p: ({ children }) => <p className="my-1.5">{children}</p>,
ul: ({ children }) => <ul className="my-1.5 list-disc pl-5">{children}</ul>,
ol: ({ children }) => <ol className="my-1.5 list-decimal pl-5">{children}</ol>,
h3: ({ children }) => <h3 className="mt-3 mb-1 text-body font-semibold">{children}</h3>,
h4: ({ children }) => <h4 className="mt-3 mb-1 border-l-2 border-brand/50 pl-2 text-label font-semibold text-muted">{children}</h4>,
h2: ({ children }) => <h2 className="mt-3 mb-1 text-title font-semibold">{children}</h2>,
code: ({ children }) => <code className="rounded bg-ink/5 px-1 font-mono text-label">{children}</code>,
}}>
{md || (streaming ? "…" : "")}
</ReactMarkdown>
{streaming && <span className="ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-brand align-middle" />}
{order.length > 0 && !streaming && (
<div className="mt-2 flex flex-wrap gap-1.5 border-t border-line pt-2">
{order.map((id, i) => {
const isRun = id.startsWith("run:");
const c = isRun ? dataRefs.find((d) => `run:${d.run_id}` === id) : citations.find((x) => x.chunk_id === id);
if (!c) return null;
return (
<button key={id} className="chip max-w-[260px] truncate"
onClick={() => (isRun ? setOpenData(c as DataRef) : setOpenChunk(c as Citation))}>
{isRun ? <Database className="h-3 w-3" /> : <FileText className="h-3 w-3" />}
<span className="truncate">
{isRun ? "数" : ""}{i + 1} · {isRun ? ((c as DataRef).metric?.name || `取数 #${(c as DataRef).run_id}`)
: ((c as Citation).heading || (c as Citation).chunk_id)}
</span>
</button>
);
})}
</div>
)}
<Modal open={!!openChunk} onClose={() => setOpenChunk(null)} title={openChunk?.heading || "原文"}
desc={openChunk ? `片段 ${openChunk.chunk_id} · 文档 #${openChunk.doc_id}` : ""} width="max-w-2xl">
<pre className="whitespace-pre-wrap font-sans text-body leading-relaxed">{openChunk?.text}</pre>
</Modal>
<Modal open={!!openData} onClose={() => setOpenData(null)} width="max-w-3xl"
title={openData?.metric?.name ? `数据来源:${openData.metric.name}` : "数据来源"}
desc={openData ? `取数记录 #${openData.run_id}${openData.period?.period ? ` · 统计期 ${openData.period.period}(${openData.period.start} ~ ${openData.period.end})` : ""}` : ""}>
{openData && <DataRefView d={openData} />}
</Modal>
</div>
);
}
export function DataRefView({ d }: { d: DataRef }) {
const [editing, setEditing] = useState(false);
const [sql, setSql] = useState(d.sql);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const [mine, setMine] = useState<{ columns: string[]; rows: unknown[][]; sql: string } | null>(null);
useEffect(() => { setSql(d.sql); setEditing(false); setMine(null); setErr(""); }, [d.run_id, d.sql]);
const rerun = async () => {
setBusy(true);
setErr("");
try {
const r = await api.runSql({ run_id: d.run_id, sql });
setMine({ columns: r.columns, rows: r.rows, sql: r.sql });
} catch (e) { setErr(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }
};
return (
<div className="space-y-3">
{d.calibre && (
<div className="rounded-lg border border-line bg-elevated p-2.5 text-label">
<span className="font-medium">口径:</span>{d.calibre.name}{d.calibre.text ? ` — ${d.calibre.text}` : ""}
</div>
)}
<div>
<div className="mb-1 flex items-center justify-between">
<span className="text-label font-medium text-muted">执行的 SQL(经只读校验)</span>
<span className="flex items-center gap-1.5">
{d.run_id > 0 && !editing && <button className="btn btn-ghost btn-sm" onClick={() => setEditing(true)}>改 SQL 重跑</button>}
<CopyButton text={d.sql} />
</span>
</div>
{editing ? (
<div className="space-y-1.5">
<textarea className="input min-h-[120px] font-mono text-label" value={sql} spellCheck={false} onChange={(e) => setSql(e.target.value)} />
<div className="flex items-center gap-2">
<button className="btn btn-primary btn-sm" disabled={busy || !sql.trim()} onClick={() => void rerun()}>
{busy ? "执行中…" : "执行"}</button>
<button className="btn btn-sm" onClick={() => { setEditing(false); setSql(d.sql); setMine(null); setErr(""); }}>不改了</button>
<span className="text-caption text-muted">只能查询,不能改数据。</span>
</div>
{err && <p className="whitespace-pre-wrap rounded-md bg-bad/5 p-2 text-label text-bad">{err}</p>}
</div>
) : (
<pre className="max-h-40 overflow-auto rounded-lg bg-ink/5 p-2.5 font-mono text-label">{d.sql}</pre>
)}
</div>
{mine && (
<div className="rounded-lg border border-brand/30 p-2.5">
<p className="mb-1.5 text-label font-medium">你改过之后的结果({mine.rows.length} 行)<span className="ml-1 font-normal text-muted">—— 上面答案里的结论还是按原来的数写的</span></p>
<DataTable columns={mine.columns} rows={mine.rows as any[][]} name={`改后-${d.run_id}`} />
</div>
)}
<RankChart columns={d.columns} rows={d.rows} unit={d.metric?.unit || ""} />
<DataTable columns={d.columns} rows={d.rows} name={d.metric?.name || `取数-${d.run_id}`} />
</div>
);
}