import type { ComponentProps } from "react";
import { cn } from "@/lib/utils";
const SHOW_REFERENCE_EVENT = "workspace:show-reference";
export function CitationLink({
href,
children,
className,
...props
}: ComponentProps<"a">) {
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();
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);
}}
{...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;
}