{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "review-11",
  "title": "Prose diff",
  "description": "Suggested edits marked inside a paragraph, each accepted or rejected from a card that glides to it or with Y and N, with J and K to move, Undo and a count that rolls.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/button.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/mesh-tile.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/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-11.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useId, useRef, 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 { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { CheckIcon, RotateCcwIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { springOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\n\nimport { isShortcutKey } from './_parts/keys';\n\nexport type Suggestion = {\n  id: string;\n  /** Words the edit takes out; empty for an insertion. */\n  removed: string;\n  /** Words the edit puts in; empty for a deletion. */\n  added: string;\n  /** Why the edit helps, in a few words. */\n  reason: string;\n};\n\nexport type ProsePiece =\n  | { kind: 'text'; text: string }\n  | { kind: 'suggestion'; suggestion: Suggestion };\n\nexport type Decision = 'accepted' | 'rejected';\n\ntype CardPlace = { left: number; top: number };\n\nconst CARD_WIDTH = 256;\n\nconst CARD_GAP = 6;\n\nconst NEXT_KEYS = ['j', 'arrowright', 'arrowdown'];\n\nconst PREVIOUS_KEYS = ['k', 'arrowleft', 'arrowup'];\n\nfunction suggestionsOf(pieces: ProsePiece[]) {\n  const suggestions: Suggestion[] = [];\n  for (const piece of pieces) {\n    if (piece.kind === 'suggestion') {\n      suggestions.push(piece.suggestion);\n    }\n  }\n  return suggestions;\n}\n\nfunction removedToneOf(decision: Decision | undefined) {\n  if (decision === 'rejected') {\n    return 'decoration-transparent bg-transparent text-foreground';\n  }\n  return 'decoration-destructive-ink/70 bg-destructive/10 text-destructive-ink';\n}\n\nfunction addedToneOf(decision: Decision | undefined) {\n  if (decision === 'accepted') {\n    return 'decoration-transparent bg-transparent text-foreground';\n  }\n  return 'decoration-success-foreground/70 bg-success/10 text-success-foreground';\n}\n\nconst PART_EXIT = { opacity: 0, transition: { duration: 0.15 } };\n\ntype SuggestionMarkProps = {\n  suggestion: Suggestion;\n  decision: Decision | undefined;\n  position: number;\n  total: number;\n  isActive: boolean;\n  isTabStop: boolean;\n  cardId: string;\n  isCardOpen: boolean;\n  register: (id: string, node: HTMLElement | null) => void;\n  onActivate: (id: string, node: HTMLElement) => void;\n};\n\nfunction SuggestionMark({\n  suggestion,\n  decision,\n  position,\n  total,\n  isActive,\n  isTabStop,\n  cardId,\n  isCardOpen,\n  register,\n  onActivate,\n}: SuggestionMarkProps) {\n  const isPending = decision === undefined;\n  const hasRemoved = suggestion.removed !== '';\n  const hasAdded = suggestion.added !== '';\n  const keepsRemoved = decision !== 'accepted';\n  const keepsAdded = decision !== 'rejected';\n  const showsRemoved = hasRemoved && keepsRemoved;\n  const showsAdded = hasAdded && keepsAdded;\n  const isExpanded = isActive && isCardOpen;\n  const parts = (\n    <>\n      <AnimatePresence initial={false}>\n        {showsRemoved && (\n          <motion.span\n            key='removed'\n            exit={PART_EXIT}\n            className={cn(\n              'rounded-[3px] line-through decoration-1 transition-[color,background-color,text-decoration-color] duration-300',\n              removedToneOf(decision)\n            )}\n          >\n            {isPending && <span className='sr-only'>Delete: </span>}\n            {suggestion.removed}\n          </motion.span>\n        )}\n      </AnimatePresence>\n      <AnimatePresence initial={false}>\n        {showsAdded && (\n          <motion.span\n            key='added'\n            exit={PART_EXIT}\n            className={cn(\n              'rounded-[3px] underline decoration-1 underline-offset-[3px] transition-[color,background-color,text-decoration-color] duration-300',\n              addedToneOf(decision)\n            )}\n          >\n            {isPending && <span className='sr-only'> Insert: </span>}\n            {suggestion.added}\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </>\n  );\n\n  if (!isPending) {\n    return <span>{parts}</span>;\n  }\n\n  function activate(event: React.SyntheticEvent<HTMLSpanElement>) {\n    onActivate(suggestion.id, event.currentTarget);\n  }\n\n  function openFromKeys(event: React.KeyboardEvent<HTMLSpanElement>) {\n    const isEnter = event.key === 'Enter';\n    const isSpace = event.key === ' ';\n    const opens = isEnter || isSpace;\n    if (opens) {\n      event.preventDefault();\n      onActivate(suggestion.id, event.currentTarget);\n    }\n  }\n\n  return (\n    <span\n      ref={(node) => register(suggestion.id, node)}\n      role='button'\n      tabIndex={tabIndexOf(isTabStop)}\n      aria-label={`Suggestion ${position} of ${total}: ${suggestion.reason}`}\n      aria-expanded={isExpanded}\n      aria-controls={cardId}\n      onFocus={activate}\n      onClick={activate}\n      onKeyDown={openFromKeys}\n      className={cn(\n        'focus-visible:ring-ring/40 cursor-pointer rounded-[3px] box-decoration-clone transition-[background-color,box-shadow] duration-150 outline-none focus-visible:ring-2',\n        activeToneOf(isActive)\n      )}\n    >\n      {parts}\n    </span>\n  );\n}\n\nfunction tabIndexOf(isTabStop: boolean) {\n  if (isTabStop) {\n    return 0;\n  }\n  return -1;\n}\n\nfunction activeToneOf(isActive: boolean) {\n  if (isActive) {\n    return 'bg-foreground/[0.06]';\n  }\n  return '';\n}\n\ntype SuggestionCardProps = {\n  suggestion: Suggestion;\n  position: number;\n  total: number;\n  place: CardPlace;\n  cardId: string;\n  onAccept: () => void;\n  onReject: () => void;\n};\n\nfunction SuggestionCard({\n  suggestion,\n  position,\n  total,\n  place,\n  cardId,\n  onAccept,\n  onReject,\n}: SuggestionCardProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const glide = springOf(shouldReduceMotion);\n\n  return (\n    <motion.div\n      id={cardId}\n      role='group'\n      aria-label={`Suggestion ${position} of ${total}`}\n      className='surface-raised absolute z-20 flex flex-col gap-2 rounded-xl p-2.5'\n      style={{ width: CARD_WIDTH }}\n      initial={{ opacity: 0, scale: 0.97, x: place.left, y: place.top }}\n      animate={{ opacity: 1, scale: 1, x: place.left, y: place.top }}\n      exit={{ opacity: 0, scale: 0.97, transition: { duration: 0.1 } }}\n      transition={glide}\n    >\n      <p className='flex items-baseline justify-between gap-2 text-xs'>\n        <span className='text-foreground font-medium'>{suggestion.reason}</span>\n        <span className='text-muted-foreground shrink-0 tabular-nums'>\n          {position} of {total}\n        </span>\n      </p>\n      <span className='flex items-center gap-1.5'>\n        <Button type='button' size='sm' onClick={onAccept}>\n          <CheckIcon />\n          Accept\n          <Kbd className='ms-0.5'>Y</Kbd>\n        </Button>\n        <Button type='button' size='sm' variant='outline' onClick={onReject}>\n          <XIcon />\n          Reject\n          <Kbd className='ms-0.5'>N</Kbd>\n        </Button>\n      </span>\n    </motion.div>\n  );\n}\n\n/** Under the last line of the mark, kept inside the paragraph so it never runs off a narrow piece. */\nfunction placeOf(container: HTMLElement, mark: HTMLElement): CardPlace {\n  const origin = container.getBoundingClientRect();\n  const fragments = mark.getClientRects();\n  const lastIndex = fragments.length - 1;\n  const last = fragments[lastIndex] ?? mark.getBoundingClientRect();\n  const rawLeft = last.left - origin.left;\n  const roomLeft = origin.width - CARD_WIDTH;\n  const maxLeft = Math.max(0, roomLeft);\n  const boundedLeft = Math.min(rawLeft, maxLeft);\n  const left = Math.max(0, boundedLeft);\n  const lineBottom = last.bottom - origin.top;\n  const top = lineBottom + CARD_GAP;\n  return { left, top };\n}\n\nfunction isMarkTarget(target: EventTarget) {\n  if (!(target instanceof HTMLElement)) {\n    return false;\n  }\n  const role = target.getAttribute('role');\n  return role === 'button';\n}\n\n/** From no active mark, moving forward lands on the first and moving back on the last. */\nfunction movedIndexOf(currentIndex: number, step: number, count: number) {\n  const hasCurrent = currentIndex >= 0;\n  if (!hasCurrent) {\n    return firstIndexFor(step, count);\n  }\n  const moved = currentIndex + step;\n  const shifted = moved + count;\n  return shifted % count;\n}\n\nfunction firstIndexFor(step: number, count: number) {\n  if (step > 0) {\n    return 0;\n  }\n  return count - 1;\n}\n\nfunction cardSuggestionOf(isCardOpen: boolean, active: Suggestion | undefined) {\n  if (!isCardOpen) {\n    return undefined;\n  }\n  return active;\n}\n\nfunction leftWordsOf(left: number, total: number): WordRollWord[] {\n  if (left === 0) {\n    return ['All', String(total), 'settled'];\n  }\n  const countWord = {\n    key: 'left',\n    text: String(left),\n    node: <MotionNumber value={left} />,\n  };\n  return [countWord, 'of', String(total), 'left'];\n}\n\ntype HistoryEntry = { ids: string[] };\n\nexport type ProseDiffProps = {\n  pieces: ProsePiece[];\n  className?: string;\n};\n\nexport function ProseDiff({ pieces, className }: ProseDiffProps) {\n  const [decisions, setDecisions] = useState<Record<string, Decision>>({});\n  const [history, setHistory] = useState<HistoryEntry[]>([]);\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [isCardOpen, setIsCardOpen] = useState(false);\n  const [place, setPlace] = useState<CardPlace>({ left: 0, top: 0 });\n  const [notice, setNotice] = useState('');\n  const containerRef = useRef<HTMLDivElement>(null);\n  const undoRef = useRef<HTMLButtonElement>(null);\n  const marks = useRef(new Map<string, HTMLElement>());\n  const isReturningFocus = useRef(false);\n  const cardId = useId();\n  const suggestions = suggestionsOf(pieces);\n  const pending = suggestions.filter(\n    (entry) => decisions[entry.id] === undefined\n  );\n  const total = suggestions.length;\n  const leftWords = leftWordsOf(pending.length, total);\n  const active = pending.find((entry) => entry.id === activeId);\n  const tabStopId = active?.id ?? pending[0]?.id;\n  const cardSuggestion = cardSuggestionOf(isCardOpen, active);\n  const hasHistory = history.length > 0;\n  const hasPending = pending.length > 0;\n\n  useEffect(() => {\n    const container = containerRef.current;\n    if (!container) {\n      return;\n    }\n    if (!activeId) {\n      return;\n    }\n    const markId = activeId;\n    const observer = new ResizeObserver(() => {\n      const mark = marks.current.get(markId);\n      if (!mark) {\n        return;\n      }\n      setPlace(placeOf(container, mark));\n    });\n    observer.observe(container);\n    return () => observer.disconnect();\n  }, [activeId]);\n\n  function register(id: string, node: HTMLElement | null) {\n    if (node) {\n      marks.current.set(id, node);\n      return;\n    }\n    marks.current.delete(id);\n  }\n\n  function activate(id: string, node: HTMLElement) {\n    const container = containerRef.current;\n    const isReturning = isReturningFocus.current;\n    isReturningFocus.current = false;\n    setActiveId(id);\n    if (!isReturning) {\n      setIsCardOpen(true);\n    }\n    if (container) {\n      setPlace(placeOf(container, node));\n    }\n  }\n\n  function focusMark(id: string) {\n    const mark = marks.current.get(id);\n    mark?.focus();\n  }\n\n  function positionOf(id: string) {\n    const index = suggestions.findIndex((entry) => entry.id === id);\n    return index + 1;\n  }\n\n  function pendingAfter(id: string, nextDecisions: Record<string, Decision>) {\n    const index = suggestions.findIndex((entry) => entry.id === id);\n    const later = suggestions.slice(index + 1);\n    const earlier = suggestions.slice(0, index);\n    const order = [...later, ...earlier];\n    return order.find((entry) => nextDecisions[entry.id] === undefined);\n  }\n\n  function decide(id: string, decision: Decision) {\n    const nextDecisions = { ...decisions, [id]: decision };\n    setDecisions(nextDecisions);\n    setHistory((current) => [...current, { ids: [id] }]);\n    const position = positionOf(id);\n    setNotice(`Suggestion ${position} ${decision}`);\n    const next = pendingAfter(id, nextDecisions);\n    if (next) {\n      focusMark(next.id);\n      return;\n    }\n    setActiveId(null);\n    setIsCardOpen(false);\n    undoRef.current?.focus();\n  }\n\n  function decideAll(decision: Decision) {\n    const ids = pending.map((entry) => entry.id);\n    if (ids.length === 0) {\n      return;\n    }\n    setDecisions((current) => {\n      const next = { ...current };\n      for (const id of ids) {\n        next[id] = decision;\n      }\n      return next;\n    });\n    setHistory((current) => [...current, { ids }]);\n    setActiveId(null);\n    setIsCardOpen(false);\n    const decided = countOf(ids.length, 'suggestion');\n    setNotice(`${decided} ${decision}`);\n  }\n\n  function undo() {\n    const last = history.at(-1);\n    if (!last) {\n      return;\n    }\n    setHistory((current) => current.slice(0, -1));\n    setDecisions((current) => {\n      const next = { ...current };\n      for (const id of last.ids) {\n        delete next[id];\n      }\n      return next;\n    });\n    const [firstId] = last.ids;\n    setNotice('Last decision undone');\n    requestAnimationFrame(() => focusMark(firstId));\n  }\n\n  function move(step: number) {\n    if (!hasPending) {\n      return;\n    }\n    const currentIndex = pending.findIndex((entry) => entry.id === activeId);\n    const index = movedIndexOf(currentIndex, step, pending.length);\n    focusMark(pending[index].id);\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (!isShortcutKey(event)) {\n      return;\n    }\n    const key = event.key.toLowerCase();\n    const isArrow = key.startsWith('arrow');\n    const isOnMark = isMarkTarget(event.target);\n    const blocksArrow = isArrow && !isOnMark;\n    if (blocksArrow) {\n      return;\n    }\n    if (key === 'escape') {\n      closeCard();\n      return;\n    }\n    if (NEXT_KEYS.includes(key)) {\n      event.preventDefault();\n      move(1);\n      return;\n    }\n    if (PREVIOUS_KEYS.includes(key)) {\n      event.preventDefault();\n      move(-1);\n      return;\n    }\n    if (!active) {\n      return;\n    }\n    if (key === 'y') {\n      event.preventDefault();\n      decide(active.id, 'accepted');\n      return;\n    }\n    if (key === 'n') {\n      event.preventDefault();\n      decide(active.id, 'rejected');\n    }\n  }\n\n  function closeCard() {\n    setIsCardOpen(false);\n    if (!activeId) {\n      return;\n    }\n    isReturningFocus.current = true;\n    focusMark(activeId);\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      setIsCardOpen(false);\n    }\n  }\n\n  return (\n    <div\n      onKeyDown={handleKeys}\n      onBlur={trackFocusLeaving}\n      className={cn('flex flex-col gap-3', className)}\n    >\n      <div ref={containerRef} className='relative'>\n        <p className='text-[15px] leading-8'>\n          {pieces.map((piece, index) => {\n            if (piece.kind === 'text') {\n              return <span key={index}>{piece.text}</span>;\n            }\n            const { suggestion } = piece;\n            return (\n              <SuggestionMark\n                key={suggestion.id}\n                suggestion={suggestion}\n                decision={decisions[suggestion.id]}\n                position={positionOf(suggestion.id)}\n                total={total}\n                isActive={suggestion.id === activeId}\n                isTabStop={suggestion.id === tabStopId}\n                cardId={cardId}\n                isCardOpen={isCardOpen}\n                register={register}\n                onActivate={activate}\n              />\n            );\n          })}\n        </p>\n        <AnimatePresence>\n          {cardSuggestion && (\n            <SuggestionCard\n              key='card'\n              suggestion={cardSuggestion}\n              position={positionOf(cardSuggestion.id)}\n              total={total}\n              place={place}\n              cardId={cardId}\n              onAccept={() => decide(cardSuggestion.id, 'accepted')}\n              onReject={() => decide(cardSuggestion.id, 'rejected')}\n            />\n          )}\n        </AnimatePresence>\n      </div>\n      <div className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n        <span className='text-muted-foreground min-w-0 flex-1 text-xs'>\n          <WordRoll words={leftWords} />\n        </span>\n        <Button\n          ref={undoRef}\n          type='button'\n          variant='ghost'\n          size='sm'\n          disabled={!hasHistory}\n          focusableWhenDisabled\n          onClick={undo}\n        >\n          <RotateCcwIcon />\n          Undo\n        </Button>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          disabled={!hasPending}\n          onClick={() => decideAll('rejected')}\n        >\n          Reject all\n        </Button>\n        <Button\n          type='button'\n          size='sm'\n          disabled={!hasPending}\n          onClick={() => decideAll('accepted')}\n        >\n          Accept all\n        </Button>\n      </div>\n      <p className='text-muted-foreground hidden items-center gap-1 text-xs @md:flex'>\n        <Kbd>J</Kbd>\n        <Kbd>K</Kbd> move, <Kbd>Y</Kbd> accepts, <Kbd>N</Kbd> rejects\n      </p>\n      <LiveRegion message={notice} />\n    </div>\n  );\n}\n\nfunction suggestion(\n  id: string,\n  removed: string,\n  added: string,\n  reason: string\n): ProsePiece {\n  return { kind: 'suggestion', suggestion: { id, removed, added, reason } };\n}\n\nfunction text(value: string): ProsePiece {\n  return { kind: 'text', text: value };\n}\n\nconst PIECES: ProsePiece[] = [\n  suggestion(\n    'opening',\n    'We are pleased to announce that starting from',\n    'From',\n    'A shorter opening'\n  ),\n  text(' 1 October, Brightmoor will '),\n  suggestion('verb', 'charge', 'bill', 'Matches the word on the invoice'),\n  text(' a flat fee of 18.40 EUR per pallet on bulk orders'),\n  suggestion(\n    'threshold',\n    '',\n    ' of 40 pallets or more',\n    'Says which orders the fee covers'\n  ),\n  text('. This makes pricing '),\n  suggestion('grammar', 'more ', '', 'Fixes the grammar'),\n  text(\n    'simpler for our customers. Orders under 40 pallets keep the tiered rates they have today. '\n  ),\n  suggestion(\n    'closing',\n    'If you have any questions, please do not hesitate to contact your account manager.',\n    'Questions? Your account manager can help.',\n    'Shorter and warmer'\n  ),\n];\n\nexport default function Review11() {\n  return (\n    <div className='bg-card hairline-ring ring-border @container w-full max-w-[38rem] rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n      <p className='text-muted-foreground mb-3 flex items-center gap-2 text-xs'>\n        <MeshTile seed='Writer' color={seriesColorOf(3)} />\n        <span>\n          <span className='text-foreground font-medium'>Writer</span> suggests\n          five edits to the customer notice\n        </span>\n      </p>\n      <ProseDiff pieces={PIECES} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/review/review-11.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"
    }
  ],
  "categories": [
    "components",
    "review"
  ],
  "type": "registry:component"
}