{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-lines",
  "title": "Code lines",
  "description": "The lines of a code block: coloured tokens, a gutter of line numbers, lines marked as highlighted, added or removed with the words they changed, the box they scroll in, which folds to its first lines and unfolds on the layout role, and the card and header they sit in.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/syntax.json",
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/fold.json",
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/code-lines.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport { useFoldMove } from '@/registry/lib/fold'\nimport { scrollRegionRingClassName, useScrollRegion } from '@/registry/lib/scroll'\nimport {\n  type CodeLanguage,\n  type CodeToken,\n  highlightCode,\n  holdColours,\n  languageName,\n  lineSet,\n  plainTokens,\n} from '@/registry/lib/syntax'\nimport {\n  type ComponentProps,\n  type CSSProperties,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The lines of a code block: coloured tokens, a gutter of line numbers, and\n * lines marked as highlighted, added or removed. The Code block frames them.\n */\n\n/** Lines by number from 1, as single lines and inclusive ranges: `[2, [5, 7]]`. */\ntype LineList = readonly (number | readonly [number, number])[]\n\ntype LineMark = 'highlighted' | 'added' | 'removed'\n\n/** One file of a Code block, or one package manager's command. */\ninterface CodeFile {\n  /** The tab's value; the title or the language when not given. */\n  value?: string\n  /** A file name, such as `button.tsx`, or a package manager. Without one, the header names the language, such as TypeScript, with no file icon. */\n  title?: string\n  /** What a screen reader calls the code, when the title doesn't set it apart from other code on the page. */\n  label?: string\n  code: string\n  language: CodeLanguage\n  /** The number of the first line, for an excerpt from further down a file. */\n  startLine?: number\n  highlighted?: LineList\n  added?: LineList\n  removed?: LineList\n  /** Lines worked out ahead with `highlightCode`, on a server, so the colours are there on the first paint. */\n  tokens?: CodeToken[][]\n}\n\ninterface CodeBlockProps {\n  files: CodeFile[]\n  /** The file shown, by value, when there are several. */\n  value?: string\n  defaultValue?: string\n  onValueChange?: (value: string) => void\n  lineNumbers?: boolean\n  /** Longer files show this many lines until expanded. */\n  collapsedLines?: number\n  expanded?: boolean\n  defaultExpanded?: boolean\n  onExpandedChange?: (expanded: boolean) => void\n  /** The tabs' name, for a screen reader: \"Package manager\". */\n  label?: string\n  className?: string\n}\n\n/** A file's tab value: its own, its title, or its language. */\nfunction fileValue(file: CodeFile) {\n  return file.value ?? file.title ?? file.language\n}\n\n/**\n * `code` as coloured lines. It is plain lines until the colours have loaded,\n * so the text is there on the first paint and nothing moves when they arrive.\n * When the code changes, as it does while it streams in, the lines that\n * haven't changed keep their colours until the new ones land, and one\n * highlight runs at a time, the next taking the code as it is by then.\n * `tokens` worked out ahead, on a server, skip the loading.\n */\nfunction useCodeTokens(\n  code: string,\n  language: CodeLanguage,\n  tokens?: CodeToken[][],\n): CodeToken[][] {\n  const plain = useMemo(() => plainTokens(code), [code])\n  const [loaded, setLoaded] = useState<{\n    code: string\n    language: CodeLanguage\n    lines: CodeToken[][]\n  }>()\n  const latest = useRef({ code, language })\n  const running = useRef(false)\n  const mounted = useRef(true)\n\n  useEffect(() => {\n    mounted.current = true\n    return () => {\n      mounted.current = false\n    }\n  }, [])\n\n  useEffect(() => {\n    latest.current = { code, language }\n    if (tokens || running.current) return\n    running.current = true\n    void (async () => {\n      let done: { code: string; language: CodeLanguage } | undefined\n      while (mounted.current && latest.current !== done) {\n        done = latest.current\n        const lines = await highlightCode(done.code, done.language).catch(() => undefined)\n        if (lines && mounted.current) setLoaded({ ...done, lines })\n      }\n      running.current = false\n    })()\n  }, [code, language, tokens])\n\n  const held = useMemo(\n    () => holdColours(plain, loaded?.language === language ? loaded.lines : undefined),\n    [plain, loaded, language],\n  )\n  if (tokens) return tokens\n  return loaded?.code === code && loaded.language === language ? loaded.lines : held\n}\n\n/** The mark of each line, by number from 1. A removed or added mark wins over a highlight. */\nfunction lineMarks({\n  highlighted,\n  added,\n  removed,\n}: {\n  highlighted?: LineList\n  added?: LineList\n  removed?: LineList\n}): (line: number) => LineMark | undefined {\n  const sets = {\n    removed: lineSet(removed),\n    added: lineSet(added),\n    highlighted: lineSet(highlighted),\n  }\n  return (line) =>\n    sets.removed.has(line)\n      ? 'removed'\n      : sets.added.has(line)\n        ? 'added'\n        : sets.highlighted.has(line)\n          ? 'highlighted'\n          : undefined\n}\n\n// A marked line's band is its colour over the surface; its bar runs down the start edge.\nconst lineMarkClassName =\n  \"relative before:pointer-events-none before:absolute before:inset-y-0 before:start-0 before:w-0.5 before:content-[''] data-[mark=added]:bg-[color-mix(in_oklab,var(--code-added)_14%,transparent)] data-[mark=added]:before:bg-(--code-added) data-[mark=highlighted]:bg-[color-mix(in_oklab,var(--primary)_9%,transparent)] data-[mark=highlighted]:before:bg-primary data-[mark=removed]:bg-[color-mix(in_oklab,var(--code-removed)_14%,transparent)] data-[mark=removed]:before:bg-(--code-removed) forced-colors:data-mark:before:bg-[CanvasText]\"\n\nconst SIGNS: Record<LineMark, string> = { added: '+', removed: '−', highlighted: '' }\n\n/** A stretch of a line's text, and whether the line kept it or changed it, such as a diff's words. */\ntype LineWord = { op: 'same' | 'added' | 'removed'; text: string }\n\n/** A token, or the part of one, and whether it sits in a word its line changed. */\ntype MarkedToken = CodeToken & { changed: boolean }\n\n/**\n * A line's tokens cut where its changed words start and end, so each piece\n * is either kept or changed. `words` spell the same line as `tokens` do;\n * where they run short, the rest is kept.\n */\nfunction markWords(\n  tokens: readonly CodeToken[],\n  words: readonly LineWord[],\n): MarkedToken[] {\n  // Where each changed stretch of the line starts and ends, in characters.\n  const stretches: [number, number][] = []\n  let at = 0\n  for (const word of words) {\n    if (word.op !== 'same') stretches.push([at, at + word.text.length])\n    at += word.text.length\n  }\n  const pieces: MarkedToken[] = []\n  let start = 0\n  for (const token of tokens) {\n    const end = start + token.content.length\n    let from = start\n    for (const [stretchStart, stretchEnd] of stretches) {\n      if (stretchEnd <= from || stretchStart >= end) continue\n      if (stretchStart > from) {\n        pieces.push({\n          ...token,\n          content: token.content.slice(from - start, stretchStart - start),\n          changed: false,\n        })\n        from = stretchStart\n      }\n      const to = Math.min(stretchEnd, end)\n      pieces.push({\n        ...token,\n        content: token.content.slice(from - start, to - start),\n        changed: true,\n      })\n      from = to\n    }\n    if (from < end)\n      pieces.push({\n        ...token,\n        content: token.content.slice(from - start),\n        changed: false,\n      })\n    start = end\n  }\n  return pieces\n}\n\n// A changed word inside an added or removed line: a deeper band of the line's colour.\nconst changedWordClassName =\n  'rounded-[2px] data-[mark=added]:bg-[color-mix(in_oklab,var(--code-added)_16%,transparent)] data-[mark=removed]:bg-[color-mix(in_oklab,var(--code-removed)_16%,transparent)] forced-colors:underline'\n\n/** One line: its number, its sign when it is added or removed, and its tokens, with the words it changed marked. */\nfunction CodeLine({\n  number,\n  mark,\n  tokens,\n  words,\n  lineNumbers,\n  signs,\n  className,\n  ...props\n}: ComponentProps<'span'> & {\n  /** Left out for a line the shown text doesn't number, such as a diff's removed line. */\n  number?: number\n  mark?: LineMark\n  tokens: CodeToken[]\n  /** The words an added or removed line kept and changed, from its partner on the other side. */\n  words?: readonly LineWord[]\n  lineNumbers: boolean\n  /** Whether the block has added or removed lines, so every line keeps a column for the sign. */\n  signs: boolean\n}) {\n  const pieces =\n    words && (mark === 'added' || mark === 'removed')\n      ? markWords(tokens, words)\n      : tokens.map((token) => ({ ...token, changed: false }))\n  return (\n    <span\n      data-slot='code-line'\n      data-line={number}\n      data-mark={mark}\n      className={cn('flex min-h-lh px-(--surface-padding)', lineMarkClassName, className)}\n      {...props}\n    >\n      {lineNumbers ? (\n        <span\n          aria-hidden\n          data-slot='code-line-number'\n          className='w-(--code-gutter) shrink-0 pe-4 text-end text-(--code-comment) tabular-nums select-none'\n        >\n          {number}\n        </span>\n      ) : null}\n      {signs ? (\n        <span\n          aria-hidden\n          data-slot='code-line-sign'\n          className='w-4 shrink-0 select-none data-[mark=added]:text-(--code-added) data-[mark=removed]:text-(--code-removed)'\n          data-mark={mark}\n        >\n          {mark ? SIGNS[mark] : ''}\n        </span>\n      ) : null}\n      <span className='flex-1 whitespace-pre'>\n        {pieces.map((token, index) => (\n          <span\n            key={index}\n            data-mark={token.changed ? mark : undefined}\n            // A changed word takes the text colour on its band: a token's own colour, such as a string's green, falls under contrast there.\n            style={token.color && !token.changed ? { color: token.color } : undefined}\n            className={cn(\n              token.italic && 'italic',\n              token.changed && changedWordClassName,\n            )}\n          >\n            {token.content}\n          </span>\n        ))}\n        {/* A marked line says so to a screen reader, which hears no colour. */}\n        {mark ? <span className='sr-only'>{` (${mark})`}</span> : null}\n      </span>\n    </span>\n  )\n}\n\n/** The gutter's width, in characters, for numbers up to `last`. */\nfunction gutterWidth(last: number) {\n  return `${String(last).length + 1}ch`\n}\n\n/**\n * Every line of a block, in a `<code>` as wide as its longest line, so a\n * marked line's band runs the whole width while it scrolls.\n */\nfunction CodeLines({\n  lines,\n  lineNumbers = false,\n  startLine = 1,\n  highlighted,\n  added,\n  removed,\n  className,\n  style,\n  ...props\n}: ComponentProps<'code'> & {\n  lines: CodeToken[][]\n  lineNumbers?: boolean\n  /** The number of the first line, for an excerpt from further down a file. */\n  startLine?: number\n  highlighted?: LineList\n  added?: LineList\n  removed?: LineList\n}) {\n  const markOf = lineMarks({ highlighted, added, removed })\n  const signs = Boolean(added?.length || removed?.length)\n  return (\n    <code\n      data-slot='code-lines'\n      className={cn('grid w-max min-w-full', className)}\n      style={\n        {\n          '--code-gutter': gutterWidth(startLine + lines.length - 1),\n          ...style,\n        } as CSSProperties\n      }\n      {...props}\n    >\n      {lines.map((tokens, index) => {\n        const number = startLine + index\n        return (\n          <CodeLine\n            key={index}\n            number={number}\n            mark={markOf(number)}\n            tokens={tokens}\n            lineNumbers={lineNumbers}\n            signs={signs}\n          />\n        )\n      })}\n    </code>\n  )\n}\n\n/**\n * The box a block's lines scroll in, on both axes, with a thin scrollbar.\n * While it scrolls it takes focus as a region named by `labelledBy`'s\n * element, or `label`. Collapsed, it shows its first `collapsedLines` lines\n * and moves to its whole height on `layout` as it expands, and back.\n */\nfunction CodeScroller({\n  label,\n  labelledBy,\n  collapsedLines,\n  collapsed = false,\n  className,\n  style,\n  children,\n  ...props\n}: ComponentProps<'pre'> & {\n  label: string\n  labelledBy?: string\n  /** How many lines show while collapsed. */\n  collapsedLines?: number\n  collapsed?: boolean\n}) {\n  const ref = useRef<HTMLPreElement>(null)\n  const folded = collapsed && collapsedLines !== undefined\n  // Folded, it scrolls only sideways, so it takes focus only when its lines are wider than it.\n  const region = useScrollRegion(ref, {\n    axis: folded ? 'x' : 'both',\n    labelledBy: () => labelledBy,\n  })\n  useFoldMove(ref, folded)\n\n  return (\n    // The box draws the region's focus ring over the lines, which would cover one of the scroller's own.\n    <div\n      data-slot='code-scroller-frame'\n      className={cn('min-w-0 rounded-[inherit]', scrollRegionRingClassName)}\n    >\n      <pre\n        ref={ref}\n        data-slot='code-scroller'\n        data-fold={folded ? '' : undefined}\n        dir='ltr'\n        {...region}\n        aria-label={region && !labelledBy ? label : undefined}\n        className={cn(\n          'scrollbar-thin max-h-(--code-block-max-height) overflow-auto py-(--surface-padding) font-mono text-[0.8125rem] leading-6 focus-visible:outline-hidden',\n          // Folded, its height is its lines' and its padding's, and it scrolls only sideways.\n          // `data-folded` comes once a fold has finished moving, so the cap never cuts the move short.\n          'data-folded:max-h-[calc(var(--code-collapsed-lines)*1lh+var(--surface-padding)*2)] data-folded:overflow-y-hidden data-moving:overflow-y-hidden',\n          // The last lines fade while it is folded, to say there are more. The fade's height is a\n          // registered property (code-css.ts), so it grows and shrinks with the box.\n          '[mask-image:linear-gradient(to_top,transparent,black_var(--code-fade,0px))] data-fold:[--code-fade:2.5rem]',\n          'rounded-[inherit] transition-[height,--code-fade] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n          className,\n        )}\n        style={\n          collapsedLines === undefined\n            ? style\n            : ({ '--code-collapsed-lines': collapsedLines, ...style } as CSSProperties)\n        }\n        {...props}\n      >\n        {children}\n      </pre>\n    </div>\n  )\n}\n\n/** Lines past the collapsed ones that aren't worth hiding: showing them costs less than a click. */\nconst COLLAPSE_SLACK = 3\n\n/** Whether this many lines fold to their first `collapsedLines`. */\nfunction collapses(lineCount: number, collapsedLines: number | undefined) {\n  return collapsedLines !== undefined && lineCount > collapsedLines + COLLAPSE_SLACK\n}\n\n/**\n * The footer of folded code: Show all, or Show fewer once it is open. Named\n * after its file, so a page of several says which one each opens.\n */\nfunction CodeFoldButton({\n  expanded,\n  lines,\n  controls,\n  file,\n  onToggle,\n}: {\n  expanded: boolean\n  /** How many lines it shows open. */\n  lines: number\n  /** The id of the box the lines scroll in. */\n  controls: string\n  file?: string\n  onToggle: () => void\n}) {\n  const words = expanded ? 'Show fewer lines' : `Show all ${lines} lines`\n  return (\n    <div data-slot='code-fold' className='border-t p-1'>\n      <Button\n        variant='ghost'\n        size='sm'\n        aria-expanded={expanded}\n        aria-controls={controls}\n        aria-label={file === undefined ? undefined : `${words} of ${file}`}\n        onClick={onToggle}\n        className='text-muted-foreground hover:text-foreground w-full'\n      >\n        <IconPlaceholder\n          lucide='ChevronDownIcon'\n          tabler='IconChevronDown'\n          hugeicons='ArrowDown01Icon'\n          phosphor='CaretDownIcon'\n          remixicon='RiArrowDownSLine'\n          aria-hidden\n          data-icon='inline-start'\n          className={cn(\n            'transition-[rotate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n            expanded && 'rotate-180',\n          )}\n        />\n        {words}\n      </Button>\n    </div>\n  )\n}\n\n// The card code sits in, and its header: what the Code block and the Diff share.\nconst codeCardClassName =\n  'bg-card text-card-foreground flex min-w-0 flex-col overflow-clip rounded-(--surface-radius) border text-sm'\nconst codeHeaderClassName =\n  'flex min-h-(--control-height-lg) min-w-0 items-center gap-2 border-b ps-(--surface-padding) pe-1.5'\n\n/** What a code card's header names: a file with its icon, or else the language. */\nfunction CodeTitle({\n  title,\n  language,\n  id,\n}: {\n  title?: string\n  language: CodeLanguage\n  id?: string\n}) {\n  return (\n    <>\n      {title !== undefined ? (\n        <IconPlaceholder\n          lucide='FileCodeIcon'\n          tabler='IconFileCode'\n          hugeicons='FileScriptIcon'\n          phosphor='FileCodeIcon'\n          remixicon='RiFileCodeLine'\n          aria-hidden\n          className='text-muted-foreground size-4 shrink-0'\n        />\n      ) : null}\n      <CutTooltip\n        render={\n          <span\n            id={id}\n            data-cut\n            dir={title !== undefined ? undefined : 'auto'}\n            className={cn(\n              'min-w-0 flex-1 truncate text-xs',\n              // A file's path is cut from its start, so its name stays.\n              title !== undefined\n                ? 'text-end font-mono [direction:rtl] rtl:text-start'\n                : 'text-muted-foreground font-medium',\n            )}\n          >\n            {title !== undefined ? <bdi dir='ltr'>{title}</bdi> : languageName(language)}\n          </span>\n        }\n      />\n    </>\n  )\n}\n\nexport {\n  CodeFoldButton,\n  collapses,\n  CodeLine,\n  CodeTitle,\n  codeCardClassName,\n  codeHeaderClassName,\n  CodeLines,\n  markWords,\n  CodeScroller,\n  fileValue,\n  gutterWidth,\n  lineMarks,\n  useCodeTokens,\n}\nexport type { CodeBlockProps, CodeFile, LineList, LineMark, MarkedToken }\n",
      "type": "registry:lib",
      "target": "@lib/code-lines.tsx"
    }
  ],
  "type": "registry:lib"
}