{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code",
  "type": "registry:ui",
  "title": "Code",
  "description": "Shared code surface: Shiki-highlighted lines, gutter, clean copy, and virtualization for large files.",
  "dependencies": [
    "@tanstack/react-virtual@^3.14.9",
    "lucide-react@^1.31.0",
    "shiki@^4.4.3"
  ],
  "registryDependencies": [
    "https://control-ui.dev/r/button.json",
    "https://control-ui.dev/r/core.json",
    "https://control-ui.dev/r/scroll-area.json",
    "https://control-ui.dev/r/tooltip.json",
    "https://control-ui.dev/r/use-copy-to-clipboard.json"
  ],
  "files": [
    {
      "path": "src/registry/knob-contracts/code-knobs.ts",
      "target": "@components/control-ui/knob-contracts/code-knobs.ts",
      "type": "registry:component",
      "content": "// Generated from src/registry/sources/control-ui/recipes/code.css by scripts/gen-knob-contracts.ts — run `bun run sync:knobs`.\nexport const codeKnobs = [\n  \"--cui-code-radius\",\n  \"--cui-code-background\",\n  \"--cui-code-border-color\",\n  \"--cui-code-shadow\",\n  \"--cui-code-title-foreground\",\n  \"--cui-code-text-foreground\",\n] as const;\nexport type CodeKnobStyle = Partial<Record<(typeof codeKnobs)[number], string>>;\n"
    },
    {
      "path": "src/registry/lib/code-tokens.ts",
      "target": "@components/control-ui/lib/code-tokens.ts",
      "type": "registry:lib",
      "content": "import type { HighlighterCore, ThemedToken } from \"shiki/core\";\n\n// shared Shiki tokenizer for code primitives (Code, CodeDiff, CodeBlockEditor, Markdown) — CSS-var theme\n// (not baked github-light/dark), tokens resolve `var(--code-token-*)`, revalued by active color scope in code.css\n// pure+isomorphic (RSC awaits, client highlights in effect); LRU cache (lang\\ncode) keeps re-highlight cheap; null = unknown lang\n\nexport type CodeTokenStyle = {\n  color?: string;\n  fontStyle?: \"italic\" | \"normal\";\n  fontWeight?: \"bold\" | \"normal\";\n  textDecoration?: \"underline\";\n};\n\nexport type CodeToken = { content: string; style?: CodeTokenStyle };\nexport type CodeTokenLine = CodeToken[];\nexport type CodeTokenLines = CodeTokenLine[];\nexport type CodeEmphasisSegment = { text: string; emphasis: boolean };\nexport type CodeTokenEmphasisRun = CodeToken & { emphasis: boolean; start: number };\n\nexport const CODE_THEME_NAME = \"agent-code\";\nexport const CODE_VARIABLE_PREFIX = \"--code-\";\n\nconst languageAliases: Record<string, string> = {\n  bash: \"bash\",\n  cjs: \"javascript\",\n  css: \"css\",\n  diff: \"diff\",\n  html: \"html\",\n  js: \"javascript\",\n  json: \"json\",\n  json5: \"json\",\n  jsx: \"jsx\",\n  markdown: \"markdown\",\n  md: \"markdown\",\n  mjs: \"javascript\",\n  node: \"javascript\",\n  py: \"python\",\n  python: \"python\",\n  sh: \"bash\",\n  shell: \"bash\",\n  ts: \"typescript\",\n  tsx: \"tsx\",\n  typescript: \"typescript\",\n  yaml: \"yaml\",\n  yml: \"yaml\",\n  zsh: \"bash\",\n};\n\n// Shiki FontStyle bitmask (Italic = 1, Bold = 2, Underline = 4).\nconst FONT_STYLE_ITALIC = 1;\nconst FONT_STYLE_BOLD = 2;\nconst FONT_STYLE_UNDERLINE = 4;\n\nlet highlighterPromise: Promise<HighlighterCore> | null = null;\n\nexport function normalizeLanguage(language?: string | null): string | undefined {\n  if (!language) return undefined;\n  return languageAliases[language.toLowerCase()];\n}\n\nfunction getHighlighter(): Promise<HighlighterCore> {\n  if (!highlighterPromise) {\n    highlighterPromise = (async () => {\n      const [{ createHighlighterCore, createCssVariablesTheme }, { createJavaScriptRegexEngine }] = await Promise.all([\n        import(\"shiki/core\"),\n        import(\"shiki/engine/javascript\"),\n      ]);\n\n      const theme = createCssVariablesTheme({\n        name: CODE_THEME_NAME,\n        variablePrefix: CODE_VARIABLE_PREFIX,\n        fontStyle: true,\n      });\n\n      return createHighlighterCore({\n        themes: [theme],\n        langs: [\n          import(\"shiki/langs/javascript.mjs\"),\n          import(\"shiki/langs/typescript.mjs\"),\n          import(\"shiki/langs/tsx.mjs\"),\n          import(\"shiki/langs/jsx.mjs\"),\n          import(\"shiki/langs/json.mjs\"),\n          import(\"shiki/langs/bash.mjs\"),\n          import(\"shiki/langs/markdown.mjs\"),\n          import(\"shiki/langs/python.mjs\"),\n          import(\"shiki/langs/css.mjs\"),\n          import(\"shiki/langs/html.mjs\"),\n          import(\"shiki/langs/yaml.mjs\"),\n          import(\"shiki/langs/diff.mjs\"),\n        ],\n        engine: createJavaScriptRegexEngine(),\n      });\n    })();\n  }\n\n  return highlighterPromise;\n}\n\nfunction tokenStyle(token: ThemedToken): CodeTokenStyle | undefined {\n  const style: CodeTokenStyle = {};\n  if (token.color) style.color = token.color;\n  const fontStyle = token.fontStyle ?? 0;\n  if (fontStyle > 0) {\n    if ((fontStyle & FONT_STYLE_ITALIC) !== 0) style.fontStyle = \"italic\";\n    if ((fontStyle & FONT_STYLE_BOLD) !== 0) style.fontWeight = \"bold\";\n    if ((fontStyle & FONT_STYLE_UNDERLINE) !== 0) style.textDecoration = \"underline\";\n  }\n  return style.color || style.fontStyle || style.fontWeight || style.textDecoration ? style : undefined;\n}\n\n// Small LRU: streaming/virtualized views re-highlight same code repeatedly.\nconst CACHE_LIMIT = 200;\nconst cache = new Map<string, CodeTokenLines | null>();\n\nfunction cacheGet(key: string): CodeTokenLines | null | undefined {\n  const value = cache.get(key);\n  if (value !== undefined) {\n    cache.delete(key); // refresh recency\n    cache.set(key, value);\n  }\n  return value;\n}\n\nfunction cacheSet(key: string, value: CodeTokenLines | null): void {\n  cache.set(key, value);\n  if (cache.size > CACHE_LIMIT) {\n    const oldest = cache.keys().next().value;\n    if (oldest !== undefined) cache.delete(oldest);\n  }\n}\n\nfunction reconstructs(value: string, parts: readonly string[]): boolean {\n  return parts.join(\"\") === value;\n}\n\nfunction coveringTokens(plain: string, tokens: CodeTokenLine | null): CodeTokenLine {\n  const parts = tokens?.filter((token) => token.content.length > 0) ?? [];\n  return reconstructs(\n    plain,\n    parts.map((token) => token.content),\n  )\n    ? parts\n    : [{ content: plain }];\n}\n\nfunction coveringSegments(plain: string, segments: readonly CodeEmphasisSegment[] | undefined): readonly CodeEmphasisSegment[] {\n  const parts = segments?.filter((segment) => segment.text.length > 0) ?? [];\n  return reconstructs(\n    plain,\n    parts.map((segment) => segment.text),\n  )\n    ? parts\n    : [{ text: plain, emphasis: false }];\n}\n\nexport function mergeCodeTokenLineWithEmphasis(\n  plain: string,\n  tokens: CodeTokenLine | null,\n  segments: readonly CodeEmphasisSegment[] | undefined,\n): CodeTokenEmphasisRun[] {\n  const validTokens = coveringTokens(plain, tokens);\n  const validSegments = coveringSegments(plain, segments);\n\n  if (plain.length === 0) return [];\n\n  const runs: CodeTokenEmphasisRun[] = [];\n  let tokenIndex = 0;\n  let segmentIndex = 0;\n  let tokenOffset = 0;\n  let segmentOffset = 0;\n  let runStart = 0;\n\n  while (tokenIndex < validTokens.length && segmentIndex < validSegments.length) {\n    const token = validTokens[tokenIndex];\n    const segment = validSegments[segmentIndex];\n    if (!token || !segment) break;\n    const length = Math.min(token.content.length - tokenOffset, segment.text.length - segmentOffset);\n    runs.push({\n      start: runStart,\n      content: token.content.slice(tokenOffset, tokenOffset + length),\n      ...(token.style ? { style: token.style } : {}),\n      emphasis: segment.emphasis,\n    });\n    runStart += length;\n\n    tokenOffset += length;\n    segmentOffset += length;\n    if (tokenOffset === token.content.length) {\n      tokenIndex += 1;\n      tokenOffset = 0;\n    }\n    if (segmentOffset === segment.text.length) {\n      segmentIndex += 1;\n      segmentOffset = 0;\n    }\n  }\n\n  return runs;\n}\n\n// null for unknown language; memoized by `lang\\ncode`\nexport async function highlightToTokens(code: string, language?: string | null): Promise<CodeTokenLines | null> {\n  const lang = normalizeLanguage(language);\n  if (!lang) return null;\n\n  const key = `${lang}\\n${code}`;\n  const cached = cacheGet(key);\n  if (cached !== undefined) return cached;\n\n  const highlighter = await getHighlighter();\n  const { tokens } = highlighter.codeToTokens(code, { lang, theme: CODE_THEME_NAME });\n  const lines: CodeTokenLines = tokens.map((line) => line.map((token) => ({ content: token.content, style: tokenStyle(token) })));\n\n  cacheSet(key, lines);\n  return lines;\n}\n"
    },
    {
      "path": "src/registry/sources/control-ui/code.css",
      "target": "@components/control-ui/styles/code.css",
      "type": "registry:file",
      "content": "/*\n * Control UI — code + diff tokens, derived from the shared theme contract.\n * --code-token-*: Shiki CSS-variables syntax palette (lib/code-tokens.ts) — follows active skin instead of a frozen palette. --diff-*: 3-tier diff colors (line/emphasis/gutter/fg per side), à la @pierre/diffs. Both skin-overridable via pack skin.css.\n * Scoped to the root color mode at zero specificity so every skin inherits the correct palette and can override it locally.\n */\n\n:where(:root) {\n  /* syntax — light (github-light adjacent, retinted onto the neutral token hue family) */\n  --code-foreground: var(--foreground);\n  --code-token-constant: oklch(0.5 0.15 250);\n  --code-token-string: oklch(0.49 0.13 150);\n  --code-token-string-expression: oklch(0.49 0.13 150);\n  --code-token-comment: oklch(0.48 0.015 285);\n  --code-token-keyword: oklch(0.53 0.2 18);\n  --code-token-parameter: oklch(0.52 0.09 55);\n  --code-token-function: oklch(0.54 0.17 300);\n  --code-token-punctuation: oklch(0.5 0.02 285);\n  --code-token-link: oklch(0.5 0.15 250);\n\n  /* diff — light. add ≈ green (H150), del ≈ red (H22). */\n  --diff-add-line: oklch(0.93 0.055 150 / 0.65);\n  --diff-add-emphasis: oklch(0.86 0.11 150 / 0.8);\n  --diff-add-gutter: oklch(0.91 0.07 150);\n  --diff-add-fg: oklch(0.48 0.11 150);\n  --diff-del-line: oklch(0.94 0.05 22 / 0.6);\n  --diff-del-emphasis: oklch(0.87 0.12 22 / 0.8);\n  --diff-del-gutter: oklch(0.92 0.07 22);\n  --diff-del-fg: oklch(0.53 0.16 22);\n  --diff-context-fg: var(--muted-foreground);\n  --diff-gutter-bg: oklch(from var(--muted) l c h / 0.5);\n}\n\n:where(.dark) {\n  /* syntax — dark (github-dark adjacent) */\n  --code-foreground: var(--foreground);\n  --code-token-constant: oklch(0.78 0.13 235);\n  --code-token-string: oklch(0.8 0.13 150);\n  --code-token-string-expression: oklch(0.8 0.13 150);\n  --code-token-comment: oklch(0.76 0.02 285);\n  --code-token-keyword: oklch(0.75 0.16 12);\n  --code-token-parameter: oklch(0.82 0.09 60);\n  --code-token-function: oklch(0.8 0.14 300);\n  --code-token-punctuation: oklch(0.72 0.02 285);\n  --code-token-link: oklch(0.78 0.13 235);\n\n  /* diff — dark */\n  --diff-add-line: oklch(0.5 0.11 150 / 0.22);\n  --diff-add-emphasis: oklch(0.6 0.14 150 / 0.34);\n  --diff-add-gutter: oklch(0.5 0.1 150 / 0.3);\n  --diff-add-fg: oklch(0.82 0.13 150);\n  --diff-del-line: oklch(0.55 0.16 22 / 0.24);\n  --diff-del-emphasis: oklch(0.62 0.18 22 / 0.36);\n  --diff-del-gutter: oklch(0.55 0.14 22 / 0.3);\n  --diff-del-fg: oklch(0.78 0.15 22);\n  --diff-context-fg: var(--muted-foreground);\n  --diff-gutter-bg: oklch(from var(--muted) l c h / 0.4);\n}\n"
    },
    {
      "path": "src/registry/sources/control-ui/recipes/code.css",
      "target": "@components/control-ui/styles/recipes/code.css",
      "type": "registry:file",
      "content": "@layer components {\n  :where([data-control-family=\"code\"][data-slot=\"root\"]) {\n    --cui-code-background: var(--background);\n    --cui-code-border-color: var(--border);\n    --cui-code-radius: var(--radius-panel);\n    --cui-code-shadow: var(--shadow-sm);\n    --cui-code-text-foreground: var(--code-foreground);\n    --cui-code-title-foreground: var(--muted-foreground);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"root\"][data-chrome=\"standalone\"]) {\n    border: 1px solid var(--cui-code-border-color);\n    border-radius: var(--cui-code-radius);\n    background: var(--cui-code-background);\n    box-shadow: var(--cui-code-shadow);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"root\"][data-chrome=\"embedded\"]) {\n    border: 0;\n    border-radius: 0;\n    background: transparent;\n    box-shadow: none;\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"header\"]) {\n    border-bottom: 1px solid var(--border);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"title\"]) {\n    color: var(--cui-code-title-foreground);\n    font-size: var(--text-label);\n    font-family: var(--font-mono);\n  }\n\n  :where([data-control-family=\"button\"][data-code-floating=\"true\"]) {\n    background: oklch(from var(--background) l c h / 0.85);\n    box-shadow:\n      inset 0 0 0 1px var(--border),\n      var(--shadow-sm);\n    backdrop-filter: blur(var(--backdrop-blur-popover));\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"grid\"]) {\n    color: var(--cui-code-text-foreground);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"grid\"][data-density=\"default\"]) {\n    font-size: var(--text-label);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"grid\"][data-density=\"compact\"]) {\n    font-size: var(--text-micro);\n  }\n\n  :where([data-control-family=\"code\"][data-slot=\"gutter\"]) {\n    color: oklch(from var(--muted-foreground) l c h / 0.6);\n    text-align: right;\n    font-variant-numeric: tabular-nums;\n  }\n}\n\n@property --cui-code-radius {\n  syntax: \"<length>\";\n  inherits: true;\n  initial-value: 0px;\n}\n\n@property --cui-code-background {\n  syntax: \"<color>\";\n  inherits: true;\n  initial-value: transparent;\n}\n\n@property --cui-code-border-color {\n  syntax: \"<color>\";\n  inherits: true;\n  initial-value: transparent;\n}\n\n@property --cui-code-shadow {\n  syntax: \"*\";\n  inherits: true;\n}\n\n@property --cui-code-title-foreground {\n  syntax: \"<color>\";\n  inherits: true;\n  initial-value: transparent;\n}\n\n@property --cui-code-text-foreground {\n  syntax: \"<color>\";\n  inherits: true;\n  initial-value: transparent;\n}\n"
    },
    {
      "path": "src/registry/sources/control-ui/ui/code.tsx",
      "target": "@components/control-ui/ui/code.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { useVirtualizer } from \"@tanstack/react-virtual\";\nimport { CheckIcon, CopyIcon } from \"lucide-react\";\nimport type { ComponentProps, CSSProperties, ReactNode } from \"react\";\nimport { Children, createContext, isValidElement, useContext, useEffect, useMemo, useRef, useState } from \"react\";\n\nimport { useCopyToClipboard } from \"@/components/control-ui/hooks/use-copy-to-clipboard\";\nimport type { CodeKnobStyle } from \"@/components/control-ui/knob-contracts/code-knobs\";\nimport { cn } from \"@/components/control-ui/lib/cn\";\nimport { type CodeTokenLines, highlightToTokens } from \"@/components/control-ui/lib/code-tokens\";\nimport { Button } from \"@/components/control-ui/ui/button\";\nimport { ScrollArea } from \"@/components/control-ui/ui/scroll-area\";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from \"@/components/control-ui/ui/tooltip\";\n\nexport type CodeOverflow = \"wrap\" | \"scroll\";\n\nexport type CodeHighlight = \"auto\" | \"none\";\n\nexport type CodeDensity = \"default\" | \"compact\";\n\nexport type CodeChrome = \"standalone\" | \"embedded\";\n\n/* Line numbers sit in select-none cells so a text selection copies clean source. CodeDiff and the\n * markdown fence renderer build on this same token renderer and row shape. */\n\n// virtualizes past this line count even without explicit `virtualize` prop\nconst VIRTUALIZE_THRESHOLD = 200;\n// estimate only — measureElement corrects it after paint\nconst ESTIMATED_LINE_HEIGHT = 20;\n\ntype CodeContextValue = { chrome: CodeChrome; density: CodeDensity; overflow: CodeOverflow; hasHeader: boolean };\n\nconst CodeContext = createContext<CodeContextValue | null>(null);\n\nfunction useCodeContext(): CodeContextValue {\n  const context = useContext(CodeContext);\n  if (!context) throw new Error(\"Code compound parts must be rendered inside <Code>.\");\n  return context;\n}\n\nexport type CodeProps = Omit<ComponentProps<\"figure\">, \"style\"> & {\n  overflow?: CodeOverflow;\n  chrome?: CodeChrome;\n  density?: CodeDensity;\n  style?: CSSProperties & CodeKnobStyle;\n};\n\nfunction hasCodeHeader(children: ReactNode) {\n  return Children.toArray(children).some((child) => isValidElement(child) && child.type === CodeHeader);\n}\n\nexport function Code({ overflow = \"scroll\", chrome = \"standalone\", density = \"default\", className, children, ...props }: CodeProps) {\n  const isEmbedded = chrome === \"embedded\";\n  const hasHeader = hasCodeHeader(children);\n\n  return (\n    <CodeContext.Provider value={{ chrome, density, overflow, hasHeader }}>\n      <figure\n        data-control-ui=\"code\"\n        data-control-family=\"code\"\n        data-slot=\"root\"\n        data-surface=\"panel\"\n        data-chrome={chrome}\n        data-density={density}\n        data-header={hasHeader ? \"true\" : undefined}\n        className={cn(\n          \"min-w-0 [--nest-gap:0.5rem]\",\n          !hasHeader && \"relative\",\n          isEmbedded ? \"my-0 overflow-hidden\" : \"my-4 overflow-hidden\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </figure>\n    </CodeContext.Provider>\n  );\n}\n\nexport type CodeHeaderProps = Omit<ComponentProps<\"figcaption\">, \"style\"> & { style?: CSSProperties & CodeKnobStyle };\n\nexport function CodeHeader({ className, ...props }: CodeHeaderProps) {\n  return (\n    <figcaption\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"header\"\n      className={cn(\"flex min-h-10 items-center justify-between gap-3 px-3 py-1.5\", className)}\n      {...props}\n    />\n  );\n}\n\nexport type CodeTitleProps = Omit<ComponentProps<\"span\">, \"style\"> & { style?: CSSProperties & CodeKnobStyle };\n\nexport function CodeTitle({ className, ...props }: CodeTitleProps) {\n  return (\n    <span\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"title\"\n      className={cn(\"block min-w-0 truncate\", className)}\n      {...props}\n    />\n  );\n}\n\nexport type CodeActionsProps = ComponentProps<\"div\"> & { style?: CSSProperties & CodeKnobStyle };\n\nexport function CodeActions({ className, ...props }: CodeActionsProps) {\n  return (\n    <div\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"actions\"\n      className={cn(\"flex shrink-0 items-center gap-1 ms-auto\", className)}\n      {...props}\n    />\n  );\n}\n\nexport type CodeCopyProps = Omit<ComponentProps<typeof Button>, \"children\" | \"onClick\"> & {\n  value: string;\n  children?: ReactNode;\n  copiedLabel?: ReactNode;\n  copiedAriaLabel?: string;\n};\n\n/* Shared by header, floating overlay, and diff, and it IS library Button, so no code surface grows bespoke copy chrome. */\nexport function CodeCopy({\n  value,\n  copiedLabel,\n  copiedAriaLabel = \"Copied\",\n  children,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: CodeCopyProps) {\n  const { isCopied, handleCopy } = useCopyToClipboard({ text: value });\n  const isIconOnly = children === undefined;\n  // text mode already carries its name in label\n  const label = ariaLabel ?? (isIconOnly ? \"Copy code\" : undefined);\n  const copied = copiedLabel ?? (isIconOnly ? <CheckIcon aria-hidden=\"true\" className=\"size-3.5\" /> : \"Copied\");\n\n  const button = (\n    <Button\n      type=\"button\"\n      variant=\"quiet\"\n      size=\"xs\"\n      aria-live=\"polite\"\n      aria-label={label && isCopied ? copiedAriaLabel : label}\n      className={cn(isIconOnly && \"size-7 p-0\", className)}\n      {...props}\n      onClick={handleCopy}\n    >\n      {isCopied ? copied : (children ?? <CopyIcon aria-hidden=\"true\" className=\"size-3.5\" />)}\n    </Button>\n  );\n\n  if (!isIconOnly) return button;\n\n  return (\n    <TooltipProvider delay={0}>\n      <Tooltip>\n        <TooltipTrigger render={button} />\n        <TooltipContent side=\"left\">{label}</TooltipContent>\n      </Tooltip>\n    </TooltipProvider>\n  );\n}\n\nexport type CodeFloatingCopyProps = Omit<CodeCopyProps, \"children\" | \"copiedLabel\">;\n\nexport function CodeFloatingCopy({ className, ...props }: CodeFloatingCopyProps) {\n  return <CodeCopy data-code-floating=\"true\" className={cn(\"absolute top-2 right-2 z-10\", className)} {...props} />;\n}\n\n/** Null until resolved, and whenever highlighting is off or language is unknown — callers fall back to plain text. */\nexport function useCodeTokens({\n  code,\n  lang,\n  tokens,\n  highlight,\n}: {\n  code: string;\n  lang?: string;\n  tokens?: CodeTokenLines | null;\n  highlight: CodeHighlight;\n}): CodeTokenLines | null {\n  const requestKey = `${lang ?? \"\"}\\n${code}`;\n  const [clientTokens, setClientTokens] = useState<{ key: string; tokens: CodeTokenLines | null } | null>(null);\n\n  useEffect(() => {\n    if (highlight === \"none\" || tokens !== undefined || !lang) return;\n    let cancelled = false;\n    void highlightToTokens(code, lang)\n      .then((result) => {\n        if (!cancelled) setClientTokens({ key: requestKey, tokens: result });\n      })\n      .catch(() => {\n        if (!cancelled) setClientTokens({ key: requestKey, tokens: null });\n      });\n    return () => {\n      cancelled = true;\n    };\n  }, [code, lang, tokens, highlight, requestKey]);\n\n  if (highlight === \"none\") return null;\n  if (tokens !== undefined) return tokens;\n  return clientTokens?.key === requestKey ? clientTokens.tokens : null;\n}\n\nexport function CodeTokenLine({ tokens, plain }: { tokens: CodeTokenLines[number] | null; plain: string }): ReactNode {\n  if (!tokens || tokens.length === 0) return plain;\n  return tokens.map((token, index) => {\n    const style: CSSProperties = { ...token.style };\n    return (\n      // biome-ignore lint/suspicious/noArrayIndexKey: token order is the identity within a line\n      <span key={index} style={style}>\n        {token.content}\n      </span>\n    );\n  });\n}\n\n// kept flat so selection over code column copies clean source\nfunction CodeRow({\n  index,\n  number,\n  tokens,\n  plain,\n  overflow,\n  showLineNumbers,\n  measureRef,\n  style,\n}: {\n  index?: number;\n  number: number;\n  tokens: CodeTokenLines[number] | null;\n  plain: string;\n  overflow: CodeOverflow;\n  showLineNumbers: boolean;\n  measureRef?: (node: HTMLDivElement | null) => void;\n  style?: CSSProperties;\n}) {\n  return (\n    <div\n      ref={measureRef}\n      data-index={index}\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"line\"\n      className=\"flex min-h-5 w-full\"\n      style={style}\n    >\n      {showLineNumbers ? (\n        <span\n          data-control-ui=\"code\"\n          data-control-family=\"code\"\n          data-slot=\"gutter\"\n          aria-hidden=\"true\"\n          className=\"shrink-0 select-none pr-3 pl-4\"\n          style={{ minWidth: \"3.5rem\" }}\n        >\n          {number}\n        </span>\n      ) : null}\n      <code\n        className={cn(\n          \"min-w-0 flex-1 pr-4\",\n          overflow === \"wrap\" ? \"whitespace-pre-wrap break-words\" : \"whitespace-pre\",\n          !showLineNumbers && \"pl-4\",\n        )}\n      >\n        <CodeTokenLine tokens={tokens} plain={plain} />\n      </code>\n    </div>\n  );\n}\n\nexport type CodeContentProps = Omit<ComponentProps<\"div\">, \"children\" | \"style\"> & {\n  code: string;\n  lang?: string;\n  tokens?: CodeTokenLines | null;\n  highlight?: CodeHighlight;\n  showLineNumbers?: boolean;\n  startLine?: number;\n  maxHeight?: string;\n  virtualize?: boolean;\n  style?: CSSProperties & CodeKnobStyle;\n};\n\nexport function CodeContent({\n  code,\n  lang,\n  tokens,\n  highlight = \"auto\",\n  showLineNumbers = false,\n  startLine = 1,\n  maxHeight = \"32rem\",\n  virtualize,\n  className,\n  ref,\n  style,\n  ...props\n}: CodeContentProps) {\n  const { chrome, density, overflow, hasHeader } = useCodeContext();\n  const resolvedTokens = useCodeTokens({ code, lang, tokens, highlight });\n  const plainLines = useMemo(() => code.split(\"\\n\"), [code]);\n  const isCompact = density === \"compact\";\n\n  const scrollRef = useRef<HTMLDivElement>(null);\n  function setScrollElement(node: HTMLDivElement | null) {\n    scrollRef.current = node;\n    if (typeof ref === \"function\") ref(node);\n    else if (ref) ref.current = node;\n  }\n  const shouldVirtualize = virtualize ?? plainLines.length > VIRTUALIZE_THRESHOLD;\n  const useScrollArea = density !== \"compact\" || overflow !== \"wrap\";\n\n  // react-doctor-disable-next-line react-hooks-js/incompatible-library\n  const virtualizer = useVirtualizer({\n    count: plainLines.length,\n    getScrollElement: () => scrollRef.current,\n    estimateSize: () => ESTIMATED_LINE_HEIGHT,\n    overscan: 24,\n    enabled: shouldVirtualize,\n  });\n\n  const gridClassName = cn(isCompact ? \"py-2\" : \"py-3\", overflow === \"scroll\" ? \"w-max min-w-full\" : \"w-full\");\n  const textStyle = style;\n\n  const grid = shouldVirtualize ? (\n    <>\n      <pre data-control-ui=\"code\" data-control-family=\"code\" data-slot=\"accessible-source\" className=\"sr-only\">\n        <code>{code}</code>\n      </pre>\n      <div\n        data-control-ui=\"code\"\n        data-control-family=\"code\"\n        data-slot=\"grid\"\n        data-density={isCompact ? \"compact\" : \"default\"}\n        aria-hidden=\"true\"\n        className={gridClassName}\n        style={{ ...textStyle, position: \"relative\", height: `${virtualizer.getTotalSize()}px` }}\n      >\n        {virtualizer.getVirtualItems().map((item) => (\n          <CodeRow\n            key={item.key}\n            index={item.index}\n            number={startLine + item.index}\n            tokens={resolvedTokens?.[item.index] ?? null}\n            plain={plainLines[item.index] ?? \"\"}\n            overflow={overflow}\n            showLineNumbers={showLineNumbers}\n            measureRef={virtualizer.measureElement}\n            style={{ position: \"absolute\", top: 0, left: 0, width: \"100%\", transform: `translateY(${item.start}px)` }}\n          />\n        ))}\n      </div>\n    </>\n  ) : (\n    <div\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"grid\"\n      data-density={isCompact ? \"compact\" : \"default\"}\n      className={gridClassName}\n      style={textStyle}\n    >\n      {plainLines.map((plain, index) => (\n        <CodeRow\n          // biome-ignore lint/suspicious/noArrayIndexKey: line position is the row identity\n          key={index}\n          number={startLine + index}\n          tokens={resolvedTokens?.[index] ?? null}\n          plain={plain}\n          overflow={overflow}\n          showLineNumbers={showLineNumbers}\n        />\n      ))}\n    </div>\n  );\n\n  const content = useScrollArea ? (\n    <ScrollArea\n      maxHeight={maxHeight}\n      viewportClassName={className}\n      viewportProps={{\n        ...props,\n        \"data-control-ui\": \"code\",\n        \"data-control-family\": \"code\",\n        \"data-slot\": \"content\",\n        style,\n      }}\n      viewportRef={setScrollElement}\n    >\n      {grid}\n    </ScrollArea>\n  ) : (\n    <div\n      ref={setScrollElement}\n      data-control-ui=\"code\"\n      data-control-family=\"code\"\n      data-slot=\"content\"\n      className={cn(\"overflow-auto\", className)}\n      style={{ ...style, maxHeight }}\n      {...props}\n    >\n      {grid}\n    </div>\n  );\n\n  // embedded means host frames block and owns copy control\n  if (hasHeader || chrome === \"embedded\") return content;\n\n  // reserves exactly overlay's footprint (top-2 + size-7) so no dead band is left\n  return (\n    <div className={cn(\"relative\", isCompact ? \"pt-7\" : \"pt-6\")}>\n      <CodeFloatingCopy value={code} />\n      {content}\n    </div>\n  );\n}\n"
    }
  ],
  "css": {
    "@import \"../components/control-ui/styles/code.css\"": {},
    "@import \"../components/control-ui/styles/recipes/code.css\"": {}
  },
  "meta": {}
}
