{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-block",
  "title": "Code Block",
  "description": "A syntax-highlighted code block with line numbers, per-line highlighting, a filename/language header, a copy button and a collapsible fade-out for long snippets.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/code-block/code-block.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type CodeBlockSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface CodeBlockProps {\n  code: string;\n  language?: string;\n  filename?: string;\n  showLineNumbers?: boolean;\n  /** 1-indexed line numbers to tint. */\n  highlightLines?: number[];\n  wrapLines?: boolean;\n  copyable?: boolean;\n  maxHeight?: number;\n  size?: CodeBlockSize;\n  theme?: \"dark\" | \"light\";\n  width?: number | string;\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: {\n    bg: \"#0E0E0E\",\n    headerBg: \"rgba(255,255,255,0.03)\",\n    border: \"rgba(255,255,255,0.09)\",\n    text: \"#F5F4F1\",\n    muted: \"rgba(245,244,241,0.5)\",\n    faint: \"rgba(245,244,241,0.28)\",\n    gutter: \"rgba(245,244,241,0.28)\",\n    highlight: \"rgba(245,244,241,0.06)\",\n    highlightBar: \"rgba(245,244,241,0.4)\",\n    hover: \"rgba(255,255,255,0.08)\",\n    keyword: \"#B8A6FF\",\n    string: \"#87FFE3\",\n    number: \"#F2A841\",\n    comment: \"rgba(245,244,241,0.4)\",\n    fadeTo: \"#0E0E0E\",\n  },\n  light: {\n    bg: \"#FFFFFF\",\n    headerBg: \"rgba(10,10,10,0.02)\",\n    border: \"rgba(10,10,10,0.1)\",\n    text: \"#0A0A0A\",\n    muted: \"rgba(10,10,10,0.5)\",\n    faint: \"rgba(10,10,10,0.3)\",\n    gutter: \"rgba(10,10,10,0.3)\",\n    highlight: \"rgba(10,10,10,0.045)\",\n    highlightBar: \"rgba(10,10,10,0.35)\",\n    hover: \"rgba(10,10,10,0.06)\",\n    keyword: \"#7C5CE0\",\n    string: \"#0F9F7F\",\n    number: \"#B7791F\",\n    comment: \"rgba(10,10,10,0.42)\",\n    fadeTo: \"#FFFFFF\",\n  },\n};\n\nconst SIZES: Record<CodeBlockSize, { font: number; lineH: number; pad: number; headerH: number }> = {\n  sm: { font: 12, lineH: 19, pad: 12, headerH: 36 },\n  md: { font: 13, lineH: 21, pad: 16, headerH: 40 },\n  lg: { font: 14.5, lineH: 23, pad: 18, headerH: 44 },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst LANG_ALIASES: Record<string, string> = { js: \"javascript\", jsx: \"javascript\", ts: \"typescript\", tsx: \"typescript\", py: \"python\", sh: \"bash\", shell: \"bash\", zsh: \"bash\", yml: \"yaml\" };\n\nconst KEYWORDS: Record<string, string[]> = {\n  javascript: [\"const\", \"let\", \"var\", \"function\", \"return\", \"if\", \"else\", \"for\", \"while\", \"do\", \"class\", \"extends\", \"new\", \"import\", \"from\", \"export\", \"default\", \"async\", \"await\", \"try\", \"catch\", \"finally\", \"throw\", \"typeof\", \"instanceof\", \"in\", \"of\", \"switch\", \"case\", \"break\", \"continue\", \"this\", \"super\", \"null\", \"undefined\", \"true\", \"false\", \"void\", \"yield\", \"static\", \"get\", \"set\"],\n  typescript: [\"interface\", \"type\", \"enum\", \"implements\", \"private\", \"public\", \"protected\", \"readonly\", \"namespace\", \"declare\", \"as\", \"is\", \"keyof\", \"infer\", \"satisfies\"],\n  python: [\"def\", \"return\", \"if\", \"elif\", \"else\", \"for\", \"while\", \"class\", \"import\", \"from\", \"as\", \"try\", \"except\", \"finally\", \"raise\", \"with\", \"lambda\", \"yield\", \"pass\", \"break\", \"continue\", \"in\", \"is\", \"not\", \"and\", \"or\", \"None\", \"True\", \"False\", \"self\", \"async\", \"await\", \"global\", \"nonlocal\", \"del\"],\n  bash: [\"if\", \"then\", \"else\", \"elif\", \"fi\", \"for\", \"while\", \"do\", \"done\", \"function\", \"return\", \"export\", \"local\", \"case\", \"esac\", \"in\", \"echo\"],\n  json: [\"true\", \"false\", \"null\"],\n  yaml: [\"true\", \"false\", \"null\"],\n  go: [\"func\", \"return\", \"if\", \"else\", \"for\", \"range\", \"package\", \"import\", \"var\", \"const\", \"type\", \"struct\", \"interface\", \"map\", \"chan\", \"go\", \"defer\", \"select\", \"switch\", \"case\", \"break\", \"continue\", \"nil\", \"true\", \"false\"],\n  rust: [\"fn\", \"let\", \"mut\", \"return\", \"if\", \"else\", \"for\", \"while\", \"loop\", \"match\", \"struct\", \"enum\", \"impl\", \"trait\", \"pub\", \"use\", \"mod\", \"self\", \"Self\", \"true\", \"false\", \"None\", \"Some\"],\n};\nKEYWORDS.typescript = [...KEYWORDS.javascript, ...KEYWORDS.typescript];\n\nconst COMMENT_PREFIX: Record<string, string> = { python: \"#\", bash: \"#\", yaml: \"#\" };\n\ninterface Segment {\n  text: string;\n  type: \"plain\" | \"comment\" | \"string\" | \"number\" | \"keyword\";\n}\n\nfunction tokenizeLine(line: string, lang: string): Segment[] {\n  const keywords = KEYWORDS[lang];\n  if (!keywords && !COMMENT_PREFIX[lang] && lang !== \"javascript\" && lang !== \"typescript\") {\n    return [{ text: line, type: \"plain\" }];\n  }\n  const commentPrefix = COMMENT_PREFIX[lang] ?? \"//\";\n  const escapedPrefix = commentPrefix.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n  const kwPattern = keywords && keywords.length ? `|\\\\b(?:${keywords.join(\"|\")})\\\\b` : \"\";\n  const pattern = new RegExp(`(${escapedPrefix}.*$)|(\\`(?:\\\\\\\\.|[^\\`\\\\\\\\])*\\`|\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\"|'(?:\\\\\\\\.|[^'\\\\\\\\])*')|(\\\\b\\\\d+(?:\\\\.\\\\d+)?\\\\b)${kwPattern}`, \"g\");\n\n  const segments: Segment[] = [];\n  let last = 0;\n  let m: RegExpExecArray | null;\n  while ((m = pattern.exec(line))) {\n    if (m.index > last) segments.push({ text: line.slice(last, m.index), type: \"plain\" });\n    const type: Segment[\"type\"] = m[1] !== undefined ? \"comment\" : m[2] !== undefined ? \"string\" : m[3] !== undefined ? \"number\" : \"keyword\";\n    segments.push({ text: m[0], type });\n    last = m.index + m[0].length;\n    if (m[0].length === 0) pattern.lastIndex++;\n  }\n  if (last < line.length) segments.push({ text: line.slice(last), type: \"plain\" });\n  return segments;\n}\n\nfunction Token({ seg, p }: { seg: Segment; p: Palette }) {\n  if (seg.type === \"plain\") return <>{seg.text}</>;\n  const colorMap: Record<Segment[\"type\"], string> = { plain: p.text, comment: p.comment, string: p.string, number: p.number, keyword: p.keyword };\n  return <span style={{ color: colorMap[seg.type], fontStyle: seg.type === \"comment\" ? \"italic\" : undefined }}>{seg.text}</span>;\n}\n\nfunction CopyIcon({ copied, size }: { copied: boolean; size: number }) {\n  return (\n    <svg width={size} height={size} viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n      {copied ? <path d=\"M3.5 8.3L6.3 11.2L12.5 4.5\" /> : <><rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8.5\" rx=\"1.5\" /><path d=\"M3.5 10.5A1.5 1.5 0 0 1 2 9V3.5A1.5 1.5 0 0 1 3.5 2H9a1.5 1.5 0 0 1 1.5 1.5\" /></>}\n    </svg>\n  );\n}\n\nexport function CodeBlock({\n  code,\n  language = \"text\",\n  filename,\n  showLineNumbers = true,\n  highlightLines = [],\n  wrapLines = false,\n  copyable = true,\n  maxHeight,\n  size = \"md\",\n  theme = \"dark\",\n  width,\n  className,\n}: CodeBlockProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const lang = LANG_ALIASES[language.toLowerCase()] ?? language.toLowerCase();\n  const lines = React.useMemo(() => code.replace(/\\n$/, \"\").split(\"\\n\"), [code]);\n  const gutterWidth = React.useMemo(() => `${String(lines.length).length}ch`, [lines.length]);\n  const highlighted = React.useMemo(() => new Set(highlightLines), [highlightLines]);\n\n  const [copied, setCopied] = React.useState(false);\n  const copyTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  React.useEffect(() => () => {\n    if (copyTimer.current) clearTimeout(copyTimer.current);\n  }, []);\n\n  const [expanded, setExpanded] = React.useState(false);\n  const bodyRef = React.useRef<HTMLDivElement>(null);\n  const [overflows, setOverflows] = React.useState(false);\n  React.useEffect(() => {\n    if (!maxHeight) return;\n    const el = bodyRef.current;\n    if (el) setOverflows(el.scrollHeight > maxHeight + 4);\n  }, [maxHeight, code]);\n\n  const copy = () => {\n    try {\n      const cb = navigator.clipboard;\n      if (cb && typeof cb.writeText === \"function\") {\n        void cb.writeText(code).then(\n          () => {\n            setCopied(true);\n            if (copyTimer.current) clearTimeout(copyTimer.current);\n            copyTimer.current = setTimeout(() => setCopied(false), 1600);\n          },\n          () => undefined,\n        );\n      }\n    } catch {\n      // clipboard can be blocked inside an embedded frame\n    }\n  };\n\n  const capped = Boolean(maxHeight) && !expanded;\n\n  return (\n    <div\n      className={cn(\"flex flex-col overflow-hidden\", className)}\n      style={{ width, maxWidth: \"100%\", borderRadius: 14, background: p.bg, border: `1px solid ${p.border}`, fontFamily: \"Inter, sans-serif\" }}\n    >\n      {(filename || language !== \"text\" || copyable) && (\n        <div className=\"flex shrink-0 items-center justify-between\" style={{ height: s.headerH, padding: `0 ${s.pad}px`, background: p.headerBg, borderBottom: `1px solid ${p.border}` }}>\n          <div className=\"flex min-w-0 items-center\" style={{ gap: 8 }}>\n            {filename ? (\n              <span className=\"truncate font-medium\" style={{ color: p.text, fontSize: s.font, fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\" }}>\n                {filename}\n              </span>\n            ) : (\n              <span className=\"font-medium uppercase\" style={{ color: p.muted, fontSize: s.font - 2, letterSpacing: \"0.06em\" }}>\n                {language}\n              </span>\n            )}\n          </div>\n          {copyable && (\n            <button\n              type=\"button\"\n              onClick={copy}\n              aria-label={copied ? \"Copied\" : \"Copy code\"}\n              className=\"flex shrink-0 cursor-pointer items-center rounded-md border-none bg-transparent outline-none focus-visible:ring-2\"\n              style={{ gap: 5, height: 26, padding: \"0 8px\", color: copied ? p.string : p.muted, fontSize: s.font - 2.5, fontWeight: 500, [\"--tw-ring-color\" as string]: p.text }}\n              onMouseEnter={(e) => (e.currentTarget.style.background = p.hover)}\n              onMouseLeave={(e) => (e.currentTarget.style.background = \"transparent\")}\n            >\n              <AnimatePresence mode=\"wait\" initial={false}>\n                <motion.span key={String(copied)} initial={{ opacity: 0, scale: 0.7 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.7 }} transition={{ duration: 0.15 }} className=\"flex items-center\" style={{ gap: 5 }}>\n                  <CopyIcon copied={copied} size={s.font} />\n                  {copied ? \"Copied\" : \"Copy\"}\n                </motion.span>\n              </AnimatePresence>\n            </button>\n          )}\n        </div>\n      )}\n\n      <div className=\"relative\">\n        <div\n          ref={bodyRef}\n          className={cn(\"overflow-x-auto\", capped && \"overflow-y-hidden\")}\n          style={{ maxHeight: capped ? maxHeight : undefined, padding: `${s.pad * 0.6}px 0` }}\n        >\n          {lines.map((line, i) => {\n            const n = i + 1;\n            const isHi = highlighted.has(n);\n            return (\n              <div\n                key={i}\n                className=\"flex\"\n                style={{ minWidth: \"100%\", width: \"fit-content\", background: isHi ? p.highlight : \"transparent\", boxShadow: isHi ? `inset 3px 0 0 0 ${p.highlightBar}` : undefined }}\n              >\n                {showLineNumbers && (\n                  <span className=\"sticky left-0 shrink-0 select-none text-right tabular-nums\" style={{ width: gutterWidth, marginRight: 16, paddingLeft: s.pad, color: p.gutter, fontSize: s.font, lineHeight: `${s.lineH}px`, fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\", background: isHi ? p.highlight : p.bg }}>\n                    {n}\n                  </span>\n                )}\n                <code\n                  className={cn(wrapLines ? \"whitespace-pre-wrap break-words\" : \"whitespace-pre\")}\n                  style={{ paddingRight: s.pad, color: p.text, fontSize: s.font, lineHeight: `${s.lineH}px`, fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\" }}\n                >\n                  {tokenizeLine(line, lang).map((seg, j) => (\n                    <Token key={j} seg={seg} p={p} />\n                  ))}\n                  {line.length === 0 && \" \"}\n                </code>\n              </div>\n            );\n          })}\n        </div>\n\n        {capped && overflows && (\n          <div className=\"pointer-events-none absolute inset-x-0 bottom-0\" style={{ height: 56, background: `linear-gradient(to bottom, transparent, ${p.fadeTo})` }} />\n        )}\n      </div>\n\n      {maxHeight && overflows && (\n        <button\n          type=\"button\"\n          onClick={() => setExpanded((v) => !v)}\n          aria-expanded={expanded}\n          className=\"flex shrink-0 cursor-pointer items-center justify-center border-none outline-none focus-visible:ring-2\"\n          style={{ height: 34, borderTop: `1px solid ${p.border}`, background: p.headerBg, color: p.muted, fontSize: s.font - 2, fontWeight: 600, gap: 5, [\"--tw-ring-color\" as string]: p.text }}\n          onMouseEnter={(e) => (e.currentTarget.style.color = p.text)}\n          onMouseLeave={(e) => (e.currentTarget.style.color = p.muted)}\n        >\n          <motion.svg width=\"11\" height=\"11\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.7\" strokeLinecap=\"round\" strokeLinejoin=\"round\" animate={{ rotate: expanded ? 180 : 0 }} transition={{ duration: 0.18 }} aria-hidden=\"true\">\n            <path d=\"M4 6L8 10L12 6\" />\n          </motion.svg>\n          {expanded ? \"Show less\" : \"Show more\"}\n        </button>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}