{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "figure-diagram",
  "title": "Diagram Figure",
  "author": "zyx1121 (https://github.com/zyx1121)",
  "description": "A drawing in box-drawing characters, set as text; its steps light one part at a time with a line under it.",
  "registryDependencies": [
    "https://ui.zyx.tw/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/zyx/components/figure-diagram.tsx",
      "content": "\"use client\"\n\nimport { useEffect, useMemo, useRef, useState } from \"react\"\n\nimport { cn } from \"../lib/utils\"\n\nimport type { Diagram } from \"../lib/figures\"\nimport { useReducedMotion } from \"../hooks/use-reduced-motion\"\n\n/** Milliseconds a step stays lit while the figure plays by itself. */\nconst STEP_MS = 2400\n\ntype Segment = { text: string; steps: number[] }\n\n/**\n * A line cut where any step's words begin or end, so the text nodes never\n * change: stepping only recolors them, and the page's decoder keeps the\n * nodes it started with.\n */\nfunction segments(line: string, lit: string[][]): Segment[] {\n  const owners: number[][] = Array.from(line, () => [])\n  lit.forEach((words, step) => {\n    for (const word of words) {\n      for (\n        let at = line.indexOf(word);\n        at !== -1;\n        at = line.indexOf(word, at + word.length)\n      ) {\n        for (let cell = at; cell < at + word.length; cell++) {\n          if (!owners[cell]!.includes(step)) owners[cell]!.push(step)\n        }\n      }\n    }\n  })\n  const out: Segment[] = []\n  for (let cell = 0; cell < line.length; cell++) {\n    const steps = owners[cell]!\n    const last = out.at(-1)\n    if (last && last.steps.join() === steps.join()) last.text += line[cell]\n    else out.push({ text: line[cell]!, steps })\n  }\n  return out\n}\n\nfunction Lines({\n  lines,\n  lit,\n  active,\n  className,\n}: {\n  lines: string[]\n  lit: string[][]\n  active: number\n  className?: string\n}) {\n  const rows = useMemo(\n    () => lines.map((line) => segments(line, lit)),\n    [lines, lit]\n  )\n  return (\n    <div\n      aria-hidden\n      className={cn(\n        \"w-max text-body leading-(--text-caption--line-height) whitespace-pre\",\n        className\n      )}\n    >\n      {rows.map((row, index) => (\n        // An empty line still takes its row.\n        <span key={index} className=\"block\">\n          {row.length === 0\n            ? \" \"\n            : row.map(({ text, steps }, at) => (\n                <span\n                  key={at}\n                  className={cn(\n                    \"motion-safe:transition-colors motion-safe:duration-state\",\n                    steps.includes(active) && \"text-foreground\"\n                  )}\n                >\n                  {text}\n                </span>\n              ))}\n        </span>\n      ))}\n    </div>\n  )\n}\n\n/**\n * A drawing in box-drawing characters (app/globals.css, `diagram`): real\n * text in the page's own face, so it is exactly as legible as the paragraphs\n * beside it and decodes in with them. Phones get the narrow drawing. The\n * drawing, its steps and their lines sit in the middle of the column.\n *\n * Every figure with steps works the same way: while it is on screen it\n * lights one step after another, with that step's line under the drawing;\n * picking a step holds it, and picking it again lets the figure play on.\n * Reduced motion never plays by itself.\n */\nexport function DiagramFigure({\n  diagram,\n  className,\n  step: driven,\n}: {\n  diagram: Diagram\n  className?: string\n  /**\n   * The step a scrolling page lights (components/scrolly.tsx). Set, the\n   * figure plays nothing, lists no steps and shows no line: the page does.\n   */\n  step?: number\n}) {\n  const steps = useMemo(() => diagram.steps ?? [], [diagram.steps])\n  const { narrow, code } = diagram\n  const middle = !code && \"mx-auto\"\n  const lit = useMemo(() => steps.map((step) => step.lit), [steps])\n  const rootRef = useRef<HTMLDivElement>(null)\n  const reducedMotion = useReducedMotion()\n  const [active, setActive] = useState(0)\n  const [held, setHeld] = useState(false)\n  const [visible, setVisible] = useState(false)\n  const shown = driven ?? active\n\n  useEffect(() => {\n    const root = rootRef.current\n    if (!root) return\n    const observer = new IntersectionObserver(\n      ([entry]) => setVisible(Boolean(entry?.isIntersecting)),\n      { threshold: 0.5 }\n    )\n    observer.observe(root)\n    return () => observer.disconnect()\n  }, [])\n\n  const playing =\n    steps.length > 1 &&\n    visible &&\n    !held &&\n    !reducedMotion &&\n    driven === undefined\n  useEffect(() => {\n    if (!playing) return\n    const id = setInterval(\n      () => setActive((step) => (step + 1) % steps.length),\n      STEP_MS\n    )\n    return () => clearInterval(id)\n  }, [playing, steps.length])\n\n  return (\n    <div ref={rootRef} className={className}>\n      <div\n        role=\"img\"\n        aria-label={diagram.alt}\n        className=\"overflow-x-auto overflow-y-hidden text-muted-foreground\"\n      >\n        <Lines\n          lines={diagram.wide}\n          lit={lit}\n          active={shown}\n          className={cn(\"w-fit\", middle, narrow && \"max-sm:hidden\")}\n        />\n        {narrow && (\n          <Lines\n            lines={narrow}\n            lit={lit}\n            active={shown}\n            className={cn(\"w-fit sm:hidden\", middle)}\n          />\n        )}\n      </div>\n      {steps.length > 0 && driven === undefined && (\n        <>\n          <ol\n            className={cn(\n              \"mt-5 flex flex-wrap gap-x-2 gap-y-1\",\n              !code && \"justify-center\"\n            )}\n          >\n            {steps.map(({ label }, index) => {\n              const current = index === active\n              return (\n                <li key={label} className=\"flex\">\n                  <button\n                    type=\"button\"\n                    aria-pressed={current && held}\n                    aria-current={current ? \"step\" : undefined}\n                    onClick={() => {\n                      setHeld(!(current && held))\n                      setActive(index)\n                    }}\n                    className={cn(\n                      \"-my-2.5 cursor-pointer py-2.5 uppercase outline-offset-4 focus-visible:outline-2\",\n                      \"motion-safe:transition-colors motion-safe:duration-state\",\n                      current\n                        ? \"bg-(--mark)/20 text-(--mark)\"\n                        : \"text-muted-foreground hover:text-foreground\"\n                    )}\n                  >\n                    <span aria-hidden className={cn(!current && \"invisible\")}>\n                      {held ? \"[\" : \">\"}\n                    </span>\n                    {label}\n                    <span\n                      aria-hidden\n                      className={cn(!(current && held) && \"invisible\")}\n                    >\n                      ]\n                    </span>\n                  </button>\n                </li>\n              )\n            })}\n          </ol>\n          {/* Every step's line shares one cell, so the tallest sets the\n              height and nothing below moves as the steps change. */}\n          <div\n            className={cn(\n              \"mt-3 grid max-w-2xl\",\n              !code && \"mx-auto text-center\"\n            )}\n          >\n            {steps.map(({ label, text }, index) => (\n              <p\n                key={label}\n                aria-hidden={index !== active}\n                className={cn(\n                  \"col-start-1 row-start-1 text-pretty\",\n                  index !== active && \"invisible\"\n                )}\n              >\n                {text}\n              </p>\n            ))}\n          </div>\n        </>\n      )}\n    </div>\n  )\n}\n",
      "type": "registry:component"
    },
    {
      "path": "registry/zyx/lib/figures.ts",
      "content": "/**\n * The figures a reader operates in an article: a drawing read part by part,\n * a choice, a quiz, a replayed run and a dial. Each is plain data, so an\n * article can keep its figures in JSON.\n */\n\n/**\n * A drawing in box-drawing characters, set as text so it is as legible as\n * the page around it. `wide` fits 66 cells (the narrowest column from the sm\n * breakpoint up); `narrow` fits 30 cells, for phones. ASCII and box-drawing\n * characters only, so every glyph keeps one cell.\n */\nexport type Diagram = {\n  kind: \"diagram\"\n  wide: string[]\n  /** Left out, phones get the wide drawing and scroll it sideways. */\n  narrow?: string[]\n  /**\n   * Pseudo code: set from the column's left edge instead of its middle, and\n   * a step lights whole lines.\n   */\n  code?: boolean\n  alt: string\n  /**\n   * The drawing read one part at a time. Each step lights the words in\n   * `lit` wherever they stand in the drawing (wide and narrow alike) and\n   * shows `text` under it. The figure plays through its steps by itself and\n   * holds on the one a reader picks.\n   */\n  steps?: { label: string; lit: string[]; text: string }[]\n}\n\n/**\n * A figure the reader operates (figure-lesson.tsx): `ask` names\n * the one choice, and each state is what one answer leads to. A state is a\n * few titled blocks of rows, with the line to take from it under them.\n */\nexport type Lesson = {\n  kind: \"lesson\"\n  ask: string\n  /** Two blocks stand side by side from the sm breakpoint up. */\n  side?: boolean\n  states: {\n    label: string\n    blocks: {\n      title: string\n      /** The rows are steps in order, so each takes its number. */\n      numbered?: boolean\n      rows: {\n        text: string\n        /** A count or a version, set at the row's right edge. */\n        value?: string\n        /** `mark` is what this state adds, `dim` what it removes. */\n        tone?: \"mark\" | \"dim\" | \"quiet\"\n      }[]\n    }[]\n    text: string\n  }[]\n}\n\n/**\n * A question the reader answers before the text does\n * (figure-quiz.tsx). Every item takes the same options; picking\n * one shows which is right, and the line that says why.\n */\nexport type Quiz = {\n  kind: \"quiz\"\n  ask: string\n  options: string[]\n  items: {\n    text: string\n    /** The index of the right option. */\n    answer: number\n    why: string\n  }[]\n}\n\n/**\n * A run replayed one event at a time (figure-trace.tsx): who\n * spoke, what was sent, and the line to take from it. Events stay on screen,\n * so the reader watches the record grow.\n */\nexport type Trace = {\n  kind: \"trace\"\n  alt: string\n  events: {\n    /** The sender, in Latin capitals: USER, MODEL, TOOL. */\n    from: string\n    /** What was sent, as written on the wire. Long lines wrap. */\n    lines: string[]\n    text: string\n  }[]\n}\n\n/**\n * A quantity the reader moves (figure-dial.tsx): each stop\n * redraws the same bars, so the eye follows what grows and what does not.\n */\nexport type Dial = {\n  kind: \"dial\"\n  ask: string\n  /** Cells in a full bar: 20 or fewer, so a phone holds it. */\n  scale: number\n  stops: {\n    label: string\n    /** The same bars at every stop, in the same order. */\n    bars: {\n      label: string\n      cells: number\n      value?: string\n      tone?: \"mark\" | \"quiet\"\n    }[]\n    text: string\n  }[]\n}\n\nexport type Figure = Diagram | Lesson | Quiz | Trace | Dial\n\n/** The words on the figures' buttons and marks, so a page can set its language. */\nexport type FigureLabels = {\n  next: string\n  again: string\n  play: string\n  stop: string\n  /** Before the line that says why, on a right pick and on a wrong one. */\n  right: string\n  wrong: string\n}\n\nexport const FIGURE_LABELS: FigureLabels = {\n  next: \"Next\",\n  again: \"Again\",\n  play: \"Play\",\n  stop: \"Pause\",\n  right: \"Right: \",\n  wrong: \"Not quite: \",\n}\n",
      "type": "registry:lib"
    },
    {
      "path": "registry/zyx/hooks/use-reduced-motion.ts",
      "content": "\"use client\"\n\nimport { useSyncExternalStore } from \"react\"\n\nconst QUERY = \"(prefers-reduced-motion: reduce)\"\n\nfunction subscribe(onChange: () => void) {\n  const query = window.matchMedia(QUERY)\n  query.addEventListener(\"change\", onChange)\n  return () => query.removeEventListener(\"change\", onChange)\n}\n\n/** True when the visitor asks for reduced motion. False while server rendering. */\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(QUERY).matches,\n    () => false\n  )\n}\n",
      "type": "registry:hook"
    }
  ],
  "meta": {
    "useWhen": "An architecture, a flow or pseudo code the reader reads part by part.",
    "notFor": "Charts of numbers; use chart.",
    "related": [
      "scrolly",
      "figure-trace"
    ]
  },
  "docs": "Use when: An architecture, a flow or pseudo code the reader reads part by part.\nNot for: Charts of numbers; use chart.\nGuide: https://ui.zyx.tw/figure-diagram.md",
  "categories": [
    "figure",
    "motion"
  ],
  "type": "registry:component"
}