{
  "schemaVersion": 1,
  "target": "react",
  "name": "code-block",
  "version": "0.1.1",
  "category": "data",
  "title": "Code Block",
  "description": "A code block with a filename tab, line numbers, highlighted lines, a copy button, and a wrap toggle, with optional dependency-free coloring for JS, TS, JSON, and shell.",
  "tags": [
    "code",
    "syntax",
    "copy",
    "snippet",
    "docs"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/code-block",
  "props": [
    {
      "name": "code",
      "type": "string",
      "description": "The source; also what Copy copies."
    },
    {
      "name": "language",
      "type": "\"ts\" | \"tsx\" | \"js\" | \"jsx\" | \"json\" | \"bash\" | \"text\"",
      "default": "\"text\"",
      "description": "Enables the built-in coloring."
    },
    {
      "name": "filename",
      "type": "string",
      "description": "Shown as the header tab. Without it the header shows the language."
    },
    {
      "name": "tokens",
      "type": "{ content, className?, color? }[][]",
      "description": "Pre-tokenized lines from your own highlighter; overrides the built-in coloring."
    },
    {
      "name": "highlight",
      "type": "boolean",
      "default": "true",
      "description": "Built-in token coloring."
    },
    {
      "name": "lineNumbers",
      "type": "boolean",
      "default": "true",
      "description": "Line number gutter."
    },
    {
      "name": "highlightLines",
      "type": "string | number[]",
      "description": "Lines to emphasize, such as \"3,7-9\"."
    },
    {
      "name": "startLine",
      "type": "number",
      "default": "1",
      "description": "First line number for excerpts."
    },
    {
      "name": "defaultWrap / wrapToggle",
      "type": "boolean / boolean",
      "default": "false / true",
      "description": "Initial wrap and whether the toggle shows."
    },
    {
      "name": "copyable",
      "type": "boolean",
      "default": "true",
      "description": "Shows the copy button."
    },
    {
      "name": "maxHeight",
      "type": "string",
      "description": "Caps the height; the code scrolls inside."
    },
    {
      "name": "actions",
      "type": "ReactNode",
      "description": "Extra header content before the buttons."
    }
  ],
  "accessibility": [
    "The code area is a focusable pre with an accessible name (\"Code: app/api/runs/route.ts\") so keyboard users can scroll long lines.",
    "Copy and Wrap are labelled icon buttons; Wrap is a toggle with aria-pressed.",
    "A polite live region announces \"Copied to clipboard\", and the icon swaps to a check for 1.8 seconds.",
    "Line numbers are aria-hidden and not selectable, so selections and screen readers get only the code.",
    "The tokenizer colors are a reading aid; text keeps AA contrast in both themes."
  ],
  "states": [
    "default",
    "highlighted lines",
    "wrapped",
    "copied",
    "no line numbers"
  ],
  "files": [
    {
      "path": "ui/code-block.tsx",
      "content": "\"use client\";\n\nimport { type ComponentProps, type CSSProperties, type ReactNode, useEffect, useMemo, useRef, useState } from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\n/** One run of text in a line. Shape matches what most highlighters emit (`content` plus a `color`). */\nexport interface CodeToken {\n  content: string;\n  /** Classes for the run, for example `\"text-emerald-700 dark:text-emerald-400\"`. */\n  className?: string;\n  /** A CSS color, as emitted by highlighters such as Shiki. */\n  color?: string;\n}\n\nexport type CodeLanguage = \"ts\" | \"tsx\" | \"js\" | \"jsx\" | \"json\" | \"bash\" | \"text\";\n\ntype TokenKind = \"plain\" | \"keyword\" | \"string\" | \"number\" | \"comment\" | \"function\" | \"type\" | \"property\" | \"punctuation\";\n\n// A restrained scheme: structure in ink, literals in two meaning hues, comments recede.\nconst tokenClass: Record<TokenKind, string | undefined> = {\n  plain: undefined,\n  keyword: \"text-zinc-950 font-medium dark:text-white\",\n  string: \"text-emerald-700 dark:text-emerald-400\",\n  number: \"text-sky-700 dark:text-sky-400\",\n  comment: \"text-zinc-400 italic dark:text-zinc-500\",\n  function: \"text-zinc-950 dark:text-white\",\n  type: \"text-amber-700 dark:text-amber-300\",\n  property: \"text-sky-700 dark:text-sky-400\",\n  punctuation: \"text-zinc-400 dark:text-zinc-500\",\n};\n\nconst jsKeywords = new Set(\n  (\n    \"as async await break case catch class const continue debugger default delete do else enum export extends finally for from function \" +\n    \"get if implements import in instanceof interface let new of package private protected public readonly return satisfies set static \" +\n    \"super switch this throw try type typeof var void while with yield keyof declare namespace abstract\"\n  ).split(\" \"),\n);\nconst literals = new Set([\"true\", \"false\", \"null\", \"undefined\", \"NaN\", \"Infinity\"]);\n\ntype Piece = { kind: TokenKind; text: string };\n\nfunction tokenizeScript(code: string, language: CodeLanguage): Piece[] {\n  const out: Piece[] = [];\n  const json = language === \"json\";\n  const bash = language === \"bash\";\n  const pattern = bash\n    ? /(#[^\\n]*)|(\"(?:\\\\.|[^\"\\\\])*\"|'[^']*')|(\\$\\{?[A-Za-z_][\\w]*\\}?)|(--?[A-Za-z][\\w-]*)|(\\b\\d+(?:\\.\\d+)?\\b)|([A-Za-z_][\\w./-]*)|(\\s+)|(.)/g\n    : /(\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/)|(\"(?:\\\\.|[^\"\\\\\\n])*\"|'(?:\\\\.|[^'\\\\\\n])*'|`(?:\\\\.|[^`\\\\])*`)|(\\b(?:0x[\\da-fA-F]+|\\d[\\d_]*(?:\\.\\d+)?(?:e[+-]?\\d+)?n?)\\b)|([A-Za-z_$][\\w$]*)|(\\s+)|([{}()[\\];,.:<>=+\\-*/!?&|%^~@])|(.)/g;\n  let match: RegExpExecArray | null;\n  let lineStart = true;\n  while ((match = pattern.exec(code))) {\n    const text = match[0];\n    if (bash) {\n      const [, comment, str, variable, flag, num, word] = match;\n      if (comment) out.push({ kind: \"comment\", text });\n      else if (str) out.push({ kind: \"string\", text });\n      else if (variable) out.push({ kind: \"property\", text });\n      else if (flag) out.push({ kind: \"type\", text });\n      else if (num) out.push({ kind: \"number\", text });\n      else if (word) out.push({ kind: lineStart ? \"function\" : \"plain\", text });\n      else out.push({ kind: \"plain\", text });\n      if (text.includes(\"\\n\")) lineStart = true;\n      else if (!/^\\s+$/.test(text)) lineStart = text === \"|\" || text === \"&\" || text === \";\";\n      continue;\n    }\n    const [, comment, str, num, ident, , punct] = match;\n    if (comment) out.push({ kind: \"comment\", text });\n    else if (str) {\n      // In JSON, a string followed by a colon is a key.\n      const rest = code.slice(pattern.lastIndex);\n      out.push({ kind: json && /^\\s*:/.test(rest) ? \"property\" : \"string\", text });\n    } else if (num) out.push({ kind: \"number\", text });\n    else if (ident) {\n      const rest = code.slice(pattern.lastIndex);\n      // A reverse search instead of findLast, which needs an ES2023 lib some projects do not target.\n      const previous = [...out].reverse().find((piece) => !/^\\s+$/.test(piece.text));\n      if (literals.has(ident)) out.push({ kind: \"number\", text });\n      else if (!json && jsKeywords.has(ident) && previous?.text !== \".\") out.push({ kind: \"keyword\", text });\n      else if (/^\\s*\\(/.test(rest) || /^\\s*=\\s*(?:async\\s*)?\\(/.test(rest)) out.push({ kind: \"function\", text });\n      else if (/^[A-Z]/.test(ident)) out.push({ kind: \"type\", text });\n      // Object keys and member access; a parameter's type annotation (after \"(\") stays plain.\n      else if (previous?.text === \".\" || (/^\\??:(?!:)/.test(rest.trimStart()) && previous?.text !== \"(\" && previous?.text !== \"<\"))\n        out.push({ kind: \"property\", text });\n      else out.push({ kind: \"plain\", text });\n    } else if (punct) out.push({ kind: \"punctuation\", text });\n    else out.push({ kind: \"plain\", text });\n  }\n  return out;\n}\n\n/**\n * A tiny, dependency-free highlighter for JavaScript, TypeScript, JSX, JSON, and shell. It colors\n * keywords, strings, numbers, comments, types, and properties; it does not parse, so treat it as\n * a reading aid. For full grammars, pass pre-tokenized `tokens` from a highlighter of your choice.\n */\nexport function tokenize(code: string, language: CodeLanguage): CodeToken[][] {\n  const lines: CodeToken[][] = [[]];\n  const pieces = language === \"text\" ? [{ kind: \"plain\" as const, text: code }] : tokenizeScript(code, language);\n  for (const piece of pieces) {\n    const parts = piece.text.split(\"\\n\");\n    parts.forEach((part, index) => {\n      if (index > 0) lines.push([]);\n      if (part) lines[lines.length - 1]!.push({ content: part, className: tokenClass[piece.kind] });\n    });\n  }\n  return lines;\n}\n\n/** Parses `\"1,4-6\"` or `[1, 4, 5, 6]` into a set of 1-based line numbers. */\nfunction parseLines(input: string | number[] | undefined) {\n  const set = new Set<number>();\n  if (!input) return set;\n  if (Array.isArray(input)) input.forEach((line) => set.add(line));\n  else\n    for (const part of input.split(\",\")) {\n      const [start, end] = part.split(\"-\").map((value) => Number.parseInt(value.trim(), 10));\n      if (start === undefined || Number.isNaN(start)) continue;\n      for (let line = start; line <= (end && !Number.isNaN(end) ? end : start); line++) set.add(line);\n    }\n  return set;\n}\n\nasync function copyText(text: string) {\n  try {\n    await navigator.clipboard.writeText(text);\n    return true;\n  } catch {\n    const area = document.createElement(\"textarea\");\n    area.value = text;\n    area.setAttribute(\"readonly\", \"\");\n    area.style.position = \"fixed\";\n    area.style.opacity = \"0\";\n    document.body.appendChild(area);\n    area.select();\n    const ok = document.execCommand(\"copy\");\n    area.remove();\n    return ok;\n  }\n}\n\nexport interface CodeBlockProps extends Omit<ComponentProps<\"figure\">, \"children\"> {\n  /** The source text. Also what the copy button copies. */\n  code: string;\n  /** Turns on the built-in coloring for js, jsx, ts, tsx, json, and bash. */\n  language?: CodeLanguage;\n  /** Shown as a tab in the header. Without it, the header shows the language. */\n  filename?: string;\n  /** Pre-tokenized lines from your own highlighter. Overrides the built-in coloring. */\n  tokens?: CodeToken[][];\n  /** Colors tokens with the built-in highlighter. Off renders plain text. */\n  highlight?: boolean;\n  lineNumbers?: boolean;\n  /** Lines to emphasize, 1-based: `\"3,7-9\"` or `[3, 7, 8, 9]`. */\n  highlightLines?: string | number[];\n  /** First line number, for excerpts from the middle of a file. */\n  startLine?: number;\n  /** Initial wrap state. Long lines scroll sideways when off. */\n  defaultWrap?: boolean;\n  /** Shows the wrap toggle in the header. */\n  wrapToggle?: boolean;\n  /** Shows the copy button. */\n  copyable?: boolean;\n  /** Caps the height; the code scrolls inside. Any CSS length, for example `\"20rem\"`. */\n  maxHeight?: string;\n  /** Extra header content, placed before the buttons. */\n  actions?: ReactNode;\n}\n\n/**\n * A code block with a filename tab, line numbers, emphasized lines, a copy button, and a wrap\n * toggle. Highlighting is optional and has no dependency.\n */\nexport function CodeBlock({\n  code,\n  language = \"text\",\n  filename,\n  tokens,\n  highlight = true,\n  lineNumbers = true,\n  highlightLines,\n  startLine = 1,\n  defaultWrap = false,\n  wrapToggle = true,\n  copyable = true,\n  maxHeight,\n  actions,\n  className,\n  ...props\n}: CodeBlockProps) {\n  const [wrap, setWrap] = useState(defaultWrap);\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const trimmed = code.replace(/\\n$/, \"\");\n  const lines = useMemo<CodeToken[][]>(\n    () => tokens ?? (highlight ? tokenize(trimmed, language) : trimmed.split(\"\\n\").map((line) => (line ? [{ content: line }] : []))),\n    [tokens, highlight, trimmed, language],\n  );\n  const marked = useMemo(() => parseLines(highlightLines), [highlightLines]);\n  const gutter = String(startLine + lines.length - 1).length;\n\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  async function onCopy() {\n    const ok = await copyText(trimmed);\n    if (!ok) return;\n    setCopied(true);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setCopied(false), 1800);\n  }\n\n  const label = filename ?? (language === \"text\" ? \"Code\" : language);\n\n  return (\n    <figure\n      data-slot=\"code-block\"\n      className={cx(\n        \"group/code m-0 grid min-w-0 overflow-hidden rounded-xl border text-sm\",\n        \"border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n        className,\n      )}\n      {...props}\n    >\n      <figcaption className=\"flex h-10 items-center gap-2 border-b border-zinc-950/[0.07] ps-3 pe-1.5 dark:border-white/[0.08]\">\n        <span className=\"flex min-w-0 items-center gap-2 font-mono text-xs text-zinc-600 dark:text-zinc-400\">\n          {filename ? <FileGlyph /> : null}\n          <span className=\"truncate\">{label}</span>\n        </span>\n        <span className=\"ms-auto flex items-center gap-0.5\">\n          {actions}\n          {wrapToggle ? (\n            <HeaderButton label=\"Wrap lines\" pressed={wrap} onClick={() => setWrap((value) => !value)}>\n              <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\">\n                <path d=\"M2.5 4h11M2.5 8h9a2 2 0 0 1 0 4H8.5m0 0 1.5-1.5M8.5 12l1.5 1.5M2.5 12h3\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n              </svg>\n            </HeaderButton>\n          ) : null}\n          {copyable ? (\n            <HeaderButton label={copied ? \"Copied\" : \"Copy code\"} onClick={onCopy}>\n              <span className=\"relative size-4\">\n                <svg\n                  aria-hidden=\"true\"\n                  viewBox=\"0 0 16 16\"\n                  fill=\"none\"\n                  className={cx(\n                    \"absolute inset-0 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n                    copied ? \"scale-90 opacity-0\" : \"scale-100 opacity-100\",\n                  )}\n                >\n                  <rect x=\"5.25\" y=\"5.25\" width=\"8\" height=\"8\" rx=\"1.75\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n                  <path d=\"M10.75 3.25A1.5 1.5 0 0 0 9.25 2.5h-5a1.75 1.75 0 0 0-1.75 1.75v5a1.5 1.5 0 0 0 .75 1.3\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n                </svg>\n                <svg\n                  aria-hidden=\"true\"\n                  viewBox=\"0 0 16 16\"\n                  fill=\"none\"\n                  className={cx(\n                    \"absolute inset-0 text-emerald-600 transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none dark:text-emerald-400\",\n                    copied ? \"scale-100 opacity-100\" : \"scale-90 opacity-0\",\n                  )}\n                >\n                  <path d=\"M3.5 8.5 6.5 11.5 12.5 4.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                </svg>\n              </span>\n            </HeaderButton>\n          ) : null}\n          <span aria-live=\"polite\" className=\"sr-only\">\n            {copied ? \"Copied to clipboard\" : \"\"}\n          </span>\n        </span>\n      </figcaption>\n      <pre\n        tabIndex={0}\n        aria-label={filename ? `Code: ${filename}` : \"Code\"}\n        style={{ maxHeight } as CSSProperties}\n        className={cx(\n          \"m-0 overflow-auto py-3 font-mono text-[13px] leading-6 text-zinc-700 dark:text-zinc-300\",\n          \"outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n          \"[scrollbar-width:thin]\",\n        )}\n      >\n        <code className={cx(\"grid\", wrap ? \"min-w-0\" : \"w-max min-w-full\")}>\n          {lines.map((line, index) => {\n            const number = startLine + index;\n            const emphasized = marked.has(number);\n            return (\n              <span\n                key={index}\n                data-highlighted={emphasized || undefined}\n                className={cx(\n                  \"flex pe-4\",\n                  lineNumbers ? \"ps-0\" : \"ps-4\",\n                  emphasized &&\n                    \"bg-zinc-950/[0.04] shadow-[inset_2px_0_0_rgb(9_9_11/0.35)] dark:bg-white/[0.06] dark:shadow-[inset_2px_0_0_rgb(255_255_255/0.45)]\",\n                )}\n              >\n                {lineNumbers ? (\n                  <span\n                    aria-hidden=\"true\"\n                    style={{ width: `${gutter + 3}ch` } as CSSProperties}\n                    className={cx(\n                      \"shrink-0 pe-4 text-right tabular-nums select-none\",\n                      emphasized ? \"text-zinc-600 dark:text-zinc-400\" : \"text-zinc-400 dark:text-zinc-600\",\n                    )}\n                  >\n                    {number}\n                  </span>\n                ) : null}\n                <span className={cx(\"min-w-0\", wrap ? \"break-words whitespace-pre-wrap\" : \"whitespace-pre\")}>\n                  {line.length === 0\n                    ? \"\\u200b\"\n                    : line.map((token, tokenIndex) => (\n                        <span key={tokenIndex} className={token.className} style={token.color ? { color: token.color } : undefined}>\n                          {token.content}\n                        </span>\n                      ))}\n                </span>\n              </span>\n            );\n          })}\n        </code>\n      </pre>\n    </figure>\n  );\n}\n\nfunction HeaderButton({\n  label,\n  pressed,\n  onClick,\n  children,\n}: {\n  label: string;\n  pressed?: boolean;\n  onClick: () => void;\n  children: ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      aria-pressed={pressed}\n      onClick={onClick}\n      className={cx(\n        \"inline-flex size-7 items-center justify-center rounded-md text-zinc-500 [&_svg]:size-4\",\n        \"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none\",\n        \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n        \"aria-pressed:bg-zinc-950/[0.06] aria-pressed:text-zinc-950 dark:aria-pressed:bg-white/[0.09] dark:aria-pressed:text-white\",\n        \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500\",\n      )}\n    >\n      {children}\n    </button>\n  );\n}\n\nfunction FileGlyph() {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3.5 shrink-0 text-zinc-400 dark:text-zinc-500\">\n      <path d=\"M4 1.75h5.25L12.5 5v8.25c0 .55-.45 1-1 1H4c-.55 0-1-.45-1-1V2.75c0-.55.45-1 1-1Z\" stroke=\"currentColor\" strokeWidth=\"1.25\" strokeLinejoin=\"round\" />\n      <path d=\"M9 1.75V5.25h3.5\" stroke=\"currentColor\" strokeWidth=\"1.25\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "import { CodeBlock } from \"@/components/shaken/ui/code-block\";\n\nconst route = `import { createRun } from \"@/lib/agent\";\n\n// Starts a run and streams its events back to the client.\nexport async function POST(request: Request) {\n  const { prompt, tools } = await request.json();\n  const run = await createRun({ prompt, tools, maxSteps: 12 });\n\n  return new Response(run.toEventStream(), {\n    headers: { \"content-type\": \"text/event-stream\" },\n  });\n}`;\n\nexport default function CodeBlockExample() {\n  return (\n    <div className=\"grid w-full max-w-2xl gap-4\">\n      <CodeBlock filename=\"app/api/runs/route.ts\" language=\"ts\" code={route} highlightLines=\"6-8\" />\n      <CodeBlock language=\"bash\" code=\"pnpm dlx @shakenui/cli add code-block\" lineNumbers={false} wrapToggle={false} />\n    </div>\n  );\n}\n"
  }
}
