{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"code-block","type":"registry:component","title":"Code Block","description":"AI-style code block with filename header, copy button, line numbers, line highlights and a tiny highlighter; long code collapses behind a height spring.","author":"GetUrUI <hello@geturui.dev>","dependencies":["motion","lucide-react"],"registryDependencies":["@geturui/copy-button"],"files":[{"path":"registry/geturui/ai/code-block.tsx","type":"registry:component","target":"components/ai/code-block.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { ChevronDown, FileCode2 } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport { CopyButton } from \"@/components/ui/copy-button\";\n\nexport type TokenType = \"keyword\" | \"string\" | \"comment\" | \"tag\" | \"number\" | \"plain\";\nexport interface Token {\n  type: TokenType;\n  text: string;\n}\n\nconst KEYWORDS = new Set(\n  (\n    \"import export from default function return const let var if else for while do switch case break continue new class extends \" +\n    \"async await try catch finally throw typeof instanceof in of as interface type enum implements public private protected readonly \" +\n    \"static void null undefined true false this super yield delete keyof satisfies def lambda pass None True False elif with is not and or \" +\n    \"fn pub use mut impl struct match self echo then fi done export npm npx pnpm\"\n  ).split(\" \"),\n);\n\nconst HASH_COMMENTS = new Set([\"bash\", \"sh\", \"shell\", \"zsh\", \"python\", \"py\", \"yaml\", \"yml\", \"toml\", \"ruby\", \"rb\"]);\nconst JSX = new Set([\"tsx\", \"jsx\", \"html\", \"xml\", \"svg\", \"vue\", \"svelte\"]);\n\n/** Splits code into lines of coloured tokens. Deliberately tiny: keywords, strings, comments, JSX tags and numbers. */\nexport function tokenize(code: string, language = \"tsx\"): Token[][] {\n  const lang = language.toLowerCase();\n  const parts = [\n    String.raw`(\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/${HASH_COMMENTS.has(lang) ? String.raw`|#[^\\n]*` : \"\"})`,\n    String.raw`(\"(?:\\\\.|[^\"\\\\\\n])*\"|'(?:\\\\.|[^'\\\\\\n])*'|` + \"`(?:\\\\\\\\.|[^`\\\\\\\\])*`)\",\n    JSX.has(lang) ? String.raw`(<\\/?[A-Za-z][\\w.:-]*|\\/>)` : \"((?!))\",\n    String.raw`\\b(\\d+(?:\\.\\d+)?)\\b`,\n    String.raw`([A-Za-z_$][\\w$]*)`,\n  ];\n  const re = new RegExp(parts.join(\"|\"), \"g\");\n  const flat: Token[] = [];\n  let last = 0;\n  for (const m of code.matchAll(re)) {\n    const i = m.index ?? 0;\n    if (i > last) flat.push({ type: \"plain\", text: code.slice(last, i) });\n    let type: TokenType = \"plain\";\n    if (m[1]) type = \"comment\";\n    else if (m[2]) type = \"string\";\n    else if (m[3]) type = \"tag\";\n    else if (m[4]) type = \"number\";\n    else if (m[5] && KEYWORDS.has(m[5])) type = \"keyword\";\n    flat.push({ type, text: m[0] });\n    last = i + m[0].length;\n  }\n  if (last < code.length) flat.push({ type: \"plain\", text: code.slice(last) });\n\n  const lines: Token[][] = [[]];\n  for (const t of flat) {\n    const pieces = t.text.split(\"\\n\");\n    pieces.forEach((p, k) => {\n      if (k > 0) lines.push([]);\n      if (p) lines[lines.length - 1].push({ type: t.type, text: p });\n    });\n  }\n  return lines;\n}\n\nconst tokenClass: Record<TokenType, string> = {\n  keyword: \"text-ember-ink\",\n  string: \"text-volt-ink\",\n  comment: \"text-ink-subtle italic\",\n  tag: \"text-info\",\n  number: \"text-warning\",\n  plain: \"\",\n};\n\nexport interface CodeBlockProps {\n  code: string;\n  /** Language label and highlighting rules (tsx, ts, js, json, bash, css, python…). */\n  language?: string;\n  filename?: string;\n  showLineNumbers?: boolean;\n  /** 1-based line numbers to highlight. */\n  highlightLines?: number[];\n  /** Collapse code longer than this many lines behind a \"Show all\" toggle. 0 disables collapsing. */\n  maxLines?: number;\n  defaultExpanded?: boolean;\n  /** Hide the copy button. */\n  hideCopy?: boolean;\n  className?: string;\n}\n\nconst LINE = 21;\nconst PAD = 12;\n\n/** AI-style code block: filename header, copy button, line numbers, a tiny highlighter and a spring collapse for long code. */\nexport function CodeBlock({\n  code,\n  language = \"tsx\",\n  filename,\n  showLineNumbers = true,\n  highlightLines = [],\n  maxLines = 14,\n  defaultExpanded = false,\n  hideCopy,\n  className,\n}: CodeBlockProps) {\n  const reduce = useReducedMotion();\n  const [expanded, setExpanded] = React.useState(defaultExpanded);\n  const lines = React.useMemo(() => tokenize(code.replace(/\\n$/, \"\"), language), [code, language]);\n  const marked = React.useMemo(() => new Set(highlightLines), [highlightLines]);\n  const collapsible = maxLines > 0 && lines.length > maxLines;\n  const open = !collapsible || expanded;\n  const bodyId = React.useId();\n  const gutter = String(lines.length).length;\n\n  return (\n    <figure className={cn(\"overflow-hidden rounded-md border border-border bg-surface-sunken text-ink\", className)}>\n      <figcaption className=\"flex h-10 items-center gap-2 border-b border-border bg-surface pl-3.5 pr-1\">\n        <FileCode2 aria-hidden className=\"size-4 shrink-0 text-ink-subtle\" />\n        <span className=\"truncate font-mono text-[12.5px] text-ink\">{filename ?? language}</span>\n        {filename && (\n          <span className=\"rounded-full border border-border px-1.5 py-px font-mono text-[10.5px] uppercase tracking-[0.4px] text-ink-subtle\">\n            {language}\n          </span>\n        )}\n        <span className=\"ml-auto\" />\n        {!hideCopy && <CopyButton value={code} label={`Copy ${filename ?? \"code\"}`} />}\n      </figcaption>\n\n      <div className=\"relative\">\n        <motion.div\n          id={bodyId}\n          initial={false}\n          animate={{ height: open ? \"auto\" : maxLines * LINE + PAD * 2 }}\n          transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 260, damping: 32 }}\n          className=\"overflow-hidden\"\n        >\n          <pre className=\"overflow-x-auto py-3 font-mono text-[12.75px]\" style={{ lineHeight: `${LINE}px` }} tabIndex={0} aria-label={filename ? `${filename} source` : \"Code\"}>\n            <code className=\"grid min-w-max\">\n              {lines.map((toks, i) => {\n                const n = i + 1;\n                const hi = marked.has(n);\n                return (\n                  <span\n                    key={i}\n                    className={cn(\n                      \"flex border-l-2 pr-4\",\n                      hi ? \"border-volt-ink bg-volt-soft\" : \"border-transparent\",\n                    )}\n                  >\n                    {showLineNumbers && (\n                      <span\n                        aria-hidden\n                        className={cn(\"select-none pl-3 pr-4 text-right tabular-nums\", hi ? \"text-volt-ink\" : \"text-ink-subtle/70\")}\n                        style={{ minWidth: `${gutter + 3.5}ch` }}\n                      >\n                        {n}\n                      </span>\n                    )}\n                    <span className={cn(\"whitespace-pre\", !showLineNumbers && \"pl-4\")}>\n                      {toks.length === 0 ? \" \" : toks.map((t, k) => (\n                        <span key={k} className={tokenClass[t.type]}>\n                          {t.text}\n                        </span>\n                      ))}\n                    </span>\n                  </span>\n                );\n              })}\n            </code>\n          </pre>\n        </motion.div>\n\n        {collapsible && (\n          <div\n            className={cn(\n              \"flex justify-center\",\n              open ? \"border-t border-border py-1.5\" : \"absolute inset-x-0 bottom-0 bg-gradient-to-t from-surface-sunken via-surface-sunken/85 to-transparent pb-2.5 pt-12\",\n            )}\n          >\n            <motion.button\n              type=\"button\"\n              whileTap={{ scale: 0.96 }}\n              aria-expanded={open}\n              aria-controls={bodyId}\n              onClick={() => setExpanded((v) => !v)}\n              className=\"inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-surface px-3 text-xs font-medium text-ink-muted outline-none transition-colors hover:border-border-strong hover:text-ink focus-visible:shadow-[var(--focus-ring)]\"\n            >\n              {open ? \"Collapse\" : `Show all ${lines.length} lines`}\n              <ChevronDown aria-hidden className={cn(\"size-3.5 transition-transform duration-300 ease-[var(--ease-spring)]\", open && \"rotate-180\")} />\n            </motion.button>\n          </div>\n        )}\n      </div>\n    </figure>\n  );\n}\n"},{"path":"LICENSE-geturui.md","type":"registry:file","target":"LICENSE-geturui.md","content":"MIT License\n\nCopyright (c) 2026 geturui.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}],"categories":["ai","ai","code","syntax","highlight","copy","snippet"],"meta":{"tier":"free","license":"MIT","docs":"https://geturui.com/docs/code-block"}}