{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-editor-shiki",
  "title": "Shiki Highlighting",
  "description": "Syntax highlighting for the code editor, tokenized with shiki using the same themes as the documentation code panels.",
  "dependencies": [
    "@codemirror/state",
    "@codemirror/view",
    "shiki"
  ],
  "registryDependencies": [
    "litingyes/blocove/code-editor-extension"
  ],
  "files": [
    {
      "path": "src/registry/blocove/lib/code-editor-shiki.ts",
      "content": "import type { HighlighterCore } from 'shiki/core'\nimport { createHighlighterCore } from 'shiki/core'\nimport { createJavaScriptRegexEngine } from 'shiki/engine/javascript'\n\nexport type CodeEditorColorScheme = 'light' | 'dark'\n\n/** A highlighted range of the document, styled with the token colors. */\nexport interface CodeEditorToken {\n  from: number\n  to: number\n  style: string\n}\n\n// Languages are loaded the first time they are used, so the editor does not\n// pull every grammar into the bundle. The keys are the names accepted by the\n// `language` prop.\nconst languages = {\n  bash: () => import('shiki/langs/shellscript.mjs'),\n  css: () => import('shiki/langs/css.mjs'),\n  diff: () => import('shiki/langs/diff.mjs'),\n  html: () => import('shiki/langs/html.mjs'),\n  javascript: () => import('shiki/langs/javascript.mjs'),\n  json: () => import('shiki/langs/json.mjs'),\n  jsx: () => import('shiki/langs/jsx.mjs'),\n  markdown: () => import('shiki/langs/markdown.mjs'),\n  python: () => import('shiki/langs/python.mjs'),\n  sql: () => import('shiki/langs/sql.mjs'),\n  tsx: () => import('shiki/langs/tsx.mjs'),\n  typescript: () => import('shiki/langs/typescript.mjs'),\n  yaml: () => import('shiki/langs/yaml.mjs'),\n}\n\nconst aliases: Record<string, keyof typeof languages> = {\n  js: 'javascript',\n  md: 'markdown',\n  py: 'python',\n  sh: 'bash',\n  shell: 'bash',\n  shellscript: 'bash',\n  ts: 'typescript',\n  yml: 'yaml',\n  zsh: 'bash',\n}\n\nconst themes: Record<CodeEditorColorScheme, string> = {\n  light: 'github-light',\n  dark: 'github-dark',\n}\n\n// Font style bits reported by shiki: 1 = italic, 2 = bold, 4 = underline.\nconst fontStyleRules = [\n  { bit: 1, css: 'font-style: italic;' },\n  { bit: 2, css: 'font-weight: 600;' },\n  { bit: 4, css: 'text-decoration: underline;' },\n] as const\n\nlet highlighter: Promise<HighlighterCore> | undefined\n\nfunction getHighlighter() {\n  highlighter ??= createHighlighterCore({\n    themes: [\n      import('shiki/themes/github-light.mjs'),\n      import('shiki/themes/github-dark.mjs'),\n    ],\n    langs: [],\n    engine: createJavaScriptRegexEngine({ forgiving: true }),\n  })\n\n  return highlighter\n}\n\nfunction resolveLanguage(language: string) {\n  const name = language.toLowerCase()\n\n  if (name in languages) {\n    return name as keyof typeof languages\n  }\n\n  return aliases[name] ?? null\n}\n\n/**\n * Tokenizes the whole document. Returns `null` for a language the editor does\n * not ship a grammar for, so the surface stays unhighlighted instead of failing.\n */\nexport async function tokenizeCodeEditor(\n  code: string,\n  language: string,\n  colorScheme: CodeEditorColorScheme,\n): Promise<CodeEditorToken[] | null> {\n  const name = resolveLanguage(language)\n\n  if (!name) {\n    return null\n  }\n\n  const shiki = await getHighlighter()\n\n  if (!shiki.getLoadedLanguages().includes(name)) {\n    await shiki.loadLanguage(languages[name])\n  }\n\n  const { tokens } = shiki.codeToTokens(code, {\n    lang: name,\n    theme: themes[colorScheme],\n  })\n\n  const highlighted: CodeEditorToken[] = []\n  let offset = 0\n\n  for (const line of tokens) {\n    for (const token of line) {\n      const from = offset\n      offset += token.content.length\n\n      if (token.content.length === 0) {\n        continue\n      }\n\n      const style = [\n        token.color\n          ? `color: ${token.color};`\n          : '',\n        ...fontStyleRules\n          .filter(rule => ((token.fontStyle ?? 0) & rule.bit) === rule.bit)\n          .map(rule => rule.css),\n      ].join('')\n\n      highlighted.push({ from, to: offset, style })\n    }\n\n    // The newline that separates this line from the next one.\n    offset += 1\n  }\n\n  return highlighted\n}\n\n/**\n * The color scheme the editor renders for. The item follows the class based\n * theme shadcn uses: the `dark` class on `<html>` or `<body>` selects the dark\n * theme, its absence the light one. Pass `colorScheme` to force either one.\n */\nexport function getCodeEditorColorScheme(): CodeEditorColorScheme {\n  if (typeof document === 'undefined') {\n    return 'light'\n  }\n\n  const darkClass = document.documentElement.classList.contains('dark')\n    || document.body?.classList.contains('dark')\n\n  return darkClass ? 'dark' : 'light'\n}\n\n/** Calls the listener when the page class based theme changes. */\nexport function subscribeCodeEditorColorScheme(listener: () => void) {\n  if (typeof document === 'undefined') {\n    return () => {}\n  }\n\n  const observer = new MutationObserver(listener)\n  observer.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['class'],\n  })\n\n  if (document.body) {\n    observer.observe(document.body, {\n      attributes: true,\n      attributeFilter: ['class'],\n    })\n  }\n\n  return () => observer.disconnect()\n}\n",
      "type": "registry:lib",
      "target": "lib/blocove/code-editor-shiki.ts"
    },
    {
      "path": "src/registry/blocove/ui/code-editor/shiki.tsx",
      "content": "import type { Extension } from '@codemirror/state'\nimport type { DecorationSet, ViewUpdate } from '@codemirror/view'\nimport type { CodeEditorExtensionContext } from '@/lib/blocove/code-editor-extension'\nimport type { CodeEditorColorScheme } from '@/lib/blocove/code-editor-shiki'\nimport { StateEffect, StateField } from '@codemirror/state'\nimport { Decoration, EditorView, ViewPlugin } from '@codemirror/view'\nimport { defineCodeEditorExtension } from '@/lib/blocove/code-editor-extension'\nimport {\n  getCodeEditorColorScheme,\n  subscribeCodeEditorColorScheme,\n  tokenizeCodeEditor,\n} from '@/lib/blocove/code-editor-shiki'\n\nexport interface CodeEditorShikiProps {\n  /** Language used by shiki. Falls back to the language of the editor root. */\n  language?: string\n  /**\n   * Theme to render. `auto` follows the `dark` class on the page, like the rest\n   * of shadcn/ui.\n   */\n  colorScheme?: CodeEditorColorScheme | 'auto'\n  /** Debounce in milliseconds before the document is tokenized again. */\n  delay?: number\n  /** Documents longer than this many characters stay unhighlighted. */\n  maxLength?: number\n}\n\ninterface ShikiOptions {\n  language?: string\n  colorScheme: CodeEditorColorScheme | 'auto'\n  delay: number\n  maxLength: number\n}\n\nconst setHighlights = StateEffect.define<DecorationSet>()\n\nconst highlightField = StateField.define<DecorationSet>({\n  create: () => Decoration.none,\n  update(decorations, transaction) {\n    let next = decorations.map(transaction.changes)\n\n    for (const effect of transaction.effects) {\n      if (effect.is(setHighlights)) {\n        next = effect.value\n      }\n    }\n\n    return next\n  },\n  provide: field => EditorView.decorations.from(field),\n})\n\nclass ShikiHighlighter {\n  private timer: ReturnType<typeof setTimeout> | undefined\n  private generation = 0\n  private destroyed = false\n  private unsubscribe: () => void\n\n  constructor(\n    private readonly view: EditorView,\n    private readonly options: ShikiOptions,\n  ) {\n    this.unsubscribe = this.options.colorScheme === 'auto'\n      ? subscribeCodeEditorColorScheme(() => this.schedule())\n      : () => {}\n    this.schedule(0)\n  }\n\n  update(update: ViewUpdate) {\n    if (update.docChanged) {\n      this.schedule()\n    }\n  }\n\n  destroy() {\n    this.destroyed = true\n    this.unsubscribe()\n\n    if (this.timer) {\n      clearTimeout(this.timer)\n    }\n  }\n\n  private schedule(delay = this.options.delay) {\n    if (this.timer) {\n      clearTimeout(this.timer)\n    }\n\n    this.timer = setTimeout(() => {\n      this.timer = undefined\n      void this.highlight()\n    }, delay)\n  }\n\n  private async highlight() {\n    const generation = ++this.generation\n    const code = this.view.state.doc.toString()\n\n    if (!this.options.language || code.length > this.options.maxLength) {\n      this.apply(Decoration.none)\n      return\n    }\n\n    const tokens = await tokenizeCodeEditor(\n      code,\n      this.options.language,\n      this.options.colorScheme === 'auto'\n        ? getCodeEditorColorScheme()\n        : this.options.colorScheme,\n    )\n\n    // The document, the language or the color scheme changed while the\n    // tokenizer was running: the result is stale.\n    if (generation !== this.generation || this.destroyed) {\n      return\n    }\n\n    if (this.view.state.doc.toString() !== code) {\n      this.schedule()\n      return\n    }\n\n    this.apply(\n      tokens\n        ? Decoration.set(\n            tokens.map(token =>\n              Decoration.mark({\n                class: 'shiki-token',\n                attributes: { style: token.style },\n              }).range(token.from, token.to),\n            ),\n            true,\n          )\n        : Decoration.none,\n    )\n  }\n\n  private apply(decorations: DecorationSet) {\n    if (this.destroyed) {\n      return\n    }\n\n    this.view.dispatch({\n      effects: setHighlights.of(decorations),\n    })\n  }\n}\n\n/**\n * Syntax highlighting through shiki. The document is tokenized with the same\n * themes and grammars as the documentation code panels, so the editor colors\n * match the rest of the page.\n */\nexport const CodeEditorShiki = defineCodeEditorExtension<CodeEditorShikiProps>(\n  'shiki',\n  (props: CodeEditorShikiProps, context: CodeEditorExtensionContext): Extension[] => {\n    const language = props.language ?? context.language\n\n    return [\n      highlightField,\n      ViewPlugin.define(view => new ShikiHighlighter(view, {\n        language,\n        colorScheme: props.colorScheme ?? 'auto',\n        delay: props.delay ?? 120,\n        maxLength: props.maxLength ?? 150_000,\n      })),\n    ]\n  },\n)\n",
      "type": "registry:ui",
      "target": "components/blocove/code-editor/shiki.tsx"
    }
  ],
  "categories": [
    "code-editor",
    "highlight"
  ],
  "type": "registry:ui"
}