{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "highlighted-code",
  "title": "Highlighted Code",
  "description": "Code in a code block with copy, highlighted with Shiki in the theme’s own colours: syntax muted, values in the chart colour, and any text you name marked, such as a key to check. It highlights code as a model streams it.",
  "dependencies": [
    "shiki@^4.5.0"
  ],
  "registryDependencies": [
    "code-block"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/highlighted-code.tsx",
      "content": "'use client'\n\nimport { type ComponentProps, type ReactNode, useEffect, useMemo, useState } from 'react'\nimport {\n  createHighlighterCore,\n  type GrammarState,\n  type HighlighterCore,\n  type ThemeRegistration,\n} from 'shiki/core'\nimport { createJavaScriptRegexEngine } from 'shiki/engine/javascript'\n\nimport {\n  CodeBlock,\n  CodeBlockActions,\n  CodeBlockContent,\n  CodeBlockCopyButton,\n  CodeBlockFooter,\n  CodeBlockHeader,\n  CodeBlockLine,\n  CodeBlockTitle,\n} from '@/components/ui/code-block'\n\nimport { cn } from '@/lib/utils'\n\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\ntype Language = keyof typeof languages\n\nconst aliases: Record<string, Language> = {\n  js: 'javascript',\n  json5: 'json',\n  jsonc: 'json',\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 muted = 'var(--color-muted-foreground)'\nconst text = 'var(--color-foreground)'\nconst value = 'var(--code-value)'\n\nconst theme: ThemeRegistration = {\n  name: 'dashboardblocks',\n  type: 'light',\n  fg: text,\n  bg: 'transparent',\n  settings: [\n    { settings: { foreground: text } },\n    {\n      scope: ['comment', 'punctuation.definition.comment'],\n      settings: { foreground: muted, fontStyle: 'italic' },\n    },\n    {\n      scope: [\n        'keyword',\n        'storage',\n        'punctuation',\n        'meta.brace',\n        'entity.other.attribute-name',\n        'constant.other.option',\n        'variable.parameter.option',\n        'markup.heading',\n        'markup.list',\n      ],\n      settings: { foreground: muted },\n    },\n    {\n      scope: [\n        'string',\n        'constant.numeric',\n        'constant.language',\n        'constant.character',\n        'support.constant',\n        'markup.inline.raw',\n        'markup.inserted',\n      ],\n      settings: { foreground: value },\n    },\n    {\n      scope: ['entity.name', 'support.type.property-name', 'meta.object-literal.key'],\n      settings: { foreground: text },\n    },\n    {\n      scope: ['markup.deleted'],\n      settings: { foreground: 'var(--color-destructive)' },\n    },\n  ],\n}\n\nlet highlighter: Promise<HighlighterCore> | undefined\n\nfunction getHighlighter() {\n  highlighter ??= createHighlighterCore({\n    themes: [theme],\n    langs: [],\n    engine: createJavaScriptRegexEngine({ forgiving: true }),\n  })\n  return highlighter\n}\n\nfunction getLanguage(language: string): Language | null {\n  const name = language.toLowerCase()\n  if (Object.hasOwn(languages, name)) return name as Language\n  return Object.hasOwn(aliases, name) ? aliases[name] : null\n}\n\ninterface Token {\n  content: string\n  color?: string\n  italic?: boolean\n}\n\ninterface Tokenizer {\n  tokenize: (\n    code: string,\n    state?: GrammarState,\n  ) => { lines: Token[][]; state?: GrammarState }\n}\n\nasync function loadTokenizer(language: string): Promise<Tokenizer | null> {\n  const lang = getLanguage(language)\n  if (!lang) return null\n  const shiki = await getHighlighter()\n  if (!shiki.getLoadedLanguages().includes(lang)) {\n    await shiki.loadLanguage(languages[lang])\n  }\n  return {\n    tokenize(code, state) {\n      const tokens = shiki.codeToTokens(code, {\n        lang,\n        theme: 'dashboardblocks',\n        grammarState: state,\n        tokenizeTimeLimit: 2000,\n      }).tokens\n      return {\n        lines: tokens.map((line) =>\n          line.map((token) => ({\n            content: token.content,\n            color: token.color,\n            italic: ((token.fontStyle ?? 0) & 1) === 1,\n          })),\n        ),\n        state: shiki.getLastGrammarState(tokens),\n      }\n    },\n  }\n}\n\nfunction useTokenLines(source: string, language: string) {\n  const code = source.endsWith('\\n') ? source.slice(0, -1) : source\n  const [loaded, setLoaded] = useState<{\n    language: string\n    tokenizer: Tokenizer | null\n  } | null>(null)\n  const tokenizer = loaded?.language === language ? loaded.tokenizer : null\n\n  useEffect(() => {\n    let cancelled = false\n    loadTokenizer(language)\n      .then((next) => {\n        if (!cancelled) setLoaded({ language, tokenizer: next })\n      })\n      .catch(() => {})\n    return () => {\n      cancelled = true\n    }\n  }, [language])\n\n  const [done, setDone] = useState<{\n    tokenizer: Tokenizer | null\n    text: string\n    lines: Token[][]\n    state?: GrammarState\n  }>({ tokenizer: null, text: '', lines: [] })\n\n  let next = done\n  if (next.tokenizer !== tokenizer || !code.startsWith(next.text)) {\n    next = { tokenizer, text: '', lines: [] }\n  }\n  const end = code.lastIndexOf('\\n') + 1\n  if (tokenizer && end > next.text.length) {\n    const result = tokenizer.tokenize(code.slice(next.text.length, end - 1), next.state)\n    next = {\n      tokenizer,\n      text: code.slice(0, end),\n      lines: [...next.lines, ...result.lines],\n      state: result.state,\n    }\n  }\n  if (next !== done) setDone(next)\n\n  const tail = code.slice(end)\n  return useMemo(() => {\n    if (!tokenizer) return code.split('\\n').map((line) => [{ content: line }])\n    return [...next.lines, tokenizer.tokenize(tail, next.state).lines[0] ?? []]\n  }, [code, tokenizer, next, tail])\n}\n\nfunction markRanges(line: string, marks: readonly string[]) {\n  const ranges: [number, number][] = []\n  for (const mark of marks) {\n    if (!mark) continue\n    let at = line.indexOf(mark)\n    while (at !== -1) {\n      ranges.push([at, at + mark.length])\n      at = line.indexOf(mark, at + mark.length)\n    }\n  }\n  ranges.sort((a, b) => a[0] - b[0])\n  const merged: [number, number][] = []\n  for (const [from, to] of ranges) {\n    const last = merged.at(-1)\n    if (last && from <= last[1]) last[1] = Math.max(last[1], to)\n    else merged.push([from, to])\n  }\n  return merged\n}\n\nfunction renderLine(tokens: Token[], marks: readonly string[]): ReactNode[] {\n  const ranges = marks.length\n    ? markRanges(tokens.map((token) => token.content).join(''), marks)\n    : []\n  const pieces: { node: ReactNode; range: number }[] = []\n  let offset = 0\n  tokens.forEach((token, index) => {\n    const style = token.color\n      ? { color: token.color, fontStyle: token.italic ? 'italic' : undefined }\n      : undefined\n    const start = offset\n    const end = offset + token.content.length\n    offset = end\n    const cuts = new Set([start, end])\n    for (const [from, to] of ranges) {\n      if (from > start && from < end) cuts.add(from)\n      if (to > start && to < end) cuts.add(to)\n    }\n    const points = [...cuts].sort((a, b) => a - b)\n    for (let i = 0; i < points.length - 1; i++) {\n      pieces.push({\n        node: (\n          <span key={`${index}-${i}`} style={style}>\n            {token.content.slice(points[i] - start, points[i + 1] - start)}\n          </span>\n        ),\n        range: ranges.findIndex(([from, to]) => points[i] >= from && points[i + 1] <= to),\n      })\n    }\n  })\n  const nodes: ReactNode[] = []\n  for (let i = 0; i < pieces.length; i++) {\n    const { range } = pieces[i]\n    if (range === -1) {\n      nodes.push(pieces[i].node)\n      continue\n    }\n    const marked: ReactNode[] = []\n    while (i < pieces.length && pieces[i].range === range) marked.push(pieces[i++].node)\n    i--\n    nodes.push(\n      <mark\n        key={`mark-${range}`}\n        data-slot='highlighted-code-mark'\n        className='bg-chart-2/10 dark:bg-chart-2/15 ring-chart-2/35 -mx-0.5 box-decoration-clone rounded-sm px-0.5 text-inherit ring-1 ring-inset'\n      >\n        {marked}\n      </mark>,\n    )\n  }\n  return nodes\n}\n\ninterface HighlightedCodeProps extends Omit<\n  ComponentProps<typeof CodeBlock>,\n  'children' | 'onCopy' | 'title'\n> {\n  /** The code, shown and copied exactly as written. It may grow while a model streams it. */\n  code: string\n  /** `tsx`, `bash`, `json` and the other languages this file lists, or an alias such as `ts` or `sh`. Any other value shows plain text. */\n  language?: string\n  /** A file name or what the code is, such as `app/layout.tsx` or `Payload`. Without one, the copy button floats over the code. */\n  title?: ReactNode\n  /** The copy button's accessible name, such as `Copy payload`. */\n  copyLabel?: string\n  /** Text to pick out wherever it appears, such as the key the reader must check is theirs. */\n  mark?: readonly string[]\n  /** Marks each line, by its index, as added or removed, as a diff shows it. Copy leaves the removed lines out. */\n  lineChanges?: readonly ('added' | 'removed' | undefined)[]\n  /** Shows the copy button. Turn it off where the page has its own Copy. @default true */\n  copyButton?: boolean\n  /** Wraps long lines instead of scrolling them sideways. */\n  wrap?: boolean\n  /** Names the code for screen readers and makes it a region. */\n  label?: string\n  /** Shown under the code, inside its frame, such as what happened after running it. */\n  footer?: ReactNode\n  /** Called when the person presses Copy, or copies text they selected in the code. */\n  onCopy?: () => void\n}\n\nfunction HighlightedCode({\n  code,\n  language = '',\n  title,\n  copyLabel = 'Copy code',\n  mark = [],\n  lineChanges,\n  copyButton = true,\n  wrap = false,\n  label,\n  footer,\n  onCopy,\n  size = 'sm',\n  className,\n  ...props\n}: HighlightedCodeProps) {\n  const lines = useTokenLines(code, language)\n  const copy = copyButton && (\n    <CodeBlockActions>\n      <CodeBlockCopyButton\n        aria-label={copyLabel}\n        onClick={onCopy}\n        value={\n          lineChanges\n            ? code\n                .split('\\n')\n                .filter((_, index) => lineChanges[index] !== 'removed')\n                .join('\\n')\n            : code\n        }\n      />\n    </CodeBlockActions>\n  )\n  return (\n    <CodeBlock\n      data-slot='highlighted-code'\n      size={size}\n      className={cn(\n        '[--code-value:var(--color-chart-3)] dark:[--code-value:var(--color-chart-1)]',\n        className,\n      )}\n      {...props}\n    >\n      {title ? (\n        <CodeBlockHeader>\n          <CodeBlockTitle>{title}</CodeBlockTitle>\n          {copy}\n        </CodeBlockHeader>\n      ) : (\n        copy\n      )}\n      <CodeBlockContent\n        onCopy={onCopy}\n        wrap={wrap}\n        className='mask-none [scrollbar-width:thin] data-wrap:mask-none data-wrap:wrap-anywhere'\n        role={label ? 'region' : undefined}\n        aria-label={label}\n      >\n        {lines.map((line, index) => (\n          <CodeBlockLine key={index} variant={lineChanges?.[index]}>\n            {renderLine(line, mark)}\n          </CodeBlockLine>\n        ))}\n      </CodeBlockContent>\n      {footer && <CodeBlockFooter>{footer}</CodeBlockFooter>}\n    </CodeBlock>\n  )\n}\n\nexport { HighlightedCode }\nexport type { HighlightedCodeProps }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/highlighted-code.tsx"
    }
  ],
  "type": "registry:component"
}
