# Animated Markdown for UI SDK (/docs/components/markdown)

Renders an AI answer's markdown as it streams: finished blocks stay put while only the last one grows, each new block rises in, unfinished syntax reads as it will once closed, and a slim caret marks where the text is arriving.

<ComponentPreview slug="markdown" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport { Markdown } from \&#x22;@/components/keyframery/markdown\&#x22;\n\nconst question = \&#x22;We spent €1,284 on the Lisbon weekend. How do we split it fairly between the four of us?\&#x22;\n\nconst intro = `## Who owes what\n\nThe weekend came to **€1,284**, so each share is **€321**. Maya paid for the flat, so she is owed the most.`\n\nconst table = `| Person | Paid | Share | Settles |\n| :-- | --: | --: | --: |\n| Maya | €612 | €321 | gets €291 |\n| Theo | €388 | €321 | gets €67 |\n| Priya | €184 | €321 | pays €137 |\n| You | €100 | €321 | pays €221 |`\n\nconst transfers = `### The fewest transfers\n\n1. You send Maya **€221**.\n2. Priya sends Maya €70 and Theo €67.\n   - Both can go through [Wise](https://wise.com) with no fee.\n\n> Three transfers settle everything, and Maya never has to send money back.`\n\nconst code = `To keep it current as receipts come in, put this in a \\`Settles\\` column:\n\n\\`\\`\\`sheets\n=SUMIF(Expenses!B:B, A2, Expenses!C:C) - SUM(Expenses!C:C) / 4\n\\`\\`\\``\n\nconst tasks = `- [x] Flat and flights logged\n- [ ] Add *Saturday's dinner* at Ramiro`\n\n/* Words with the spaces after them, so a chunk never splits a word. */\nconst chunk = (text: string) => text.match(/\\s*\\S+/g) ?? []\n\nexport default function MarkdownDemo({\n  caret = true,\n  showTable = true,\n  showCode = true,\n  rate = 40,\n  themeInk = \&#x22;\&#x22;,\n  themeMuted = \&#x22;\&#x22;,\n  themeLink = \&#x22;\&#x22;,\n  themeCaret = \&#x22;\&#x22;,\n  themeCodeFace = \&#x22;\&#x22;,\n  themeFont = 14,\n  themeGap = 12,\n}: {\n  caret?: boolean\n  showTable?: boolean\n  showCode?: boolean\n  rate?: number\n  themeInk?: string\n  themeMuted?: string\n  themeLink?: string\n  themeCaret?: string\n  themeCodeFace?: string\n  themeFont?: number\n  themeGap?: number\n}) {\n  const answer = [intro, showTable && table, transfers, showCode && code, tasks].filter(Boolean).join(\&#x22;\\n\\n\&#x22;)\n  const [shown, setShown] = React.useState<string | null>(null)\n  const timer = React.useRef<ReturnType<typeof setTimeout>>(undefined)\n  const scroller = React.useRef<HTMLDivElement>(null)\n  React.useEffect(() => () => clearTimeout(timer.current), [])\n\n  const streaming = shown !== null\n  const text = shown ?? answer\n\n  /* A model's stream: one to three words at a time, at an uneven pace. */\n  const regenerate = (e: React.MouseEvent<HTMLButtonElement>) => {\n    const speed = parseFloat(getComputedStyle(e.currentTarget).getPropertyValue(\&#x22;--kf-speed\&#x22;)) || 1\n    const words = chunk(answer)\n    clearTimeout(timer.current)\n    let at = 0\n    setShown(\&#x22;\&#x22;)\n    scroller.current?.scrollTo({ top: 0 })\n    const tick = () => {\n      at = Math.min(words.length, at + 1 + (at % 3 === 0 ? 1 : 0) + (at % 7 === 0 ? 1 : 0))\n      if (at >= words.length) {\n        setShown(null)\n        return\n      }\n      setShown(words.slice(0, at).join(\&#x22;\&#x22;))\n      timer.current = setTimeout(tick, ((1000 / rate) * 1.6 + (at % 5) * 6) * Math.max(0.5, speed))\n    }\n    timer.current = setTimeout(tick, 320 * speed)\n  }\n\n  /* Follow the end while it streams. */\n  React.useLayoutEffect(() => {\n    const el = scroller.current\n    if (el && streaming) el.scrollTop = el.scrollHeight\n  }, [text, streaming])\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeInk ? { \&#x22;--markdown-ink\&#x22;: themeInk } : null),\n    ...(themeMuted ? { \&#x22;--markdown-muted\&#x22;: themeMuted } : null),\n    ...(themeLink ? { \&#x22;--markdown-link\&#x22;: themeLink } : null),\n    ...(themeCaret ? { \&#x22;--markdown-caret\&#x22;: themeCaret } : null),\n    ...(themeCodeFace ? { \&#x22;--markdown-code-face\&#x22;: themeCodeFace } : null),\n    ...(themeFont !== 14 ? { \&#x22;--markdown-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeGap !== 12 ? { \&#x22;--markdown-gap\&#x22;: `${themeGap}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;@container flex w-full max-w-[520px] flex-col\&#x22;>\n      <div className=\&#x22;flex justify-end\&#x22;>\n        <div className=\&#x22;max-w-[85%] rounded-[16px] rounded-br-[6px] bg-muted px-3.5 py-2.5 text-[13px] leading-snug\&#x22;>{question}</div>\n      </div>\n\n      <div\n        ref={scroller}\n        className=\&#x22;mt-4 h-[400px] overflow-y-auto overscroll-contain pe-1 [scrollbar-width:none] [mask-image:linear-gradient(to_bottom,transparent,black_20px,black_calc(100%-28px),transparent)] @max-[26rem]:h-[460px]\&#x22;\n      >\n        <Markdown streaming={streaming} caret={caret} className=\&#x22;py-4\&#x22; aria-label=\&#x22;Answer\&#x22;>\n          {text}\n        </Markdown>\n      </div>\n\n      <div className=\&#x22;mt-2 flex items-center gap-1 text-[12px] text-muted-foreground\&#x22;>\n        <span className=\&#x22;me-auto\&#x22;>{streaming ? \&#x22;Writing…\&#x22; : \&#x22;Answered in 4.1s\&#x22;}</span>\n        <button\n          type=\&#x22;button\&#x22;\n          data-play=\&#x22;regenerate\&#x22;\n          onClick={regenerate}\n          disabled={streaming}\n          className=\&#x22;inline-flex h-7 items-center gap-1.5 rounded-[8px] px-2.5 leading-none font-medium outline-none transition-[scale,color,background-color,opacity] duration-[calc(150ms*var(--kf-speed,1))] ease-house hover:bg-foreground/[0.045] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[calc(1-0.04*var(--kf-flourish,1))] disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none\&#x22;\n        >\n          <svg viewBox=\&#x22;0 0 16 16\&#x22; fill=\&#x22;none\&#x22; stroke=\&#x22;currentColor\&#x22; strokeWidth=\&#x22;1.5\&#x22; strokeLinecap=\&#x22;round\&#x22; strokeLinejoin=\&#x22;round\&#x22; aria-hidden className=\&#x22;size-3.5\&#x22;>\n            <path d=\&#x22;M13.25 8a5.25 5.25 0 1 1-1.54-3.71M13.25 2.75v2.5h-2.5\&#x22; />\n          </svg>\n          Regenerate\n        </button>\n      </div>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;caret&#x22;:[1272,1276],&#x22;showTable&#x22;:[1292,1296],&#x22;showCode&#x22;:[1311,1315],&#x22;rate&#x22;:[1326,1328],&#x22;themeInk&#x22;:[1343,1345],&#x22;themeMuted&#x22;:[1362,1364],&#x22;themeLink&#x22;:[1380,1382],&#x22;themeCaret&#x22;:[1399,1401],&#x22;themeCodeFace&#x22;:[1421,1423],&#x22;themeFont&#x22;:[1439,1441],&#x22;themeGap&#x22;:[1456,1458]},&#x22;root&#x22;:[3706,5473],&#x22;importOffset&#x22;:105}" />

## Installation [#installation]

**React**

**CLI**

```bash
npx shadcn@latest add @keyframery/markdown
```

This adds `components/keyframery/markdown.tsx` and its primitive to your project, and installs UI SDK, along with `agent-content`, [code-block](/docs/components/code-block), which it builds on. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.17 @ui-sdk/react@0.1.0-beta.17 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation/manual#add-the-motion-tokens) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "subtle" | "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"subtle"` (the default), `"calm"`, `"springy"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Add what it builds on**

Install [code-block](/docs/components/code-block) the same way first. Add `agent-content` with the CLI: `npx shadcn@latest add @keyframery/agent-content`.

**Copy the component**

**components/keyframery/markdown.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/markdown"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --markdown-ink: Body text; default: text-foreground.
   --markdown-muted: Quotes, list markers and table headers; default: text-muted-foreground.
   --markdown-link: Links; default: text-foreground.
   --markdown-caret: Caret; default: bg-foreground.
   --markdown-code-face: Inline code surface; default: bg-muted.
   --markdown-font: Body size; default: text-[14px].
   --markdown-gap: Block spacing; default: gap-3.
*/

/* Styled markdown: the animated primitive plus the Keyframery look. Plain reading type on the theme's
   own tokens: quiet headings one weight step up, underlined links, inline code on a muted chip,
   tables in a hairline sheet with tabular figures, fenced code in Keyframery's code block, and a
   slim caret while the answer streams. */

import * as React from "react"

import {
  CodeBlock,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockHeader,
  CodeBlockTitle,
} from "@/components/keyframery/code-block"
import {
  Markdown as MarkdownRoot,
  type MarkdownCodeBlockProps,
  type MarkdownComponents,
  type MarkdownProps,
} from "@/components/keyframery/primitives/markdown"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}


/* Fenced code: the styled code block, its language in the header and a copy key that waits for the
   closing fence. */
function MarkdownCodeBlock({ code, language, info, complete }: MarkdownCodeBlockProps) {
  return (
    <CodeBlock code={code} language={language} data-writing={complete ? undefined : ""} className="text-[13px]">
      <CodeBlockHeader>
        <CodeBlockTitle className="font-mono font-normal">{info || "code"}</CodeBlockTitle>
        <CodeBlockCopyButton className="ms-auto transition-[opacity,scale] duration-[calc(150ms*var(--kf-speed,1))] ease-house in-data-writing:pointer-events-none in-data-writing:opacity-0 motion-reduce:transition-none" />
      </CodeBlockHeader>
      <CodeBlockContent />
    </CodeBlock>
  )
}

const styled: MarkdownComponents = { codeBlock: MarkdownCodeBlock }

const look = cn(
  "flex min-w-0 flex-col gap-[var(--markdown-gap,0.75rem)] text-[length:var(--markdown-font,14px)] leading-[1.65] [overflow-wrap:anywhere]",
  "text-[color:var(--markdown-ink,var(--foreground))]",
  /* Headings: one weight step up, a little more air above them than between paragraphs. */
  "[&_[data-slot=markdown-heading]]:font-semibold [&_[data-slot=markdown-heading]]:leading-[1.3] [&_[data-slot=markdown-heading]]:tracking-tight",
  "[&>[data-slot=markdown-heading]:not(:first-child)]:mt-[calc(var(--markdown-gap,0.75rem)*0.6)]",
  "[&_[data-level='1']]:text-[1.43em] [&_[data-level='2']]:text-[1.22em] [&_[data-level='3']]:text-[1.07em]",
  /* Inline. */
  "[&_[data-slot=markdown-strong]]:font-semibold [&_[data-slot=markdown-em]]:italic",
  "[&_[data-slot=markdown-del]]:line-through [&_[data-slot=markdown-del]]:decoration-[color-mix(in_oklab,currentColor_55%,transparent)]",
  "[&_[data-slot=markdown-del]]:text-[color:var(--markdown-muted,var(--muted-foreground))]",
  "[&_[data-slot=markdown-code]]:rounded-[5px] [&_[data-slot=markdown-code]]:bg-[var(--markdown-code-face,var(--muted))] [&_[data-slot=markdown-code]]:px-[0.35em] [&_[data-slot=markdown-code]]:py-[0.12em] [&_[data-slot=markdown-code]]:font-mono [&_[data-slot=markdown-code]]:text-[0.86em] [&_[data-slot=markdown-code]]:[box-decoration-break:clone]",
  "[&_[data-slot=markdown-link]]:rounded-[3px] [&_[data-slot=markdown-link]]:text-[color:var(--markdown-link,var(--foreground))] [&_[data-slot=markdown-link]]:underline [&_[data-slot=markdown-link]]:decoration-[color-mix(in_oklab,currentColor_32%,transparent)] [&_[data-slot=markdown-link]]:decoration-1 [&_[data-slot=markdown-link]]:underline-offset-[3px] [&_[data-slot=markdown-link]]:outline-none",
  "[&_[data-slot=markdown-link]]:transition-[text-decoration-color] [&_[data-slot=markdown-link]]:duration-[calc(150ms*var(--kf-speed,1))] [&_[data-slot=markdown-link]]:ease-house motion-reduce:[&_[data-slot=markdown-link]]:transition-none",
  "[&_[data-slot=markdown-link][href]:hover]:decoration-current [&_[data-slot=markdown-link]]:focus-visible:ring-2 [&_[data-slot=markdown-link]]:focus-visible:ring-ring [&_[data-slot=markdown-link]]:focus-visible:ring-offset-2 [&_[data-slot=markdown-link]]:focus-visible:ring-offset-background",
  /* Lists: muted markers, a hanging indent, a little air between items. */
  "[&_[data-slot=markdown-list]]:list-disc [&_[data-slot=markdown-list]]:ps-[1.35em] [&_[data-slot=markdown-list][data-ordered]]:list-decimal",
  "[&_[data-slot=markdown-list]_[data-slot=markdown-list]:not([data-ordered])]:list-[circle]",
  "[&_[data-slot=markdown-item]]:ps-[0.15em] [&_[data-slot=markdown-item]]:marker:tabular-nums",
  "[&_[data-slot=markdown-item]]:marker:text-[color:var(--markdown-muted,var(--muted-foreground))]",
  "[&_[data-slot=markdown-item]+[data-slot=markdown-item]]:mt-[0.3em] [&_[data-slot=markdown-item]>*+*]:mt-[0.3em] [&_[data-slot=markdown-item]>[data-slot=markdown-list]]:mt-[0.3em]",
  /* Tasks: a small read-only box in place of the bullet. */
  "[&_[data-slot=markdown-list][data-tasks]]:list-none [&_[data-slot=markdown-list][data-tasks]]:ps-0",
  "[&_[data-slot=markdown-item][data-task]]:ps-[1.6em] [&_[data-slot=markdown-item][data-task]]:-indent-[1.6em] [&_[data-slot=markdown-item][data-task]_*]:indent-0",
  "[&_[data-slot=markdown-checkbox]]:me-[0.6em] [&_[data-slot=markdown-checkbox]]:inline-grid [&_[data-slot=markdown-checkbox]]:size-[1em] [&_[data-slot=markdown-checkbox]]:translate-y-[0.14em] [&_[data-slot=markdown-checkbox]]:place-items-center [&_[data-slot=markdown-checkbox]]:rounded-[4px] [&_[data-slot=markdown-checkbox]]:align-baseline",
  "[&_[data-slot=markdown-checkbox]]:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_24%,transparent)]",
  "[&_[data-slot=markdown-checkbox][data-checked]]:bg-primary [&_[data-slot=markdown-checkbox][data-checked]]:text-primary-foreground [&_[data-slot=markdown-checkbox][data-checked]]:shadow-none [&_[data-slot=markdown-checkbox]_svg]:size-[0.75em]",
  /* Quote: a hairline rule at the start, muted text. */
  "[&_[data-slot=markdown-quote]]:flex [&_[data-slot=markdown-quote]]:flex-col [&_[data-slot=markdown-quote]]:gap-[calc(var(--markdown-gap,0.75rem)*0.6)] [&_[data-slot=markdown-quote]]:border-s-2 [&_[data-slot=markdown-quote]]:border-border [&_[data-slot=markdown-quote]]:ps-[0.9em]",
  "[&_[data-slot=markdown-quote]]:text-[color:var(--markdown-muted,var(--muted-foreground))]",
  "[&_[data-slot=markdown-rule]]:my-[calc(var(--markdown-gap,0.75rem)*0.4)] [&_[data-slot=markdown-rule]]:h-px [&_[data-slot=markdown-rule]]:border-0 [&_[data-slot=markdown-rule]]:bg-border",
  /* Table: a hairline sheet that scrolls sideways on a narrow screen. */
  "[&_[data-slot=markdown-table]]:max-w-full [&_[data-slot=markdown-table]]:overflow-x-auto [&_[data-slot=markdown-table]]:rounded-[10px] [&_[data-slot=markdown-table]]:[scrollbar-width:thin]",
  "[&_[data-slot=markdown-table]]:shadow-[inset_0_0_0_1px_var(--border)]",
  "[&_[data-slot=markdown-table]_table]:w-full [&_[data-slot=markdown-table]_table]:border-collapse [&_[data-slot=markdown-table]_table]:text-[0.93em] [&_[data-slot=markdown-table]_table]:leading-[1.45] [&_[data-slot=markdown-table]_table]:tabular-nums",
  "[&_[data-slot=markdown-table]_th]:bg-[color-mix(in_oklab,var(--muted)_60%,transparent)] [&_[data-slot=markdown-table]_th]:px-3 [&_[data-slot=markdown-table]_th]:py-2 [&_[data-slot=markdown-table]_th]:text-start [&_[data-slot=markdown-table]_th]:font-medium [&_[data-slot=markdown-table]_th]:whitespace-nowrap",
  "[&_[data-slot=markdown-table]_th]:text-[color:var(--markdown-muted,var(--muted-foreground))]",
  "[&_[data-slot=markdown-table]_td]:border-t [&_[data-slot=markdown-table]_td]:border-border [&_[data-slot=markdown-table]_td]:px-3 [&_[data-slot=markdown-table]_td]:py-2",
  "[&_[data-slot=markdown-table]_:is(th,td):first-child]:ps-3.5 [&_[data-slot=markdown-table]_:is(th,td):last-child]:pe-3.5",
  /* Caret: a slim bar at the end of the text. */
  "[&_[data-slot=markdown-caret]]:ms-[1px] [&_[data-slot=markdown-caret]]:inline-block [&_[data-slot=markdown-caret]]:h-[1.1em] [&_[data-slot=markdown-caret]]:w-[2px] [&_[data-slot=markdown-caret]]:translate-y-[0.2em] [&_[data-slot=markdown-caret]]:rounded-full [&_[data-slot=markdown-caret]]:bg-[var(--markdown-caret,var(--foreground))]",
)

/* The answer's text, as markdown. Pass the string as children or `content`; set `streaming` while it
   is still arriving. */
function Markdown({ speed, className, components, ...props }: MarkdownProps & SpeedProps) {
  const merged = React.useMemo(() => (components ? { ...styled, ...components } : styled), [components])
  return (
    <Speed speed={speed}>
      <MarkdownRoot className={withClass(look, className)} components={merged} {...props} />
    </Speed>
  )
}

export { Markdown, MarkdownCodeBlock }
export type { MarkdownCodeBlockProps, MarkdownComponents, MarkdownProps } from "@/components/keyframery/primitives/markdown"
```

**components/keyframery/primitives/markdown.tsx**

```tsx
"use client"

/* Animated streaming markdown, on UI SDK's core. UI SDK ships none, so the parser and the primitive
   are defined in `@/components/core/markdown` and rendered here; fenced code is Keyframery's code
   block (through its animated primitive). This file adds motion only. Colours, type and spacing stay
   yours (style the `data-slot` of each element).

   - Steady: every block is drawn from its own source and kept as it is while later text arrives, so
     finished blocks never re-render or move; only the last block grows.
   - Rise: a new block fades up out of a soft blur as it arrives.
   - Caret: while `streaming`, a caret sits at the end of the text and pulses softly.
   The rise scales with --kf-flourish (at 0 a block is simply there); the caret says "still writing"
   and always shows. */

import { createParts } from "@ui-sdk/react/primitive"
import * as React from "react"

import {
  CodeBlock,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockHeader,
  CodeBlockTitle,
} from "@/components/keyframery/primitives/code-block"
import type { CodeBlockLanguage } from "@/components/keyframery/core/code-block-core"
import { markdown, parseMarkdown, type MarkdownBlock, type MarkdownInline } from "@/components/keyframery/core/markdown-core"
import { cn } from "@/lib/utils"

const parts = createParts(markdown, { root: "div", caret: "span" })

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/** What a fenced code block renderer receives. */
type MarkdownCodeBlockProps = {
  /** The code, without its fences. */
  code: string
  /** The tokenizer's language for the fence's info string ("text" when unknown). */
  language: CodeBlockLanguage
  /** The fence's info string as written, like "tsx" or "python". */
  info: string
  /** False while the closing fence has not arrived yet. */
  complete: boolean
}

type MarkdownElement =
  | "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "a" | "strong" | "em" | "del" | "code" | "br"
  | "ul" | "ol" | "li" | "blockquote" | "hr" | "table" | "thead" | "tbody" | "tr" | "th" | "td"

/** Your own element for any of them, and `codeBlock` for fenced code. Each gets the element's props, including its `data-slot`. */
type MarkdownComponents = Partial<Record<MarkdownElement, React.ElementType>> & {
  codeBlock?: React.ComponentType<MarkdownCodeBlockProps>
}

const keyframes = [
  "@keyframes kf-markdown-rise{from{opacity:0;translate:0 calc(6px*var(--kf-flourish,1));filter:blur(calc(3px*var(--kf-flourish,1)))}}",
  "@keyframes kf-markdown-caret{50%{opacity:0.2}}",
].join("")

/* The default code block: the animated code block's parts, with the fence's language and a copy
   button. Its lines arrive as they stream in. */
function DefaultCodeBlock({ code, language, info, complete }: MarkdownCodeBlockProps) {
  return (
    <CodeBlock code={code} language={language} data-writing={complete ? undefined : ""}>
      <CodeBlockHeader>
        <CodeBlockTitle>{info || "code"}</CodeBlockTitle>
        <CodeBlockCopyButton />
      </CodeBlockHeader>
      <CodeBlockContent />
    </CodeBlock>
  )
}

type Ctx = { components: MarkdownComponents }

const el = (ctx: Ctx, tag: MarkdownElement) => ctx.components[tag] ?? tag

function Inlines({ nodes, ctx }: { nodes: MarkdownInline[]; ctx: Ctx }) {
  return nodes.map((node, i) => {
    switch (node.type) {
      case "text":
        return <React.Fragment key={i}>{node.text}</React.Fragment>
      case "break": {
        const Br = el(ctx, "br")
        return <Br key={i} />
      }
      case "code": {
        const Code = el(ctx, "code")
        return (
          <Code key={i} data-slot="markdown-code">
            {node.text}
          </Code>
        )
      }
      case "strong":
      case "em":
      case "del": {
        const Tag = el(ctx, node.type)
        return (
          <Tag key={i} data-slot={`markdown-${node.type}`}>
            <Inlines nodes={node.children} ctx={ctx} />
          </Tag>
        )
      }
      case "link": {
        const A = el(ctx, "a")
        const external = node.href ? /^(?:https?:)?\/\//i.test(node.href) : false
        return (
          <A
            key={i}
            data-slot="markdown-link"
            data-pending={node.href ? undefined : ""}
            href={node.href}
            title={node.title}
            rel="noreferrer"
            target={external ? "_blank" : undefined}
          >
            <Inlines nodes={node.children} ctx={ctx} />
          </A>
        )
      }
    }
  })
}

/* A block that takes the caret at its end. */
function BlockView({ block, ctx, caret }: { block: MarkdownBlock; ctx: Ctx; caret?: React.ReactNode }) {
  switch (block.type) {
    case "paragraph": {
      const P = el(ctx, "p")
      return (
        <P data-slot="markdown-paragraph">
          <Inlines nodes={block.children} ctx={ctx} />
          {caret}
        </P>
      )
    }
    case "heading": {
      const H = el(ctx, `h${block.level}`)
      return (
        <H data-slot="markdown-heading" data-level={block.level}>
          <Inlines nodes={block.children} ctx={ctx} />
          {caret}
        </H>
      )
    }
    case "rule": {
      const Hr = el(ctx, "hr")
      return <Hr data-slot="markdown-rule" />
    }
    case "quote": {
      const Quote = el(ctx, "blockquote")
      return (
        <Quote data-slot="markdown-quote">
          <Blocks blocks={block.children} ctx={ctx} caret={caret} />
        </Quote>
      )
    }
    case "code": {
      const Code = ctx.components.codeBlock ?? DefaultCodeBlock
      return (
        <div data-slot="markdown-code-block" data-writing={block.complete ? undefined : ""}>
          <Code code={block.code} language={block.language} info={block.info} complete={block.complete} />
        </div>
      )
    }
    case "list": {
      const List = el(ctx, block.ordered ? "ol" : "ul")
      const Li = el(ctx, "li")
      const tasks = block.items.some((item) => item.checked !== undefined)
      return (
        <List
          data-slot="markdown-list"
          data-ordered={block.ordered ? "" : undefined}
          data-tasks={tasks ? "" : undefined}
          start={block.ordered && block.start !== 1 ? block.start : undefined}
        >
          {block.items.map((item, n) => {
            const end = n === block.items.length - 1 ? caret : undefined
            const only = item.children.length === 1 && item.children[0].type === "paragraph" ? item.children[0] : undefined
            return (
              <Li
                key={n}
                data-slot="markdown-item"
                data-task={item.checked === undefined ? undefined : ""}
                data-checked={item.checked ? "" : undefined}
              >
                {item.checked !== undefined && <TaskMark checked={item.checked} />}
                {only && only.type === "paragraph" ? (
                  <>
                    <Inlines nodes={only.children} ctx={ctx} />
                    {end}
                  </>
                ) : (
                  <Blocks blocks={item.children} ctx={ctx} caret={end} />
                )}
              </Li>
            )
          })}
        </List>
      )
    }
    case "table": {
      const Table = el(ctx, "table")
      const Thead = el(ctx, "thead")
      const Tbody = el(ctx, "tbody")
      const Tr = el(ctx, "tr")
      const Th = el(ctx, "th")
      const Td = el(ctx, "td")
      const align = (n: number) => (block.align[n] ? { textAlign: block.align[n] } : undefined)
      /* The caret sits in the last cell that has text so far. */
      const lastRow = block.rows[block.rows.length - 1]
      const caretCell = lastRow ? Math.max(0, lastRow.findLastIndex((cell) => cell.length > 0)) : -1
      return (
        <div data-slot="markdown-table">
          <Table>
            <Thead>
              <Tr>
                {block.head.map((cell, n) => (
                  <Th key={n} scope="col" style={align(n)} data-align={block.align[n]}>
                    <Inlines nodes={cell} ctx={ctx} />
                  </Th>
                ))}
              </Tr>
            </Thead>
            {block.rows.length > 0 && (
              <Tbody>
                {block.rows.map((row, r) => (
                  <Tr key={r}>
                    {row.map((cell, n) => (
                      <Td key={n} style={align(n)} data-align={block.align[n]}>
                        <Inlines nodes={cell} ctx={ctx} />
                        {r === block.rows.length - 1 && n === caretCell ? caret : undefined}
                      </Td>
                    ))}
                  </Tr>
                ))}
              </Tbody>
            )}
          </Table>
        </div>
      )
    }
  }
}

/* Read only: a task's tick. Screen readers hear "done" or "to do" before the item. */
function TaskMark({ checked }: { checked: boolean }) {
  return (
    <span data-slot="markdown-checkbox" data-checked={checked ? "" : undefined} role="img" aria-label={checked ? "Done" : "To do"}>
      {checked && (
        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M4 8.5 6.75 11 12 5.25" />
        </svg>
      )}
    </span>
  )
}

/* Equal source, equal block: a finished block is never drawn again while the text after it grows. */
const Block = React.memo(
  BlockView,
  (a, b) => a.block.source === b.block.source && a.block.live === b.block.live && a.block.type === b.block.type && a.ctx === b.ctx && a.caret === b.caret,
)

function Blocks({ blocks, ctx, caret }: { blocks: MarkdownBlock[]; ctx: Ctx; caret?: React.ReactNode }) {
  return blocks.map((block, i) => <Block key={i} block={block} ctx={ctx} caret={i === blocks.length - 1 ? caret : undefined} />)
}

type MarkdownProps = Omit<React.ComponentProps<typeof parts.Root>, "children" | "content"> & {
  /** The markdown. `content` works too; `children` wins when both are given. */
  children?: string | null
  content?: string | null
  /** True while the text is still arriving: its end reads as unfinished, and the caret shows. */
  streaming?: boolean
  /** Show the caret while streaming. Default true. */
  caret?: boolean
  /** Your own elements, by tag name, and `codeBlock` for fenced code. Keep the object stable (outside render or memoized). */
  components?: MarkdownComponents
}

const none: MarkdownComponents = {}

/* Each direct child (a block) rises in as it arrives. */
function Markdown({ children, content, streaming = false, caret = true, components = none, className, ...props }: MarkdownProps) {
  const source = children ?? content ?? ""
  const blocks = React.useMemo(() => parseMarkdown(source, { streaming }), [source, streaming])
  const ctx = React.useMemo(() => ({ components }), [components])
  const mark = streaming && caret ? <MarkdownCaret /> : undefined
  return (
    <>
      <style href="kf-markdown" precedence="default">
        {keyframes}
      </style>
      <parts.Root
        streaming={streaming}
        className={withClass(
          cn(
            "*:animate-[kf-markdown-rise_calc(380ms*var(--kf-speed,1)*var(--kf-flourish,1))_var(--ease-house)_backwards]",
            /* Code lines arrive as they stream; none waits for a cascade. */
            "[&_[data-slot=code-block-line]]:[animation-delay:0ms]",
            "motion-reduce:*:animate-none!",
          ),
          className,
        )}
        {...props}
      >
        <Blocks blocks={blocks} ctx={ctx} caret={mark} />
        {mark && !blocks.length && <p data-slot="markdown-paragraph">{mark}</p>}
      </parts.Root>
    </>
  )
}

/* The caret pulses softly while the text arrives. It is the "still writing" signal, so it keeps
   pulsing at any flourish; reduced motion holds it still. */
function MarkdownCaret({ className, ...props }: React.ComponentProps<typeof parts.Caret>) {
  return (
    <parts.Caret
      className={withClass(
        "animate-[kf-markdown-caret_calc(1000ms*var(--kf-speed,1))_var(--ease-house)_infinite] motion-reduce:animate-none",
        className,
      )}
      {...props}
    />
  )
}

export { Markdown, MarkdownCaret }
export type { MarkdownCodeBlockProps, MarkdownComponents, MarkdownElement, MarkdownProps }
export { parseMarkdown, type MarkdownBlock, type MarkdownInline } from "@/components/keyframery/core/markdown-core"
```

**components/keyframery/core/markdown-core.ts**

````ts
/* Streaming markdown, as a UI SDK primitive. UI SDK ships none, so it is defined with its core: the
   same definition and the same parser render in React, Vue, Svelte, Solid and web components.

   It owns the parsing: a small in-house markdown parser (no package) that turns a string into
   blocks, built for text that is still arriving. Each block carries the exact source it came from,
   so a renderer can keep every finished block as it is and redraw only the one that is growing.
   While `streaming` is true, the last block is "live": what is unfinished there reads as it will
   once it is finished, instead of flashing raw syntax:

   - an unclosed ``` fence is a code block in progress (`complete: false`);
   - an unclosed `**`, `*`, `_`, `~~` or backtick formats the rest of the text as if it were closed;
   - a link whose URL is still arriving shows its text, without an address yet;
   - a table's half-written row is padded to the header's columns, and a table whose header has no
     divider line yet waits instead of showing pipes;
   - a last line that is only the start of a marker (`-`, `1.`, `##`, `>`, `|`, a short fence)
     waits for the next character before it shows.

   Raw HTML is never interpreted (renderers show it as text), and links keep only http, https,
   mailto, tel and relative addresses: anything else, like `javascript:`, renders as plain text. */

import { definePrimitive } from "@ui-sdk/core"

import { bindAgentContent } from "@/components/keyframery/core/agent-content-core"
import type { CodeBlockLanguage } from "@/components/keyframery/core/code-block-core"

/* ---------- The tree ---------- */

type MarkdownInline =
  | { type: "text"; text: string }
  | { type: "strong" | "em" | "del"; children: MarkdownInline[] }
  | { type: "code"; text: string }
  /** `href` is missing while the address is still arriving, or when it was unsafe. */
  | { type: "link"; href?: string; title?: string; children: MarkdownInline[] }
  | { type: "break" }

type MarkdownAlign = "left" | "center" | "right" | undefined

type MarkdownListItem = { checked?: boolean; children: MarkdownBlock[] }

type BlockBase = {
  /** The source lines the block came from: equal source, equal block. */
  source: string
  /** The block is the end of a stream that is still arriving. */
  live: boolean
}

type MarkdownBlock = BlockBase &
  (
    | { type: "paragraph"; children: MarkdownInline[] }
    | { type: "heading"; level: 1 | 2 | 3 | 4 | 5 | 6; children: MarkdownInline[] }
    | { type: "code"; info: string; language: CodeBlockLanguage; code: string; complete: boolean }
    | { type: "list"; ordered: boolean; start: number; items: MarkdownListItem[] }
    | { type: "quote"; children: MarkdownBlock[] }
    | { type: "rule" }
    | { type: "table"; align: MarkdownAlign[]; head: MarkdownInline[][]; rows: MarkdownInline[][][] }
  )

/* A block without its source and live flag, kept per kind. */
type BlockBody = MarkdownBlock extends infer B ? (B extends unknown ? Omit<B, "source" | "live"> : never) : never

/* ---------- Safety ---------- */

/** An address a link may open, or undefined. Relative addresses and http, https, mailto and tel only. */
function safeHref(url: string): string | undefined {
  const href = url.trim()
  if (!href) return undefined
  const plain = href.replace(/[\u0000- \u007f-\u009f]/g, "").toLowerCase()
  const scheme = /^([a-z][a-z0-9+.-]*):/.exec(plain)
  if (!scheme) return href
  return ["http", "https", "mailto", "tel"].includes(scheme[1]) ? href : undefined
}

/* ---------- Code languages ---------- */

const languages: Record<string, CodeBlockLanguage> = {
  ts: "ts", typescript: "ts", tsx: "tsx", js: "js", javascript: "js", mjs: "js", cjs: "js", jsx: "jsx",
  json: "json", jsonc: "json", css: "css", scss: "css", html: "html", xml: "html", svg: "html", vue: "html",
  bash: "bash", sh: "bash", shell: "bash", zsh: "bash", console: "bash", terminal: "bash",
}

/** The code block tokenizer's language for a fence's info string; anything unknown is plain text. */
function codeLanguage(info: string): CodeBlockLanguage {
  return languages[info.trim().split(/\s+/)[0]?.toLowerCase() ?? ""] ?? "text"
}

/* ---------- Inline ---------- */

const ESCAPABLE = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/
const isSpace = (c: string | undefined) => c === undefined || /\s/.test(c)
const isWord = (c: string | undefined) => c !== undefined && /[\p{L}\p{N}]/u.test(c)

const runOf = (src: string, at: number) => {
  let end = at
  while (src[end] === src[at]) end++
  return end - at
}

/* The end of a code span that opens at `at`, or -1. */
function codeSpanEnd(src: string, at: number) {
  const run = runOf(src, at)
  let j = at + run
  while (j < src.length) {
    if (src[j] === "`") {
      const close = runOf(src, j)
      if (close === run) return j + close
      j += close
    } else j++
  }
  return -1
}

/* Where the closing `delim` (`*`, `**`, `_`, `__` or `~~`) for an opener whose content starts at
   `from` begins, or -1. Code spans and escapes are skipped; a run that also opens (space before it)
   is not a closer. */
function findCloser(src: string, from: number, delim: string) {
  const ch = delim[0]
  const size = delim.length
  let j = from
  while (j < src.length) {
    const c = src[j]
    if (c === "\\") {
      j += 2
      continue
    }
    if (c === "`") {
      const end = codeSpanEnd(src, j)
      if (end > 0) {
        j = end
        continue
      }
    }
    if (c === ch) {
      const run = runOf(src, j)
      const fits = ch === "~" ? run >= 2 : size === 1 ? run === 1 || run >= 3 : run >= 2
      const after = src[j + run]
      if (fits && j > from && !isSpace(src[j - 1]) && !(ch === "_" && isWord(after))) return j + run - size
      j += run
      continue
    }
    j++
  }
  return -1
}

/* The `]` that closes a `[` at `at`, or -1. */
function bracketEnd(src: string, at: number) {
  let depth = 0
  for (let j = at; j < src.length; j++) {
    const c = src[j]
    if (c === "\\") j++
    else if (c === "`") {
      const end = codeSpanEnd(src, j)
      if (end > 0) j = end - 1
    } else if (c === "[") depth++
    else if (c === "]" && --depth === 0) return j
  }
  return -1
}

/* The `)` that closes a `(` at `at`, or -1. */
function parenEnd(src: string, at: number) {
  let depth = 0
  for (let j = at; j < src.length; j++) {
    const c = src[j]
    if (c === "\\") j++
    else if (c === "(") depth++
    else if (c === ")" && --depth === 0) return j
    else if (c === "\n") return -1
  }
  return -1
}

const BARE_URL = /^https?:\/\/[^\s<>"]*[^\s<>".,:;'!?)\]*_~]/

/** Inline markdown to nodes. `live`: the text is the end of a stream that is still arriving. */
function parseInline(src: string, live = false): MarkdownInline[] {
  const out: MarkdownInline[] = []
  let text = ""
  const flush = () => {
    if (text) out.push({ type: "text", text })
    text = ""
  }
  const push = (...nodes: MarkdownInline[]) => {
    flush()
    out.push(...nodes)
  }

  let i = 0
  while (i < src.length) {
    const c = src[i]
    const next = src[i + 1]

    if (c === "\\") {
      if (next === "\n") {
        push({ type: "break" })
        i += 2
      } else if (next !== undefined && ESCAPABLE.test(next)) {
        text += next
        i += 2
      } else {
        if (!(live && next === undefined)) text += c
        i++
      }
      continue
    }

    if (c === "\n") {
      const hard = / {2,}$/.test(text)
      text = text.replace(/ +$/, "")
      if (hard) push({ type: "break" })
      else text += "\n"
      i++
      continue
    }

    if (c === "`") {
      const run = runOf(src, i)
      const end = codeSpanEnd(src, i)
      if (end > 0) {
        let code = src.slice(i + run, end - run).replace(/\n/g, " ")
        if (code.length > 2 && code.startsWith(" ") && code.endsWith(" ") && code.trim()) code = code.slice(1, -1)
        push({ type: "code", text: code })
        i = end
      } else if (live) {
        const code = src.slice(i + run).replace(/\n/g, " ")
        if (code) push({ type: "code", text: code })
        i = src.length
      } else {
        text += src.slice(i, i + run)
        i += run
      }
      continue
    }

    if (c === "<") {
      const auto = /^<((?:https?:\/\/|mailto:)[^\s<>]+)>/i.exec(src.slice(i))
      if (auto) {
        const href = safeHref(auto[1])
        push({ type: "link", href, children: [{ type: "text", text: auto[1].replace(/^mailto:/i, "") }] })
        i += auto[0].length
        continue
      }
      const br = /^<br\s*\/?>/i.exec(src.slice(i))
      if (br) {
        push({ type: "break" })
        i += br[0].length
        continue
      }
    }

    if (c === "h" && !isWord(src[i - 1]) && (src.startsWith("http://", i) || src.startsWith("https://", i))) {
      const url = BARE_URL.exec(src.slice(i))
      if (url) {
        push({ type: "link", href: safeHref(url[0]), children: [{ type: "text", text: url[0] }] })
        i += url[0].length
        continue
      }
    }

    if (c === "[" || (c === "!" && next === "[")) {
      const at = c === "!" ? i + 1 : i
      const close = bracketEnd(src, at)
      if (close < 0) {
        if (live) {
          /* Maybe a link, maybe not: show its words without the bracket for now. */
          push(...parseInline(src.slice(at + 1), live))
          i = src.length
          continue
        }
      } else {
        const label = src.slice(at + 1, close)
        const children = parseInline(label, false)
        if (src[close + 1] === "(") {
          const end = parenEnd(src, close + 1)
          if (end > 0) {
            const target = /^\s*<?([^\s>]*)>?(?:\s+["'(](.*)["')])?\s*$/.exec(src.slice(close + 2, end))
            const href = target ? safeHref(target[1]) : undefined
            /* An unsafe address (javascript:, data: and the like) leaves only the words. */
            if (href === undefined) push(...children)
            else push({ type: "link", href, title: target?.[2], children })
            i = end + 1
            continue
          }
          if (live) {
            /* The address is still arriving. */
            push({ type: "link", children })
            i = src.length
            continue
          }
        } else if (live && close === src.length - 1) {
          push(...children)
          i = src.length
          continue
        }
      }
      text += c
      i++
      continue
    }

    if (c === "*" || c === "_" || c === "~") {
      const run = runOf(src, i)
      const after = src[i + run]
      if (live && after === undefined) {
        /* A marker with nothing after it yet: wait for the next character. */
        i += run
        continue
      }
      const opens = !isSpace(after) && !(c === "_" && isWord(src[i - 1])) && (c !== "~" || run >= 2)
      if (opens) {
        const size = c === "~" ? 2 : Math.min(run, 2)
        const delim = c.repeat(size)
        const type = c === "~" ? "del" : size === 2 ? "strong" : "em"
        const from = i + size
        const close = findCloser(src, from, delim)
        if (close > 0) {
          push({ type, children: parseInline(src.slice(from, close), false) })
          i = close + size
          continue
        }
        if (live) {
          const rest = src.slice(from)
          if (rest.trim()) push({ type, children: parseInline(rest, live) })
          i = src.length
          continue
        }
      }
      text += src.slice(i, i + run)
      i += run
      continue
    }

    text += c
    i++
  }
  flush()
  return out
}

/* ---------- Blocks ---------- */

const FENCE = /^( {0,3})(`{3,}|~{3,})(.*)$/
const HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/
const RULE = /^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/
const QUOTE = /^ {0,3}>/
const LIST = /^( *)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*)|$)/
const DELIMITER = /^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$/
const PARTIAL_DELIMITER = /^\s*\|?[\s:|-]*$/
/* A last line that is only the start of something: wait for the next character. */
const PARTIAL = /^\s*(?:[-*+_=>|~]{1,3}|`{1,3}|#{1,6}|\d{1,9}[.)]?)\s*$/

const blank = (line: string | undefined) => line === undefined || !line.trim()
const indentOf = (line: string) => line.length - line.trimStart().length

function splitRow(line: string): string[] {
  let row = line.trim()
  if (row.startsWith("|")) row = row.slice(1)
  if (row.endsWith("|") && !row.endsWith("\\|")) row = row.slice(0, -1)
  const cells: string[] = []
  let cell = ""
  for (let j = 0; j < row.length; j++) {
    const c = row[j]
    if (c === "\\" && row[j + 1] === "|") {
      cell += "|"
      j++
    } else if (c === "`") {
      const end = codeSpanEnd(row, j)
      if (end > 0) {
        cell += row.slice(j, end)
        j = end - 1
      } else cell += c
    } else if (c === "|") {
      cells.push(cell.trim())
      cell = ""
    } else cell += c
  }
  cells.push(cell.trim())
  return cells
}

const alignOf = (cell: string): MarkdownAlign => {
  const left = cell.startsWith(":")
  const right = cell.endsWith(":")
  return left && right ? "center" : right ? "right" : left ? "left" : undefined
}

/* A table starts here: a row with pipes over a divider line, or, at the live end of a stream, a row
   that starts with a pipe and may yet get one. */
function tableStarts(lines: string[], i: number, live: boolean) {
  const line = lines[i]
  if (!line.includes("|")) return false
  const next = lines[i + 1]
  if (next !== undefined && DELIMITER.test(next) && next.includes("|") && !(live && i + 1 === lines.length - 1 && !next.includes("-"))) return true
  if (!live || !line.trimStart().startsWith("|")) return false
  return i === lines.length - 1 || (i + 1 === lines.length - 1 && PARTIAL_DELIMITER.test(next))
}

function startsBlock(lines: string[], i: number, live: boolean) {
  const line = lines[i]
  return FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || LIST.test(line) || tableStarts(lines, i, live)
}

/** Block markdown to blocks. `live`: the lines are the end of a stream that is still arriving. */
function parseBlocks(lines: string[], live: boolean): MarkdownBlock[] {
  const blocks: MarkdownBlock[] = []
  const last = lines.length - 1
  let i = 0

  /* Each block is live when the stream is and the block reaches the end of the lines. */
  const add = (block: BlockBody, from: number, to: number) =>
    blocks.push({ ...block, source: lines.slice(from, to).join("\n"), live: live && to > last } as MarkdownBlock)
  const reachesEnd = (to: number) => live && to > last

  while (i <= last) {
    const line = lines[i]
    if (blank(line)) {
      i++
      continue
    }
    if (live && i === last && PARTIAL.test(line)) break
    const from = i

    const fence = FENCE.exec(line)
    if (fence && !(fence[2][0] === "`" && fence[3].includes("`"))) {
      const [, indent, marks, info] = fence
      const close = new RegExp(`^ {0,3}${marks[0] === "`" ? "`" : "~"}{${marks.length},}\\s*$`)
      const code: string[] = []
      let complete = false
      i++
      while (i <= last) {
        if (close.test(lines[i])) {
          complete = true
          i++
          break
        }
        code.push(lines[i].startsWith(indent) ? lines[i].slice(indent.length) : lines[i].trimStart())
        i++
      }
      /* A closing fence still being typed is not code. */
      if (!complete && live && code.length && new RegExp(`^ {0,3}\\${marks[0]}{1,${marks.length}}\\s*$`).test(code[code.length - 1])) code.pop()
      add({ type: "code", info: info.trim(), language: codeLanguage(info), code: code.join("\n"), complete }, from, i)
      continue
    }

    const heading = HEADING.exec(line)
    if (heading) {
      i++
      add({ type: "heading", level: heading[1].length as 1 | 2 | 3 | 4 | 5 | 6, children: parseInline(heading[2] ?? "", reachesEnd(i)) }, from, i)
      continue
    }

    if (RULE.test(line)) {
      i++
      add({ type: "rule" }, from, i)
      continue
    }

    if (QUOTE.test(line)) {
      const inner: string[] = []
      while (i <= last && !blank(lines[i]) && (QUOTE.test(lines[i]) || !startsBlock(lines, i, live))) {
        inner.push(lines[i].replace(/^ {0,3}> ?/, ""))
        i++
      }
      add({ type: "quote", children: parseBlocks(inner, reachesEnd(i)) }, from, i)
      continue
    }

    const first = LIST.exec(line)
    if (first) {
      const ordered = /\d/.test(first[2])
      const indent = first[1].length
      const items: { checked?: boolean; lines: string[] }[] = []
      while (i <= last) {
        const m = LIST.exec(lines[i])
        if (!m || /\d/.test(m[2]) !== ordered || m[1].length > indent + 1 || m[1].length < indent) break
        if (live && i === last && PARTIAL.test(lines[i])) break
        const gap = m[3]?.length ?? 1
        const contentIndent = m[1].length + m[2].length + (gap > 4 ? 1 : gap)
        const item = { lines: [m[4] ?? ""] } as { checked?: boolean; lines: string[] }
        i++
        while (i <= last) {
          const l = lines[i]
          if (blank(l)) {
            let j = i
            while (j <= last && blank(lines[j])) j++
            if (j > last || indentOf(lines[j]) <= indent) break
            item.lines.push("")
            i++
            continue
          }
          if (indentOf(l) > indent) {
            item.lines.push(l.slice(Math.min(indentOf(l), contentIndent)))
            i++
            continue
          }
          /* A line that carries on the paragraph before it, without indenting. */
          if (!blank(lines[i - 1]) && !startsBlock(lines, i, live)) {
            item.lines.push(l.trimStart())
            i++
            continue
          }
          break
        }
        const task = /^\[([ xX])\](?:\s+|$)/.exec(item.lines[0])
        if (task) {
          item.checked = task[1] !== " "
          item.lines[0] = item.lines[0].slice(task[0].length)
        } else if (live && i > last && item.lines.length === 1 && /^\[[ xX]?$/.test(item.lines[0])) {
          item.lines[0] = ""
        }
        items.push(item)
        /* Blank lines between items: the next item continues the list. */
        let j = i
        while (j <= last && blank(lines[j])) j++
        if (j > i && j <= last && LIST.test(lines[j])) i = j
      }
      if (items.length) {
        const start = ordered ? parseInt(first[2], 10) : 1
        add(
          {
            type: "list",
            ordered,
            start,
            items: items.map((item, n) => ({
              checked: item.checked,
              children: parseBlocks(item.lines, reachesEnd(i) && n === items.length - 1),
            })),
          },
          from,
          i,
        )
        continue
      }
      if (i === from) break
      continue
    }

    if (tableStarts(lines, i, live)) {
      const head = splitRow(line)
      const divider = lines[i + 1]
      if (divider === undefined || !DELIMITER.test(divider) || !divider.includes("-")) {
        /* A header with no divider yet: wait, rather than show pipes. */
        if (live && i + 2 > last) break
      }
      const align = head.map((_, n) => alignOf(splitRow(divider ?? "")[n] ?? ""))
      i += divider === undefined ? 1 : 2
      const rows: string[][] = []
      while (i <= last && !blank(lines[i]) && lines[i].includes("|")) {
        rows.push(splitRow(lines[i]))
        i++
      }
      const end = reachesEnd(i)
      const fit = (cells: string[]) => head.map((_, n) => cells[n] ?? "")
      add(
        {
          type: "table",
          align,
          head: head.map((cell) => parseInline(cell, false)),
          rows: rows.map((cells, r) =>
            fit(cells).map((cell, n) => parseInline(cell, end && r === rows.length - 1 && n === Math.min(cells.length, head.length) - 1)),
          ),
        },
        from,
        i,
      )
      continue
    }

    const text: string[] = []
    while (i <= last && !blank(lines[i]) && (i === from || !startsBlock(lines, i, live))) {
      if (live && i === last && i > from && PARTIAL.test(lines[i])) break
      text.push(i === from ? lines[i].trimStart() : lines[i])
      i++
    }
    if (!text.length) break
    add({ type: "paragraph", children: parseInline(text.join("\n"), reachesEnd(i)) }, from, i)
  }
  return blocks
}

/** Markdown to blocks. While `streaming`, the end is read as unfinished (see the top of this file). */
function parseMarkdown(source: string, { streaming = false }: { streaming?: boolean } = {}): MarkdownBlock[] {
  const lines = source.replace(/\r\n?/g, "\n").replace(/^\t+/gm, (tabs) => "    ".repeat(tabs.length)).split("\n")
  return parseBlocks(lines, streaming)
}

/** The plain text of inline nodes, for labels and agents. */
function inlineText(nodes: MarkdownInline[]): string {
  return nodes.map((node) => ("text" in node ? node.text : node.type === "break" ? "\n" : inlineText(node.children))).join("")
}

/* ---------- The primitive ---------- */

type MarkdownOptions = {
  /** True while the text is still arriving: the end reads as unfinished, and the caret shows. */
  streaming?: boolean
}

const markdown = definePrimitive({
  name: "markdown",
  options: { streaming: "boolean" },
  state: (options: MarkdownOptions) => ({ content: "", streaming: options.streaming ?? false }),
  sync: (options) => ({ streaming: options.streaming ?? false }),
  controlled: ["content"],
  api: () => ({}),
  slots: (slot) => ({
    root: slot<{}, { streaming: boolean }>({
      state: (state) => ({ streaming: state.streaming }),
      attrs: (state) => ({
        "data-streaming": state.streaming ? "" : undefined,
        "aria-busy": state.streaming ? "true" : undefined,
      }),
      /* An agent reads the answer as text. */
      bind: (el, part) => bindAgentContent(el, (content) => part.store.set({ content })),
    }),
    /* Decorative: shows where the text is arriving. */
    caret: slot({
      attrs: () => ({ "aria-hidden": "true" }),
    }),
  }),
  agent: { actions: [] },
})

export {
  codeLanguage,
  inlineText,
  markdown,
  parseInline,
  parseMarkdown,
  safeHref,
  type MarkdownAlign,
  type MarkdownBlock,
  type MarkdownInline,
  type MarkdownListItem,
  type MarkdownOptions,
}
````

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

**Vue**

```bash
npx shadcn-vue@latest add https://keyframery.com/r/vue/markdown.json
```

This adds `components/keyframery/markdown/` (one file per part, with the same part names as React) to your Vue or Nuxt project, installs UI SDK for Vue and adds the motion tokens to your global CSS. See [Install for Vue](/docs/installation/vue).

## Usage [#usage]

**React**

```tsx
import { Markdown } from "@/components/keyframery/markdown"

export default function Usage() {
  return <Markdown>{"Your table for two is booked for **Saturday at 19:30**."}</Markdown>
}
```

**Vue**

```vue
<script setup lang="ts">
import { Markdown } from "@/components/keyframery/markdown"
</script>

<template>
  <Markdown>Your table for two is booked for **Saturday at 19:30**.</Markdown>
</template>
```

## Examples [#examples]

### Streaming [#streaming]

Pass the text as it arrives and set `streaming` until it ends. Finished blocks stay exactly where they are, an unclosed `**` or fence reads as it will once closed, and a caret marks the end.

<ExamplePreview name="markdown/streaming">
**React**

  ```tsx
  import * as React from "react"

  import { Markdown } from "@/components/keyframery/markdown"

  const reply = `Here is the plan for **Sunday morning**:

  1. Pastéis de Belém opens at 08:00, so go first.
  2. Walk ten minutes to the Jerónimos Monastery.

  > Tickets sell out by 10:00 in summer.`

  const words = reply.match(/\s*\S+/g) ?? []

  export default function MarkdownStreaming() {
    const [at, setAt] = React.useState(0)
    React.useEffect(() => {
      /* A word every 70ms, then a pause, then again. */
      const timer = setInterval(() => setAt((n) => (n >= words.length + 25 ? 0 : n + 1)), 70)
      return () => clearInterval(timer)
    }, [])
    return (
      <Markdown className="w-full max-w-[380px]" streaming={at < words.length}>
        {words.slice(0, at).join("")}
      </Markdown>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { onBeforeUnmount, ref } from "vue"

  import { Markdown } from "@/components/keyframery/markdown"

  const reply = `Here is the plan for **Sunday morning**:

  1. Pastéis de Belém opens at 08:00, so go first.
  2. Walk ten minutes to the Jerónimos Monastery.

  > Tickets sell out by 10:00 in summer.`

  const words = reply.match(/\s*\S+/g) ?? []

  const at = ref(0)
  /* A word every 70ms, then a pause, then again. */
  const timer = setInterval(() => (at.value = at.value >= words.length + 25 ? 0 : at.value + 1), 70)
  onBeforeUnmount(() => clearInterval(timer))
  </script>

  <template>
    <Markdown class="w-full max-w-[380px]" :streaming="at < words.length">{{ words.slice(0, at).join("") }}</Markdown>
  </template>
  ```
</ExamplePreview>

### Code and tables [#code-and-tables]

Fenced code is Keyframery's code block, with its language and a copy button. Tables scroll sideways on a narrow screen and take their column alignment from the divider row.

<ExamplePreview name="markdown/code-and-tables">
**React**

  ```tsx
  import { Markdown } from "@/components/keyframery/markdown"

  const text = `| Stop | Arrives | Platform |
  | :-- | --: | :-: |
  | Coimbra-B | 10:42 | 2 |
  | Porto Campanhã | 11:58 | 5 |

  \`\`\`bash
  curl https://api.example.com/trains?from=lisbon
  \`\`\``

  export default function MarkdownCodeAndTables() {
    return <Markdown className="w-full max-w-[420px]">{text}</Markdown>
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { Markdown } from "@/components/keyframery/markdown"

  const text = `| Stop | Arrives | Platform |
  | :-- | --: | :-: |
  | Coimbra-B | 10:42 | 2 |
  | Porto Campanhã | 11:58 | 5 |

  \`\`\`bash
  curl https://api.example.com/trains?from=lisbon
  \`\`\``
  </script>

  <template>
    <Markdown class="w-full max-w-[420px]">{{ text }}</Markdown>
  </template>
  ```
</ExamplePreview>

### Your own elements [#your-own-elements]

`components` swaps any element by its tag name, and `codeBlock` replaces fenced code. Each gets the element's props, including its `data-slot`, so the styles still reach it. Keep the object outside render.

<ExamplePreview name="markdown/components">
**React**

  ```tsx
  import type * as React from "react"

  import { Markdown, type MarkdownComponents } from "@/components/keyframery/markdown"

  const components: MarkdownComponents = {
    a: (props: React.ComponentProps<"a">) => <a {...props} className="font-medium text-primary" />,
  }

  export default function MarkdownComponentsExample() {
    return (
      <Markdown className="max-w-[380px]" components={components}>
        {"Your refund is on its way. Track it in [your orders](#orders) or reply here with the order number."}
      </Markdown>
    )
  }
  ```

**Vue**

  ```vue
  <script setup lang="ts">
  import { h } from "vue"

  import { Markdown, type MarkdownComponents } from "@/components/keyframery/markdown"

  const components: MarkdownComponents = {
    a: (props: Record<string, unknown>) => h("a", { ...props, class: "font-medium text-primary" }),
  }
  </script>

  <template>
    <Markdown class="max-w-[380px]" :components="components">Your refund is on its way. Track it in [your orders](#orders) or reply here with the order number.</Markdown>
  </template>
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                           |
| ----------- | ---------------------------------------------------------------------------------------------------------------------- |
| **Steady**  | Each block is drawn from its own source, so finished blocks never re-render or move while the text after them arrives. |
| **Rise**    | A new block fades up out of a soft blur as it starts.                                                                  |
| **Caret**   | While streaming, a slim caret sits at the end of the text and pulses softly; it stays still for reduced motion.        |
| **Cascade** | Fenced code arrives line by line in Keyframery's code block, and its copy key appears when the closing fence lands.    |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this markdown moves, pass `speed`:

```tsx
<Markdown speed="fast">
  …
</Markdown>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable               | What it changes                        | Default               |
| ---------------------- | -------------------------------------- | --------------------- |
| `--markdown-ink`       | Body text                              | text-foreground       |
| `--markdown-muted`     | Quotes, list markers and table headers | text-muted-foreground |
| `--markdown-link`      | Links                                  | text-foreground       |
| `--markdown-caret`     | Caret                                  | bg-foreground         |
| `--markdown-code-face` | Inline code surface                    | bg-muted              |
| `--markdown-font`      | Body size                              | text-\[14px]          |
| `--markdown-gap`       | Block spacing                          | gap-3                 |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Markdown [#markdown]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;streaming&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;True while the text is still arriving: an unclosed `**`, fence, link or table row reads as it will once closed, and the caret shows.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;caret&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Show the caret while streaming. Default true.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;components&#x22;,&#x22;type&#x22;:&#x22;MarkdownComponents&#x22;,&#x22;full&#x22;:&#x22;MarkdownComponents&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Your own element for any tag (`p`, `h1` to `h6`, `a`, `strong`, `em`, `del`, `code`, `ul`, `ol`, `li`, `blockquote`, `hr`, `table` and its parts), and `codeBlock` for fenced code. Keep the object stable.&#x22;,&#x22;required&#x22;:false}]" />

### MarkdownCodeBlock [#markdowncodeblock]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;code&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The code, without its fences.&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;language&#x22;,&#x22;type&#x22;:&#x22;\&#x22;text\&#x22; | \&#x22;html\&#x22; | \&#x22;ts\&#x22; | \&#x22;tsx\&#x22; | \&#x22;js\&#x22; | \&#x22;jsx\&#x22; | \&#x22;json\&#x22; | \&#x22;css\&#x22; | \&#x22;bash\&#x22;&#x22;,&#x22;full&#x22;:&#x22;CodeBlockLanguage&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The tokenizer's language for the fence's info string (\&#x22;text\&#x22; when unknown).&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;info&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The fence's info string as written, like \&#x22;tsx\&#x22; or \&#x22;python\&#x22;.&#x22;,&#x22;required&#x22;:true},{&#x22;name&#x22;:&#x22;complete&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;False while the closing fence has not arrived yet.&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `MarkdownCaret`: a `<span>`

## Keyboard [#keyboard]

| Key              | What it does                                                             |
| ---------------- | ------------------------------------------------------------------------ |
| <kbd>Tab</kbd>   | Moves to the next link, then to a code block's code and its copy button. |
| <kbd>Enter</kbd> | Opens the focused link. Links to other sites open in a new tab.          |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a markdown, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/markdown-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/markdown`.

## Questions

### How does the animated Markdown for UI SDK move?

Steady: Each block is drawn from its own source, so finished blocks never re-render or move while the text after them arrives. Rise: A new block fades up out of a soft blur as it starts. Caret: While streaming, a slim caret sits at the end of the text and pulses softly; it stays still for reduced motion. Cascade: Fenced code arrives line by line in Keyframery's code block, and its copy key appears when the closing fence lands.

### Do I need Motion or Framer Motion for the animated Markdown?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no markdown. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/markdown-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Markdown when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
