{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "diff",
  "title": "Diff",
  "description": "A change shown as a diff and accepted or rejected piece by piece: Code diff marks the lines and the words inside them, Text diff the words in running prose, and both follow an after that still arrives.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/animated-number.json",
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/code-lines.json",
    "https://kinoui.com/r/controllable.json",
    "https://kinoui.com/r/diff-math.json",
    "https://kinoui.com/r/diff-review.json",
    "https://kinoui.com/r/flow.json",
    "https://kinoui.com/r/fold.json",
    "https://kinoui.com/r/number-format.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/syntax.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/diff.tsx",
      "content": "'use client'\n\nimport { AnimatedNumber } from '@/registry/components/kino/animated-number'\nimport { Button } from '@/registry/components/kino/button'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport {\n  CodeFoldButton,\n  CodeLine,\n  CodeScroller,\n  CodeTitle,\n  collapses,\n  codeCardClassName,\n  codeHeaderClassName,\n  gutterWidth,\n  useCodeTokens,\n} from '@/registry/lib/code-lines'\nimport { useControllable } from '@/registry/lib/controllable'\nimport {\n  type CodeDiff as CodeDiffResult,\n  diffCode,\n  diffText,\n  type Resolution,\n  type Resolved,\n  wordsOf,\n} from '@/registry/lib/diff-math'\nimport { type DiffReviewDetails, diffReview } from '@/registry/lib/diff-review'\nimport { flowItemClassName, useFlow } from '@/registry/lib/flow'\nimport { bringTopBack } from '@/registry/lib/fold'\nimport { numberFormatter } from '@/registry/lib/number-format'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { type CodeLanguage, languageName } from '@/registry/lib/syntax'\nimport { type PartProps, usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport {\n  type CSSProperties,\n  type ReactNode,\n  useCallback,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * A change shown as a diff, with each piece accepted or rejected where it\n * sits. Code diff shows lines in a gutter, removed above added, with the\n * words a line changed marked inside it; Text diff shows words in running\n * prose, struck out and underlined. A decided change takes its side: the\n * other one leaves and what follows closes the gap, on `layout`.\n */\n\ntype DiffProps = Omit<PartProps<'div'>, 'className' | 'children'> & {\n  before: string\n  after: string\n  /** Whether after has all arrived. Until it has, before past what after has reached stays as it is. */\n  complete?: boolean\n  /** What was decided about each change, by id. */\n  resolved?: Resolved\n  defaultResolved?: Resolved\n  /** Called when changes are accepted or rejected, with the ones decided in `details.ids`. Without it, the diff only shows the changes. */\n  onResolvedChange?: (resolved: Resolved, details: DiffReviewDetails) => void\n  className?: string\n}\n\nconst integer = numberFormatter(undefined, { maximumFractionDigits: 0 })\n\nfunction AcceptIcon() {\n  return (\n    <IconPlaceholder\n      lucide='CheckIcon'\n      tabler='IconCheck'\n      hugeicons='Tick02Icon'\n      phosphor='CheckIcon'\n      remixicon='RiCheckLine'\n      aria-hidden\n    />\n  )\n}\n\nfunction RejectIcon() {\n  return (\n    <IconPlaceholder\n      lucide='XIcon'\n      tabler='IconX'\n      hugeicons='Cancel01Icon'\n      phosphor='XIcon'\n      remixicon='RiCloseLine'\n      aria-hidden\n    />\n  )\n}\n\n// The group a review sits in takes focus once nothing is left to decide, with the controls' ring.\nconst reviewFocusClassName =\n  'focus-visible:outline-hidden focus-visible:ring-3 focus-visible:ring-ring/50 forced-colors:focus-visible:outline-2'\n\n/**\n * The review both views share: the primitive, an announcement of each\n * decision, and focus that moves on to the same button of the next change\n * still open, or to the group once none follows.\n */\nfunction useReview(\n  props: Pick<\n    DiffProps,\n    'resolved' | 'defaultResolved' | 'onResolvedChange' | 'complete'\n  >,\n  ids: readonly string[],\n  growing: readonly string[],\n  /** What each change is called as the diff reads with `resolved`, such as \"change at line 8\". */\n  namesOf: (resolved: Resolved) => ReadonlyMap<string, string>,\n  /** The buyer's ref on the root, beside the review's own. */\n  forwarded: PartProps<'div'>['ref'],\n) {\n  // The root as state, so the buyer's ref and the review's own merge without reading a ref in render.\n  const [root, setRoot] = useState<HTMLDivElement | null>(null)\n  const ownRef = useMemo(() => mergeRefs(forwarded, setRoot), [forwarded])\n  const moveFocus = useRef<{ after: string; kind: Resolution } | null>(null)\n  const review = usePrimitive(diffReview, {\n    resolved: props.resolved,\n    defaultResolved: props.defaultResolved,\n    onResolvedChange: (resolved: Resolved, details: DiffReviewDetails) => {\n      props.onResolvedChange?.(resolved, details)\n      if (details.canceled) return\n      const word = details.resolution === 'accepted' ? 'Accepted' : 'Rejected'\n      announce(\n        details.ids.length === 1\n          ? `${word} ${namesOf(review.instance.get().resolved).get(details.ids[0]) ?? 'change'}`\n          : `${word} ${integer.format(details.ids.length)} changes`,\n      )\n      const last = details.ids.at(-1)\n      if (last !== undefined && root?.contains(document.activeElement)) {\n        moveFocus.current = { after: last, kind: details.resolution }\n      }\n    },\n    changes: ids,\n    namesOf,\n    growing,\n    complete: props.complete ?? true,\n    readOnly: !props.onResolvedChange,\n  })\n\n  // Once the decision has rendered, focus moves on, never back to a change already passed.\n  useLayoutEffect(() => {\n    const move = moveFocus.current\n    if (move === null || !root) return\n    moveFocus.current = null\n    const from = ids.indexOf(move.after)\n    const attribute = move.kind === 'accepted' ? 'data-diff-accept' : 'data-diff-reject'\n    const target = review.api\n      .open()\n      .filter((id) => ids.indexOf(id) > from)\n      .map((id) =>\n        root.querySelector<HTMLButtonElement>(`[${attribute}=\"${CSS.escape(id)}\"]`),\n      )\n      .find((button) => button && !button.disabled)\n    ;(target ?? root).focus({ preventScroll: target === undefined })\n  })\n\n  return { review, root, rootRef: ownRef }\n}\n\n/** Accept and Reject for one change, named after where it is. */\nfunction ChangeButtons({\n  id,\n  name,\n  disabled,\n  onDecide,\n  compact = false,\n}: {\n  id: string\n  /** Where the change is: \"change at line 12\". */\n  name: string\n  disabled: boolean\n  onDecide: (resolution: Resolution, event: Event) => void\n  /** Icons only, for a change inside prose. */\n  compact?: boolean\n}) {\n  return (\n    <>\n      <Button\n        variant='ghost'\n        size={compact ? 'icon-xs' : 'xs'}\n        aria-label={`Reject ${name}`}\n        data-diff-reject={id}\n        disabled={disabled}\n        onClick={(event) => onDecide('rejected', event.nativeEvent)}\n      >\n        {compact ? <RejectIcon /> : 'Reject'}\n      </Button>\n      <Button\n        variant={compact ? 'ghost' : 'secondary'}\n        size={compact ? 'icon-xs' : 'xs'}\n        aria-label={`Accept ${name}`}\n        data-diff-accept={id}\n        disabled={disabled}\n        onClick={(event) => onDecide('accepted', event.nativeEvent)}\n      >\n        {compact ? <AcceptIcon /> : 'Accept'}\n      </Button>\n    </>\n  )\n}\n\n/** Accept all and Reject all, with how many changes they decide; only while more than one is open. */\nfunction AllButtons({\n  open,\n  disabled,\n  onAll,\n}: {\n  open: number\n  disabled: boolean\n  onAll: (resolution: Resolution, event: Event) => void\n}) {\n  if (open < 2) return null\n  const count = `${integer.format(open)} changes`\n  return (\n    <div className='flex shrink-0 gap-0.5 @max-sm/diff:basis-full @max-sm/diff:justify-end'>\n      <Button\n        variant='ghost'\n        size='xs'\n        aria-label={`Reject all ${count}`}\n        disabled={disabled}\n        onClick={(event) => onAll('rejected', event.nativeEvent)}\n      >\n        Reject all\n      </Button>\n      <Button\n        variant='secondary'\n        size='xs'\n        aria-label={`Accept all ${count}`}\n        disabled={disabled}\n        onClick={(event) => onAll('accepted', event.nativeEvent)}\n      >\n        Accept all\n      </Button>\n    </div>\n  )\n}\n\n/** Lines added and removed, as signs a person reads and words a screen reader hears. */\nfunction Counts({ added, removed }: { added: number; removed: number }) {\n  return (\n    <span dir='ltr' className='flex shrink-0 gap-1.5 font-mono text-xs tabular-nums'>\n      <span className='text-(--code-added)'>\n        <span aria-hidden>+</span>\n        <AnimatedNumber value={added} />\n        <span className='sr-only'> added,</span>\n      </span>\n      <span className='text-(--code-removed)'>\n        <span aria-hidden>−</span>\n        <AnimatedNumber value={removed} />\n        <span className='sr-only'> removed</span>\n      </span>\n    </span>\n  )\n}\n\n/** A Code diff's header: the file, the lines it adds and removes, and what decides them all. */\nfunction CodeDiffHeader({\n  title,\n  language,\n  open,\n  children,\n}: {\n  title?: string\n  language: CodeLanguage\n  /** The changes still open, whose lines it counts. */\n  open: readonly CodeDiffResult['changes'][number][]\n  children?: ReactNode\n}) {\n  const added = open.reduce((lines, change) => lines + change.added.length, 0)\n  const removed = open.reduce((lines, change) => lines + change.removed.length, 0)\n  return (\n    // Below a phone's width the buttons take a row of their own, so the file keeps its name.\n    <div\n      data-slot='diff-header'\n      className={cn(codeHeaderClassName, '@max-sm/diff:flex-wrap @max-sm/diff:py-1.5')}\n    >\n      <CodeTitle title={title} language={language} />\n      {added + removed > 0 ? <Counts added={added} removed={removed} /> : null}\n      {children}\n    </div>\n  )\n}\n\n/** How many of a Text diff's changes are still open: for its foot, in the words of the page around it. */\nfunction ReviewStatus({\n  open,\n  total,\n  complete,\n}: {\n  open: number\n  total: number\n  complete: boolean\n}) {\n  return (\n    <span dir='auto' className='text-muted-foreground min-w-0 text-xs tabular-nums'>\n      <bdi>\n        {total === 0 && !complete\n          ? 'Changes arriving'\n          : open === 0\n            ? 'All changes decided'\n            : `${integer.format(open)} of ${integer.format(total)} ${total === 1 ? 'change' : 'changes'} to review`}\n      </bdi>\n    </span>\n  )\n}\n\n/**\n * Each Code diff change's name, by the line it starts on in the gutter as\n * the code reads now: kept and pending lines count, and a change counts the\n * side it shows (its added lines while open). A change's name follows it,\n * so what a screen reader or an agent hears matches the number a person sees.\n */\nfunction codeChangeNames(\n  diff: CodeDiffResult,\n  resolved: Resolved,\n  { startLine = 1, file }: { startLine?: number; file?: string } = {},\n) {\n  const names = new Map<string, string>()\n  const where = file === undefined ? '' : ` in ${file}`\n  let line = startLine\n  for (const row of diff.rows) {\n    if (row.kind !== 'change') {\n      line++\n      continue\n    }\n    names.set(row.change.id, `change at line ${integer.format(line)}${where}`)\n    line +=\n      resolved[row.change.id] === 'rejected'\n        ? row.change.removed.length\n        : row.change.added.length\n  }\n  return names\n}\n\n/** Each Text diff change's name, by its place among them. */\nfunction textChangeNames(ids: readonly string[]) {\n  return new Map(\n    ids.map((id, index) => [\n      id,\n      `change ${integer.format(index + 1)} of ${integer.format(ids.length)}`,\n    ]),\n  )\n}\n\n/** A frame whose height follows the changes as they come and go, and takes each chunk's at once while after arrives. */\nconst frameClassName =\n  'overflow-clip transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none data-arriving:transition-none'\n\n// A line's band and bar fade as its change is decided, held at their end once there.\nconst lineFadeClassName =\n  'transition-[background-color] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing) before:transition-[background-color] before:duration-(--motion-layout-duration) before:ease-(--motion-layout-fade-easing)'\n\n// Before that after hasn't reached: plain text in the muted colour, with no syntax colours, which would fall under contrast.\nconst pendingLineClassName = 'text-muted-foreground'\n\n// A change in prose: what leaves is struck through, what arrives underlined, each on its own tint.\nconst removedWordClassName =\n  'bg-[color-mix(in_oklab,var(--code-removed)_14%,transparent)] text-[color-mix(in_oklch,var(--code-removed),var(--foreground)_35%)] line-through decoration-[color-mix(in_oklab,var(--code-removed)_70%,transparent)] forced-colors:decoration-[CanvasText]'\nconst addedWordClassName =\n  'bg-[color-mix(in_oklab,var(--code-added)_14%,transparent)] underline decoration-(--code-added) decoration-2 underline-offset-3 forced-colors:decoration-[CanvasText]'\n\n// A word's tint and line fade as its change is decided; the item around it moves.\nconst wordFadeClassName =\n  'transition-[background-color,text-decoration-color,color] duration-(--motion-layout-duration) ease-(--motion-layout-fade-easing)'\n\n/**\n * A piece of prose before it is laid out as items: a stretch of words with\n * its look, or something set among them.\n */\ntype ProsePiece =\n  | {\n      kind: 'words'\n      text: string\n      /** Where the text starts in its side, for keys that hold as decisions change. */\n      at: number\n      side: 'b' | 'a'\n      className?: string\n      /** Spaces inside it are items, so a change's tint runs unbroken across them. */\n      spaces?: boolean\n      /** Shown to the eye only, when `said` reads it out whole. */\n      hidden?: boolean\n    }\n  /**\n   * Something set among the words: a change's buttons, text only a screen\n   * reader hears, or the space between a change's sides, which a mark after\n   * it doesn't reach past.\n   */\n  | { kind: 'beside' | 'said' | 'gap'; key: string; node: ReactNode }\n\n// A word or a mark alone, which reads with the word before it.\nconst isMark = (token: string) => token.trim() !== '' && !/[\\p{L}\\p{N}]/u.test(token)\n\n/**\n * Prose as items that flow, for `useFlow`'s `[data-diff-word]`: each word an\n * inline block, white space between kept words left as text. A mark that\n * follows a word sits in the word's item, past anything set among them, so a\n * line never starts with a full stop.\n */\nfunction proseItems(\n  pieces: readonly ProsePiece[],\n  /** While after arrives: every item lands in place, since a glide every chunk would never settle. */\n  held: boolean,\n): ReactNode[] {\n  type Token = { key: string; text: string; className?: string; hidden?: boolean }\n  type Item =\n    | { kind: 'word'; tokens: Token[]; beside?: { key: string; node: ReactNode } }\n    | { kind: 'space'; text: string; key: string; className?: string; spaced: boolean }\n    | { kind: 'node'; key: string; node: ReactNode; joins: boolean }\n  const items: Item[] = []\n  for (const piece of pieces) {\n    // A change's buttons sit in its last word's item, past the spaces after it, so they never start a line alone.\n    if (piece.kind === 'beside') {\n      let back = items.length - 1\n      while (\n        back >= 0 &&\n        (items[back].kind === 'space' ||\n          (items[back].kind === 'node' && (items[back] as { joins: boolean }).joins))\n      )\n        back--\n      const word = items[back]\n      if (word?.kind === 'word' && word.beside === undefined) {\n        word.beside = { key: piece.key, node: piece.node }\n        continue\n      }\n      items.push({\n        kind: 'node',\n        key: piece.key,\n        joins: true,\n        node: (\n          <span\n            key={piece.key}\n            data-diff-word=''\n            data-diff-key={piece.key}\n            data-flow-held={held ? '' : undefined}\n            className={cn(flowItemClassName, besideClassName)}\n          >\n            {piece.node}\n          </span>\n        ),\n      })\n      continue\n    }\n    if (piece.kind !== 'words') {\n      items.push({\n        kind: 'node',\n        key: piece.key,\n        node: piece.node,\n        joins: piece.kind !== 'gap',\n      })\n      continue\n    }\n    let at = piece.at\n    const words = wordsOf(piece.text)\n    for (const [index, text] of words.entries()) {\n      const token = {\n        key: `${piece.side}${at}`,\n        text,\n        className: piece.className,\n        hidden: piece.hidden,\n      }\n      at += text.length\n      if (text.trim() === '') {\n        items.push({\n          kind: 'space',\n          text,\n          key: token.key,\n          // Only a space between two of its words takes a change's look: one at its edge would strike or tint past them.\n          className:\n            index === 0 || index === words.length - 1 ? undefined : piece.className,\n          spaced: !!piece.spaces,\n        })\n        continue\n      }\n      // A mark joins the word before it, past anything set among the words after it.\n      let back = items.length - 1\n      while (\n        back >= 0 &&\n        items[back].kind === 'node' &&\n        (items[back] as { joins: boolean }).joins\n      )\n        back--\n      const before = items[back]\n      if (isMark(text) && before?.kind === 'word') {\n        before.tokens.push(token)\n        continue\n      }\n      items.push({ kind: 'word', tokens: [token] })\n    }\n  }\n  return items.map((item) => {\n    if (item.kind === 'node') return item.node\n    if (item.kind === 'space') {\n      return item.spaced ? (\n        <span\n          key={item.key}\n          aria-hidden\n          data-diff-word=''\n          data-diff-key={item.key}\n          data-flow-held={held ? '' : undefined}\n          className={cn('inline-block whitespace-pre', flowItemClassName)}\n        >\n          <span className={cn(wordFadeClassName, item.className)}>{item.text}</span>\n        </span>\n      ) : (\n        item.text\n      )\n    }\n    const [first] = item.tokens\n    return (\n      <span\n        key={first.key}\n        data-diff-word=''\n        data-diff-key={first.key}\n        data-flow-held={held ? '' : undefined}\n        className={cn('inline-block whitespace-pre', flowItemClassName)}\n      >\n        {item.tokens.map((token) => (\n          <span\n            key={token.key}\n            aria-hidden={token.hidden || undefined}\n            className={cn(wordFadeClassName, token.className)}\n          >\n            {token.text}\n          </span>\n        ))}\n        {item.beside ? (\n          <span key={item.beside.key} className={besideClassName}>\n            {item.beside.node}\n          </span>\n        ) : null}\n      </span>\n    )\n  })\n}\n\n// A change's buttons after its words, on the text's line.\nconst besideClassName = 'ms-0.5 inline-flex translate-y-0.5 gap-px align-text-bottom'\n\n/** An open change's sides as a screen reader hears them: one deletion and one insertion, not a word at a time. */\nfunction SaidChange({ removed, added }: { removed: string; added: string }) {\n  return (\n    <span className='sr-only'>\n      {removed ? <del>{removed}</del> : null}\n      {removed && added ? ' ' : null}\n      {added ? <ins>{added}</ins> : null}\n    </span>\n  )\n}\n\nfunction CodeDiff({\n  before,\n  after,\n  complete = true,\n  language,\n  title,\n  lineNumbers = true,\n  startLine = 1,\n  collapsedLines,\n  expanded: expandedProp,\n  defaultExpanded = false,\n  onExpandedChange,\n  resolved,\n  defaultResolved,\n  onResolvedChange,\n  className,\n  ref,\n  ...props\n}: DiffProps & {\n  language: CodeLanguage\n  /** A file name, such as `invoice.ts`. Without one, the header names the language. */\n  title?: string\n  lineNumbers?: boolean\n  /** The number of `before`'s first line, when it is a part of a file. */\n  startLine?: number\n  /** Past this many lines, it shows these first and a button that shows them all. */\n  collapsedLines?: number\n  expanded?: boolean\n  defaultExpanded?: boolean\n  onExpandedChange?: (expanded: boolean) => void\n}) {\n  const scrollerId = useId()\n  const [expanded, setExpanded] = useControllable(\n    expandedProp,\n    defaultExpanded,\n    onExpandedChange,\n  )\n  const diff = useMemo(\n    () => diffCode(before, after, { complete }),\n    [before, after, complete],\n  )\n  const ids = useMemo(() => diff.changes.map((change) => change.id), [diff])\n  const namesOf = useCallback(\n    (resolved: Resolved) => codeChangeNames(diff, resolved, { startLine, file: title }),\n    [diff, startLine, title],\n  )\n  const { review, root, rootRef } = useReview(\n    { resolved, defaultResolved, onResolvedChange, complete },\n    ids,\n    diff.growing,\n    namesOf,\n    ref,\n  )\n  const beforeTokens = useCodeTokens(before, language)\n  const afterTokens = useCodeTokens(after, language)\n  const { frame, row } = useFlow<HTMLDivElement, HTMLElement>(\n    '[data-diff-row]',\n    'data-diff-key',\n  )\n  const rowRef = useMemo(() => mergeRefs(row, markMounted), [row])\n  const name = title ?? languageName(language)\n  // The most lines the gutter can count: every kept line, and the longer side of each change.\n  const mostLines = diff.rows.reduce(\n    (lines, row) =>\n      lines +\n      (row.kind === 'change'\n        ? Math.max(row.change.removed.length, row.change.added.length)\n        : 1),\n    0,\n  )\n  // Every line it can show at once: each kept line, and both sides of each change.\n  const allLines = diff.rows.reduce(\n    (lines, row) =>\n      lines +\n      (row.kind === 'change' ? row.change.removed.length + row.change.added.length : 1),\n    0,\n  )\n  const collapsible = collapses(allLines, collapsedLines)\n  const toggle = () => {\n    if (expanded && root) bringTopBack(root)\n    setExpanded(!expanded)\n  }\n\n  return usePart(\n    review,\n    'root',\n    {},\n    {\n      ...props,\n      ref: rootRef,\n      tabIndex: -1,\n      'aria-label': `Changes to ${name}`,\n      className: cn(\n        codeCardClassName,\n        '@container/diff',\n        reviewFocusClassName,\n        className,\n      ),\n      children: ({ resolved, readOnly }: { resolved: Resolved; readOnly: boolean }) => {\n        const names = namesOf(resolved)\n        const open = ids.filter((id) => resolved[id] === undefined)\n        let number = startLine - 1\n        const lines: ReactNode[] = []\n        const line = (\n          key: string,\n          text: string,\n          tokens: Parameters<typeof CodeLine>[0]['tokens'] | undefined,\n          options: {\n            mark?: 'added' | 'removed'\n            words?: Parameters<typeof CodeLine>[0]['words']\n            counted: boolean\n            pending?: boolean\n          },\n        ) => {\n          if (options.counted) number++\n          lines.push(\n            <div\n              key={key}\n              data-diff-row=''\n              data-diff-key={key}\n              data-flow-held={complete ? undefined : ''}\n              data-pending={options.pending ? '' : undefined}\n              className={flowItemClassName}\n            >\n              <CodeLine\n                number={options.counted ? number : undefined}\n                mark={options.mark}\n                tokens={\n                  (options.pending ? undefined : tokens) ??\n                  (text ? [{ content: text }] : [])\n                }\n                words={options.words}\n                lineNumbers={lineNumbers}\n                signs\n                className={cn(lineFadeClassName, options.pending && pendingLineClassName)}\n              />\n            </div>,\n          )\n        }\n        for (const row of diff.rows) {\n          if (row.kind === 'same') {\n            line(`b${row.before}`, row.text, afterTokens[row.after - 1], {\n              counted: true,\n            })\n            continue\n          }\n          if (row.kind === 'pending') {\n            line(`b${row.before}`, row.text, undefined, { counted: true, pending: true })\n            continue\n          }\n          const { change } = row\n          const decided = resolved[change.id]\n          if (decided !== 'accepted') {\n            for (const removed of change.removed) {\n              line(`b${removed.number}`, removed.text, beforeTokens[removed.number - 1], {\n                mark: decided === undefined ? 'removed' : undefined,\n                words: removed.words,\n                counted: decided === 'rejected',\n              })\n            }\n          }\n          if (decided !== 'rejected') {\n            for (const added of change.added) {\n              line(`a${added.number}`, added.text, afterTokens[added.number - 1], {\n                mark: decided === undefined ? 'added' : undefined,\n                words: added.words,\n                counted: true,\n              })\n            }\n          }\n          if (decided === undefined && !readOnly) {\n            // Under the change, in a row of its own, so the buttons never cover the code they decide.\n            lines.push(\n              <div\n                key={`c${change.id}`}\n                data-diff-row=''\n                data-diff-key={`c${change.id}`}\n                data-flow-held={complete ? undefined : ''}\n                className={cn(flowItemClassName, 'flex justify-end')}\n              >\n                <div className='sticky end-0 flex gap-0.5 px-1.5 py-1 font-sans'>\n                  <ChangeButtons\n                    id={change.id}\n                    name={names.get(change.id) ?? change.id}\n                    disabled={diff.growing.includes(change.id)}\n                    onDecide={(resolution, event) =>\n                      resolution === 'accepted'\n                        ? review.api.accept(change.id, event)\n                        : review.api.reject(change.id, event)\n                    }\n                  />\n                </div>\n              </div>,\n            )\n          }\n        }\n        return (\n          <>\n            <CodeDiffHeader\n              title={title}\n              language={language}\n              open={diff.changes.filter((change) => resolved[change.id] === undefined)}\n            >\n              {readOnly ? null : (\n                <AllButtons\n                  open={open.length}\n                  disabled={!complete}\n                  onAll={(resolution, event) =>\n                    resolution === 'accepted'\n                      ? review.api.acceptAll(event)\n                      : review.api.rejectAll(event)\n                  }\n                />\n              )}\n            </CodeDiffHeader>\n            {diff.changes.length === 0 && complete ? (\n              <p className='text-muted-foreground p-(--surface-padding) text-sm'>\n                No changes\n              </p>\n            ) : (\n              <CodeScroller\n                id={scrollerId}\n                label={`${name} changes`}\n                collapsed={collapsible && !expanded}\n                collapsedLines={collapsible ? collapsedLines : undefined}\n                className='bg-muted/50'\n              >\n                <div\n                  ref={frame}\n                  data-arriving={complete ? undefined : ''}\n                  className={cn(frameClassName, 'w-max min-w-full')}\n                >\n                  <code\n                    ref={rowRef}\n                    data-slot='code-lines'\n                    className='group/flow relative isolate grid w-max min-w-full'\n                    style={\n                      {\n                        '--code-gutter': gutterWidth(\n                          Math.max(startLine - 1 + mostLines, 1),\n                        ),\n                      } as CSSProperties\n                    }\n                  >\n                    {lines}\n                  </code>\n                </div>\n              </CodeScroller>\n            )}\n            {collapsible ? (\n              <CodeFoldButton\n                expanded={expanded}\n                lines={allLines}\n                controls={scrollerId}\n                file={title}\n                onToggle={toggle}\n              />\n            ) : null}\n          </>\n        )\n      },\n    },\n  )\n}\n\nfunction TextDiff({\n  before,\n  after,\n  complete = true,\n  label = 'Suggested changes',\n  resolved,\n  defaultResolved,\n  onResolvedChange,\n  className,\n  ref,\n  ...props\n}: DiffProps & {\n  /** What a screen reader calls the changes. */\n  label?: string\n}) {\n  const diff = useMemo(\n    () => diffText(before, after, { complete }),\n    [before, after, complete],\n  )\n  const ids = useMemo(() => diff.changes.map((change) => change.id), [diff])\n  const namesOf = useCallback(() => textChangeNames(ids), [ids])\n  const { review, rootRef } = useReview(\n    { resolved, defaultResolved, onResolvedChange, complete },\n    ids,\n    diff.growing,\n    namesOf,\n    ref,\n  )\n  const { frame, row } = useFlow<HTMLDivElement, HTMLDivElement>(\n    '[data-diff-word]',\n    'data-diff-key',\n  )\n  const rowRef = useMemo(() => mergeRefs(row, markMounted), [row])\n\n  return usePart(\n    review,\n    'root',\n    {},\n    {\n      ...props,\n      ref: rootRef,\n      tabIndex: -1,\n      'aria-label': label,\n      className: cn(\n        'flex min-w-0 flex-col gap-3 rounded-(--surface-radius)',\n        reviewFocusClassName,\n        className,\n      ),\n      children: ({ resolved, readOnly }: { resolved: Resolved; readOnly: boolean }) => {\n        const names = namesOf()\n        const open = ids.filter((id) => resolved[id] === undefined)\n        const pieces: ProsePiece[] = []\n        let atBefore = 0\n        let atAfter = 0\n        for (const part of diff.parts) {\n          if (part.kind === 'same') {\n            pieces.push({ kind: 'words', text: part.text, at: atBefore, side: 'b' })\n            atBefore += part.text.length\n            atAfter += part.text.length\n            continue\n          }\n          if (part.kind === 'pending') {\n            pieces.push({\n              kind: 'words',\n              text: part.text,\n              at: atBefore,\n              side: 'b',\n              className: 'text-muted-foreground',\n            })\n            atBefore += part.text.length\n            continue\n          }\n          const { change } = part\n          const decided = resolved[change.id]\n          const open = decided === undefined\n          if (open) {\n            pieces.push({\n              kind: 'said',\n              key: `s${change.id}`,\n              node: (\n                <SaidChange\n                  key={`s${change.id}`}\n                  removed={change.removed}\n                  added={change.added}\n                />\n              ),\n            })\n          }\n          if (decided !== 'accepted') {\n            pieces.push({\n              kind: 'words',\n              text: change.removed,\n              at: atBefore,\n              side: 'b',\n              className: open ? removedWordClassName : undefined,\n              spaces: true,\n              hidden: open,\n            })\n          }\n          if (open && change.removed && change.added) {\n            pieces.push({ kind: 'gap', key: `g${change.id}`, node: ' ' })\n          }\n          if (decided !== 'rejected') {\n            pieces.push({\n              kind: 'words',\n              text: change.added,\n              at: atAfter,\n              side: 'a',\n              className: open ? addedWordClassName : undefined,\n              spaces: true,\n              hidden: open,\n            })\n          }\n          if (open && !readOnly) {\n            pieces.push({\n              kind: 'beside',\n              key: `c${change.id}`,\n              node: (\n                <ChangeButtons\n                  id={change.id}\n                  name={names.get(change.id) ?? change.id}\n                  compact\n                  disabled={diff.growing.includes(change.id)}\n                  onDecide={(resolution, event) =>\n                    resolution === 'accepted'\n                      ? review.api.accept(change.id, event)\n                      : review.api.reject(change.id, event)\n                  }\n                />\n              ),\n            })\n          }\n          atBefore += change.removed.length\n          atAfter += change.added.length\n        }\n        return (\n          <>\n            <div\n              ref={frame}\n              data-arriving={complete ? undefined : ''}\n              className={frameClassName}\n            >\n              <div\n                ref={rowRef}\n                className='group/flow relative isolate text-sm leading-7 whitespace-pre-wrap'\n              >\n                {proseItems(pieces, !complete)}\n              </div>\n            </div>\n            {/* Kept while after arrives, so the foot doesn't leave and come back as the first change forms. */}\n            {!readOnly && (ids.length > 0 || !complete) ? (\n              <div className='flex flex-wrap items-center justify-between gap-2 border-t pt-2'>\n                <ReviewStatus open={open.length} total={ids.length} complete={complete} />\n                <AllButtons\n                  open={open.length}\n                  disabled={!complete}\n                  onAll={(resolution, event) =>\n                    resolution === 'accepted'\n                      ? review.api.acceptAll(event)\n                      : review.api.rejectAll(event)\n                  }\n                />\n              </div>\n            ) : null}\n          </>\n        )\n      },\n    },\n  )\n}\n\nexport { CodeDiff, TextDiff }\nexport { codeChangeNames }\nexport type { DiffProps }\n",
      "type": "registry:component",
      "target": "@components/kino/diff.tsx"
    }
  ],
  "css": {
    "@property --code-fade": {
      "syntax": "'<length>'",
      "inherits": "false",
      "initial-value": "0px"
    },
    ":root": {
      "--code-keyword": "oklch(0.47 0.19 330)",
      "--code-string": "oklch(0.46 0.12 155)",
      "--code-string-expression": "oklch(0.46 0.12 155)",
      "--code-function": "oklch(0.47 0.17 260)",
      "--code-link": "oklch(0.47 0.17 260)",
      "--code-constant": "oklch(0.48 0.13 50)",
      "--code-parameter": "oklch(0.48 0.15 20)",
      "--code-comment": "oklch(0.47 0 0)",
      "--code-punctuation": "oklch(0.42 0 0)",
      "--code-added": "oklch(0.55 0.14 155)",
      "--code-removed": "oklch(0.56 0.2 25)"
    },
    ".dark": {
      "--code-keyword": "oklch(0.78 0.14 330)",
      "--code-string": "oklch(0.8 0.13 155)",
      "--code-string-expression": "oklch(0.8 0.13 155)",
      "--code-function": "oklch(0.78 0.12 255)",
      "--code-link": "oklch(0.78 0.12 255)",
      "--code-constant": "oklch(0.82 0.12 65)",
      "--code-parameter": "oklch(0.8 0.11 25)",
      "--code-comment": "oklch(0.7 0 0)",
      "--code-punctuation": "oklch(0.75 0 0)",
      "--code-added": "oklch(0.72 0.15 155)",
      "--code-removed": "oklch(0.7 0.17 25)"
    }
  },
  "type": "registry:component"
}