"use client"; import { useMemo } from "react"; import type { AnchorHTMLAttributes, HTMLAttributes, ReactNode } from "react"; import { MessageResponse, type MessageResponseProps, } from "@/components/ai-elements/message"; import { streamdownPlugins } from "@/core/streamdown"; import { createMarkdownAnchorResolver, isInPageAnchor, scrollToInPageAnchor, } from "@/core/utils/markdown"; import { cn } from "@/lib/utils"; import { CitationLink } from "../citations/citation-link"; function isExternalUrl(href: string | undefined): boolean { return !!href && /^https?:\/\//.test(href); } function extractTextFromChildren(children: ReactNode): string { if (typeof children === "string" || typeof children === "number") return String(children); if (Array.isArray(children)) return children.map(extractTextFromChildren).join(""); return ""; } export type MarkdownContentProps = { content: string; isLoading: boolean; rehypePlugins: MessageResponseProps["rehypePlugins"]; className?: string; remarkPlugins?: MessageResponseProps["remarkPlugins"]; components?: MessageResponseProps["components"]; }; /** Renders markdown content. */ export function MarkdownContent({ content, rehypePlugins, className, remarkPlugins = streamdownPlugins.remarkPlugins, components: componentsFromProps, }: MarkdownContentProps) { const anchorResolver = useMemo(() => createMarkdownAnchorResolver(content), [content]); const components = useMemo(() => { const heading = (level: 1 | 2 | 3 | 4 | 5 | 6) => { const Tag = `h${level}` as const; return ({ children, id, ...props }: HTMLAttributes) => ( {children} ); }; return { h1: heading(1), h2: heading(2), h3: heading(3), h4: heading(4), h5: heading(5), h6: heading(6), a: (props: AnchorHTMLAttributes) => { if (props.href?.startsWith("#reference-")) { return ; } if (typeof props.children === "string") { const match = /^citation:(.+)$/.exec(props.children); if (match) { const [, text] = match; return {text}; } } const { className, target, rel, ...rest } = props; const external = isExternalUrl(props.href); const resolvedHref = anchorResolver.resolveHref( props.href, extractTextFromChildren(props.children), ); if (resolvedHref === null) { return ( {props.children} ); } const finalHref = resolvedHref ?? props.href; return ( { // HashRouter would turn a `#section` click into a route change → 404. // Scroll to the heading ourselves instead. if (isInPageAnchor(finalHref)) { event.preventDefault(); scrollToInPageAnchor(event.currentTarget, finalHref); } rest.onClick?.(event); }} /> ); }, ...componentsFromProps, }; }, [anchorResolver, componentsFromProps]); if (!content) return null; return (
{content}
); }