{
  "name": "code-block",
  "type": "registry:ui",
  "framework": "react",
  "title": "Code Block",
  "description": "A monospace preformatted block that colours its own source from a language name.",
  "dependencies": [
    "class-variance-authority"
  ],
  "files": [
    {
      "path": "ui/code-block.tsx",
      "content": "import { cva, type VariantProps } from \"class-variance-authority\"\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst codeTokenVariants = cva(\"\", {\n  variants: {\n    kind: {\n      keyword: \"text-newt-code-keyword\",\n      string: \"text-newt-code-string\",\n      comment: \"text-newt-code-comment\",\n      function: \"text-newt-code-function\",\n    },\n  },\n})\n\nexport interface CodeTokenProps\n  extends\n    React.ComponentProps<\"span\">,\n    VariantProps<typeof codeTokenVariants> {}\n\nconst CodeToken = React.forwardRef<HTMLSpanElement, CodeTokenProps>(\n  ({ className, kind, ...props }, ref) => (\n    <span\n      ref={ref}\n      className={cn(codeTokenVariants({ kind }), className)}\n      {...props}\n    />\n  )\n)\nCodeToken.displayName = \"CodeToken\"\n\n/** A run of source, coloured by `kind` when given, plain when not. */\nexport interface CodeTokenSpec {\n  readonly text: string\n  readonly kind?: VariantProps<typeof codeTokenVariants>[\"kind\"]\n}\n\n/* ---------------------------------------------------------------------------\n * The scanner\n *\n * Four colours is all this block has, so it needs four answers, not a parse\n * tree: comment, string, keyword, call. That is small enough to ship inside\n * the component — a chat message showing six lines of code should not pull a\n * highlighter and a grammar in behind it. Anything that needs real grammar\n * (a diff, a language not listed here, semantic colours) produces its own runs\n * and hands them over as `tokens`.\n * ------------------------------------------------------------------------ */\n\nexport type CodeLanguage = \"ts\" | \"tsx\" | \"js\" | \"jsx\" | \"json\" | \"bash\" | \"sh\"\n\ninterface LanguageRules {\n  /** Words painted as keywords wherever they stand alone. */\n  readonly keywords: readonly string[]\n  /** Runs to the end of the line. Empty when the language has none. */\n  readonly lineComment: string\n  /** Whether a slash-star pair opens a comment. */\n  readonly blockComments: boolean\n  /** The characters that open a string, each closed by itself. */\n  readonly quotes: string\n}\n\nconst JS_KEYWORDS = [\n  \"as\",\n  \"async\",\n  \"await\",\n  \"break\",\n  \"case\",\n  \"catch\",\n  \"class\",\n  \"const\",\n  \"continue\",\n  \"default\",\n  \"delete\",\n  \"do\",\n  \"else\",\n  \"enum\",\n  \"export\",\n  \"extends\",\n  \"false\",\n  \"finally\",\n  \"for\",\n  \"from\",\n  \"function\",\n  \"if\",\n  \"implements\",\n  \"import\",\n  \"in\",\n  \"instanceof\",\n  \"interface\",\n  \"let\",\n  \"new\",\n  \"null\",\n  \"of\",\n  \"return\",\n  \"satisfies\",\n  \"static\",\n  \"super\",\n  \"switch\",\n  \"this\",\n  \"throw\",\n  \"true\",\n  \"try\",\n  \"type\",\n  \"typeof\",\n  \"undefined\",\n  \"var\",\n  \"void\",\n  \"while\",\n  \"yield\",\n]\n\nconst SHELL_KEYWORDS = [\n  \"case\",\n  \"cd\",\n  \"do\",\n  \"done\",\n  \"echo\",\n  \"elif\",\n  \"else\",\n  \"esac\",\n  \"exit\",\n  \"export\",\n  \"fi\",\n  \"for\",\n  \"function\",\n  \"if\",\n  \"in\",\n  \"local\",\n  \"return\",\n  \"then\",\n  \"while\",\n]\n\nconst JS_RULES = {\n  keywords: JS_KEYWORDS,\n  lineComment: \"//\",\n  blockComments: true,\n  quotes: \"\\\"'`\",\n} as const satisfies LanguageRules\n\nconst SHELL_RULES = {\n  keywords: SHELL_KEYWORDS,\n  lineComment: \"#\",\n  blockComments: false,\n  quotes: \"\\\"'\",\n} as const satisfies LanguageRules\n\nconst LANGUAGES = {\n  ts: JS_RULES,\n  tsx: JS_RULES,\n  js: JS_RULES,\n  jsx: JS_RULES,\n  json: {\n    keywords: [\"false\", \"null\", \"true\"],\n    lineComment: \"\",\n    blockComments: false,\n    quotes: '\"',\n  },\n  bash: SHELL_RULES,\n  sh: SHELL_RULES,\n} as const satisfies Record<CodeLanguage, LanguageRules>\n\nconst IDENTIFIER_START = /[A-Za-z_$]/\nconst IDENTIFIER_PART = /[A-Za-z0-9_$]/\n\n/** Where the string opened at `start` ends, past its closing quote. */\nfunction endOfString(code: string, start: number): number {\n  const quote = code[start]\n  let index = start + 1\n  while (index < code.length) {\n    if (code[index] === \"\\\\\") {\n      index += 2\n      continue\n    }\n    if (code[index] === quote) return index + 1\n    index += 1\n  }\n  return code.length\n}\n\n/** Where the identifier starting at `start` ends. */\nfunction endOfIdentifier(code: string, start: number): number {\n  let index = start + 1\n  while (index < code.length && IDENTIFIER_PART.test(code[index] ?? \"\")) {\n    index += 1\n  }\n  return index\n}\n\n/**\n * Splits source into coloured runs. Unrecognised text stays plain, so a\n * language this scanner reads badly is dull rather than wrong.\n */\nexport function tokenizeCode(\n  code: string,\n  language: CodeLanguage\n): readonly CodeTokenSpec[] {\n  const rules: LanguageRules = LANGUAGES[language]\n  const tokens: CodeTokenSpec[] = []\n  let plain = \"\"\n  let index = 0\n\n  function flush() {\n    if (plain !== \"\") {\n      tokens.push({ text: plain })\n      plain = \"\"\n    }\n  }\n\n  while (index < code.length) {\n    const char = code[index] ?? \"\"\n\n    if (rules.lineComment !== \"\" && code.startsWith(rules.lineComment, index)) {\n      const newline = code.indexOf(\"\\n\", index)\n      const end = newline === -1 ? code.length : newline\n      flush()\n      tokens.push({ text: code.slice(index, end), kind: \"comment\" })\n      index = end\n      continue\n    }\n\n    if (rules.blockComments && code.startsWith(\"/*\", index)) {\n      const close = code.indexOf(\"*/\", index + 2)\n      const end = close === -1 ? code.length : close + 2\n      flush()\n      tokens.push({ text: code.slice(index, end), kind: \"comment\" })\n      index = end\n      continue\n    }\n\n    if (rules.quotes.includes(char)) {\n      const end = endOfString(code, index)\n      flush()\n      tokens.push({ text: code.slice(index, end), kind: \"string\" })\n      index = end\n      continue\n    }\n\n    if (IDENTIFIER_START.test(char)) {\n      const end = endOfIdentifier(code, index)\n      const word = code.slice(index, end)\n      /* A name is a call when a bracket follows it, which is as far as a\n       * scanner without a parser can honestly go. */\n      const kind = rules.keywords.includes(word)\n        ? \"keyword\"\n        : code[end] === \"(\"\n          ? \"function\"\n          : undefined\n      if (kind === undefined) {\n        plain += word\n      } else {\n        flush()\n        tokens.push({ text: word, kind })\n      }\n      index = end\n      continue\n    }\n\n    plain += char\n    index += 1\n  }\n\n  flush()\n  return tokens\n}\n\n/* ------------------------------------------------------------------------ */\n\ntype PreProps = Omit<React.ComponentProps<\"pre\">, \"children\">\n\ninterface HighlightedCodeBlockProps extends PreProps {\n  /** Colours the source with the built-in scanner. */\n  language: CodeLanguage\n  /** The source, when a prop reads better than a child. */\n  code?: string\n  /** The source. A template literal keeps its newlines; JSX text does not. */\n  children?: string\n  tokens?: never\n}\n\ninterface TokenisedCodeBlockProps extends PreProps {\n  language?: never\n  code?: never\n  /** Runs from a real highlighter, for what the scanner cannot read. */\n  tokens: readonly CodeTokenSpec[]\n  children?: never\n}\n\ninterface ComposedCodeBlockProps extends PreProps {\n  language?: never\n  code?: never\n  tokens?: never\n  /** `CodeToken` children, placed by hand. */\n  children?: React.ReactNode\n}\n\nexport type CodeBlockProps =\n  | HighlightedCodeBlockProps\n  | TokenisedCodeBlockProps\n  | ComposedCodeBlockProps\n\nfunction paint(tokens: readonly CodeTokenSpec[]): React.ReactNode {\n  return tokens.map((token, index) =>\n    token.kind === undefined ? (\n      <React.Fragment key={index}>{token.text}</React.Fragment>\n    ) : (\n      <CodeToken key={index} kind={token.kind}>\n        {token.text}\n      </CodeToken>\n    )\n  )\n}\n\nfunction contentOf(props: CodeBlockProps): React.ReactNode {\n  if (props.language !== undefined) {\n    return paint(\n      tokenizeCode(props.code ?? props.children ?? \"\", props.language)\n    )\n  }\n  if (props.tokens !== undefined) return paint(props.tokens)\n  return props.children\n}\n\nconst CodeBlock = React.forwardRef<HTMLPreElement, CodeBlockProps>(\n  (props, ref) => {\n    /* The four authoring props are read by `contentOf`; peeling them off here\n     * is only so they never reach the DOM. */\n    const {\n      className,\n      language: _language,\n      code: _code,\n      tokens: _tokens,\n      children: _children,\n      ...rest\n    } = props\n    return (\n      <pre\n        ref={ref}\n        className={cn(\n          \"overflow-x-auto rounded-[var(--newt-radius-md)] border border-newt-border bg-newt-code-bg p-4 font-[family-name:var(--newt-font-mono)] text-[13px] leading-[1.6] text-newt-text-secondary\",\n          className\n        )}\n        {...rest}\n      >\n        {contentOf(props)}\n      </pre>\n    )\n  }\n)\nCodeBlock.displayName = \"CodeBlock\"\n\nexport { CodeBlock, CodeToken, codeTokenVariants }\n",
      "type": "registry:ui"
    }
  ]
}