{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "syntax",
  "title": "Syntax",
  "description": "Code as lines of coloured tokens, read by Shiki with its regular expressions in JavaScript (no WebAssembly). Shiki and each language load the first time they are needed, in the browser or on a server, and the colours are CSS variables.",
  "dependencies": [
    "shiki"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/lib/syntax.ts",
      "content": "import type { BundledLanguage } from 'shiki/langs'\n\n/*\n * Code as lines of coloured tokens, for the Code block. Shiki reads the\n * grammar; the colours are CSS variables (`--code-keyword`, `--code-string`\n * and the rest), so they follow the theme and a project changes them in its\n * CSS. Shiki and each language load the first time they are needed, in the\n * browser or on a server, so a page that shows no code never fetches them.\n */\n\n/** A run of text in one colour. With no `color` it takes the block's text colour. */\nexport interface CodeToken {\n  content: string\n  /** A CSS colour, such as `var(--code-keyword)`. */\n  color?: string\n  italic?: boolean\n}\n\n/**\n * A language by its name or alias (`tsx`, `bash`, `sh`), or plain `text`.\n * Any other, such as a Markdown fence's `mermaid`, shows as plain text.\n */\nexport type CodeLanguage = Exclude<BundledLanguage, 'ansi'> | 'text' | (string & {})\n\nconst LANGUAGE_NAMES: Record<string, string> = {\n  bash: 'Bash',\n  c: 'C',\n  cpp: 'C++',\n  csharp: 'C#',\n  cs: 'C#',\n  css: 'CSS',\n  diff: 'Diff',\n  dockerfile: 'Dockerfile',\n  go: 'Go',\n  graphql: 'GraphQL',\n  html: 'HTML',\n  java: 'Java',\n  javascript: 'JavaScript',\n  js: 'JavaScript',\n  json: 'JSON',\n  jsonc: 'JSON',\n  jsx: 'JSX',\n  kotlin: 'Kotlin',\n  markdown: 'Markdown',\n  md: 'Markdown',\n  mdx: 'MDX',\n  php: 'PHP',\n  python: 'Python',\n  py: 'Python',\n  ruby: 'Ruby',\n  rb: 'Ruby',\n  rust: 'Rust',\n  rs: 'Rust',\n  scss: 'SCSS',\n  sh: 'Shell',\n  shell: 'Shell',\n  shellscript: 'Shell',\n  sql: 'SQL',\n  swift: 'Swift',\n  text: 'Plain text',\n  toml: 'TOML',\n  ts: 'TypeScript',\n  tsx: 'TSX',\n  typescript: 'TypeScript',\n  xml: 'XML',\n  yaml: 'YAML',\n  yml: 'YAML',\n  zsh: 'Zsh',\n}\n\n/** A language's name as a person writes it (`ts` is TypeScript), or the id itself for one not listed. */\nexport function languageName(language: string): string {\n  return LANGUAGE_NAMES[language.toLowerCase()] ?? language\n}\n\ntype Highlighter = import('shiki/core').HighlighterCore\n\nlet highlighter: Promise<Highlighter> | undefined\n\nfunction getHighlighter(): Promise<Highlighter> {\n  highlighter ??= Promise.all([\n    import('shiki/core'),\n    import('shiki/engine/javascript'),\n  ]).then(\n    ([\n      { createHighlighterCore, createCssVariablesTheme },\n      { createJavaScriptRegexEngine },\n    ]) =>\n      createHighlighterCore({\n        // The regular expression engine in JavaScript, so there is no WebAssembly to fetch.\n        engine: createJavaScriptRegexEngine(),\n        themes: [\n          createCssVariablesTheme({\n            name: 'kino',\n            variablePrefix: '--code-',\n            fontStyle: true,\n          }),\n        ],\n        langs: [],\n      }),\n  )\n  return highlighter\n}\n\n/** The lines of `code`, without the newline that ends the last one. */\nexport function codeLines(code: string): string[] {\n  return code.replace(/\\r\\n?/g, '\\n').replace(/\\n$/, '').split('\\n')\n}\n\n/** `code` as lines of one token each, as it shows before its colours load. */\nexport function plainTokens(code: string): CodeToken[][] {\n  return codeLines(code).map((line) => (line ? [{ content: line }] : []))\n}\n\n/**\n * `plain` lines with the colours `coloured` gave them, for as much of each\n * line as hasn't changed since, so code that grows keeps its colours while\n * the new ones load, and only what changed shows plain.\n */\nexport function holdColours(\n  plain: CodeToken[][],\n  coloured: CodeToken[][] | undefined,\n): CodeToken[][] {\n  if (!coloured) return plain\n  return plain.map((line, index) => {\n    const held = coloured[index]\n    if (!held) return line\n    const text = line.map((token) => token.content).join('')\n    const kept: CodeToken[] = []\n    let at = 0\n    for (const token of held) {\n      const same = commonLength(token.content, text.slice(at))\n      if (same)\n        kept.push(\n          same === token.content.length\n            ? token\n            : { ...token, content: token.content.slice(0, same) },\n        )\n      at += same\n      if (same < token.content.length) break\n    }\n    if (at === text.length) return kept\n    return [...kept, { content: text.slice(at) }]\n  })\n}\n\nfunction commonLength(a: string, b: string): number {\n  let i = 0\n  while (i < a.length && i < b.length && a[i] === b[i]) i++\n  return i\n}\n\n/**\n * Shiki's colour for a token, in Kino's names: `var(--code-token-keyword)`\n * becomes `var(--code-keyword)`, and its text colour none, so it inherits.\n */\nexport function tokenColor(color: string | undefined): string | undefined {\n  if (!color || color === 'var(--code-foreground)') return undefined\n  // A diff's lines take the colours of the block's added and removed lines.\n  if (color === 'var(--code-token-inserted)') return 'var(--code-added)'\n  if (color === 'var(--code-token-deleted)') return 'var(--code-removed)'\n  return color.replace('var(--code-token-', 'var(--code-')\n}\n\n/** Joins tokens of one colour that follow each other, so a line has as few as it can. */\nexport function mergeTokens(line: CodeToken[]): CodeToken[] {\n  const merged: CodeToken[] = []\n  for (const token of line) {\n    const last = merged.at(-1)\n    if (last && last.color === token.color && last.italic === token.italic) {\n      last.content += token.content\n    } else {\n      merged.push({ ...token })\n    }\n  }\n  return merged\n}\n\nfunction isBundled(\n  language: string,\n  bundled: Record<BundledLanguage, unknown>,\n): language is BundledLanguage {\n  return Object.hasOwn(bundled, language)\n}\n\n/**\n * `code` as lines of coloured tokens. A language shiki doesn't know, or one\n * that fails to load, comes back as plain lines.\n */\nexport async function highlightCode(\n  code: string,\n  language: CodeLanguage,\n): Promise<CodeToken[][]> {\n  if (language === 'text') return plainTokens(code)\n  const [shiki, { bundledLanguages }] = await Promise.all([\n    getHighlighter(),\n    import('shiki/langs'),\n  ])\n  if (!isBundled(language, bundledLanguages)) return plainTokens(code)\n  try {\n    if (!shiki.getLoadedLanguages().includes(language)) {\n      await shiki.loadLanguage(bundledLanguages[language])\n    }\n  } catch {\n    return plainTokens(code)\n  }\n  const lines = shiki.codeToTokensBase(codeLines(code).join('\\n'), {\n    lang: language,\n    theme: 'kino',\n  })\n  return lines.map((line) =>\n    mergeTokens(\n      line.map((token) => ({\n        content: token.content,\n        color: tokenColor(token.color),\n        // Shiki's FontStyle.Italic is 1.\n        italic: ((token.fontStyle ?? 0) & 1) === 1 || undefined,\n      })),\n    ),\n  )\n}\n\n/**\n * The line numbers a list names, counting from 1: single lines and\n * inclusive ranges, such as `[1, [4, 6]]` for 1, 4, 5 and 6. A range\n * written backwards counts the same.\n */\nexport function lineSet(lines: readonly (number | readonly [number, number])[] = []) {\n  const set = new Set<number>()\n  for (const entry of lines) {\n    const [from, to] = typeof entry === 'number' ? [entry, entry] : entry\n    for (let line = Math.min(from, to); line <= Math.max(from, to); line += 1)\n      set.add(line)\n  }\n  return set\n}\n",
      "type": "registry:lib",
      "target": "@lib/syntax.ts"
    }
  ],
  "type": "registry:lib"
}