"use client"
import {
createContext,
memo,
useContext,
useState,
type ComponentPropsWithoutRef,
type ReactNode,
} from "react"
import ReactMarkdown, { type ExtraProps } from "react-markdown"
import remarkGfm from "remark-gfm"
import { CheckIcon, CopyIcon } from "lucide-react"
import { cn } from "@/lib/utils"
import {
CitationChip,
childrenToPlainText,
isCitationLabel,
} from "@/registry/tonic/citation/citation"
import { Button } from "@/registry/tonic/ui/button"
const BlockCodeContext = createContext(false)
type MarkdownElementProps = ComponentPropsWithoutRef<"pre"> & ExtraProps
type CodeElementProps = ComponentPropsWithoutRef<"code"> & ExtraProps
function CodeHeader({ language, code }: { language?: string; code: string }) {
const [copied, setCopied] = useState(false)
return (
<div className="border-border/50 bg-muted/50 mt-3 flex items-center justify-between rounded-t-xl border border-b-0 px-3.5 py-1.5 text-xs">
<span className="text-muted-foreground font-medium lowercase">
{language || "text"}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="size-6"
aria-label="Copy code"
onClick={async () => {
if (!code || copied) return
await navigator.clipboard.writeText(code)
setCopied(true)
window.setTimeout(() => setCopied(false), 1500)
}}
>
{copied ? (
<CheckIcon className="size-3.5" />
) : (
<CopyIcon className="size-3.5" />
)}
</Button>
</div>
)
}
const markdownComponents = {
h1: ({ className, ...props }: ComponentPropsWithoutRef<"h1">) => (
<h1
className={cn(
"mt-5 mb-2 scroll-m-20 text-[15px] font-semibold first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h2: ({ className, ...props }: ComponentPropsWithoutRef<"h2">) => (
<h2
className={cn(
"mt-5 mb-2 scroll-m-20 text-[15px] font-semibold first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h3: ({ className, ...props }: ComponentPropsWithoutRef<"h3">) => (
<h3
className={cn(
"mt-4 mb-1.5 scroll-m-20 text-[15px] font-semibold first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
h4: ({ className, ...props }: ComponentPropsWithoutRef<"h4">) => (
<h4
className={cn(
"mt-3.5 mb-1 scroll-m-20 text-[15px] font-medium first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
p: ({ className, ...props }: ComponentPropsWithoutRef<"p">) => (
<p
className={cn(
"my-3 text-[15px] leading-6 first:mt-0 last:mb-0",
className
)}
{...props}
/>
),
a: function MarkdownLink({
className,
children,
href,
title,
...props
}: ComponentPropsWithoutRef<"a">) {
const label = childrenToPlainText(children)
if (href && isCitationLabel(label) && /^https?:\/\//i.test(href)) {
return (
<CitationChip
index={label.replace(/[\[\]]/g, "")}
href={href}
title={typeof title === "string" ? title : undefined}
/>
)
}
return (
<a
href={href}
title={title}
target="_blank"
rel="noreferrer"
className={cn("text-foreground underline underline-offset-2", className)}
{...props}
>
{children}
</a>
)
},
ul: ({ className, ...props }: ComponentPropsWithoutRef<"ul">) => (
<ul
className={cn("my-3 list-disc space-y-1 ps-5 text-[15px] leading-6", className)}
{...props}
/>
),
ol: ({ className, ...props }: ComponentPropsWithoutRef<"ol">) => (
<ol
className={cn(
"my-3 list-decimal space-y-1 ps-5 text-[15px] leading-6",
className
)}
{...props}
/>
),
li: ({ className, ...props }: ComponentPropsWithoutRef<"li">) => (
<li className={cn("leading-6", className)} {...props} />
),
blockquote: ({
className,
...props
}: ComponentPropsWithoutRef<"blockquote">) => (
<blockquote
className={cn(
"border-border text-muted-foreground my-3 border-l-2 ps-3",
className
)}
{...props}
/>
),
table: ({ className, ...props }: ComponentPropsWithoutRef<"table">) => (
<div className="my-3 overflow-x-auto">
<table
className={cn("w-full border-collapse text-[13px]", className)}
{...props}
/>
</div>
),
th: ({ className, ...props }: ComponentPropsWithoutRef<"th">) => (
<th
className={cn(
"border-border border-b px-2 py-1.5 text-start font-medium",
className
)}
{...props}
/>
),
td: ({ className, ...props }: ComponentPropsWithoutRef<"td">) => (
<td
className={cn("border-border/60 border-b px-2 py-1.5 align-top", className)}
{...props}
/>
),
hr: ({ className, ...props }: ComponentPropsWithoutRef<"hr">) => (
<hr className={cn("border-border my-4", className)} {...props} />
),
pre: ({ children, className, ...props }: MarkdownElementProps) => {
const codeChild = Array.isArray(children) ? children[0] : children
const codeProps =
codeChild &&
typeof codeChild === "object" &&
"props" in codeChild
? (codeChild.props as { className?: string; children?: ReactNode })
: undefined
const language = codeProps?.className?.match(/language-([^\s]+)/)?.[1]
const codeText = childrenToPlainText(codeProps?.children ?? children)
return (
<BlockCodeContext.Provider value={true}>
<div className="my-3 first:mt-0 last:mb-0">
<CodeHeader language={language} code={codeText} />
<pre
className={cn(
"border-border/50 bg-muted/30 overflow-x-auto rounded-b-xl border border-t-0 p-3.5 text-[13px] leading-relaxed",
className
)}
{...props}
>
{children}
</pre>
</div>
</BlockCodeContext.Provider>
)
},
code: ({ className, children, ...props }: CodeElementProps) => {
const isBlock = useContext(BlockCodeContext)
return (
<code
className={cn(
!isBlock &&
"bg-muted rounded-md px-1.5 py-0.5 font-mono text-[0.85em]",
className
)}
{...props}
>
{children}
</code>
)
},
}
export const MessageMarkdown = memo(function MessageMarkdown({
text,
className,
}: {
readonly text: string
readonly className?: string
}) {
return (
<div data-slot="message-markdown" className={cn("aui-md", className)}>
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
{text}
</ReactMarkdown>
</div>
)
})