Skip to content

The platform for continuously improving AI agents.

6.0 KB
Raw Blame
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
import { createElement, useEffect, useMemo, useRef, useState } from "react";

import { type Components, Streamdown } from "streamdown";

import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { PROSE } from "@/lib/typography";
import { cn } from "@/lib/utils";
import { ChatInlineCitation, entityCitation, type ResolveCitation } from "./chat-inline-citation";

export interface MarkdownProps {
  text: string;
  streaming?: boolean;
  className?: string;
  style?: CSSProperties;
  resolveCitation?: ResolveCitation;
}

type ElementProps = HTMLAttributes<HTMLElement> & { node?: unknown };
const heading = "m-0 mt-2 leading-[1.35] font-semibold tracking-[-0.01em] text-balance first:mt-0";
const cell = "px-2.5 py-1.5 text-left align-top";

const element = (tag: string, base: string) => {
  const Element = ({ node: _node, className, ...props }: ElementProps) =>
    createElement(tag, { ...props, className: cn(base, className) });
  Element.displayName = `Markdown.${tag}`;
  return Element;
};

const textOf = (node: ReactNode): string => {
  if (typeof node === "string" || typeof node === "number") return String(node);
  return Array.isArray(node) ? node.map(textOf).join("") : "";
};

function CodeBlock({ className, children }: ElementProps) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const code = textOf(children).replace(/\n$/u, "");
  const language = className?.match(/language-([^\s]+)/u)?.[1];
  useEffect(
    () => () => {
      if (timer.current !== null) clearTimeout(timer.current);
    },
    []
  );
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(code);
    } catch {
      // Clipboard permissions can be denied even on a secure page.
      return;
    }
    setCopied(true);
    if (timer.current !== null) clearTimeout(timer.current);
    timer.current = setTimeout(() => setCopied(false), 1600);
  };
  return (
    <div
      className="relative min-w-0 rounded-sm bg-muted"
      data-language={language}
      data-slot="markdown-code"
    >
      <pre className="m-0 overflow-x-auto py-2.5 pr-11 pl-3 font-mono text-[0.86em] leading-[1.6] [overflow-wrap:normal] whitespace-pre">
        <code>{code}</code>
      </pre>
      <Button
        aria-label={copied ? "Copied" : "Copy code"}
        className="absolute top-1.5 right-1.5 text-muted-foreground"
        onClick={copy}
        size="icon-sm"
        type="button"
        variant="ghost"
      >
        {copied ? <Icon.success className="size-3.5" /> : <Icon.copy className="size-3.5" />}
      </Button>
    </div>
  );
}

const components: Components = {
  blockquote: element(
    "blockquote",
    "m-0 flex flex-col gap-2 border-l-2 border-border pl-3 text-muted-foreground"
  ),
  code: CodeBlock,
  del: element("del", "text-muted-foreground"),
  em: element("em", "italic"),
  h1: element("h1", cn(heading, "text-[1.3em]")),
  h2: element("h2", cn(heading, "text-[1.15em]")),
  h3: element("h3", cn(heading, "text-[1em]")),
  h4: element("h4", cn(heading, "text-[1em]")),
  h5: element("h5", cn(heading, "text-[1em]")),
  h6: element("h6", cn(heading, "text-[1em] text-muted-foreground")),
  hr: element("hr", "my-1 h-px w-full border-0 bg-border/70"),
  // Remote image URLs can disclose conversation content to their hosts.
  img: ({ alt }) => <span>{alt}</span>,
  inlineCode: element(
    "code",
    "rounded-sm bg-foreground/6 box-decoration-clone px-1 py-px font-mono text-[0.86em]"
  ),
  li: element("li", "pl-0.5 [&>ol]:mt-1 [&>ul]:mt-1"),
  ol: element("ol", "m-0 flex list-decimal flex-col gap-1 pl-5 marker:text-muted-foreground"),
  p: element("p", "m-0"),
  strong: element("strong", "font-semibold"),
  table: ({ node: _node, className, children, ...props }) => (
    <div
      className="max-w-full overflow-x-auto rounded-sm border border-border"
      data-slot="markdown-table"
    >
      <table
        {...props}
        className={cn("w-full border-collapse text-[0.86em] leading-[1.45]", className)}
      >
        {children}
      </table>
    </div>
  ),
  td: element("td", cell),
  th: element("th", cn(cell, "font-medium")),
  thead: element("thead", "bg-muted"),
  tr: element("tr", "border-t border-border/60 first:border-t-0"),
  ul: element("ul", "m-0 flex list-disc flex-col gap-1 pl-5 marker:text-muted-foreground"),
};
const linkSafety = { enabled: false } as const;

export function Markdown({
  text,
  streaming = false,
  className,
  style,
  resolveCitation = entityCitation,
}: MarkdownProps) {
  const renderers = useMemo(
    () => ({
      ...components,
      a: ({ href, children }: { href?: string; children?: ReactNode }) => {
        const target = href ? resolveCitation(href) : undefined;
        if (target) return <ChatInlineCitation target={target}>{children}</ChatInlineCitation>;
        if (href && /^#(?:node|cell)=/.test(href)) return <span>{children}</span>;
        return (
          <a
            className="rounded-sm font-medium text-inherit underline decoration-foreground/25 underline-offset-2 transition-colors hover:decoration-current focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:outline-none"
            href={href}
            rel="noopener noreferrer"
            target="_blank"
          >
            {children}
          </a>
        );
      },
    }),
    [resolveCitation]
  );
  return (
    <div
      className={cn(
        PROSE,
        "min-w-0 text-[15px] leading-[1.6] tracking-[-0.005em] [overflow-wrap:anywhere]",
        className
      )}
      data-slot="markdown"
      data-streaming={streaming ? "true" : undefined}
      style={style}
    >
      <Streamdown
        className="flex min-w-0 flex-col gap-3 space-y-0"
        components={renderers}
        controls={false}
        isAnimating={streaming}
        linkSafety={linkSafety}
        parseIncompleteMarkdown={streaming}
      >
        {text.replace(/\]\(cell:([a-zA-Z0-9-]+)\)/g, "](#cell=$1)")}
      </Streamdown>
    </div>
  );
}