AnswerPanel.tsx 4.83 KB
import { Check, Copy, FileText, Quote } from "lucide-react";
import { useMemo, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { cn, formatDuration, shortHeading } from "@/lib/utils";
import { Badge, Empty } from "@/components/ui";
import type { Citation } from "@/lib/types";

/**
 * 答案区:流式 Markdown + 可点击引用。
 *
 * v1 的答案是一次性返回的(用户干等 20~30 秒),引用只是章节名字符串,点不动。
 * 这里把 `[^chunk_id]` 渲染成上标角标,点一下直接打开对应原文片段。
 */
export function AnswerPanel({ answer, streaming, citations, durationMs, onOpenChunk, embedded }: {
  answer: string;
  streaming: boolean;
  citations: Citation[];
  durationMs: number;
  onOpenChunk: (id: string) => void;
  /** 对话流里内嵌展示:不强占父容器高度、不用自己的滚动条,随页面一起滚动。 */
  embedded?: boolean;
}) {
  const [copied, setCopied] = useState(false);

  // 把 [^id] 换成一个可点的标记,交给 Markdown 的 code 渲染器处理
  const prepared = useMemo(() => {
    const order = new Map<string, number>();
    citations.forEach((c, i) => order.set(c.chunk_id, i + 1));
    return answer.replace(/\[\^([A-Za-z0-9:_\-]+)\]/g, (_m, id: string) => {
      const n = order.get(id) ?? order.size + 1;
      if (!order.has(id)) order.set(id, n);
      return `\`†${n}†${id}\``;
    });
  }, [answer, citations]);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(answer);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch { /* 剪贴板不可用时静默 */ }
  };

  if (!answer && !streaming) {
    if (embedded) return null;
    return (
      <Empty icon={<Quote className="h-8 w-8" />} title="还没有回答"
             desc="输入一个业务问题并开始检索,答案会逐字流式出现在这里,并带上可点击的原文引用。" />
    );
  }

  return (
    <div className={cn(embedded ? "flex flex-col" : "flex h-full flex-col")}>
      <div className={cn("flex shrink-0 items-center gap-2", embedded ? "py-1.5" : "border-b border-line px-3 py-2")}>
        {!embedded && <h3 className="text-[13px] font-semibold">回答</h3>}
        {durationMs > 0 && <Badge>{formatDuration(durationMs)}</Badge>}
        {streaming && (
          <span className="flex items-center gap-1 text-[11px] text-brand">
            <i className="h-1.5 w-1.5 animate-pulse rounded-full bg-brand" />生成中
          </span>
        )}
        <button className="btn btn-ghost btn-sm ml-auto" onClick={copy} title="复制全文">
          {copied ? <Check className="h-3.5 w-3.5 text-ok" /> : <Copy className="h-3.5 w-3.5" />}
        </button>
      </div>

      <div className={embedded ? "" : "min-h-0 flex-1 overflow-auto px-4 py-3"}>
        <div className="prose-answer">
          <ReactMarkdown
            remarkPlugins={[remarkGfm]}
            components={{
              code({ children, className, ...rest }) {
                const text = String(children);
                const m = /^†(\d+)†(.+)$/.exec(text);
                if (m) {
                  return (
                    <button
                      onClick={() => onOpenChunk(m[2])}
                      title={`查看原文 ${m[2]}`}
                      className="mx-0.5 inline-flex h-4 min-w-4 items-center justify-center rounded
                                 bg-brand/15 px-1 align-super text-[10px] font-semibold text-brand
                                 hover:bg-brand/30"
                    >{m[1]}</button>
                  );
                }
                return <code className={className} {...rest}>{children}</code>;
              },
            }}
          >{prepared}</ReactMarkdown>
          {streaming && <span className="ml-0.5 inline-block h-4 w-[2px] animate-pulse bg-brand align-middle" />}
        </div>
      </div>

      {citations.length > 0 && (
        <div className={cn("shrink-0", embedded ? "pt-2" : "border-t border-line px-3 py-2")}>
          <p className="mb-1.5 flex items-center gap-1 text-[11px] font-medium text-muted">
            <FileText className="h-3 w-3" />引用来源({citations.length})—— 点击查看原文
          </p>
          <div className="flex flex-wrap gap-1.5">
            {citations.map((c, i) => (
              <button key={c.chunk_id}
                      className="chip hover:border-brand/50"
                      onClick={() => onOpenChunk(c.chunk_id)}>
                <span className="grid h-4 w-4 place-items-center rounded bg-brand/15 text-[10px] font-semibold text-brand">
                  {i + 1}
                </span>
                <span className="max-w-[16rem] truncate">{shortHeading(c.heading)}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}