{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-05",
  "title": "Inline diff",
  "description": "Two versions compared in the browser, changed words tinted inside their lines, unchanged runs folded behind a count, and each hunk settled by Accept or Reject.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/chip.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-word-roll.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/theme.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-05.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { 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  CheckIcon,\n  ChevronsUpDownIcon,\n  FileTextIcon,\n  RotateCcwIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Chip } from '@/registry/ndeko/ui/chip';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport {\n  blocksOf,\n  changeCountsOf,\n  hunkHeaderOf,\n  lineDiffOf,\n  partnersOf,\n  wordDiffOf,\n  type DiffBlock,\n  type DiffLine,\n  type WordPiece,\n} from './_parts/diff';\nimport { pathPartsOf } from './_parts/path-parts';\nimport { useContainerWidth } from './_parts/use-container-width';\n\nexport type HunkDecision = 'accepted' | 'rejected';\n\nexport type InlineDiffLayout = 'unified' | 'split';\n\ntype SplitRow = {\n  key: string;\n  left: DiffLine | null;\n  right: DiffLine | null;\n};\n\n/** Two columns of code need this much of the piece; below it the view stays unified. */\nconst SPLIT_MIN_WIDTH = 640;\n\nconst CONTEXT_LINES = 2;\n\nconst MIN_FOLD = 4;\n\nconst LINE_TONE: Record<DiffLine['kind'], string> = {\n  same: '',\n  removed: 'bg-destructive/10',\n  added: 'bg-success/10',\n};\n\nconst WORD_TONE: Record<DiffLine['kind'], string> = {\n  same: '',\n  removed: 'bg-destructive/25 rounded-[3px]',\n  added: 'bg-success/30 rounded-[3px]',\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\nconst NUMBER_CELL =\n  'text-muted-foreground/70 w-8 shrink-0 pe-1.5 text-end tabular-nums select-none';\n\nfunction numberText(number: number | null) {\n  if (number === null) {\n    return '';\n  }\n  return String(number);\n}\n\nfunction piecesOf(line: DiffLine, partner: DiffLine | undefined) {\n  const plain: WordPiece[] = [{ text: line.text, isChanged: false }];\n  if (!partner) {\n    return plain;\n  }\n  if (line.kind === 'removed') {\n    const diff = wordDiffOf(line.text, partner.text);\n    return diff.before;\n  }\n  if (line.kind === 'added') {\n    const diff = wordDiffOf(partner.text, line.text);\n    return diff.after;\n  }\n  return plain;\n}\n\nfunction CodeText({\n  line,\n  partner,\n}: {\n  line: DiffLine;\n  partner: DiffLine | undefined;\n}) {\n  const pieces = piecesOf(line, partner);\n\n  return (\n    <code className='whitespace-pre'>\n      {pieces.map((piece, index) => {\n        if (piece.isChanged) {\n          return (\n            <span key={index} className={WORD_TONE[line.kind]}>\n              {piece.text}\n            </span>\n          );\n        }\n        return <span key={index}>{piece.text}</span>;\n      })}\n    </code>\n  );\n}\n\ntype CodeLineProps = {\n  line: DiffLine;\n  partner: DiffLine | undefined;\n  numbers: 'both' | 'old' | 'new';\n  isResolved?: boolean;\n};\n\nfunction CodeLine({\n  line,\n  partner,\n  numbers,\n  isResolved = false,\n}: CodeLineProps) {\n  const kind = lineKindOf(line, isResolved);\n  const showsBoth = numbers === 'both';\n  const sideNumber = sideNumberOf(line, numbers);\n\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[kind]\n      )}\n    >\n      {showsBoth && (\n        <>\n          <span className={NUMBER_CELL}>{numberText(line.oldNumber)}</span>\n          <span className={NUMBER_CELL}>{numberText(line.newNumber)}</span>\n        </>\n      )}\n      {!showsBoth && (\n        <span className={NUMBER_CELL}>{numberText(sideNumber)}</span>\n      )}\n      <span\n        aria-hidden='true'\n        className={cn('w-4 shrink-0 text-center select-none', SIGN_TONE[kind])}\n      >\n        {SIGN[kind]}\n      </span>\n      <span className='sr-only'>{SPOKEN_KIND[kind]}</span>\n      {isResolved && <code className='whitespace-pre'>{line.text}</code>}\n      {!isResolved && <CodeText line={line} partner={partner} />}\n    </div>\n  );\n}\n\nfunction lineKindOf(line: DiffLine, isResolved: boolean) {\n  if (isResolved) {\n    return 'same';\n  }\n  return line.kind;\n}\n\nfunction sideNumberOf(line: DiffLine, numbers: 'both' | 'old' | 'new') {\n  if (numbers === 'new') {\n    return line.newNumber;\n  }\n  return line.oldNumber;\n}\n\n/** Context sits on both sides; each run of removed lines faces the added lines that replace it. */\nexport function splitRowsOf(lines: DiffLine[]): SplitRow[] {\n  const rows: SplitRow[] = [];\n  let removed: DiffLine[] = [];\n  let added: DiffLine[] = [];\n\n  function flush() {\n    const height = Math.max(removed.length, added.length);\n    for (let index = 0; index < height; index += 1) {\n      const left = removed[index] ?? null;\n      const right = added[index] ?? null;\n      const leftKey = left?.key ?? '';\n      const rightKey = right?.key ?? '';\n      rows.push({ key: `${leftKey}|${rightKey}`, left, right });\n    }\n    removed = [];\n    added = [];\n  }\n\n  for (const line of lines) {\n    if (line.kind === 'same') {\n      flush();\n      rows.push({ key: line.key, left: line, right: line });\n      continue;\n    }\n    if (line.kind === 'removed') {\n      const startsNewChange = added.length > 0;\n      if (startsNewChange) {\n        flush();\n      }\n      removed.push(line);\n      continue;\n    }\n    added.push(line);\n  }\n  flush();\n  return rows;\n}\n\nfunction EmptyCell() {\n  return (\n    <div\n      aria-hidden='true'\n      className='bg-foreground/[0.03] dark:bg-foreground/[0.05] min-h-5'\n    />\n  );\n}\n\ntype LinesViewProps = {\n  lines: DiffLine[];\n  partners: Map<string, DiffLine>;\n  layout: InlineDiffLayout;\n};\n\nfunction LinesView({ lines, partners, layout }: LinesViewProps) {\n  if (layout === 'split') {\n    const rows = splitRowsOf(lines);\n    return (\n      <div className='grid w-max min-w-full grid-cols-[repeat(2,minmax(max-content,1fr))]'>\n        {rows.map((row) => (\n          <div key={row.key} className='contents'>\n            {row.left && (\n              <CodeLine\n                line={row.left}\n                partner={partners.get(row.left.key)}\n                numbers='old'\n              />\n            )}\n            {!row.left && <EmptyCell />}\n            {row.right && (\n              <CodeLine\n                line={row.right}\n                partner={partners.get(row.right.key)}\n                numbers='new'\n              />\n            )}\n            {!row.right && <EmptyCell />}\n          </div>\n        ))}\n      </div>\n    );\n  }\n  return (\n    <div className='w-max min-w-full'>\n      {lines.map((line) => (\n        <CodeLine\n          key={line.key}\n          line={line}\n          partner={partners.get(line.key)}\n          numbers='both'\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction resolvedLinesOf(lines: DiffLine[], decision: HunkDecision) {\n  const dropped = droppedKindOf(decision);\n  return lines.filter((line) => line.kind !== dropped);\n}\n\nfunction droppedKindOf(decision: HunkDecision) {\n  if (decision === 'accepted') {\n    return 'removed';\n  }\n  return 'added';\n}\n\nconst DECISION_WORD: Record<HunkDecision, string> = {\n  accepted: 'Accepted',\n  rejected: 'Rejected',\n};\n\nconst DECISION_COLOR: Record<HunkDecision, string> = {\n  accepted: 'var(--success)',\n  rejected: 'var(--muted-foreground)',\n};\n\nfunction resolvedNumbersOf(decision: HunkDecision) {\n  if (decision === 'accepted') {\n    return 'new';\n  }\n  return 'old';\n}\n\nconst BODY_SWAP = {\n  initial: { opacity: 0, filter: 'blur(2px)' },\n  animate: { opacity: 1, filter: 'blur(0px)' },\n  exit: { opacity: 0, filter: 'blur(2px)' },\n  transition: { duration: 0.2, ease: [0.23, 1, 0.32, 1] },\n} as const;\n\nconst BODY_FADE = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0 },\n  transition: { duration: 0.15 },\n} as const;\n\nfunction bodyMotionOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return BODY_FADE;\n  }\n  return BODY_SWAP;\n}\n\ntype HunkViewProps = {\n  lines: DiffLine[];\n  partners: Map<string, DiffLine>;\n  layout: InlineDiffLayout;\n  decision: HunkDecision | undefined;\n  onDecide: (decision: HunkDecision) => void;\n  onUndo: () => void;\n};\n\nfunction HunkView({\n  lines,\n  partners,\n  layout,\n  decision,\n  onDecide,\n  onUndo,\n}: HunkViewProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const bodyMotion = bodyMotionOf(shouldReduceMotion);\n  const header = hunkHeaderOf(lines);\n  const bodyKey = `${decision ?? 'open'}-${layout}`;\n\n  return (\n    <section\n      aria-label={hunkLabelOf(header, decision)}\n      className='flex flex-col'\n    >\n      <header className='bg-foreground/[0.035] dark:bg-foreground/[0.05] flex min-h-8 items-center gap-2 ps-3 pe-1.5'>\n        <span className='text-muted-foreground min-w-0 flex-1 truncate font-mono text-xs'>\n          {header}\n        </span>\n        <AnimatePresence initial={false} mode='popLayout'>\n          {decision && (\n            <motion.span\n              key={decision}\n              className='flex'\n              initial={{ opacity: 0, scale: 0.95 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={{ opacity: 0 }}\n              transition={{ duration: 0.15 }}\n            >\n              <Chip color={DECISION_COLOR[decision]}>\n                {DECISION_WORD[decision]}\n              </Chip>\n            </motion.span>\n          )}\n        </AnimatePresence>\n        {decision && (\n          <Button\n            type='button'\n            variant='ghost'\n            size='sm'\n            onClick={onUndo}\n            className='text-muted-foreground h-6 px-2'\n          >\n            <RotateCcwIcon className='size-3.5' />\n            Undo\n          </Button>\n        )}\n        {!decision && (\n          <span className='flex items-center gap-1'>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              onClick={() => onDecide('accepted')}\n              className='h-6 px-2'\n            >\n              <CheckIcon className='text-success-foreground size-3.5' />\n              Accept\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              onClick={() => onDecide('rejected')}\n              className='h-6 px-2'\n            >\n              <XIcon className='text-destructive-ink size-3.5' />\n              Reject\n            </Button>\n          </span>\n        )}\n      </header>\n      <AnimatedSize>\n        <div className='relative'>\n          <AnimatePresence initial={false} mode='popLayout'>\n            <motion.div key={bodyKey} {...bodyMotion}>\n              <CodeScroller label={header}>\n                {decision && (\n                  <ResolvedLines lines={lines} decision={decision} />\n                )}\n                {!decision && (\n                  <LinesView\n                    lines={lines}\n                    partners={partners}\n                    layout={layout}\n                  />\n                )}\n              </CodeScroller>\n            </motion.div>\n          </AnimatePresence>\n        </div>\n      </AnimatedSize>\n    </section>\n  );\n}\n\n/** Long lines scroll sideways inside their own block, so the header and its buttons stay in view. */\nfunction CodeScroller({\n  label,\n  children,\n}: {\n  label: string;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      role='region'\n      aria-label={`Code, ${label}`}\n      tabIndex={0}\n      className='focus-visible:ring-ring/25 overflow-x-auto py-0.5 outline-none focus-visible:ring-[3px] focus-visible:ring-inset'\n    >\n      {children}\n    </div>\n  );\n}\n\nfunction ResolvedLines({\n  lines,\n  decision,\n}: {\n  lines: DiffLine[];\n  decision: HunkDecision;\n}) {\n  const kept = resolvedLinesOf(lines, decision);\n  const numbers = resolvedNumbersOf(decision);\n\n  return (\n    <div className='w-max min-w-full'>\n      {kept.map((line) => (\n        <CodeLine\n          key={line.key}\n          line={line}\n          partner={undefined}\n          numbers={numbers}\n          isResolved\n        />\n      ))}\n    </div>\n  );\n}\n\nfunction hunkLabelOf(header: string, decision: HunkDecision | undefined) {\n  if (!decision) {\n    return `Hunk ${header}`;\n  }\n  return `Hunk ${header}, ${DECISION_WORD[decision]}`;\n}\n\nfunction foldLabelOf(count: number, isOpen: boolean) {\n  const lines = countOf(count, 'unchanged line');\n  if (isOpen) {\n    return `Hide ${lines}`;\n  }\n  return lines;\n}\n\ntype FoldRowProps = {\n  block: Extract<DiffBlock, { kind: 'fold' }>;\n  isOpen: boolean;\n  onToggle: () => void;\n};\n\nfunction FoldRow({ block, isOpen, onToggle }: FoldRowProps) {\n  const label = foldLabelOf(block.lines.length, isOpen);\n\n  return (\n    <div className='flex flex-col'>\n      <button\n        type='button'\n        aria-expanded={isOpen}\n        onClick={onToggle}\n        className='text-muted-foreground hover:bg-foreground/[0.04] hover:text-foreground focus-visible:ring-ring/25 flex h-7 w-full cursor-pointer items-center gap-2 ps-3 text-xs transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-inset'\n      >\n        <ChevronsUpDownIcon className='size-3.5' />\n        <Swap swapKey={label}>{label}</Swap>\n      </button>\n      <Fold open={isOpen}>\n        <CodeScroller label={label}>\n          <div className='w-max min-w-full'>\n            {block.lines.map((line) => (\n              <CodeLine\n                key={line.key}\n                line={line}\n                partner={undefined}\n                numbers='both'\n              />\n            ))}\n          </div>\n        </CodeScroller>\n      </Fold>\n    </div>\n  );\n}\n\nexport type InlineDiffProps = {\n  path: string;\n  before: string;\n  after: string;\n  layout: InlineDiffLayout;\n  decisions: Record<string, HunkDecision>;\n  onDecide: (hunkKey: string, decision: HunkDecision | null) => void;\n  className?: string;\n};\n\nexport function InlineDiff({\n  path,\n  before,\n  after,\n  layout,\n  decisions,\n  onDecide,\n  className,\n}: InlineDiffProps) {\n  const [openFolds, setOpenFolds] = useState<string[]>([]);\n  const beforeLines = before.split('\\n');\n  const afterLines = after.split('\\n');\n  const lines = lineDiffOf(beforeLines, afterLines);\n  const partners = partnersOf(lines);\n  const blocks = blocksOf(lines, CONTEXT_LINES, MIN_FOLD);\n  const counts = changeCountsOf(lines);\n  const { folder, name } = pathPartsOf(path);\n\n  function toggleFold(key: string) {\n    setOpenFolds((current) => {\n      const isOpen = current.includes(key);\n      if (isOpen) {\n        return current.filter((candidate) => candidate !== key);\n      }\n      return [...current, key];\n    });\n  }\n\n  return (\n    <div\n      className={cn(\n        'bg-foreground/[0.02] dark:bg-foreground/[0.035] flex flex-col overflow-hidden rounded-lg',\n        className\n      )}\n    >\n      <div className='flex items-center gap-2 px-3 py-2'>\n        <FileTextIcon className='text-muted-foreground size-3.5 shrink-0' />\n        <span className='min-w-0 flex-1 truncate font-mono text-xs'>\n          <span className='text-muted-foreground'>{folder}</span>\n          {name}\n        </span>\n        <span className='flex shrink-0 items-center gap-1.5 font-mono text-xs tabular-nums'>\n          <span className='text-success-foreground'>+{counts.additions}</span>\n          <span className='text-destructive-ink'>−{counts.deletions}</span>\n        </span>\n      </div>\n      <div aria-label={`Changes to ${name}`} role='group'>\n        <div className='flex min-w-0 flex-col gap-px'>\n          {blocks.map((block) => {\n            if (block.kind === 'fold') {\n              const isOpen = openFolds.includes(block.key);\n              return (\n                <FoldRow\n                  key={block.key}\n                  block={block}\n                  isOpen={isOpen}\n                  onToggle={() => toggleFold(block.key)}\n                />\n              );\n            }\n            return (\n              <HunkView\n                key={block.key}\n                lines={block.lines}\n                partners={partners}\n                layout={layout}\n                decision={decisions[block.key]}\n                onDecide={(decision) => onDecide(block.key, decision)}\n                onUndo={() => onDecide(block.key, null)}\n              />\n            );\n          })}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst PATH = 'src/orders/checkout.ts';\n\nconst BEFORE = `import { palletFee } from '../billing/pallet-fee';\nimport { vatFor } from '../billing/vat';\nimport { roundCents } from '../money';\nimport type { Cart, CartLine, Checkout } from './types';\n\nconst ORDER_PREFIX = 'BM';\n\nexport function orderNumberOf(cart: Cart) {\n  const year = cart.date.slice(0, 4);\n  const serial = String(cart.serial).padStart(5, '0');\n  return \\`\\${ORDER_PREFIX}-\\${year}-\\${serial}\\`;\n}\n\nexport function lineTotalOf(line: CartLine) {\n  const total = line.unitPrice * line.quantity;\n  return roundCents(total);\n}\n\nexport function subtotalOf(cart: Cart) {\n  let total = 0;\n  for (const line of cart.lines) {\n    total += lineTotalOf(line);\n  }\n  return roundCents(total);\n}\n\nexport function shippingOf(cart: Cart) {\n  const pallets = cart.lines.length;\n  return palletFee({ pallets, date: cart.date });\n}\n\nexport function discountOf(cart: Cart) {\n  if (!cart.coupon) {\n    return 0;\n  }\n  return cart.coupon.amount;\n}\n\nexport function isEmptyCart(cart: Cart) {\n  return cart.lines.length === 0;\n}\n\nexport function itemCountOf(cart: Cart) {\n  let count = 0;\n  for (const line of cart.lines) {\n    count += line.quantity;\n  }\n  return count;\n}\n\nexport function checkoutOf(cart: Cart): Checkout {\n  const subtotal = subtotalOf(cart);\n  const shipping = shippingOf(cart);\n  const discount = discountOf(cart);\n  const vat = vatFor(subtotal + shipping);\n  const total = subtotal + shipping + vat - discount;\n  return { subtotal, shipping, discount, vat, total };\n}`;\n\nconst AFTER = `import { palletFee } from '../billing/pallet-fee';\nimport { vatFor } from '../billing/vat';\nimport { roundCents } from '../money';\nimport type { Cart, CartLine, Checkout } from './types';\n\nconst ORDER_PREFIX = 'BM';\nconst UNITS_PER_PALLET = 40;\n\nexport function orderNumberOf(cart: Cart) {\n  const year = cart.date.slice(0, 4);\n  const serial = String(cart.serial).padStart(5, '0');\n  return \\`\\${ORDER_PREFIX}-\\${year}-\\${serial}\\`;\n}\n\nexport function lineTotalOf(line: CartLine) {\n  const total = line.unitPrice * line.quantity;\n  return roundCents(total);\n}\n\nexport function subtotalOf(cart: Cart) {\n  let total = 0;\n  for (const line of cart.lines) {\n    total += lineTotalOf(line);\n  }\n  return roundCents(total);\n}\n\nfunction palletsOf(cart: Cart) {\n  const units = itemCountOf(cart);\n  return Math.ceil(units / UNITS_PER_PALLET);\n}\n\nexport function shippingOf(cart: Cart) {\n  const pallets = palletsOf(cart);\n  return palletFee({ pallets, date: cart.date });\n}\n\nexport function discountOf(cart: Cart) {\n  if (!cart.coupon) {\n    return 0;\n  }\n  return Math.min(cart.coupon.amount, subtotalOf(cart));\n}\n\nexport function isEmptyCart(cart: Cart) {\n  return cart.lines.length === 0;\n}\n\nexport function itemCountOf(cart: Cart) {\n  let count = 0;\n  for (const line of cart.lines) {\n    count += line.quantity;\n  }\n  return count;\n}\n\nexport function checkoutOf(cart: Cart): Checkout {\n  const subtotal = subtotalOf(cart);\n  const shipping = shippingOf(cart);\n  const discount = discountOf(cart);\n  const taxable = subtotal + shipping - discount;\n  const vat = vatFor(taxable);\n  const total = taxable + vat;\n  return { subtotal, shipping, discount, vat, total };\n}`;\n\nconst LAYOUTS: Segment<InlineDiffLayout>[] = [\n  { value: 'unified', label: 'Unified' },\n  { value: 'split', label: 'Split' },\n];\n\nfunction layoutOf(choice: InlineDiffLayout, isWide: boolean) {\n  if (isWide) {\n    return choice;\n  }\n  return 'unified';\n}\n\nfunction hunkCountOf(before: string, after: string) {\n  const beforeLines = before.split('\\n');\n  const afterLines = after.split('\\n');\n  const lines = lineDiffOf(beforeLines, afterLines);\n  const blocks = blocksOf(lines, CONTEXT_LINES, MIN_FOLD);\n  const hunks = blocks.filter((block) => block.kind === 'hunk');\n  return hunks.length;\n}\n\nconst HUNK_COUNT = hunkCountOf(BEFORE, AFTER);\n\nfunction decidedWordsOf(decided: number, total: number): WordRollWord[] {\n  const countWord = {\n    key: 'decided',\n    text: String(decided),\n    node: <MotionNumber value={decided} />,\n  };\n  return [countWord, 'of', String(total), 'hunks', 'decided'];\n}\n\nfunction noticeOf(decision: HunkDecision | null) {\n  if (decision === 'accepted') {\n    return 'Hunk accepted';\n  }\n  if (decision === 'rejected') {\n    return 'Hunk rejected';\n  }\n  return 'Decision undone';\n}\n\nexport default function Review05() {\n  const [layoutChoice, setLayoutChoice] = useState<InlineDiffLayout>('unified');\n  const [decisions, setDecisions] = useState<Record<string, HunkDecision>>({});\n  const [notice, setNotice] = useState('');\n  const [frame, setFrame] = useState<HTMLDivElement | null>(null);\n  const width = useContainerWidth(frame, 720);\n  const isWide = width >= SPLIT_MIN_WIDTH;\n  const layout = layoutOf(layoutChoice, isWide);\n  const decidedCount = Object.keys(decisions).length;\n  const decidedWords = decidedWordsOf(decidedCount, HUNK_COUNT);\n\n  function decide(hunkKey: string, decision: HunkDecision | null) {\n    setDecisions((current) => {\n      const next = { ...current };\n      if (decision === null) {\n        delete next[hunkKey];\n        return next;\n      }\n      next[hunkKey] = decision;\n      return next;\n    });\n    setNotice(noticeOf(decision));\n  }\n\n  return (\n    <div\n      ref={setFrame}\n      className='bg-card hairline-ring ring-border flex w-full max-w-[52rem] flex-col gap-3 rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n    >\n      <div className='flex flex-wrap items-center justify-between gap-x-3 gap-y-2 px-1'>\n        <span className='text-muted-foreground text-xs'>\n          <WordRoll words={decidedWords} />\n        </span>\n        <AnimatePresence initial={false}>\n          {isWide && (\n            <motion.span\n              key='layout'\n              className='flex'\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0 }}\n            >\n              <Segments\n                value={layoutChoice}\n                segments={LAYOUTS}\n                onValueChange={setLayoutChoice}\n                label='Diff layout'\n                className='w-40'\n              />\n            </motion.span>\n          )}\n        </AnimatePresence>\n      </div>\n      <InlineDiff\n        path={PATH}\n        before={BEFORE}\n        after={AFTER}\n        layout={layout}\n        decisions={decisions}\n        onDecide={decide}\n      />\n      <LiveRegion message={notice} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/review/review-05.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"
    },
    {
      "path": "registry/ndeko/components/review/_parts/use-container-width.ts",
      "content": "'use client';\n\nimport { useLayoutEffect, useState } from 'react';\n\n/**\n * The width of an element as it resizes. A piece in a narrow column of a wide window switches layout\n * by the room it has, which the viewport cannot tell.\n */\nexport function useContainerWidth(\n  target: HTMLElement | null,\n  fallback: number\n) {\n  const [width, setWidth] = useState(fallback);\n\n  useLayoutEffect(() => {\n    if (!target) {\n      return;\n    }\n    const observer = new ResizeObserver(([entry]) => {\n      const box = entry.contentBoxSize[0];\n      setWidth(box.inlineSize);\n    });\n    observer.observe(target);\n    return () => observer.disconnect();\n  }, [target]);\n\n  return width;\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/use-container-width.ts"
    }
  ],
  "categories": [
    "components",
    "review"
  ],
  "type": "registry:component"
}