359 lines
15 KiB
TypeScript
359 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import React, { useState } from "react";
|
|
import type { ChatMessage, Citation } from "@duoc-thu/shared-types";
|
|
import {
|
|
ShieldCheck,
|
|
FileCheck2,
|
|
Copy,
|
|
Check,
|
|
AlertTriangle,
|
|
Pill,
|
|
Sparkles,
|
|
Info,
|
|
RotateCcw,
|
|
ExternalLink,
|
|
BookOpen,
|
|
CornerDownRight,
|
|
} from "lucide-react";
|
|
import { cn } from "./lib/utils";
|
|
import { citationSectionLabel } from "./CitationCard";
|
|
|
|
// Display-only patch, 2026-08-13: exactly 3 of 684 catalog entries have "Đ"/
|
|
// "đ" in their canonical name (ingestion's slug generator maps every other
|
|
// Vietnamese diacritic to its base Latin letter, but drops "Đ"/"đ" entirely
|
|
// instead of mapping it to "D"/"d" — it is not a combining-mark decomposition
|
|
// under Unicode NFKD, so a generic accent-strip silently loses it). Fixing
|
|
// the underlying drug_id would mean re-keying every citation chunk_id built
|
|
// from it in the already-loaded Qdrant corpus, so this only corrects the
|
|
// header label shown to the user, not the data. Verified against the full
|
|
// catalog (`ingestion/data/verified/drug_entities.json`): these are the only
|
|
// 3 affected ids.
|
|
const DRUG_ID_DISPLAY_OVERRIDES: Record<string, string> = {
|
|
giai_oc_to_uon_van_hap_phu_vac_xin_uon_van_hap_phu:
|
|
"GIẢI ĐỘC TỐ UỐN VÁN HẤP PHỤ (VẮC XIN UỐN VÁN HẤP PHỤ)",
|
|
khang_oc_to_bach_hau: "KHÁNG ĐỘC TỐ BẠCH HẦU",
|
|
thuoc_uong_bu_nuoc_va_ien_giai: "THUỐC UỐNG BÙ NƯỚC VÀ ĐIỆN GIẢI",
|
|
};
|
|
|
|
function formatResolvedDrugId(resolvedDrugId: string): string {
|
|
return resolvedDrugId
|
|
.split(",")
|
|
.map((id) => id.trim())
|
|
.filter(Boolean)
|
|
.map((id) => DRUG_ID_DISPLAY_OVERRIDES[id] ?? id.replace(/_/g, " ").toUpperCase())
|
|
.join(", ");
|
|
}
|
|
|
|
interface ChatBubbleProps {
|
|
message: ChatMessage;
|
|
// `allCitations` is THIS message's own citation list (`message.citations`)
|
|
// — found live 2026-08-07: the caller previously had no way to know which
|
|
// message a click came from, so it kept showing whatever citation array a
|
|
// LATER message had most recently loaded. Clicking [1] on an old answer
|
|
// (e.g. Omeprazol's mechanism) displayed a completely unrelated later
|
|
// drug's evidence (e.g. Kanamycin) in the source panel — a real, live-
|
|
// reported bug for a product whose entire value proposition is a
|
|
// verifiable citation trail.
|
|
onCitationClick?: (citation: Citation, index: number, allCitations: Citation[]) => void;
|
|
activeCitationIndex?: number | null;
|
|
onRetry?: () => void;
|
|
/** Fired when the user picks a quick-reply chip instead of typing — sends that text as the next turn. */
|
|
onQuickReply?: (text: string) => void;
|
|
className?: string;
|
|
}
|
|
|
|
export function ChatBubble({
|
|
message,
|
|
onCitationClick,
|
|
activeCitationIndex,
|
|
onRetry,
|
|
onQuickReply,
|
|
className,
|
|
}: ChatBubbleProps) {
|
|
const [copied, setCopied] = useState(false);
|
|
const isUser = message.role === "user";
|
|
|
|
const handleCopy = () => {
|
|
navigator.clipboard.writeText(message.content);
|
|
setCopied(true);
|
|
setTimeout(() => setCopied(false), 2000);
|
|
};
|
|
|
|
if (isUser) {
|
|
return (
|
|
<div className={cn("flex w-full justify-end my-3", className)}>
|
|
<div className="max-w-2xl rounded-2xl bg-accent-primary text-txt-inverse px-4 py-3 shadow-sm text-sm font-medium leading-relaxed">
|
|
{message.content}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Citation markers must render INLINE within whatever block (paragraph/
|
|
// bullet/heading) they end the sentence of — never split out as a bare
|
|
// top-level element. Found live 2026-08-07: the old approach split the
|
|
// WHOLE content on `[n]` first and only then broke each piece into lines,
|
|
// so a citation sitting on its own source line (a common shape for a
|
|
// multi-band dosing answer, e.g. "...5,4 g/ngày\n[1]\n; cấp tính...") ended
|
|
// up as a bare `<button>` between two block-level `<p>`s — visually its
|
|
// own orphaned line, fragmenting a short list into a choppy one-clause-
|
|
// per-line mess instead of a readable paragraph or bullet list.
|
|
const renderInline = (text: string, keyPrefix: string, citations?: Citation[]) => {
|
|
const segments = text.split(/(\[\d+\])/g);
|
|
return segments.map((seg, i) => {
|
|
const match = seg.match(/^\[(\d+)\]$/);
|
|
if (!match) {
|
|
return <React.Fragment key={`${keyPrefix}-t-${i}`}>{formatBoldText(seg)}</React.Fragment>;
|
|
}
|
|
const citationIndex = parseInt(match[1], 10);
|
|
const citationObj = citations && citations[citationIndex - 1];
|
|
const isActive = activeCitationIndex === citationIndex;
|
|
return (
|
|
<button
|
|
key={`${keyPrefix}-c-${i}`}
|
|
id={`citation-marker-${citationIndex}`}
|
|
onClick={() => {
|
|
if (citationObj) {
|
|
onCitationClick?.(citationObj, citationIndex, citations ?? []);
|
|
}
|
|
}}
|
|
title={citationObj ? `${citationObj.drugName} (${citationObj.sectionType})` : `Trích dẫn [${citationIndex}]`}
|
|
className={cn(
|
|
"inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 mx-0.5 rounded-full text-[0.68rem] font-extrabold tracking-tight transition-all align-baseline cursor-pointer select-none",
|
|
isActive
|
|
? "bg-accent-primary text-txt-inverse scale-110 shadow-md ring-2 ring-accent-glow glass-beam-glow"
|
|
: "bg-accent-soft text-accent-primary hover:bg-accent-primary hover:text-txt-inverse border border-border-subtle"
|
|
)}
|
|
>
|
|
{citationIndex}
|
|
</button>
|
|
);
|
|
});
|
|
};
|
|
|
|
// Helper to parse citations [1], [2] in markdown content
|
|
const renderStructuredContent = (content: string, citations?: Citation[]) => {
|
|
const lines = content.split("\n");
|
|
return lines.map((line, lineIdx) => {
|
|
if (!line.trim()) return <br key={lineIdx} />;
|
|
|
|
// Heading 2 or 3
|
|
if (line.startsWith("### ") || line.startsWith("## ")) {
|
|
return (
|
|
<h3 key={lineIdx} className="text-base font-extrabold text-txt-primary mt-3 mb-1.5 flex items-center gap-2">
|
|
<span className="w-1.5 h-4 rounded-full bg-accent-primary inline-block" />
|
|
{renderInline(line.replace(/^#+\s*/, ""), `h-${lineIdx}`, citations)}
|
|
</h3>
|
|
);
|
|
}
|
|
|
|
// Bullet points
|
|
if (line.trim().startsWith("- ") || line.trim().startsWith("* ")) {
|
|
return (
|
|
<li key={lineIdx} className="ml-4 list-disc text-txt-secondary mb-1">
|
|
{renderInline(line.trim().replace(/^[-*]\s*/, ""), `li-${lineIdx}`, citations)}
|
|
</li>
|
|
);
|
|
}
|
|
|
|
// Warning block / Note
|
|
if (line.includes("Chống chỉ định") || line.includes("Cảnh báo") || line.includes("Thận trọng")) {
|
|
return (
|
|
<div key={lineIdx} className="my-2 rounded-xl border border-status-warning/40 bg-status-warning-bg/60 p-3 text-xs leading-relaxed text-txt-primary flex items-start gap-2.5">
|
|
<AlertTriangle className="h-4 w-4 text-status-warning shrink-0 mt-0.5" />
|
|
<div>{renderInline(line, `w-${lineIdx}`, citations)}</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// The primary clinical answer text — the one thing on this whole card
|
|
// a clinician actually needs to read, so it carries more visual
|
|
// weight than the surrounding header/footer chrome (found live
|
|
// 2026-08-07: previously the same low-emphasis size/weight as
|
|
// everything else, easy to skim past).
|
|
return (
|
|
<p key={lineIdx} className="mb-2 text-txt-primary text-[0.95rem] font-medium leading-relaxed">
|
|
{renderInline(line, `p-${lineIdx}`, citations)}
|
|
</p>
|
|
);
|
|
});
|
|
};
|
|
|
|
const formatBoldText = (text: string) => {
|
|
const boldParts = text.split(/(\*\*.*?\*\*)/g);
|
|
return boldParts.map((bPart, bIdx) => {
|
|
if (bPart.startsWith("**") && bPart.endsWith("**")) {
|
|
return (
|
|
<strong key={bIdx} className="font-bold text-txt-primary">
|
|
{bPart.slice(2, -2)}
|
|
</strong>
|
|
);
|
|
}
|
|
return bPart;
|
|
});
|
|
};
|
|
|
|
const renderAnswerBlocks = () => {
|
|
if (!message.blocks?.length) return null;
|
|
|
|
return (
|
|
<div className="space-y-5">
|
|
{message.blocks.map((block, blockIndex) => {
|
|
const warning = block.kind === "warning" && message.answerPlan?.needsWarning;
|
|
const showHeading = message.blocks!.length > 1 || message.answerPlan?.showHeading;
|
|
const sourceIds = Array.from(new Set(block.claims.flatMap((claim) => claim.sourceIds)));
|
|
const sources = sourceIds.flatMap((sourceId) => {
|
|
const index = message.citations?.findIndex((item) => item.chunkId === sourceId) ?? -1;
|
|
const citation = index >= 0 ? message.citations?.[index] : undefined;
|
|
return citation ? [{ citation, index }] : [];
|
|
});
|
|
return (
|
|
<section
|
|
key={`${block.title}-${blockIndex}`}
|
|
className={cn(
|
|
warning && "rounded-lg border-l-2 border-status-warning bg-status-warning-bg/25 px-3 py-2"
|
|
)}
|
|
>
|
|
{showHeading && (
|
|
<h4 className="mb-2 flex items-center gap-2 text-sm font-bold text-txt-primary">
|
|
{warning && <AlertTriangle className="h-4 w-4 shrink-0 text-status-warning" />}
|
|
{block.title}
|
|
</h4>
|
|
)}
|
|
<ul className="list-none space-y-2 p-0" style={{ listStyle: "none" }}>
|
|
{block.claims.map((claim, claimIndex) => (
|
|
<li
|
|
key={`${blockIndex}-${claimIndex}`}
|
|
className="text-[0.96rem] leading-relaxed text-txt-primary"
|
|
style={{ listStyle: "none" }}
|
|
>
|
|
<div className="flex items-start gap-2.5">
|
|
{message.answerPlan?.layout !== "prose" && (
|
|
<span className="mt-[0.6rem] h-1.5 w-1.5 shrink-0 rounded-full bg-accent-primary" />
|
|
)}
|
|
<div>{formatBoldText(claim.text)}</div>
|
|
</div>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
{sources.length > 0 && (
|
|
<div className="mt-2.5 flex flex-wrap gap-x-3 gap-y-1">
|
|
{sources.map(({ citation, index }) => (
|
|
<button
|
|
key={citation.chunkId}
|
|
onClick={() => onCitationClick?.(citation, index + 1, message.citations ?? [])}
|
|
className="inline-flex items-center gap-1 text-[0.7rem] font-medium text-txt-muted transition-colors hover:text-accent-primary"
|
|
>
|
|
<BookOpen className="h-3 w-3" />
|
|
{/* Several distinct chunks routinely share one drug,
|
|
section and printed page (seen live 2026-08-11:
|
|
three chips all reading "METFORMIN · Liều lượng &
|
|
Cách dùng · tr. 957"), which reads as the same
|
|
link repeated. They are deliberately not collapsed
|
|
by label: each chip opens a different evidence
|
|
block and provenance is a hard guardrail. Instead
|
|
each carries the number the evidence panel already
|
|
shows on its cards, so a chip maps to exactly one
|
|
card. The number stays off single-source blocks,
|
|
where there is nothing to disambiguate. */}
|
|
Xem căn cứ{sources.length > 1 ? ` [${index + 1}]` : ""} · {citation.drugName} · {citationSectionLabel(citation.sectionType)} · tr. {citation.sourcePageRange[0]}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</section>
|
|
);
|
|
})}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<article
|
|
className={cn(
|
|
"my-5 w-full",
|
|
className
|
|
)}
|
|
>
|
|
<header className="mb-2.5 flex flex-wrap items-center justify-between gap-2">
|
|
<div className="flex items-center gap-2">
|
|
<div className="flex h-6 w-6 items-center justify-center rounded-full bg-accent-soft text-accent-primary">
|
|
<BookOpen className="h-3.5 w-3.5" />
|
|
</div>
|
|
<span className="text-xs font-semibold text-txt-secondary">
|
|
{message.resolvedDrugId ? formatResolvedDrugId(message.resolvedDrugId) : "Trợ lý Dược thư"}
|
|
</span>
|
|
{message.decision === "answerable" && message.grounded !== false && (
|
|
<span className="inline-flex items-center gap-1 text-[0.68rem] font-medium text-status-success">
|
|
<ShieldCheck className="h-3 w-3" />
|
|
Có căn cứ Dược thư
|
|
</span>
|
|
)}
|
|
</div>
|
|
<time className="hidden text-[0.68rem] text-txt-muted sm:inline">
|
|
{new Date(message.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
|
|
</time>
|
|
</header>
|
|
|
|
{/* Document Body */}
|
|
<div className={cn(
|
|
"medical-document-body rounded-2xl px-4 py-3.5 sm:px-5",
|
|
message.grounded === false ? "bg-status-warning-bg/25" : "bg-surface"
|
|
)}>
|
|
{message.blocks?.length
|
|
? renderAnswerBlocks()
|
|
: renderStructuredContent(message.content, message.citations)}
|
|
</div>
|
|
|
|
{/* Quick-reply chips — only for a clarify turn the model gave a few
|
|
natural discrete answers to; free text always still works. */}
|
|
{onQuickReply && message.quickReplies && message.quickReplies.length > 0 && (
|
|
<div className="px-4 pb-3 flex flex-wrap gap-2">
|
|
{message.quickReplies.map((reply, idx) => (
|
|
<button
|
|
key={idx}
|
|
onClick={() => onQuickReply?.(reply)}
|
|
className="inline-flex items-center gap-1.5 rounded-full border border-border-accent bg-accent-soft px-3 py-1.5 text-xs font-bold text-accent-primary hover:bg-accent-primary hover:text-txt-inverse transition-colors"
|
|
>
|
|
<CornerDownRight className="h-3 w-3" />
|
|
{reply}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
<footer className="mt-1 flex justify-end gap-1 text-xs text-txt-muted">
|
|
<div className="flex items-center gap-2">
|
|
{onRetry && (
|
|
<button
|
|
onClick={onRetry}
|
|
className="flex items-center gap-1 rounded-lg px-2.5 py-1 text-txt-muted hover:bg-surface-hover hover:text-txt-primary transition-colors text-xs font-medium"
|
|
>
|
|
<RotateCcw className="h-3.5 w-3.5" />
|
|
<span>Thử lại</span>
|
|
</button>
|
|
)}
|
|
|
|
<button
|
|
onClick={handleCopy}
|
|
className="flex items-center gap-1 rounded-lg px-2.5 py-1 text-txt-muted hover:bg-surface-hover hover:text-txt-primary transition-colors text-xs font-medium"
|
|
>
|
|
{copied ? (
|
|
<>
|
|
<Check className="h-3.5 w-3.5 text-status-success" />
|
|
<span className="text-status-success font-bold">Đã chép</span>
|
|
</>
|
|
) : (
|
|
<>
|
|
<Copy className="h-3.5 w-3.5" />
|
|
<span>Sao chép</span>
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
</footer>
|
|
</article>
|
|
);
|
|
}
|