{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-block",
  "title": "Code block",
  "description": "Highlighted code with line numbers, a filename tab and a copy key. No highlighting dependency.",
  "dependencies": [
    "lucide-react@1.73.0"
  ],
  "registryDependencies": [
    "https://www.cyberspec.dev/r/cyber.json",
    "https://www.cyberspec.dev/r/button.json"
  ],
  "files": [
    {
      "path": "registry/cyber/ui/code-block.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { Check, Copy, FileCode2, X } from \"lucide-react\"\nimport { Button } from \"@/registry/cyber/ui/button\"\nimport { haptic } from \"@/registry/cyber/lib/haptics\"\nimport { sfx } from \"@/registry/cyber/lib/sound\"\nimport { copyText } from \"@/registry/cyber/lib/clipboard\"\nimport \"@/registry/cyber/ui/cyber/code-block.css\"\n\ntype Language = \"ts\" | \"tsx\" | \"js\" | \"bash\" | \"json\" | \"css\" | \"text\"\n\n// What a stretch of code is. \"name\" is whatever gives code its structure\n// in a language: a JSX tag, a JSON key, a CSS property, a shell command.\ntype Kind = \"comment\" | \"string\" | \"keyword\" | \"number\" | \"constant\" | \"name\" | \"punct\" | \"plain\"\ntype Token = { kind: Kind; text: string }\n\n// A grammar is a list of rules tried in order at each position. A rule is a\n// sticky pattern and the kind it yields, or a function that looks at what's\n// around the match and decides, returning null to let the next rule try.\ntype Rule = [pattern: RegExp, kind: Kind | ((source: string, start: number, end: number) => Kind | null)]\n\nconst words = (list: string) => new Set(list.split(\" \"))\n\nconst doubleQuoted = `\"(?:\\\\\\\\.|[^\"\\\\\\\\\\\\n])*\"`\nconst singleQuoted = `'(?:\\\\\\\\.|[^'\\\\\\\\\\\\n])*'`\n\n// ── JavaScript and TypeScript ───────────────────────────────────────────\n\nconst jsKeywords = words(\n  \"async await break case catch class const continue debugger default delete do else enum export extends finally for function if implements import in instanceof interface keyof let new private protected public readonly return satisfies static super switch this throw try typeof var void while yield\",\n)\n// Words that are keywords only where the grammar puts them: `type Foo =` is\n// one, the `type` in `type=\"submit\"` isn't.\nconst jsContextual = words(\"as from of type\")\nconst jsConstants = words(\"true false null undefined NaN Infinity\")\n\nconst jsWord =\n  (jsx: boolean) =>\n  (source: string, start: number, end: number): Kind => {\n    const word = source.slice(start, end)\n    const before = source[start - 1]\n    // A member of something, whatever it's called: `list.default`.\n    if (before === \".\") return \"plain\"\n    if (jsConstants.has(word)) return \"constant\"\n    if (jsKeywords.has(word)) return \"keyword\"\n    if (jsContextual.has(word)) return /^\\s*[^\\s=:,;.)}\\]?]/.test(source.slice(end, end + 16)) ? \"keyword\" : \"plain\"\n    if (jsx) {\n      // A tag: the word right after `<` or `</`, unless that `<` follows a\n      // name or a closing bracket, where it's a generic or a comparison.\n      const open = before === \"<\" ? start - 1 : before === \"/\" && source[start - 2] === \"<\" ? start - 2 : -1\n      if (open >= 0 && !/[\\w$)\\]]/.test(source[open - 1] ?? \"\")) return \"name\"\n    }\n    return \"plain\"\n  }\n\nconst javascript = (jsx: boolean): Rule[] => [\n  [/\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\//y, \"comment\"],\n  [new RegExp(`${doubleQuoted}|${singleQuoted}|\\`(?:\\\\\\\\[\\\\s\\\\S]|[^\\`\\\\\\\\])*\\``, \"y\"), \"string\"],\n  [/(?:0[xX][\\da-fA-F_]+|0[bB][01_]+|\\d[\\d_]*(?:\\.[\\d_]+)?(?:[eE][+-]?\\d+)?)n?/y, \"number\"],\n  [/[A-Za-z_$][\\w$]*/y, jsWord(jsx)],\n]\n\n// ── JSON ────────────────────────────────────────────────────────────────\n\nconst json: Rule[] = [\n  // A string followed by a colon is a key.\n  [new RegExp(doubleQuoted, \"y\"), (source, _start, end) => (/^\\s*:/.test(source.slice(end, end + 8)) ? \"name\" : \"string\")],\n  [/-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y, \"number\"],\n  [/\\b(?:true|false|null)\\b/y, \"constant\"],\n]\n\n// ── CSS ─────────────────────────────────────────────────────────────────\n\nconst css: Rule[] = [\n  [/\\/\\*[\\s\\S]*?\\*\\//y, \"comment\"],\n  [new RegExp(`${doubleQuoted}|${singleQuoted}`, \"y\"), \"string\"],\n  [/@[\\w-]+/y, \"keyword\"],\n  [/#[\\da-fA-F]{3,8}(?![\\w-])/y, \"constant\"],\n  [\n    /--[\\w-]+|-?[A-Za-z_][\\w-]*/y,\n    (source, start, end) => {\n      if (source.startsWith(\"--\", start)) return \"constant\"\n      if (source[start - 1] === \"!\") return \"keyword\"\n      // A property: a word, a colon, then a value that ends before any\n      // brace opens. `a:hover {` is a selector; `color: red;` isn't.\n      const after = /^\\s*:(?!:)[^{}\\n;]*(;|\\}|\\n|$)/.test(source.slice(end, end + 200))\n      return after ? \"name\" : \"plain\"\n    },\n  ],\n  [/[+-]?(?:\\d*\\.)?\\d+(?:%|[a-zA-Z]+)?/y, \"number\"],\n]\n\n// ── Shell ───────────────────────────────────────────────────────────────\n\nconst bashKeywords = words(\"if then else elif fi for in do done while until case esac function return export local readonly cd echo exit set unset source alias sudo\")\nconst afterSpace = (source: string, start: number) => start === 0 || /\\s/.test(source[start - 1])\n\nconst bash: Rule[] = [\n  [/#[^\\n]*/y, (source, start) => (afterSpace(source, start) ? \"comment\" : null)],\n  [new RegExp(`\"(?:\\\\\\\\.|[^\"\\\\\\\\])*\"|${singleQuoted}`, \"y\"), \"string\"],\n  [/\\$(?:\\{[^}\\n]*\\}|[A-Za-z_]\\w*|[0-9@#?*!$-])/y, \"constant\"],\n  [/--?[A-Za-z][\\w-]*/y, (source, start) => (afterSpace(source, start) ? \"constant\" : null)],\n  [/\\d+(?:\\.\\d+)?(?![\\w.-])/y, (source, start) => (afterSpace(source, start) || source[start - 1] === \"=\" ? \"number\" : null)],\n  [\n    /[A-Za-z_][\\w.-]*/y,\n    (source, start, end) => {\n      if (bashKeywords.has(source.slice(start, end))) return \"keyword\"\n      // A command: the first word of a line, or of what follows a pipe, a\n      // semicolon, `&&` or `$(`.\n      return /(?:^|[\\n|;&(])[ \\t]*$/.test(source.slice(Math.max(0, start - 40), start)) ? \"name\" : \"plain\"\n    },\n  ],\n]\n\nconst grammars: Record<Exclude<Language, \"text\">, Rule[]> = {\n  ts: javascript(false),\n  tsx: javascript(true),\n  js: javascript(true),\n  json,\n  css,\n  bash,\n}\n\nconst tags: Record<Language, string> = { ts: \"TS\", tsx: \"TSX\", js: \"JS\", bash: \"Bash\", json: \"JSON\", css: \"CSS\", text: \"Text\" }\n\n// One pass over the source: at each position the first rule that matches\n// wins, and anything no rule wants is punctuation or plain text. Neighbors\n// of the same kind are joined, so the page gets as few spans as it can.\nfunction tokenize(source: string, rules: Rule[]) {\n  const tokens: Token[] = []\n  const push = (kind: Kind, text: string) => {\n    const last = tokens[tokens.length - 1]\n    if (last && last.kind === kind) last.text += text\n    else tokens.push({ kind, text })\n  }\n  let index = 0\n  scan: while (index < source.length) {\n    for (const [pattern, kind] of rules) {\n      pattern.lastIndex = index\n      const match = pattern.exec(source)\n      if (!match || !match[0]) continue\n      const end = index + match[0].length\n      const resolved = typeof kind === \"function\" ? kind(source, index, end) : kind\n      if (!resolved) continue\n      push(resolved, match[0])\n      index = end\n      continue scan\n    }\n    push(/[\\s\\p{L}\\p{N}_]/u.test(source[index]) ? \"plain\" : \"punct\", source[index])\n    index += 1\n  }\n  return tokens\n}\n\n// Tokens can run across lines (a block comment, a template string): cut\n// them at the line breaks, so each line can be laid out with its number.\nfunction toLines(tokens: Token[]) {\n  const lines: Token[][] = [[]]\n  for (const token of tokens) {\n    token.text.split(\"\\n\").forEach((part, index) => {\n      if (index > 0) lines.push([])\n      if (part) lines[lines.length - 1].push({ kind: token.kind, text: part })\n    })\n  }\n  return lines\n}\n\n// Below this width there's no room over the panel for a tab, a tag and a\n// key with a word on it.\nconst compactBelow = 288\n\n// Two facts about the panel that depend on its size: whether its content\n// overflows it, either way, and whether it's too narrow for the full head.\nfunction usePanelSize(ref: React.RefObject<HTMLElement | null>) {\n  const [size, setSize] = React.useState({ overflows: false, compact: false })\n  React.useLayoutEffect(() => {\n    const node = ref.current\n    if (!node) return\n    const measure = () => {\n      const overflows = node.scrollWidth > node.clientWidth + 1 || node.scrollHeight > node.clientHeight + 1\n      const compact = node.offsetWidth < compactBelow\n      setSize((last) => (last.overflows === overflows && last.compact === compact ? last : { overflows, compact }))\n    }\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(node)\n    if (node.firstElementChild) observer.observe(node.firstElementChild)\n    return () => observer.disconnect()\n  }, [ref])\n  return size\n}\n\n// Code on a panel: numbered lines, highlighted by a small tokenizer of its\n// own, under a tab with the file's name, a language tag and a copy key. The\n// key confirms in the signal color, the line numbers light with it, and the\n// result is announced.\n//\n// - `code`: the source. A blank first line and trailing blank lines are\n//   dropped, so it can be written as a template string.\n// - `language`: \"ts\", \"tsx\", \"js\", \"bash\", \"json\", \"css\", or \"text\" for no\n//   highlighting.\n// - `filename`: printed on the tab, and used to name the block.\n// - `label` names the block for assistive technology when there's no\n//   filename, or when the filename isn't enough.\n// - `numbers`: set it false to drop the line numbers.\n// - `maxLines`: the block scrolls vertically past this many lines.\n//\n// Long lines scroll sideways inside the panel rather than wrapping, and\n// whenever the panel scrolls it can take focus, so the arrow keys move it.\n// In a narrow column the key keeps only its icon, and the tag gives its\n// room to the filename.\nfunction CodeBlock({\n  code,\n  language = \"text\",\n  filename,\n  label,\n  numbers = true,\n  maxLines,\n  onCopy,\n  style,\n  ...props\n}: Omit<React.ComponentProps<\"div\">, \"children\" | \"onCopy\"> & {\n  code: string\n  language?: Language\n  filename?: string\n  label?: string\n  numbers?: boolean\n  maxLines?: number\n  onCopy?: (code: string) => void\n}) {\n  const source = React.useMemo(() => code.replace(/^\\n/, \"\").replace(/\\s+$/, \"\"), [code])\n  const lines = React.useMemo(() => toLines(language === \"text\" ? [{ kind: \"plain\", text: source }] : tokenize(source, grammars[language])), [source, language])\n  const bytes = React.useMemo(() => new TextEncoder().encode(source).length, [source])\n  const [state, setState] = React.useState<\"idle\" | \"copied\" | \"failed\">(\"idle\")\n  const timer = React.useRef<number | undefined>(undefined)\n  const mounted = React.useRef(true)\n  const body = React.useRef<HTMLDivElement>(null)\n  const { overflows, compact } = usePanelSize(body)\n  const name = label ?? filename ?? `${tags[language]} code`\n\n  React.useEffect(() => {\n    mounted.current = true\n    return () => {\n      mounted.current = false\n      window.clearTimeout(timer.current)\n    }\n  }, [])\n\n  // Returning the Promise keeps the key pending until the clipboard answers.\n  const copy = async () => {\n    window.clearTimeout(timer.current)\n    try {\n      await copyText(source)\n      if (!mounted.current) return\n      setState(\"copied\")\n      sfx(\"success\")\n      haptic(\"success\")\n      onCopy?.(source)\n    } catch {\n      if (!mounted.current) return\n      setState(\"failed\")\n      sfx(\"deny\")\n      haptic(\"error\")\n    }\n    if (mounted.current) timer.current = window.setTimeout(() => setState(\"idle\"), 1800)\n  }\n\n  const digits = Math.max(2, String(lines.length).length)\n  return (\n    <div\n      data-kit=\"code-block\"\n      data-language={language}\n      data-state={state}\n      data-compact={compact ? \"\" : undefined}\n      style={{ \"--max-lines\": maxLines, \"--digits\": digits, ...style } as React.CSSProperties}\n      {...props}\n    >\n      <div data-kit=\"code-block-head\">\n        {filename && (\n          <span data-kit=\"code-block-file\" data-frame=\"tr\" title={filename}>\n            <FileCode2 aria-hidden />\n            <span data-kit=\"code-block-filename\">{filename}</span>\n          </span>\n        )}\n        <span data-kit=\"code-block-lang\">{tags[language]}</span>\n        <span data-kit=\"code-block-copy\">\n          {/* The key plays the outcome's sound itself, so the press is silent. */}\n          <Button\n            size=\"sm\"\n            tone={state === \"copied\" ? \"signal\" : state === \"failed\" ? \"flag\" : \"secondary\"}\n            // In a narrow column the key is its icon alone; the word stays\n            // in its name.\n            icon={compact}\n            data-sfx=\"none\"\n            onClick={copy}\n          >\n            {state === \"copied\" ? <Check aria-hidden /> : state === \"failed\" ? <X aria-hidden /> : <Copy aria-hidden />}\n            <span data-kit=\"code-block-copy-label\">{state === \"copied\" ? \"Copied\" : state === \"failed\" ? \"Failed\" : \"Copy\"}</span>\n            <span data-sr-only> {name}</span>\n          </Button>\n        </span>\n      </div>\n      <div\n        ref={body}\n        data-kit=\"code-block-body\"\n        data-frame=\"br\"\n        data-numbers={numbers ? \"\" : undefined}\n        // A panel that scrolls has to be reachable without a pointer.\n        tabIndex={overflows ? 0 : undefined}\n        role={overflows ? \"region\" : undefined}\n        aria-label={overflows ? name : undefined}\n      >\n        <pre data-kit=\"code-block-pre\">\n          <code>\n            {lines.map((line, index) => (\n              <span key={index} data-kit=\"code-block-line\">\n                {numbers && (\n                  <span data-kit=\"code-block-number\" aria-hidden>\n                    {String(index + 1).padStart(digits, \"0\")}\n                  </span>\n                )}\n                <span data-kit=\"code-block-text\">\n                  {line.map((token, at) =>\n                    token.kind === \"plain\" ? (\n                      token.text\n                    ) : (\n                      <span key={at} data-token={token.kind}>\n                        {token.text}\n                      </span>\n                    ),\n                  )}\n                  {\"\\n\"}\n                </span>\n              </span>\n            ))}\n          </code>\n        </pre>\n      </div>\n      <span data-micro aria-hidden>\n        LN {String(lines.length).padStart(2, \"0\")} // {bytes} B // UTF-8\n      </span>\n      <span data-sr-only role=\"status\">\n        {state === \"copied\" ? \"Copied to clipboard\" : state === \"failed\" ? \"Couldn't copy\" : \"\"}\n      </span>\n    </div>\n  )\n}\n\nexport { CodeBlock }\nexport type { Language as CodeBlockLanguage }\n",
      "type": "registry:ui",
      "target": "@ui/code-block.tsx"
    },
    {
      "path": "registry/cyber/ui/cyber/code-block.css",
      "content": "@layer ui-sdk, cyber.tokens, cyber.base, cyber.ui, cyber.blocks, cyber.fx, cyber.a11y;\n\n@layer cyber.ui {\n  [data-skin=\"cyber\"] [data-kit=\"code-block\"] {\n    --code-fill: var(--cy-panel);\n    --code-line: 1.6;\n\n    position: relative;\n    display: grid;\n    width: 100%;\n    min-width: 0;\n    text-align: start;\n\n    & > [data-micro] {\n      margin-block-start: 5px;\n    }\n  }\n\n  /* The row over the panel: the file's tab stands on the panel's top edge,\n     and the language tag and the copy key float a little above it. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-head\"] {\n    display: flex;\n    align-items: flex-end;\n    gap: 10px;\n    min-width: 0;\n  }\n\n  /* The tab. Its foot overlaps the panel's top edge by the width of a\n     line, so the two read as one outline. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-file\"] {\n    --frame-cut: 8px;\n    --frame-line: var(--cy-line-deco);\n    --frame-fill: var(--code-fill);\n    --frame-image: none;\n\n    display: inline-flex;\n    align-items: center;\n    gap: 7px;\n    min-width: 0;\n    height: var(--cy-h-sm);\n    margin-block-end: -1px;\n    padding-inline: 9px 16px;\n    font-family: var(--cy-mono);\n    font-size: var(--cy-text-xs);\n    color: var(--cy-ink);\n\n    & svg {\n      width: 14px;\n      height: 14px;\n    }\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-filename\"] {\n    min-width: 0;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-lang\"] {\n    flex: none;\n    display: inline-flex;\n    align-items: center;\n    height: var(--cy-h-sm);\n    margin-block-end: 6px;\n    margin-inline-start: auto;\n    font-family: var(--cy-mono);\n    font-size: var(--cy-text-xs);\n    letter-spacing: 0.08em;\n    text-transform: uppercase;\n    color: var(--cy-ink-mute);\n\n    /* With no tab before it, the tag takes the tab's place. */\n    &:first-child {\n      margin-inline: 0 auto;\n    }\n\n    /* Too narrow for both: the filename's extension says the language. */\n    [data-compact] [data-kit=\"code-block-file\"] ~ & {\n      display: none;\n    }\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-copy\"] {\n    flex: none;\n    display: flex;\n    margin-block-end: 6px;\n    margin-inline-start: auto;\n\n    [data-kit=\"code-block-lang\"] + & {\n      margin-inline-start: 0;\n    }\n    [data-compact] [data-kit=\"code-block-file\"] ~ & {\n      margin-inline-start: auto;\n    }\n  }\n\n  /* Wide enough for the longest of its words, so the key doesn't change\n     size as it confirms. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-copy-label\"] {\n    min-width: 3.2em;\n    text-align: start;\n\n    /* Compact: the word leaves the key's face but stays in its name. */\n    [data-compact] & {\n      position: absolute;\n      width: 1px;\n      height: 1px;\n      min-width: 0;\n      overflow: hidden;\n      clip-path: inset(50%);\n      white-space: nowrap;\n    }\n  }\n\n  /* The panel is the scroller: long lines run off its edge rather than\n     wrap, and it takes focus whenever there's somewhere to scroll to. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-body\"] {\n    --frame-cut: var(--cy-cut);\n    --frame-line: var(--cy-line-deco);\n    --frame-fill: var(--code-fill);\n    --frame-image: none;\n\n    min-width: 0;\n    max-height: calc(var(--max-lines, 1000) * var(--code-line) * var(--cy-text-sm) + 22px);\n    padding-block: 10px;\n    overflow: auto;\n    overscroll-behavior-x: contain;\n    font-family: var(--cy-mono);\n    font-size: var(--cy-text-sm);\n    line-height: var(--code-line);\n    color: var(--cy-ink-hi);\n    tab-size: 2;\n    /* Code is read character by character: => stays two characters. */\n    font-variant-ligatures: none;\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-pre\"] {\n    width: max-content;\n    min-width: 100%;\n    margin: 0;\n    font: inherit;\n\n    & code {\n      font: inherit;\n    }\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-line\"] {\n    display: flex;\n  }\n\n  /* The gutter stays put while the code scrolls under it. It isn't part of\n     the code, so it can't be selected with it. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-number\"] {\n    position: sticky;\n    inset-inline-start: 0;\n    flex: none;\n    min-width: calc(var(--digits, 2) * 1ch + 21px);\n    padding-inline: 10px;\n    border-inline-end: 1px solid var(--cy-line-deco);\n    text-align: end;\n    color: var(--cy-ink-mute);\n    background: var(--code-fill);\n    user-select: none;\n    transition: color var(--cy-t) linear;\n\n    /* Copied: the numbers light in the signal color for as long as the key\n       says so, as if the lines had just been read out. */\n    [data-state=\"copied\"] & {\n      color: var(--cy-signal);\n    }\n  }\n\n  [data-skin=\"cyber\"] [data-kit=\"code-block-text\"] {\n    flex: none;\n    padding-inline: 12px 16px;\n    white-space: pre;\n  }\n\n  /* Without a gutter the code starts at the panel's own padding. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-body\"]:not([data-numbers]) [data-kit=\"code-block-text\"] {\n    padding-inline-start: 14px;\n  }\n\n  /* The palette: keywords in the accent, strings green, numbers and\n     constants in the signal color, comments muted. Names (a tag, a key, a\n     property, a command) take the violet, so a file's structure reads apart\n     from its keywords. Identifiers stay the near-white of body text. */\n  [data-skin=\"cyber\"] [data-kit=\"code-block-text\"] [data-token] {\n    &[data-token=\"comment\"] {\n      color: var(--cy-ink-mute);\n    }\n    &[data-token=\"string\"] {\n      color: var(--cy-ok);\n    }\n    &[data-token=\"keyword\"] {\n      color: var(--cy-ink);\n    }\n    &:is([data-token=\"number\"], [data-token=\"constant\"]) {\n      color: var(--cy-signal);\n    }\n    &[data-token=\"name\"] {\n      color: var(--cy-epic);\n    }\n    &[data-token=\"punct\"] {\n      color: color-mix(in srgb, var(--cy-ink-hi) 62%, var(--cy-panel));\n    }\n  }\n}\n",
      "type": "registry:file",
      "target": "@ui/cyber/code-block.css"
    }
  ],
  "type": "registry:ui"
}
