{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "markdown",
  "title": "Markdown",
  "description": "A streaming-safe markdown renderer. Every node is a semantic element inside a shadcn/typeset container, so the typography comes from typeset, and the append-only cache re-parses only the open block while the source grows.",
  "dependencies": [
    "cn"
  ],
  "registryDependencies": [
    "litingyes/blocove/markdown-parse"
  ],
  "files": [
    {
      "path": "src/registry/blocove/ui/markdown/markdown.tsx",
      "content": "/* eslint-disable react/no-array-index-key -- parsed list items, table rows and cells are positional, so the index is the stable identity. */\n\nimport type { ReactNode } from 'react'\nimport type {\n  MarkdownBlock,\n  MarkdownCache,\n  MarkdownComponents,\n  MarkdownInline,\n  MarkdownListBlock,\n  MarkdownTableBlock,\n} from '@/lib/blocove/markdown-parse'\nimport { cn } from 'cn'\nimport { Fragment, memo, useMemo, useRef, useState } from 'react'\nimport { extendMarkdown, parseMarkdown } from '@/lib/blocove/markdown-parse'\n\nexport type { MarkdownComponents }\n\nexport interface MarkdownProps {\n  /** Markdown source. Growing the string incrementally is what the shell is built for. */\n  source: string\n  /** Mark the surface as still receiving tokens. */\n  streaming?: boolean\n  /** Apply the shadcn/typeset styles to the rendered nodes. */\n  typeset?: boolean\n  /** Optional renderers for the capability items, keyed by node family. */\n  components?: MarkdownComponents\n  className?: string\n  /** Applied to the typeset element that holds the nodes. */\n  contentClassName?: string\n}\n\n/**\n * Keeps the parse cache in state and re-parses only the open tail when the\n * source grows. The render-phase update mirrors `useHighlightedCode`: the cache\n * is derived from the props, so it is computed during render and committed\n * immediately.\n */\nfunction useMarkdownBlocks(source: string): MarkdownCache {\n  const [cache, setCache] = useState(() => parseMarkdown(source))\n\n  if (cache.source !== source) {\n    const next = extendMarkdown(cache, source)\n\n    if (next !== cache) {\n      setCache(next)\n    }\n\n    return next\n  }\n\n  return cache\n}\n\nfunction fencesEqual(\n  a: MarkdownComponents['fences'],\n  b: MarkdownComponents['fences'],\n): boolean {\n  if (a === b) {\n    return true\n  }\n\n  if (!a || !b) {\n    return false\n  }\n\n  const keys = Object.keys(a)\n\n  return keys.length === Object.keys(b).length\n    && keys.every(key => a[key] === b[key])\n}\n\n/**\n * The `components` map is rebuilt by callers that pass an inline object. Blocks\n * are memoized on the map, so it is held stable until one of its entries does\n * change; `fences` is compared entry by entry for the same reason. Module\n * constants are still the cheapest way to keep the map stable.\n */\nfunction useStableComponents(components: MarkdownComponents | undefined): MarkdownComponents | undefined {\n  const ref = useRef(components)\n\n  if (\n    ref.current?.code !== components?.code\n    || ref.current?.math !== components?.math\n    || !fencesEqual(ref.current?.fences, components?.fences)\n  ) {\n    ref.current = components\n  }\n\n  return ref.current\n}\n\nfunction renderMath(\n  value: string,\n  display: boolean,\n  components: MarkdownComponents | undefined,\n  streaming: boolean,\n  key: string,\n): ReactNode {\n  const MathRenderer = components?.math\n\n  if (MathRenderer) {\n    return <MathRenderer key={key} value={value} display={display} streaming={streaming} />\n  }\n\n  return (\n    <code key={key}>\n      {display\n        ? `$$${value}$$`\n        : `$${value}$`}\n    </code>\n  )\n}\n\nfunction renderInline(\n  nodes: MarkdownInline[],\n  components: MarkdownComponents | undefined,\n  footnotes: ReadonlyMap<string, number>,\n  streaming = false,\n): ReactNode {\n  return nodes.map((node, index) => {\n    const key = `${node.kind}-${index}`\n\n    switch (node.kind) {\n      case 'text':\n        return node.value\n      case 'strong':\n        return <strong key={key}>{renderInline(node.children, components, footnotes)}</strong>\n      case 'emphasis':\n        return <em key={key}>{renderInline(node.children, components, footnotes)}</em>\n      case 'del':\n        return <del key={key}>{renderInline(node.children, components, footnotes)}</del>\n      case 'code':\n        return <code key={key}>{node.value}</code>\n      case 'link':\n        return (\n          <a key={key} href={node.href} title={node.title}>\n            {renderInline(node.children, components, footnotes)}\n          </a>\n        )\n      case 'image':\n        return (\n          <img\n            key={key}\n            src={node.src}\n            alt={node.alt}\n            title={node.title}\n            loading=\"lazy\"\n            decoding=\"async\"\n          />\n        )\n      case 'math':\n        return renderMath(node.value, false, components, streaming, key)\n      case 'footnote-ref': {\n        const number = footnotes.get(node.id)\n\n        // A reference without a definition stays literal.\n        return number === undefined\n          ? `[^${node.id}]`\n          : (\n              <sup key={key}>\n                <a href={`#fn-${node.id}`} id={`fnref-${node.id}`}>{number}</a>\n              </sup>\n            )\n      }\n      case 'break':\n        return node.hard\n          ? <br key={key} />\n          : ' '\n      default:\n        return null\n    }\n  })\n}\n\ninterface BlockViewProps {\n  block: MarkdownBlock\n  components?: MarkdownComponents\n  footnotes: ReadonlyMap<string, number>\n  streaming: boolean\n  /** The source has stopped growing, so nothing can change anymore. */\n  final: boolean\n}\n\n/**\n * One parsed block. Memoized on the block object: the cache keeps finished\n * blocks by identity while the source grows, so a re-render of the shell does\n * not rebuild the subtree — a highlighted fence is not tokenized again and no\n * element remounts mid-stream.\n */\nconst MarkdownBlockView = memo(function MarkdownBlockView({\n  block,\n  components,\n  footnotes,\n  streaming,\n  final,\n}: BlockViewProps) {\n  switch (block.kind) {\n    case 'heading': {\n      const Tag = `h${block.level}` as 'h1'\n      return (\n        <Tag data-streaming={streaming || undefined}>\n          {renderInline(block.inline, components, footnotes)}\n        </Tag>\n      )\n    }\n    case 'paragraph':\n      return (\n        <p data-streaming={streaming || undefined}>\n          {renderInline(block.inline, components, footnotes, streaming)}\n        </p>\n      )\n    case 'rule':\n      return <hr />\n    case 'code': {\n      const FenceRenderer = components?.fences?.[block.language.toLowerCase()]\n        ?? components?.code\n\n      if (FenceRenderer) {\n        return (\n          <FenceRenderer\n            language={block.language}\n            code={block.code}\n            streaming={streaming}\n            complete={block.terminated || final}\n          />\n        )\n      }\n\n      return (\n        <pre data-streaming={streaming || undefined}>\n          <code className={block.language\n            ? `language-${block.language}`\n            : undefined}\n          >\n            {block.code}\n          </code>\n        </pre>\n      )\n    }\n    case 'blockquote':\n      return (\n        <blockquote data-streaming={streaming || undefined}>\n          {block.children.map(child => (\n            <MarkdownBlockView\n              key={child.start}\n              block={child}\n              components={components}\n              footnotes={footnotes}\n              streaming={false}\n              final={final}\n            />\n          ))}\n        </blockquote>\n      )\n    case 'list':\n      return (\n        <MarkdownList\n          block={block}\n          components={components}\n          footnotes={footnotes}\n          streaming={streaming}\n          final={final}\n        />\n      )\n    case 'table':\n      return (\n        <MarkdownTable\n          block={block}\n          components={components}\n          footnotes={footnotes}\n          streaming={streaming}\n        />\n      )\n    case 'math':\n      return renderMath(block.value, true, components, streaming, `math-${block.start}`)\n    case 'footnote':\n      return null\n  }\n})\n\nfunction MarkdownList({\n  block,\n  components,\n  footnotes,\n  streaming,\n  final,\n}: {\n  block: MarkdownListBlock\n  components?: MarkdownComponents\n  footnotes: ReadonlyMap<string, number>\n  streaming: boolean\n  final: boolean\n}) {\n  const Tag = block.ordered ? 'ol' : 'ul'\n  const tasks = block.items.some(item => item.task !== null)\n\n  return (\n    <Tag\n      start={block.ordered && block.startNumber !== 1\n        ? block.startNumber\n        : undefined}\n      className={tasks ? 'contains-task-list' : undefined}\n      data-streaming={streaming || undefined}\n    >\n      {block.items.map((item, index) => (\n        <li\n          key={index}\n          className={item.task ? 'task-list-item' : undefined}\n        >\n          {item.task\n            ? (\n                <input\n                  type=\"checkbox\"\n                  checked={item.task === 'checked'}\n                  disabled\n                  readOnly\n                />\n              )\n            : null}\n          {item.children.map((child) => {\n            // A tight list renders the item paragraph without a wrapper.\n            if (block.tight && child.kind === 'paragraph') {\n              return (\n                <Fragment key={child.start}>\n                  {renderInline(child.inline, components, footnotes, streaming)}\n                </Fragment>\n              )\n            }\n\n            return (\n              <MarkdownBlockView\n                key={child.start}\n                block={child}\n                components={components}\n                footnotes={footnotes}\n                streaming={false}\n                final={final}\n              />\n            )\n          })}\n        </li>\n      ))}\n    </Tag>\n  )\n}\n\nfunction MarkdownTable({\n  block,\n  components,\n  footnotes,\n  streaming,\n}: {\n  block: MarkdownTableBlock\n  components?: MarkdownComponents\n  footnotes: ReadonlyMap<string, number>\n  streaming: boolean\n}) {\n  return (\n    <table data-streaming={streaming || undefined}>\n      <thead>\n        <tr>\n          {block.header.map((cell, index) => (\n            <th key={index} align={block.align[index] ?? undefined}>\n              {renderInline(cell, components, footnotes)}\n            </th>\n          ))}\n        </tr>\n      </thead>\n      <tbody>\n        {block.rows.map((row, rowIndex) => (\n          <tr key={rowIndex}>\n            {row.map((cell, cellIndex) => (\n              <td key={cellIndex} align={block.align[cellIndex] ?? undefined}>\n                {renderInline(cell, components, footnotes)}\n              </td>\n            ))}\n          </tr>\n        ))}\n      </tbody>\n    </table>\n  )\n}\n\n/**\n * Markdown renderer. Parses `source` into semantic elements inside a\n * shadcn/typeset container, so every node style comes from the typeset\n * stylesheet instead of a parallel one. The layout element carries `data-slot`;\n * the typeset element deliberately does not, because `.typeset [data-slot]` and\n * its descendants are excluded from the type styles.\n */\nexport function Markdown({\n  source,\n  streaming = false,\n  typeset = true,\n  components,\n  className,\n  contentClassName,\n}: MarkdownProps) {\n  const cache = useMarkdownBlocks(source)\n  const blocks = cache.blocks\n  const stableComponents = useStableComponents(components)\n\n  // The numbering and the trailing section are derived state: they only change\n  // when a definition appears, so the map keeps its identity while streaming.\n  const footnoteKey = blocks\n    .filter(block => block.kind === 'footnote')\n    .map(block => block.kind === 'footnote'\n      ? block.id\n      : '')\n    .join('\\n')\n  const footnotes = useMemo(() => {\n    const numbers = new Map<string, number>()\n\n    if (footnoteKey !== '') {\n      for (const id of footnoteKey.split('\\n')) {\n        numbers.set(id, numbers.size + 1)\n      }\n    }\n\n    return numbers\n  }, [footnoteKey])\n\n  const visible = blocks.filter(block => block.kind !== 'footnote')\n  const definitions = blocks.filter(block => block.kind === 'footnote')\n  const lastIndex = visible.length - 1\n\n  return (\n    <div data-slot=\"markdown\" className={cn('w-full', className)}>\n      <div\n        className={cn(typeset && 'typeset typeset-docs', contentClassName)}\n        data-streaming={streaming || undefined}\n        aria-busy={streaming || undefined}\n      >\n        {visible.map((block, index) => (\n          <MarkdownBlockView\n            key={block.start}\n            block={block}\n            components={stableComponents}\n            footnotes={footnotes}\n            streaming={streaming && index === lastIndex}\n            final={!streaming}\n          />\n        ))}\n\n        {definitions.length > 0\n          ? (\n              <section data-footnotes>\n                <ol>\n                  {definitions.map(block => (\n                    <li key={block.start} id={`fn-${block.id}`}>\n                      {renderInline(block.inline, stableComponents, footnotes)}\n                    </li>\n                  ))}\n                </ol>\n              </section>\n            )\n          : null}\n      </div>\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/blocove/markdown/markdown.tsx"
    }
  ],
  "categories": [
    "markdown",
    "shell"
  ],
  "type": "registry:ui"
}