AskAnswer.tsx 7.21 KB
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Database, FileText } from "lucide-react";
import { useMemo, useState } from "react";
import { Badge, CopyButton, Modal } from "@/components/ui";
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-[13.5px] 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-[10px] font-semibold text-brand2 hover:bg-brand2/25"
                    : "mx-0.5 rounded bg-brand/15 px-1 align-super text-[10px] 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-[12.5px]">{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-[14px] font-semibold">{children}</h3>,
          h2: ({ children }) => <h2 className="mt-3 mb-1 text-[15px] font-semibold">{children}</h2>,
          code: ({ children }) => <code className="rounded bg-ink/5 px-1 font-mono text-[12px]">{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-[13px] 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 }) {
  return (
    <div className="space-y-3">
      {d.calibre && (
        <div className="rounded-lg border border-line bg-elevated p-2.5 text-[12.5px]">
          <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-[12px] font-medium text-muted">执行的 SQL(经只读校验)</span>
          <CopyButton text={d.sql} />
        </div>
        <pre className="max-h-40 overflow-auto rounded-lg bg-ink/5 p-2.5 font-mono text-[11.5px]">{d.sql}</pre>
      </div>
      <DataTable columns={d.columns} rows={d.rows} />
    </div>
  );
}

export function DataTable({ columns, rows, max = 50 }: { columns: string[]; rows: any[][]; max?: number }) {
  if (!columns?.length) return <p className="text-[12px] text-muted">无数据</p>;
  return (
    <div className="max-h-80 overflow-auto rounded-lg border border-line">
      <table className="w-full text-[12px]">
        <thead className="sticky top-0 bg-elevated">
          <tr>{columns.map((c) => <th key={c} className="border-b border-line px-2 py-1.5 text-left font-medium">{c}</th>)}</tr>
        </thead>
        <tbody>
          {rows.slice(0, max).map((r, i) => (
            <tr key={i} className="odd:bg-ink/[0.02]">
              {r.map((v, j) => <td key={j} className="border-b border-line/60 px-2 py-1 tabular-nums">{v === null ? "∅" : String(v)}</td>)}
            </tr>
          ))}
        </tbody>
      </table>
      {rows.length > max && <p className="px-2 py-1 text-[11px] text-muted">仅显示前 {max} 行,共 {rows.length} 行</p>}
      {rows.length === 0 && <p className="px-2 py-2 text-[12px] text-muted">查询成功,但没有数据</p>}
    </div>
  );
}

export function RefBadge({ n }: { n: number }) {
  return <Badge tone="bg-brand2/10 text-brand2">{n}</Badge>;
}