{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-06",
  "title": "Change summary",
  "description": "Every file an agent changed with a status tile, a five-block bar and counts, filtered by status, each row unfolding its own diff.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/toggle-group.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/review/review-06.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll, type WordRollWord } from '@/components/core/word-roll';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  ArrowRightIcon,\n  ChevronDownIcon,\n  ListCollapseIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf, nounOf } from '@/registry/ndeko/lib/words';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ToggleGroup, ToggleGroupItem } from '@/registry/ndeko/ui/toggle-group';\n\nimport {\n  blocksOf,\n  changeCountsOf,\n  lineDiffOf,\n  type DiffBlock,\n  type DiffLine,\n} from './_parts/diff';\nimport { pathPartsOf } from './_parts/path-parts';\n\nexport type FileStatus = 'added' | 'modified' | 'deleted' | 'renamed';\n\nexport type ChangedFile = {\n  path: string;\n  /** For a renamed file, where it lived before. */\n  previousPath?: string;\n  status: FileStatus;\n  before: string;\n  after: string;\n};\n\ntype BarBlock = 'added' | 'removed' | 'neutral';\n\nconst STATUSES: FileStatus[] = ['added', 'modified', 'deleted', 'renamed'];\n\nconst STATUS_LETTER: Record<FileStatus, string> = {\n  added: 'A',\n  modified: 'M',\n  deleted: 'D',\n  renamed: 'R',\n};\n\nconst STATUS_WORD: Record<FileStatus, string> = {\n  added: 'Added',\n  modified: 'Modified',\n  deleted: 'Deleted',\n  renamed: 'Renamed',\n};\n\nconst STATUS_COLOR: Record<FileStatus, string> = {\n  added: 'var(--success)',\n  modified: 'var(--info)',\n  deleted: 'var(--destructive)',\n  renamed: 'var(--warning)',\n};\n\nconst BAR_SIZE = 5;\n\nconst BAR_TONE: Record<BarBlock, string> = {\n  added: 'bg-success',\n  removed: 'bg-destructive',\n  neutral: 'bg-foreground/15',\n};\n\nconst LINE_TONE: Record<DiffLine['kind'], string> = {\n  same: '',\n  removed: 'bg-destructive/10',\n  added: 'bg-success/10',\n};\n\nconst SIGN: Record<DiffLine['kind'], string> = {\n  same: ' ',\n  removed: '−',\n  added: '+',\n};\n\nconst SIGN_TONE: Record<DiffLine['kind'], string> = {\n  same: 'text-muted-foreground',\n  removed: 'text-destructive-ink',\n  added: 'text-success-foreground',\n};\n\nconst SPOKEN_KIND: Record<DiffLine['kind'], string> = {\n  same: '',\n  removed: 'Removed: ',\n  added: 'Added: ',\n};\n\nfunction linesOfText(text: string) {\n  if (text === '') {\n    return [];\n  }\n  return text.split('\\n');\n}\n\nexport function diffOfFile(file: ChangedFile) {\n  const before = linesOfText(file.before);\n  const after = linesOfText(file.after);\n  return lineDiffOf(before, after);\n}\n\n/** Five blocks shared between additions and deletions; a change under five lines leaves the rest grey. */\nexport function barOf(additions: number, deletions: number): BarBlock[] {\n  const total = additions + deletions;\n  const filled = Math.min(BAR_SIZE, total);\n  const share = additions / Math.max(total, 1);\n  const addedBlocks = Math.round(share * filled);\n  const removedBlocks = filled - addedBlocks;\n  const blocks: BarBlock[] = [];\n  for (let index = 0; index < BAR_SIZE; index += 1) {\n    blocks.push(blockAt(index, addedBlocks, removedBlocks));\n  }\n  return blocks;\n}\n\nfunction blockAt(index: number, addedBlocks: number, removedBlocks: number) {\n  if (index < addedBlocks) {\n    return 'added';\n  }\n  const removedEnd = addedBlocks + removedBlocks;\n  if (index < removedEnd) {\n    return 'removed';\n  }\n  return 'neutral';\n}\n\nfunction StatusTile({ status }: { status: FileStatus }) {\n  const style = { '--chip': STATUS_COLOR[status] } as React.CSSProperties;\n\n  return (\n    <span\n      style={style}\n      className='chip-3d inline-flex size-5 shrink-0 items-center justify-center rounded-[5px] font-mono text-[11px] font-semibold'\n    >\n      <span aria-hidden='true'>{STATUS_LETTER[status]}</span>\n      <span className='sr-only'>{STATUS_WORD[status]}</span>\n    </span>\n  );\n}\n\nfunction ChangeBar({\n  additions,\n  deletions,\n}: {\n  additions: number;\n  deletions: number;\n}) {\n  const blocks = barOf(additions, deletions);\n\n  return (\n    <span aria-hidden='true' className='flex shrink-0 items-center gap-0.5'>\n      {blocks.map((block, index) => (\n        <span\n          key={index}\n          className={cn('size-1.5 rounded-[2px]', BAR_TONE[block])}\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction FilePath({ file }: { file: ChangedFile }) {\n  const { folder, name } = pathPartsOf(file.path);\n  const previous = file.previousPath;\n\n  return (\n    <span className='flex min-w-0 flex-1 items-center gap-1 font-mono text-xs'>\n      {previous && (\n        <>\n          <span className='text-muted-foreground min-w-0 truncate'>\n            {previous}\n          </span>\n          <ArrowRightIcon className='text-muted-foreground size-3 shrink-0' />\n        </>\n      )}\n      <span className='min-w-0 truncate'>\n        <span className='text-muted-foreground'>{folder}</span>\n        {name}\n      </span>\n    </span>\n  );\n}\n\nfunction CodeLine({ line }: { line: DiffLine }) {\n  return (\n    <div\n      className={cn(\n        'flex min-h-5 items-stretch pe-3 font-mono text-xs leading-5',\n        LINE_TONE[line.kind]\n      )}\n    >\n      <span className='text-muted-foreground/70 w-8 shrink-0 pe-1.5 text-end tabular-nums select-none'>\n        {line.oldNumber ?? ''}\n      </span>\n      <span className='text-muted-foreground/70 w-8 shrink-0 pe-1.5 text-end tabular-nums select-none'>\n        {line.newNumber ?? ''}\n      </span>\n      <span\n        aria-hidden='true'\n        className={cn(\n          'w-4 shrink-0 text-center select-none',\n          SIGN_TONE[line.kind]\n        )}\n      >\n        {SIGN[line.kind]}\n      </span>\n      <span className='sr-only'>{SPOKEN_KIND[line.kind]}</span>\n      <code className='whitespace-pre'>{line.text}</code>\n    </div>\n  );\n}\n\nfunction FoldNote({ block }: { block: DiffBlock }) {\n  const count = block.lines.length;\n\n  return (\n    <p className='text-muted-foreground bg-foreground/[0.03] px-3 py-1 text-xs'>\n      {countOf(count, 'unchanged line')}\n    </p>\n  );\n}\n\nfunction FileDiff({ lines, name }: { lines: DiffLine[]; name: string }) {\n  const blocks = blocksOf(lines, 2, 4);\n\n  return (\n    <div\n      role='region'\n      aria-label={`Changes to ${name}`}\n      tabIndex={0}\n      className='focus-visible:ring-ring/25 overflow-x-auto rounded-md outline-none focus-visible:ring-[3px]'\n    >\n      <div className='flex w-max min-w-full flex-col'>\n        {blocks.map((block) => {\n          if (block.kind === 'fold') {\n            return <FoldNote key={block.key} block={block} />;\n          }\n          return (\n            <div key={block.key}>\n              {block.lines.map((line) => (\n                <CodeLine key={line.key} line={line} />\n              ))}\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nfunction chevronTurnOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'rotate-180';\n  }\n  return 'rotate-0';\n}\n\ntype FileRowProps = {\n  file: ChangedFile;\n  isOpen: boolean;\n  onToggle: () => void;\n};\n\nexport function FileRow({ file, isOpen, onToggle }: FileRowProps) {\n  const panelId = useId();\n  const lines = diffOfFile(file);\n  const { additions, deletions } = changeCountsOf(lines);\n  const { name } = pathPartsOf(file.path);\n  const addedWords = countOf(additions, 'addition');\n  const removedWords = countOf(deletions, 'deletion');\n  const counts = `${addedWords}, ${removedWords}`;\n\n  return (\n    <div className='flex flex-col'>\n      <button\n        type='button'\n        aria-expanded={isOpen}\n        aria-controls={panelId}\n        onClick={onToggle}\n        className='hover:bg-foreground/[0.03] focus-visible:ring-ring/25 flex h-10 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2 text-start outline-none focus-visible:ring-[3px]'\n      >\n        <StatusTile status={file.status} />\n        <FilePath file={file} />\n        <ChangeBar additions={additions} deletions={deletions} />\n        <span className='flex w-16 shrink-0 justify-end gap-1.5 font-mono text-xs tabular-nums'>\n          <span className='text-success-foreground'>+{additions}</span>\n          <span className='text-destructive-ink'>−{deletions}</span>\n          <span className='sr-only'>{counts}</span>\n        </span>\n        <ChevronDownIcon\n          className={cn(\n            'text-muted-foreground size-4 shrink-0 transition-transform duration-200 ease-(--ease-out-strong)',\n            chevronTurnOf(isOpen)\n          )}\n        />\n      </button>\n      <Fold open={isOpen} id={panelId}>\n        <div className='px-2 pt-1 pb-2'>\n          <div className='bg-foreground/[0.025] dark:bg-foreground/[0.04] rounded-md'>\n            <FileDiff lines={lines} name={name} />\n          </div>\n        </div>\n      </Fold>\n    </div>\n  );\n}\n\nfunction totalsOf(files: ChangedFile[]) {\n  let additions = 0;\n  let deletions = 0;\n  for (const file of files) {\n    const lines = diffOfFile(file);\n    const counts = changeCountsOf(lines);\n    additions += counts.additions;\n    deletions += counts.deletions;\n  }\n  return { additions, deletions };\n}\n\nfunction countWithStatus(files: ChangedFile[], status: FileStatus) {\n  const matching = files.filter((file) => file.status === status);\n  return matching.length;\n}\n\nfunction isShownBy(file: ChangedFile, statuses: FileStatus[]) {\n  if (statuses.length === 0) {\n    return true;\n  }\n  return statuses.includes(file.status);\n}\n\nfunction shownWordsOf(shown: number, total: number): WordRollWord[] {\n  const countWord = {\n    key: 'shown',\n    text: String(shown),\n    node: <MotionNumber value={shown} />,\n  };\n  if (shown === total) {\n    return ['All', countWord, nounOf(total, 'file'), 'shown'];\n  }\n  return ['Showing', countWord, 'of', String(total), nounOf(total, 'file')];\n}\n\nfunction expandLabelOf(isAllOpen: boolean) {\n  if (isAllOpen) {\n    return 'Collapse all';\n  }\n  return 'Expand all';\n}\n\nfunction statusesFrom(values: unknown[]) {\n  return STATUSES.filter((status) => values.includes(status));\n}\n\nexport type ChangeSummaryProps = {\n  files: ChangedFile[];\n  className?: string;\n};\n\nexport function ChangeSummary({ files, className }: ChangeSummaryProps) {\n  const [openPaths, setOpenPaths] = useState<string[]>([]);\n  const [statuses, setStatuses] = useState<FileStatus[]>([]);\n  const [notice, setNotice] = useState('');\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const totals = totalsOf(files);\n  const shownFiles = files.filter((file) => isShownBy(file, statuses));\n  const shownPaths = shownFiles.map((file) => file.path);\n  const isAllOpen = shownPaths.every((path) => openPaths.includes(path));\n  const hasShown = shownFiles.length > 0;\n  const expandLabel = expandLabelOf(isAllOpen);\n  const shownWords = shownWordsOf(shownFiles.length, files.length);\n\n  function toggle(path: string) {\n    const isOpen = openPaths.includes(path);\n    const { name } = pathPartsOf(path);\n    if (isOpen) {\n      setOpenPaths((current) => current.filter((open) => open !== path));\n      setNotice(`${name} folded`);\n      return;\n    }\n    setOpenPaths((current) => [...current, path]);\n    setNotice(`${name} opened`);\n  }\n\n  function toggleAll() {\n    if (isAllOpen) {\n      setOpenPaths([]);\n      setNotice('Every file folded');\n      return;\n    }\n    setOpenPaths(shownPaths);\n    setNotice('Every shown file opened');\n  }\n\n  function changeStatuses(values: unknown[]) {\n    const next = statusesFrom(values);\n    setStatuses(next);\n    const count = files.filter((file) => isShownBy(file, next)).length;\n    setNotice(`Showing ${countOf(count, 'file')}`);\n  }\n\n  return (\n    <section\n      aria-label='Changed files'\n      className={cn('flex flex-col gap-3', className)}\n    >\n      <header className='flex flex-wrap items-center gap-x-3 gap-y-2 px-1'>\n        <p className='min-w-0 flex-1 text-[13px]'>\n          <span className='font-medium'>\n            {countOf(files.length, 'file')} changed\n          </span>\n          <span className='ms-2 font-mono text-xs tabular-nums'>\n            <span className='text-success-foreground'>+{totals.additions}</span>{' '}\n            <span className='text-destructive-ink'>−{totals.deletions}</span>\n          </span>\n        </p>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          onClick={toggleAll}\n          disabled={!hasShown}\n          className='text-muted-foreground'\n        >\n          <ListCollapseIcon />\n          <Swap swapKey={expandLabel}>{expandLabel}</Swap>\n        </Button>\n      </header>\n      <div className='flex flex-wrap items-center gap-2 px-1'>\n        <ToggleGroup\n          aria-label='Filter by status'\n          multiple\n          value={statuses}\n          onValueChange={changeStatuses}\n          size='sm'\n          className='flex-wrap gap-1'\n        >\n          {STATUSES.map((status) => {\n            const count = countWithStatus(files, status);\n            return (\n              <ToggleGroupItem\n                key={status}\n                value={status}\n                disabled={count === 0}\n                variant='outline'\n                className='data-pressed:bg-primary/10 data-pressed:text-primary-ink dark:data-pressed:bg-primary/15 h-7 gap-1.5 rounded-full ps-1 pe-2.5 text-xs'\n              >\n                <StatusTile status={status} />\n                {STATUS_WORD[status]}\n                <span className='text-muted-foreground tabular-nums'>\n                  {count}\n                </span>\n              </ToggleGroupItem>\n            );\n          })}\n        </ToggleGroup>\n      </div>\n      <p className='text-muted-foreground px-1 text-xs'>\n        <WordRoll words={shownWords} />\n      </p>\n      <ul className='flex flex-col'>\n        <AnimatePresence initial={false}>\n          {shownFiles.map((file) => (\n            <motion.li\n              key={file.path}\n              className='overflow-hidden'\n              {...rowPresence}\n            >\n              <FileRow\n                file={file}\n                isOpen={openPaths.includes(file.path)}\n                onToggle={() => toggle(file.path)}\n              />\n            </motion.li>\n          ))}\n        </AnimatePresence>\n      </ul>\n      {!hasShown && (\n        <p className='text-muted-foreground px-1 py-4 text-center text-[13px]'>\n          No file has this status\n        </p>\n      )}\n      <LiveRegion message={notice} />\n    </section>\n  );\n}\n\nconst FILES: ChangedFile[] = [\n  {\n    path: 'src/billing/pallet-fee.ts',\n    status: 'modified',\n    before: `import { tierFor } from './tiers';\n\nexport function palletFee(order: Order) {\n  const tier = tierFor(order.pallets);\n  return money(order.pallets * TIER_RATES[tier]);\n}`,\n    after: `import { FLAT_FROM_PALLETS, tierFor } from './pallet-tiers';\n\nexport const FLAT_FEE_EUR = 18.4;\n\nexport function palletFee(order: Order) {\n  if (order.pallets >= FLAT_FROM_PALLETS) {\n    return money(order.pallets * FLAT_FEE_EUR);\n  }\n  const tier = tierFor(order.pallets);\n  return money(order.pallets * TIER_RATES[tier]);\n}`,\n  },\n  {\n    path: 'src/billing/pallet-fee.test.ts',\n    status: 'added',\n    before: '',\n    after: `import { palletFee } from './pallet-fee';\n\ntest('bills 40 pallets at the flat fee', () => {\n  const fee = palletFee({ pallets: 40, date: '2026-10-02' });\n  expect(fee.amount).toBe(736);\n});\n\ntest('keeps the tiers under 40 pallets', () => {\n  const fee = palletFee({ pallets: 10, date: '2026-10-02' });\n  expect(fee.amount).toBe(159);\n});`,\n  },\n  {\n    path: 'src/billing/pallet-tiers.ts',\n    previousPath: 'src/billing/tiers.ts',\n    status: 'renamed',\n    before: `export const TIER_LIMITS = [10, 25];\n\nexport function tierFor(pallets: number) {\n  return TIER_LIMITS.filter((limit) => pallets > limit).length;\n}`,\n    after: `export const TIER_LIMITS = [10, 25];\nexport const FLAT_FROM_PALLETS = 40;\n\nexport function tierFor(pallets: number) {\n  return TIER_LIMITS.filter((limit) => pallets > limit).length;\n}`,\n  },\n  {\n    path: 'src/orders/checkout.ts',\n    status: 'modified',\n    before: `export function shippingOf(cart: Cart) {\n  const pallets = cart.lines.length;\n  return palletFee({ pallets, date: cart.date });\n}`,\n    after: `export function shippingOf(cart: Cart) {\n  const pallets = palletsOf(cart);\n  return palletFee({ pallets, date: cart.date });\n}`,\n  },\n  {\n    path: 'src/billing/legacy-fee.ts',\n    status: 'deleted',\n    before: `import { palletFee } from './pallet-fee';\n\n/** @deprecated Use palletFee. */\nexport const legacyPalletFee = palletFee;`,\n    after: '',\n  },\n  {\n    path: 'docs/pricing.md',\n    status: 'modified',\n    before: `## Pallet fees\n\nEvery order is billed by tier, from 15.90 EUR per pallet.`,\n    after: `## Pallet fees\n\nFrom 1 October, orders of 40 pallets or more pay a flat 18.40 EUR per pallet.\nSmaller orders are billed by tier, from 15.90 EUR per pallet.`,\n  },\n];\n\nexport default function Review06() {\n  return (\n    <div className='bg-card hairline-ring ring-border w-full max-w-[44rem] rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n      <ChangeSummary files={FILES} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/review/review-06.tsx"
    },
    {
      "path": "registry/ndeko/components/review/_parts/diff.ts",
      "content": "export type LineKind = 'same' | 'added' | 'removed';\n\nexport type DiffLine = {\n  key: string;\n  kind: LineKind;\n  text: string;\n  oldNumber: number | null;\n  newNumber: number | null;\n};\n\nexport type WordPiece = {\n  text: string;\n  isChanged: boolean;\n};\n\nexport type DiffBlock =\n  | { kind: 'hunk'; key: string; lines: DiffLine[] }\n  | { kind: 'fold'; key: string; lines: DiffLine[] };\n\nconst SPACE_RUN = /(\\s+)/;\n\nfunction emptyTable(rows: number, columns: number) {\n  const table: number[][] = [];\n  for (let row = 0; row <= rows; row += 1) {\n    const width = columns + 1;\n    const cells = Array.from({ length: width }, () => 0);\n    table.push(cells);\n  }\n  return table;\n}\n\n/** Lengths of the longest common runs from each pair of positions to the end. */\nfunction commonLengths(before: readonly string[], after: readonly string[]) {\n  const table = emptyTable(before.length, after.length);\n  for (let row = before.length - 1; row >= 0; row -= 1) {\n    for (let column = after.length - 1; column >= 0; column -= 1) {\n      const isSame = before[row] === after[column];\n      if (isSame) {\n        const diagonal = table[row + 1][column + 1];\n        table[row][column] = diagonal + 1;\n        continue;\n      }\n      const below = table[row + 1][column];\n      const right = table[row][column + 1];\n      table[row][column] = Math.max(below, right);\n    }\n  }\n  return table;\n}\n\ntype Step = 'same' | 'remove' | 'add';\n\nfunction stepsOf(before: readonly string[], after: readonly string[]) {\n  const table = commonLengths(before, after);\n  const steps: Step[] = [];\n  let row = 0;\n  let column = 0;\n  while (row < before.length && column < after.length) {\n    const isSame = before[row] === after[column];\n    if (isSame) {\n      steps.push('same');\n      row += 1;\n      column += 1;\n      continue;\n    }\n    const keptByRemoving = table[row + 1][column];\n    const keptByAdding = table[row][column + 1];\n    const removesFirst = keptByRemoving >= keptByAdding;\n    if (removesFirst) {\n      steps.push('remove');\n      row += 1;\n      continue;\n    }\n    steps.push('add');\n    column += 1;\n  }\n  while (row < before.length) {\n    steps.push('remove');\n    row += 1;\n  }\n  while (column < after.length) {\n    steps.push('add');\n    column += 1;\n  }\n  return steps;\n}\n\nexport function lineDiffOf(before: string[], after: string[]): DiffLine[] {\n  const steps = stepsOf(before, after);\n  const lines: DiffLine[] = [];\n  let oldIndex = 0;\n  let newIndex = 0;\n  for (const step of steps) {\n    const oldNumber = oldIndex + 1;\n    const newNumber = newIndex + 1;\n    if (step === 'same') {\n      lines.push({\n        key: `s${oldNumber}-${newNumber}`,\n        kind: 'same',\n        text: after[newIndex],\n        oldNumber,\n        newNumber,\n      });\n      oldIndex += 1;\n      newIndex += 1;\n      continue;\n    }\n    if (step === 'remove') {\n      lines.push({\n        key: `r${oldNumber}`,\n        kind: 'removed',\n        text: before[oldIndex],\n        oldNumber,\n        newNumber: null,\n      });\n      oldIndex += 1;\n      continue;\n    }\n    lines.push({\n      key: `a${newNumber}`,\n      kind: 'added',\n      text: after[newIndex],\n      oldNumber: null,\n      newNumber,\n    });\n    newIndex += 1;\n  }\n  return lines;\n}\n\nfunction tokensOf(text: string) {\n  const parts = text.split(SPACE_RUN);\n  return parts.filter((part) => part !== '');\n}\n\nfunction pushPiece(pieces: WordPiece[], text: string, isChanged: boolean) {\n  const last = pieces[pieces.length - 1];\n  const extendsLast = last !== undefined && last.isChanged === isChanged;\n  if (extendsLast) {\n    last.text += text;\n    return;\n  }\n  pieces.push({ text, isChanged });\n}\n\nexport function wordDiffOf(before: string, after: string) {\n  const beforeTokens = tokensOf(before);\n  const afterTokens = tokensOf(after);\n  const steps = stepsOf(beforeTokens, afterTokens);\n  const beforePieces: WordPiece[] = [];\n  const afterPieces: WordPiece[] = [];\n  let oldIndex = 0;\n  let newIndex = 0;\n  for (const step of steps) {\n    if (step === 'same') {\n      pushPiece(beforePieces, beforeTokens[oldIndex], false);\n      pushPiece(afterPieces, afterTokens[newIndex], false);\n      oldIndex += 1;\n      newIndex += 1;\n      continue;\n    }\n    if (step === 'remove') {\n      pushPiece(beforePieces, beforeTokens[oldIndex], true);\n      oldIndex += 1;\n      continue;\n    }\n    pushPiece(afterPieces, afterTokens[newIndex], true);\n    newIndex += 1;\n  }\n  return { before: beforePieces, after: afterPieces };\n}\n\n/** Pairs each removed line with the added line in the same position of its change, both ways. */\nexport function partnersOf(lines: DiffLine[]) {\n  const partners = new Map<string, DiffLine>();\n  let removed: DiffLine[] = [];\n  let added: DiffLine[] = [];\n\n  function settle() {\n    const count = Math.min(removed.length, added.length);\n    for (let index = 0; index < count; index += 1) {\n      partners.set(removed[index].key, added[index]);\n      partners.set(added[index].key, removed[index]);\n    }\n    removed = [];\n    added = [];\n  }\n\n  for (const line of lines) {\n    if (line.kind === 'same') {\n      settle();\n      continue;\n    }\n    if (line.kind === 'removed') {\n      const isNewChange = added.length > 0;\n      if (isNewChange) {\n        settle();\n      }\n      removed.push(line);\n      continue;\n    }\n    added.push(line);\n  }\n  settle();\n  return partners;\n}\n\nfunction nearChangeOf(lines: DiffLine[], context: number) {\n  const isNear = lines.map(() => false);\n  lines.forEach((line, index) => {\n    if (line.kind === 'same') {\n      return;\n    }\n    const first = Math.max(0, index - context);\n    const last = Math.min(lines.length - 1, index + context);\n    for (let near = first; near <= last; near += 1) {\n      isNear[near] = true;\n    }\n  });\n  return isNear;\n}\n\n/**\n * Changed lines with `context` lines around them become hunks; the unchanged runs between them fold,\n * unless they are shorter than `minFold`, which would hide less than the button that replaces them.\n */\nexport function blocksOf(\n  lines: DiffLine[],\n  context: number,\n  minFold: number\n): DiffBlock[] {\n  const isNear = nearChangeOf(lines, context);\n  const blocks: DiffBlock[] = [];\n  let run: DiffLine[] = [];\n  let runIsNear = true;\n\n  function appendHunk(key: string) {\n    const previous = blocks.at(-1);\n    if (previous?.kind === 'hunk') {\n      previous.lines.push(...run);\n      return;\n    }\n    blocks.push({ kind: 'hunk', key, lines: run });\n  }\n\n  function closeRun() {\n    if (run.length === 0) {\n      return;\n    }\n    const key = run[0].key;\n    const isShortRun = run.length < minFold;\n    const isHunk = runIsNear || isShortRun;\n    if (isHunk) {\n      appendHunk(key);\n    }\n    if (!isHunk) {\n      blocks.push({ kind: 'fold', key, lines: run });\n    }\n    run = [];\n  }\n\n  lines.forEach((line, index) => {\n    const lineIsNear = isNear[index];\n    if (lineIsNear !== runIsNear) {\n      closeRun();\n      runIsNear = lineIsNear;\n    }\n    run.push(line);\n  });\n  closeRun();\n  return blocks;\n}\n\nfunction firstNumberOf(numbers: (number | null)[]) {\n  const found = numbers.find((number) => number !== null);\n  return found ?? 0;\n}\n\nfunction countOfKind(lines: DiffLine[], kinds: LineKind[]) {\n  const matching = lines.filter((line) => kinds.includes(line.kind));\n  return matching.length;\n}\n\n/** \"@@ -12,4 +12,6 @@\": where the hunk starts in each version and how many lines it covers there. */\nexport function hunkHeaderOf(lines: DiffLine[]) {\n  const oldNumbers = lines.map((line) => line.oldNumber);\n  const newNumbers = lines.map((line) => line.newNumber);\n  const oldStart = firstNumberOf(oldNumbers);\n  const newStart = firstNumberOf(newNumbers);\n  const oldCount = countOfKind(lines, ['same', 'removed']);\n  const newCount = countOfKind(lines, ['same', 'added']);\n  return `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`;\n}\n\nexport function changeCountsOf(lines: DiffLine[]) {\n  const additions = countOfKind(lines, ['added']);\n  const deletions = countOfKind(lines, ['removed']);\n  return { additions, deletions };\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/diff.ts"
    },
    {
      "path": "registry/ndeko/components/review/_parts/path-parts.ts",
      "content": "export function pathPartsOf(path: string) {\n  const slash = path.lastIndexOf('/');\n  if (slash < 0) {\n    return { folder: '', name: path };\n  }\n  const nameStart = slash + 1;\n  const folder = path.slice(0, nameStart);\n  const name = path.slice(nameStart);\n  return { folder, name };\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/path-parts.ts"
    }
  ],
  "categories": [
    "components",
    "review"
  ],
  "type": "registry:component"
}