{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-04",
  "title": "Diff review",
  "description": "Hunks stream in line by line and take a verdict stamp from Keep or Reject, rejected ones fold, J, K, Y and N drive it, and unified slides apart into split.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "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/kbd.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.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/replay-button.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-demo-run.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/review/review-04.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useRef, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll, type WordRollWord } from '@/components/core/word-roll';\nimport type { RunScriptStep } from '@/registry/ndeko/hooks/use-agent-run';\nimport { useDemoRun } from '@/registry/ndeko/hooks/use-demo-run';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport {\n  emptyRun,\n  type RunSnapshot,\n  type ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport {\n  CheckIcon,\n  FileTextIcon,\n  RotateCcwIcon,\n  XIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { EASE_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\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 } from '@/registry/ndeko/ui/chat-motion';\nimport { Chip } from '@/registry/ndeko/ui/chip';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { isShortcutKey } from './_parts/keys';\nimport { pathPartsOf } from './_parts/path-parts';\nimport { useContainerWidth } from './_parts/use-container-width';\n\nexport type HunkLineKind = 'context' | 'removed' | 'added';\n\nexport type HunkLine = {\n  id: string;\n  kind: HunkLineKind;\n  text: string;\n  oldNumber: number | null;\n  newNumber: number | null;\n};\n\nexport type ReviewHunk = {\n  id: string;\n  header: string;\n  lines: HunkLine[];\n};\n\nexport type HunkVerdict = 'kept' | 'rejected';\n\nexport type DiffLayout = 'unified' | 'split';\n\ntype Placement = {\n  key: string;\n  line: HunkLine;\n  row: number;\n  column: 1 | 2;\n  side: 'both' | 'old' | 'new';\n};\n\n/** Under this width of the piece, two columns of code would not fit, so the split folds back to unified. */\nconst SPLIT_MIN_WIDTH = 640;\n\nconst LINE_TONE: Record<HunkLineKind, string> = {\n  context: '',\n  removed: 'bg-destructive/10',\n  added: 'bg-success/10',\n};\n\nconst SIGN: Record<HunkLineKind, string> = {\n  context: ' ',\n  removed: '−',\n  added: '+',\n};\n\nconst SIGN_TONE: Record<HunkLineKind, string> = {\n  context: 'text-muted-foreground',\n  removed: 'text-destructive-ink',\n  added: 'text-success-foreground',\n};\n\nconst SPOKEN_KIND: Record<HunkLineKind, string> = {\n  context: '',\n  removed: 'Removed: ',\n  added: 'Added: ',\n};\n\nfunction unifiedPlacementsOf(lines: HunkLine[]): Placement[] {\n  return lines.map((line, index) => ({\n    key: line.id,\n    line,\n    row: index + 1,\n    column: 1,\n    side: 'both',\n  }));\n}\n\n/** Context sits on both sides; each run of removed lines faces the added lines that replace it. */\nfunction splitPlacementsOf(lines: HunkLine[]): Placement[] {\n  const placements: Placement[] = [];\n  let row = 1;\n  let removed: HunkLine[] = [];\n  let added: HunkLine[] = [];\n\n  function flush() {\n    removed.forEach((line, index) => {\n      placements.push({\n        key: line.id,\n        line,\n        row: row + index,\n        column: 1,\n        side: 'old',\n      });\n    });\n    added.forEach((line, index) => {\n      placements.push({\n        key: line.id,\n        line,\n        row: row + index,\n        column: 2,\n        side: 'new',\n      });\n    });\n    const height = Math.max(removed.length, added.length);\n    row += height;\n    removed = [];\n    added = [];\n  }\n\n  for (const line of lines) {\n    if (line.kind === 'context') {\n      flush();\n      placements.push({ key: line.id, line, row, column: 1, side: 'old' });\n      placements.push({\n        key: `${line.id}-copy`,\n        line,\n        row,\n        column: 2,\n        side: 'new',\n      });\n      row += 1;\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 placements;\n}\n\nfunction placementsOf(lines: HunkLine[], layout: DiffLayout) {\n  if (layout === 'split') {\n    return splitPlacementsOf(lines);\n  }\n  return unifiedPlacementsOf(lines);\n}\n\nfunction gridColumnsOf(layout: DiffLayout) {\n  if (layout === 'split') {\n    return 'grid-cols-[repeat(2,minmax(max-content,1fr))]';\n  }\n  return 'grid-cols-[minmax(max-content,1fr)]';\n}\n\nfunction numberText(number: number | null) {\n  if (number === null) {\n    return '';\n  }\n  return String(number);\n}\n\nfunction sideNumberOf(placement: Placement) {\n  if (placement.side === 'new') {\n    return placement.line.newNumber;\n  }\n  return placement.line.oldNumber;\n}\n\nfunction LineCell({ placement }: { placement: Placement }) {\n  const { line } = placement;\n  const isUnified = placement.side === 'both';\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[line.kind]\n      )}\n    >\n      {isUnified && (\n        <>\n          <span className='text-muted-foreground/70 w-8 shrink-0 pe-1.5 text-end tabular-nums select-none'>\n            {numberText(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            {numberText(line.newNumber)}\n          </span>\n        </>\n      )}\n      {!isUnified && (\n        <span className='text-muted-foreground/70 w-8 shrink-0 pe-1.5 text-end tabular-nums select-none'>\n          {numberText(sideNumberOf(placement))}\n        </span>\n      )}\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\nconst STAMP_IN = {\n  initial: { opacity: 0, scale: 1.12 },\n  animate: { opacity: 1, scale: 1 },\n  exit: { opacity: 0, scale: 0.96 },\n  transition: { duration: 0.12, ease: EASE_OUT_STRONG },\n} as const;\n\nconst STAMP_FADE = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0 },\n  transition: { duration: 0.12 },\n} as const;\n\nfunction stampMotionOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return STAMP_FADE;\n  }\n  return STAMP_IN;\n}\n\nconst VERDICT_WORD: Record<HunkVerdict, string> = {\n  kept: 'Kept',\n  rejected: 'Rejected',\n};\n\nconst VERDICT_COLOR: Record<HunkVerdict, string> = {\n  kept: 'var(--success)',\n  rejected: 'var(--destructive)',\n};\n\nconst VERDICT_PAST: Record<HunkVerdict, string> = {\n  kept: 'kept',\n  rejected: 'rejected',\n};\n\nfunction isStreamingCall(call: ToolCall) {\n  return call.status !== 'done';\n}\n\nfunction layoutTransitionOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return { duration: 0 };\n  }\n  return { type: 'spring' as const, bounce: 0, duration: 0.4 };\n}\n\nfunction hunkLabelOf(\n  hunk: ReviewHunk,\n  index: number,\n  total: number,\n  verdict: HunkVerdict | undefined\n) {\n  const position = index + 1;\n  const base = `Hunk ${position} of ${total}, ${hunk.header}`;\n  if (!verdict) {\n    return base;\n  }\n  return `${base}, ${VERDICT_WORD[verdict]}`;\n}\n\nfunction surfaceOf(isCurrent: boolean) {\n  if (isCurrent) {\n    return 'bg-foreground/[0.035] dark:bg-foreground/[0.05]';\n  }\n  return 'bg-foreground/[0.02] dark:bg-foreground/[0.03]';\n}\n\ntype HunkViewProps = {\n  hunk: ReviewHunk;\n  index: number;\n  total: number;\n  shownLines: number;\n  isStreaming: boolean;\n  verdict: HunkVerdict | undefined;\n  layout: DiffLayout;\n  isCurrent: boolean;\n  onVerdict: (hunkId: string, verdict: HunkVerdict) => void;\n  onUndo: (hunkId: string) => void;\n  onFocusHunk: (hunkId: string) => void;\n  registerHunk: (hunkId: string, node: HTMLElement | null) => void;\n};\n\nexport function HunkView({\n  hunk,\n  index,\n  total,\n  shownLines,\n  isStreaming,\n  verdict,\n  layout,\n  isCurrent,\n  onVerdict,\n  onUndo,\n  onFocusHunk,\n  registerHunk,\n}: HunkViewProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const stampMotion = stampMotionOf(shouldReduceMotion);\n  const layoutTransition = layoutTransitionOf(shouldReduceMotion);\n  const visibleLines = hunk.lines.slice(0, shownLines);\n  const placements = placementsOf(visibleLines, layout);\n  const isKept = verdict === 'kept';\n  const isRejected = verdict === 'rejected';\n  const hasVerdict = verdict !== undefined;\n  const canDecide = !isStreaming && !hasVerdict;\n  const position = index + 1;\n\n  return (\n    <section\n      ref={(node) => registerHunk(hunk.id, node)}\n      tabIndex={0}\n      aria-label={hunkLabelOf(hunk, index, total, verdict)}\n      onFocus={() => onFocusHunk(hunk.id)}\n      className={cn(\n        'focus-visible:ring-ring/25 flex flex-col overflow-hidden rounded-lg transition-colors duration-150 outline-none focus-visible:ring-[3px]',\n        surfaceOf(isCurrent)\n      )}\n    >\n      <header className='flex min-h-9 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          {hunk.header}\n        </span>\n        <AnimatePresence initial={false} mode='popLayout'>\n          {verdict && (\n            <motion.span key={verdict} className='flex' {...stampMotion}>\n              <Chip color={VERDICT_COLOR[verdict]}>\n                {isKept && <CheckIcon />}\n                {isRejected && <XIcon />}\n                {VERDICT_WORD[verdict]}\n              </Chip>\n            </motion.span>\n          )}\n        </AnimatePresence>\n        {hasVerdict && (\n          <Button\n            type='button'\n            variant='ghost'\n            size='sm'\n            onClick={() => onUndo(hunk.id)}\n            aria-label={`Undo the verdict on hunk ${position}`}\n            className='text-muted-foreground h-7 px-2'\n          >\n            <RotateCcwIcon className='size-3.5' />\n            Undo\n          </Button>\n        )}\n        {!hasVerdict && (\n          <span className='flex items-center gap-1'>\n            <Button\n              type='button'\n              variant='outline'\n              size='sm'\n              disabled={!canDecide}\n              onClick={() => onVerdict(hunk.id, 'kept')}\n            >\n              Keep\n              <Kbd className='ms-0.5 hidden @md:inline-flex'>Y</Kbd>\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              disabled={!canDecide}\n              onClick={() => onVerdict(hunk.id, 'rejected')}\n            >\n              Reject\n              <Kbd className='ms-0.5 hidden @md:inline-flex'>N</Kbd>\n            </Button>\n          </span>\n        )}\n      </header>\n      <Fold open={!isRejected}>\n        <div className='overflow-x-auto pb-1.5'>\n          <div className={cn('grid w-max min-w-full', gridColumnsOf(layout))}>\n            <AnimatePresence initial={false}>\n              {placements.map((placement) => (\n                <motion.div\n                  key={placement.key}\n                  layout='position'\n                  transition={layoutTransition}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                  style={{\n                    gridRow: placement.row,\n                    gridColumn: placement.column,\n                  }}\n                >\n                  <LineCell placement={placement} />\n                </motion.div>\n              ))}\n            </AnimatePresence>\n          </div>\n        </div>\n      </Fold>\n    </section>\n  );\n}\n\ntype HunkSource = {\n  id: string;\n  oldStart: number;\n  newStart: number;\n  /** Each line starts with its sign: a space for context, a minus, or a plus. */\n  lines: string[];\n};\n\nconst KIND_OF_SIGN: Record<string, HunkLineKind> = {\n  ' ': 'context',\n  '-': 'removed',\n  '+': 'added',\n};\n\nfunction hunkOf(source: HunkSource): ReviewHunk {\n  let oldNumber = source.oldStart;\n  let newNumber = source.newStart;\n  let oldCount = 0;\n  let newCount = 0;\n  const lines: HunkLine[] = source.lines.map((raw, index) => {\n    const sign = raw.charAt(0);\n    const kind = KIND_OF_SIGN[sign] ?? 'context';\n    const text = raw.slice(1);\n    const id = `${source.id}-${index}`;\n    if (kind === 'context') {\n      const line = { id, kind, text, oldNumber, newNumber };\n      oldNumber += 1;\n      newNumber += 1;\n      oldCount += 1;\n      newCount += 1;\n      return line;\n    }\n    if (kind === 'removed') {\n      const line = { id, kind, text, oldNumber, newNumber: null };\n      oldNumber += 1;\n      oldCount += 1;\n      return line;\n    }\n    const line = { id, kind, text, oldNumber: null, newNumber };\n    newNumber += 1;\n    newCount += 1;\n    return line;\n  });\n  const header = `@@ -${source.oldStart},${oldCount} +${source.newStart},${newCount} @@`;\n  return { id: source.id, header, lines };\n}\n\nconst FILE_PATH = 'src/billing/pallet-fee.ts';\n\nconst HUNKS: ReviewHunk[] = [\n  hunkOf({\n    id: 'imports',\n    oldStart: 1,\n    newStart: 1,\n    lines: [\n      \" import { money } from '../money';\",\n      \"-import { tierFor } from './tiers';\",\n      \"+import { FLAT_FROM_PALLETS, tierFor } from './tiers';\",\n      \" import type { Order } from './types';\",\n    ],\n  }),\n  hunkOf({\n    id: 'constants',\n    oldStart: 8,\n    newStart: 8,\n    lines: [\n      ' export const TIER_RATES = [15.9, 15.2, 14.6];',\n      '+export const FLAT_FEE_EUR = 18.4;',\n      \"+export const FLAT_FEE_START = '2026-10-01';\",\n      ' ',\n    ],\n  }),\n  hunkOf({\n    id: 'fee',\n    oldStart: 14,\n    newStart: 16,\n    lines: [\n      ' export function palletFee(order: Order) {',\n      '+  if (isFlatOrder(order)) {',\n      '+    return money(order.pallets * FLAT_FEE_EUR);',\n      '+  }',\n      '   const tier = tierFor(order.pallets);',\n      '-  return money(order.pallets * TIER_RATES[tier]);',\n      '+  const rate = TIER_RATES[tier];',\n      '+  return money(order.pallets * rate);',\n      ' }',\n    ],\n  }),\n  hunkOf({\n    id: 'legacy',\n    oldStart: 18,\n    newStart: 24,\n    lines: [\n      ' ',\n      '-/** @deprecated Use palletFee. */',\n      '-export const legacyPalletFee = palletFee;',\n      '+function isFlatOrder(order: Order) {',\n      '+  const isBulk = order.pallets >= FLAT_FROM_PALLETS;',\n      '+  const isAfterStart = order.date >= FLAT_FEE_START;',\n      '+  return isBulk && isAfterStart;',\n      '+}',\n    ],\n  }),\n];\n\nfunction totalsOf(hunks: ReviewHunk[]) {\n  let additions = 0;\n  let deletions = 0;\n  for (const hunk of hunks) {\n    for (const line of hunk.lines) {\n      if (line.kind === 'added') {\n        additions += 1;\n      }\n      if (line.kind === 'removed') {\n        deletions += 1;\n      }\n    }\n  }\n  return { additions, deletions };\n}\n\nconst TOTALS = totalsOf(HUNKS);\n\nconst LINE_MS = 70;\n\nconst HUNK_GAP_MS = 260;\n\nfunction scriptOf(hunks: ReviewHunk[]): RunScriptStep[] {\n  const steps: RunScriptStep[] = [\n    { after: 400, event: { type: 'run.started' } },\n  ];\n  for (const hunk of hunks) {\n    steps.push({\n      after: HUNK_GAP_MS,\n      event: {\n        type: 'call.started',\n        call: {\n          id: hunk.id,\n          tool: 'edit_file',\n          label: hunk.header,\n          status: 'running',\n          output: { lines: 0 },\n        },\n      },\n    });\n    for (let shown = 1; shown <= hunk.lines.length; shown += 1) {\n      steps.push({\n        after: LINE_MS,\n        event: {\n          type: 'call.updated',\n          id: hunk.id,\n          patch: { output: { lines: shown } },\n        },\n      });\n    }\n    steps.push({\n      after: 0,\n      event: { type: 'call.updated', id: hunk.id, patch: { status: 'done' } },\n    });\n  }\n  steps.push({ after: 0, event: { type: 'run.finished', status: 'done' } });\n  return steps;\n}\n\nconst SCRIPT = scriptOf(HUNKS);\n\nconst INITIAL_RUN = emptyRun({ id: 'diff-review', title: FILE_PATH });\n\ntype LinesOutput = { lines: number };\n\nfunction isLinesOutput(value: unknown): value is LinesOutput {\n  if (typeof value !== 'object' || value === null) {\n    return false;\n  }\n  return typeof (value as LinesOutput).lines === 'number';\n}\n\nfunction shownLinesOf(call: ToolCall) {\n  if (isLinesOutput(call.output)) {\n    return call.output.lines;\n  }\n  return 0;\n}\n\nfunction streamedHunksOf(run: RunSnapshot) {\n  const streamed: { hunk: ReviewHunk; call: ToolCall }[] = [];\n  for (const hunk of HUNKS) {\n    const call = run.calls.find((candidate) => candidate.id === hunk.id);\n    if (call) {\n      streamed.push({ hunk, call });\n    }\n  }\n  return streamed;\n}\n\nfunction reviewedWordsOf(reviewed: number, total: number): WordRollWord[] {\n  const countWord = {\n    key: 'reviewed',\n    text: String(reviewed),\n    node: <MotionNumber value={reviewed} />,\n  };\n  return [countWord, 'of', String(total), 'hunks', 'reviewed'];\n}\n\nconst LAYOUTS: Segment<DiffLayout>[] = [\n  { value: 'unified', label: 'Unified' },\n  { value: 'split', label: 'Split' },\n];\n\nfunction layoutOf(choice: DiffLayout, isWide: boolean): DiffLayout {\n  if (isWide) {\n    return choice;\n  }\n  return 'unified';\n}\n\nfunction applyLabelsOf(keptCount: number): Record<MorphState, string> {\n  const changes = countOf(keptCount, 'kept change');\n  const idle = idleApplyLabelOf(keptCount, changes);\n  return {\n    idle,\n    busy: 'Applying',\n    done: 'Applied',\n  };\n}\n\nfunction idleApplyLabelOf(keptCount: number, changes: string) {\n  if (keptCount === 0) {\n    return 'Nothing kept to apply';\n  }\n  return `Apply ${changes}`;\n}\n\nfunction positionOf(hunkId: string) {\n  const index = HUNKS.findIndex((hunk) => hunk.id === hunkId);\n  return index + 1;\n}\n\nconst APPLYING_MS = 900;\n\nexport default function Review04() {\n  const [verdicts, setVerdicts] = useState<Record<string, HunkVerdict>>({});\n  const [currentId, setCurrentId] = useState<string | null>(null);\n  const [layoutChoice, setLayoutChoice] = useState<DiffLayout>('unified');\n  const [applyState, setApplyState] = useState<MorphState>('idle');\n  const [notice, setNotice] = useState('');\n  const [frame, setFrame] = useState<HTMLDivElement | null>(null);\n  const hunkNodes = useRef(new Map<string, HTMLElement>());\n  const { schedule, clearAll } = useTimeouts();\n  const { ref, snapshot, restart } = useDemoRun(SCRIPT, {\n    initial: INITIAL_RUN,\n  });\n  const width = useContainerWidth(frame, 720);\n  const isWide = width >= SPLIT_MIN_WIDTH;\n  const layout = layoutOf(layoutChoice, isWide);\n  const streamed = streamedHunksOf(snapshot);\n  const hasNoHunk = streamed.length === 0;\n  const reviewedCount = Object.keys(verdicts).length;\n  const keptHunks = HUNKS.filter((hunk) => verdicts[hunk.id] === 'kept');\n  const keptCount = keptHunks.length;\n  const isAllReviewed = reviewedCount === HUNKS.length;\n  const isApplied = applyState === 'done';\n  const canApply = isAllReviewed && keptCount > 0;\n  const { folder, name } = pathPartsOf(FILE_PATH);\n  const reviewedWords = reviewedWordsOf(reviewedCount, HUNKS.length);\n\n  function registerHunk(hunkId: string, node: HTMLElement | null) {\n    if (node) {\n      hunkNodes.current.set(hunkId, node);\n      return;\n    }\n    hunkNodes.current.delete(hunkId);\n  }\n\n  function focusHunk(hunkId: string) {\n    const node = hunkNodes.current.get(hunkId);\n    node?.focus();\n  }\n\n  function streamedIds() {\n    return streamed.map((entry) => entry.hunk.id);\n  }\n\n  function nextOpenAfter(\n    hunkId: string,\n    nextVerdicts: Record<string, HunkVerdict>\n  ) {\n    const ids = streamedIds();\n    const start = ids.indexOf(hunkId);\n    const later = ids.slice(start + 1);\n    const earlier = ids.slice(0, start);\n    const order = [...later, ...earlier];\n    return order.find((id) => nextVerdicts[id] === undefined);\n  }\n\n  function decide(hunkId: string, verdict: HunkVerdict) {\n    if (isApplied) {\n      return;\n    }\n    const nextVerdicts = { ...verdicts, [hunkId]: verdict };\n    setVerdicts(nextVerdicts);\n    const position = positionOf(hunkId);\n    setNotice(`Hunk ${position} ${VERDICT_PAST[verdict]}`);\n    const nextId = nextOpenAfter(hunkId, nextVerdicts);\n    focusHunk(nextId ?? hunkId);\n  }\n\n  function undo(hunkId: string) {\n    setVerdicts((current) => {\n      const next = { ...current };\n      delete next[hunkId];\n      return next;\n    });\n    setApplyState('idle');\n    setNotice('Verdict undone');\n    focusHunk(hunkId);\n  }\n\n  function move(step: number) {\n    const ids = streamedIds();\n    if (ids.length === 0) {\n      return;\n    }\n    const currentIndex = ids.indexOf(currentId ?? '');\n    const target = currentIndex + step;\n    const bounded = Math.min(ids.length - 1, Math.max(0, target));\n    focusHunk(ids[bounded]);\n  }\n\n  function targetHunkId() {\n    if (currentId) {\n      return currentId;\n    }\n    const ids = streamedIds();\n    return ids.find((id) => verdicts[id] === undefined);\n  }\n\n  function isStreamedDone(hunkId: string) {\n    const entry = streamed.find((candidate) => candidate.hunk.id === hunkId);\n    return entry?.call.status === 'done';\n  }\n\n  function decideFromKeys(verdict: HunkVerdict) {\n    const hunkId = targetHunkId();\n    if (!hunkId) {\n      return;\n    }\n    const hasVerdict = verdicts[hunkId] !== undefined;\n    const isReady = isStreamedDone(hunkId);\n    const canDecide = isReady && !hasVerdict;\n    if (canDecide) {\n      decide(hunkId, verdict);\n    }\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (!isShortcutKey(event)) {\n      return;\n    }\n    const key = event.key.toLowerCase();\n    if (key === 'j') {\n      event.preventDefault();\n      move(1);\n      return;\n    }\n    if (key === 'k') {\n      event.preventDefault();\n      move(-1);\n      return;\n    }\n    if (key === 'y') {\n      event.preventDefault();\n      decideFromKeys('kept');\n      return;\n    }\n    if (key === 'n') {\n      event.preventDefault();\n      decideFromKeys('rejected');\n    }\n  }\n\n  function trackFocusLeaving(event: React.FocusEvent<HTMLDivElement>) {\n    const next = event.relatedTarget;\n    const staysInside =\n      next instanceof Node && event.currentTarget.contains(next);\n    if (!staysInside) {\n      setCurrentId(null);\n    }\n  }\n\n  function apply() {\n    if (!canApply) {\n      return;\n    }\n    setApplyState('busy');\n    schedule(() => {\n      setApplyState('done');\n      setNotice(`Applied ${countOf(keptCount, 'change')} to ${name}`);\n    }, APPLYING_MS);\n  }\n\n  function replay() {\n    clearAll();\n    setVerdicts({});\n    setCurrentId(null);\n    setApplyState('idle');\n    setNotice('');\n    restart();\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      onKeyDown={handleKeys}\n      onBlur={trackFocusLeaving}\n      className='bg-card hairline-ring ring-border @container 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      <header className='flex flex-wrap items-center gap-x-3 gap-y-2 px-1'>\n        <span className='flex min-w-0 flex-1 basis-48 items-center gap-2'>\n          <span className='keycap-3d text-muted-foreground inline-flex size-6 shrink-0 items-center justify-center rounded-md'>\n            <FileTextIcon className='size-3.5' />\n          </span>\n          <span className='min-w-0 truncate font-mono text-[13px]'>\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'>+{TOTALS.additions}</span>\n            <span className='text-destructive-ink'>−{TOTALS.deletions}</span>\n          </span>\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      </header>\n\n      <div ref={setFrame} className='flex flex-col gap-2'>\n        <ul aria-label='Hunks' className='flex flex-col gap-2'>\n          <AnimatePresence initial={false}>\n            {streamed.map((entry, index) => (\n              <motion.li\n                key={entry.hunk.id}\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                exit={{ opacity: 0 }}\n                transition={{ duration: 0.2 }}\n              >\n                <HunkView\n                  hunk={entry.hunk}\n                  index={index}\n                  total={HUNKS.length}\n                  shownLines={shownLinesOf(entry.call)}\n                  isStreaming={isStreamingCall(entry.call)}\n                  verdict={verdicts[entry.hunk.id]}\n                  layout={layout}\n                  isCurrent={currentId === entry.hunk.id}\n                  onVerdict={decide}\n                  onUndo={undo}\n                  onFocusHunk={setCurrentId}\n                  registerHunk={registerHunk}\n                />\n              </motion.li>\n            ))}\n          </AnimatePresence>\n        </ul>\n        {hasNoHunk && (\n          <p className='text-muted-foreground px-1 py-6 text-center text-[13px]'>\n            The agent is preparing its changes\n          </p>\n        )}\n      </div>\n\n      <footer className='flex flex-wrap items-center gap-x-3 gap-y-2 px-1'>\n        <span className='text-muted-foreground min-w-0 flex-1 text-xs'>\n          <WordRoll words={reviewedWords} />\n        </span>\n        <span className='text-muted-foreground hidden items-center gap-1 text-xs @lg:flex'>\n          <Kbd>J</Kbd>\n          <Kbd>K</Kbd> move, <Kbd>Y</Kbd> keeps, <Kbd>N</Kbd> rejects\n        </span>\n        <AnimatedSize as='span' axis='width'>\n          <span className='flex items-center gap-2'>\n            <ReplayButton\n              isShown={isApplied}\n              onReplay={replay}\n              label='Review again'\n            />\n            <MorphButton\n              type='button'\n              size='sm'\n              state={applyState}\n              labels={applyLabelsOf(keptCount)}\n              disabled={!canApply}\n              onClick={apply}\n            />\n          </span>\n        </AnimatedSize>\n      </footer>\n      <LiveRegion message={notice} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/review/review-04.tsx"
    },
    {
      "path": "registry/ndeko/components/review/_parts/keys.ts",
      "content": "const FIELD_SELECTOR = 'input, textarea, select, [contenteditable=\"true\"]';\n\nexport function isTypingTarget(target: EventTarget | null) {\n  if (!(target instanceof HTMLElement)) {\n    return false;\n  }\n  const isField = target.matches(FIELD_SELECTOR);\n  return isField || target.isContentEditable;\n}\n\nexport function hasModifierKey(event: React.KeyboardEvent) {\n  const hasCommand = event.metaKey || event.ctrlKey;\n  return hasCommand || event.altKey;\n}\n\n/** Keydown that started inside this element, not in a menu or popover portalled out of it. */\nexport function isOwnKey(event: React.KeyboardEvent<HTMLElement>) {\n  const target = event.target;\n  if (!(target instanceof Node)) {\n    return false;\n  }\n  return event.currentTarget.contains(target);\n}\n\n/**\n * Single-letter shortcuts act only while focus is inside the piece, never while a field takes the\n * typing and never with a modifier held, so they cannot steal a browser or system shortcut.\n */\nexport function isShortcutKey(event: React.KeyboardEvent<HTMLElement>) {\n  const isTyping = isTypingTarget(event.target);\n  const hasModifier = hasModifierKey(event);\n  const isOwn = isOwnKey(event);\n  const isBlocked = isTyping || hasModifier;\n  return isOwn && !isBlocked;\n}\n",
      "type": "registry:component",
      "target": "components/review/_parts/keys.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"
}