import type { ComponentProps } from "react"; import { cn } from "@/lib/utils"; const SHOW_REFERENCE_EVENT = "workspace:show-reference"; export function CitationLink({ href, children, className, onReferenceClick, onClick, ...props }: ComponentProps<"a"> & { /** Lets a message renderer show an in-place source preview instead of scrolling. */ onReferenceClick?: (referenceId: string) => void; }) { const childrenText = normalizeCitationText(children); const displayText = childrenText ?? ""; const referenceId = href?.startsWith("#reference-") ? href.slice("#reference-".length) : null; if (referenceId) { const badgeLabel = displayText.replace(/^\[|\]$/g, "") || referenceId; return ( { event.preventDefault(); if (onReferenceClick) { onReferenceClick(referenceId); onClick?.(event); return; } const batchId = event.currentTarget.closest("[data-reference-batch-id]") ?.dataset.referenceBatchId; window.dispatchEvent( new CustomEvent(SHOW_REFERENCE_EVENT, { detail: { batchId, referenceId }, }), ); const scroll = () => { const target = document.getElementById(`reference-${referenceId}`); target?.scrollIntoView({ behavior: "smooth", block: "center" }); }; window.setTimeout(scroll, 240); onClick?.(event); }} {...props} > {badgeLabel} ); } return ( {displayText || children} ); } function normalizeCitationText(children: ComponentProps<"a">["children"]) { if (typeof children !== "string") { return null; } let text = children.trim(); while (/^citation:\s*/i.test(text)) { text = text.replace(/^citation:\s*/i, ""); } return text; }