{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "prompt-06",
  "title": "Rewrite in place",
  "description": "Select a phrase, say how it should read and watch it rewritten as a tracked change word by word, whose marks fade into the text when you accept it.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-loader.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.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"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/prompt/prompt-06.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport {\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react';\n\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\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  hiddenIf,\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowUpIcon,\n  CheckIcon,\n  CircleAlertIcon,\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 { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { TextLoader } from '@/registry/ndeko/ui/chat-loader';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { isOwnKey, useAutosize } from './_parts/use-autosize';\n\nexport type RewriteRequest = {\n  phrase: string;\n  instruction: string;\n  before: string;\n  after: string;\n  /** 1 for the first take, then one more for each Try again. */\n  attempt: number;\n};\n\ntype Range = {\n  start: number;\n  end: number;\n};\n\ntype Mode =\n  'idle' | 'rewriting' | 'review' | 'accepting' | 'settling' | 'failed';\n\ntype DiffKind = 'same' | 'removed' | 'added';\n\ntype DiffPart = {\n  kind: DiffKind;\n  word: string;\n};\n\nconst QUICK_ASKS = ['Shorter', 'Friendlier', 'More direct'] as const;\n\nexport type QuickAsk = (typeof QUICK_ASKS)[number];\n\n/** A suggestion already on screen: the phrase, how it was asked and what came back. */\nexport type RewriteReview = {\n  start: number;\n  end: number;\n  instruction: string;\n  proposal: string;\n};\n\nexport type RewriteHandle = {\n  /** Selects a phrase, as dragging over it or Shift with the arrows does. */\n  select: (start: number, end: number) => void;\n  /** Shows a button of the bar held down. */\n  press: (key: QuickAsk | 'accept') => void;\n  ask: (instruction: string) => void;\n  accept: () => void;\n  discard: () => void;\n  review: (review: RewriteReview) => void;\n};\n\n/** The tint is one flat colour drawn as an image, so it can grow over the phrase from its first letter to its last, line after line. */\nconst PHRASE_TINT = [\n  'rounded-[3px] bg-no-repeat [background-image:linear-gradient(var(--tint),var(--tint))]',\n  '[--tint:color-mix(in_oklab,var(--primary)_15%,transparent)] dark:[--tint:color-mix(in_oklab,var(--primary)_25%,transparent)]',\n  'bg-[length:100%_100%] transition-[background-size] duration-300 ease-(--ease-out-strong) starting:bg-[length:0%_100%]',\n].join(' ');\n\nconst BAR_GAP = 8;\n\nconst ACCEPT_FADE_MS = 160;\n\nconst SETTLE_MS = 700;\n\nconst WORD_STAGGER_S = 0.06;\n\n/** The paragraph and its mirror share these metrics, so the phrase is measured where it is drawn. */\nconst TEXT_BOX = 'px-1 py-0.5 text-sm leading-6';\n\n/** A read-only textarea keeps no caret for Shift and the arrows, so the text stays selectable and edits are refused instead. */\nfunction refuseEdit(event: Event) {\n  event.preventDefault();\n}\n\nfunction keepValue() {}\n\nconst WORD_CHARACTER = /[\\p{L}\\p{N}'’-]/u;\n\nconst SPACE = /\\s/;\n\nfunction isSpaceAt(text: string, index: number) {\n  const character = text[index] ?? '';\n  return SPACE.test(character);\n}\n\nfunction isWordAt(text: string, index: number) {\n  const character = text[index] ?? '';\n  return WORD_CHARACTER.test(character);\n}\n\n/** A selection grown to whole words and trimmed of spaces, so a rewrite never cuts a word in half. */\nexport function phraseRangeOf(\n  text: string,\n  start: number,\n  end: number\n): Range | null {\n  let from = start;\n  let to = end;\n  while (from < to && isSpaceAt(text, from)) {\n    from += 1;\n  }\n  while (to > from && isSpaceAt(text, to - 1)) {\n    to -= 1;\n  }\n  if (from >= to) {\n    return null;\n  }\n  while (from > 0 && isWordAt(text, from - 1)) {\n    from -= 1;\n  }\n  while (to < text.length && isWordAt(text, to)) {\n    to += 1;\n  }\n  return { start: from, end: to };\n}\n\nfunction sameRange(first: Range | null, second: Range | null) {\n  if (first === null) {\n    return second === null;\n  }\n  if (second === null) {\n    return false;\n  }\n  const sameStart = first.start === second.start;\n  return sameStart && first.end === second.end;\n}\n\nfunction wordsIn(text: string) {\n  const trimmed = text.trim();\n  if (trimmed === '') {\n    return [];\n  }\n  return trimmed.split(/\\s+/);\n}\n\nfunction zeroRow(length: number) {\n  return Array.from({ length }, () => 0);\n}\n\nfunction lcsTable(oldWords: string[], newWords: string[]) {\n  const rowCount = oldWords.length + 1;\n  const columnCount = newWords.length + 1;\n  const table = Array.from({ length: rowCount }, () => zeroRow(columnCount));\n  for (let row = oldWords.length - 1; row >= 0; row -= 1) {\n    for (let column = newWords.length - 1; column >= 0; column -= 1) {\n      const isSame = oldWords[row] === newWords[column];\n      if (isSame) {\n        table[row][column] = table[row + 1][column + 1] + 1;\n        continue;\n      }\n      const skipOld = table[row + 1][column];\n      const skipNew = table[row][column + 1];\n      table[row][column] = Math.max(skipOld, skipNew);\n    }\n  }\n  return table;\n}\n\n/** Word by word: what stays, what goes and what arrives, removals before their replacement. */\nexport function diffWords(oldText: string, newText: string): DiffPart[] {\n  const oldWords = wordsIn(oldText);\n  const newWords = wordsIn(newText);\n  const table = lcsTable(oldWords, newWords);\n  const parts: DiffPart[] = [];\n  let row = 0;\n  let column = 0;\n  while (row < oldWords.length && column < newWords.length) {\n    const isSame = oldWords[row] === newWords[column];\n    if (isSame) {\n      parts.push({ kind: 'same', word: oldWords[row] });\n      row += 1;\n      column += 1;\n      continue;\n    }\n    const keepsMoreBySkippingOld =\n      table[row + 1][column] >= table[row][column + 1];\n    if (keepsMoreBySkippingOld) {\n      parts.push({ kind: 'removed', word: oldWords[row] });\n      row += 1;\n      continue;\n    }\n    parts.push({ kind: 'added', word: newWords[column] });\n    column += 1;\n  }\n  for (const word of oldWords.slice(row)) {\n    parts.push({ kind: 'removed', word });\n  }\n  for (const word of newWords.slice(column)) {\n    parts.push({ kind: 'added', word });\n  }\n  return parts;\n}\n\nfunction placeBar(\n  container: HTMLElement,\n  bar: HTMLElement,\n  phrase: HTMLElement\n) {\n  const box = container.getBoundingClientRect();\n  const whole = phrase.getBoundingClientRect();\n  const lines = phrase.getClientRects();\n  const firstLine = lines[0] ?? whole;\n  const lineCentre = (firstLine.left + firstLine.right) / 2;\n  const centre = lineCentre - box.left;\n  const barWidth = bar.offsetWidth;\n  const barHeight = bar.offsetHeight;\n  const wantedLeft = centre - barWidth / 2;\n  const maxLeft = Math.max(0, box.width - barWidth);\n  const left = Math.min(Math.max(0, wantedLeft), maxLeft);\n  const firstLineTop = firstLine.top - box.top;\n  const above = firstLineTop - barHeight - BAR_GAP;\n  const below = whole.bottom - box.top + BAR_GAP;\n  bar.style.left = `${left}px`;\n  if (above >= 0) {\n    bar.style.top = `${above}px`;\n    return;\n  }\n  bar.style.top = `${below}px`;\n}\n\nfunction wordStyleOf(kind: DiffKind) {\n  if (kind === 'removed') {\n    return 'text-destructive-ink/60 decoration-destructive-ink/60 line-through transition-[color,text-decoration-color] duration-300 starting:text-foreground starting:decoration-transparent';\n  }\n  if (kind === 'added') {\n    return 'text-primary-ink decoration-primary-ink/50 underline underline-offset-[3px]';\n  }\n  return '';\n}\n\nfunction spaceBefore(index: number) {\n  if (index === 0) {\n    return '';\n  }\n  return ' ';\n}\n\ntype TrackedChangeProps = {\n  parts: DiffPart[];\n  isAccepting: boolean;\n  phraseRef: React.Ref<HTMLSpanElement>;\n};\n\nfunction arrivalDelaysOf(parts: DiffPart[]) {\n  const delays: number[] = [];\n  let addedCount = 0;\n  for (const part of parts) {\n    const delay = addedCount * WORD_STAGGER_S;\n    delays.push(delay);\n    if (part.kind === 'added') {\n      addedCount += 1;\n    }\n  }\n  return delays;\n}\n\nfunction TrackedChange({ parts, isAccepting, phraseRef }: TrackedChangeProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const delays = arrivalDelaysOf(parts);\n  const arrival = arrivalOf(shouldReduceMotion);\n  const removedOpacity = removedOpacityOf(isAccepting);\n\n  return (\n    <span ref={phraseRef}>\n      {parts.map((part, index) => {\n        const space = spaceBefore(index);\n        if (part.kind === 'removed') {\n          return (\n            <span key={`removed-${index}`}>\n              {space}\n              <motion.del\n                initial={false}\n                animate={{ opacity: removedOpacity }}\n                transition={{ duration: 0.15 }}\n                className={wordStyleOf('removed')}\n              >\n                {part.word}\n              </motion.del>\n            </span>\n          );\n        }\n        if (part.kind === 'added') {\n          return (\n            <span key={`added-${index}`}>\n              {space}\n              <motion.ins\n                initial={arrival}\n                animate={{ opacity: 1, y: 0 }}\n                transition={{\n                  duration: 0.22,\n                  ease: EASE_OUT_STRONG,\n                  delay: delays[index],\n                }}\n                className={cn('inline-block', wordStyleOf('added'))}\n              >\n                {part.word}\n              </motion.ins>\n            </span>\n          );\n        }\n        return (\n          <span key={`same-${index}`}>\n            {space}\n            {part.word}\n          </span>\n        );\n      })}\n    </span>\n  );\n}\n\nfunction removedOpacityOf(isAccepting: boolean) {\n  if (isAccepting) {\n    return 0;\n  }\n  return 1;\n}\n\nfunction arrivalOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return { opacity: 0, y: 0 };\n  }\n  return { opacity: 0, y: 3 };\n}\n\nconst BAR_RISE = { duration: 0.18, ease: EASE_OUT_STRONG };\n\nconst BAR_PRESENCE = {\n  initial: { opacity: 0, y: 6, scale: 0.97 },\n  animate: { opacity: 1, y: 0, scale: 1 },\n  exit: { opacity: 0, scale: 0.97, transition: { duration: 0.1 } },\n  transition: BAR_RISE,\n};\n\n/** In a demonstration the bar waits for the tint to cross the phrase, so the two read as one after the other. */\nconst BAR_AFTER_SWEEP = {\n  ...BAR_PRESENCE,\n  transition: { ...BAR_RISE, delay: 0.24 },\n};\n\nconst BAR_FADE = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0, transition: { duration: 0.1 } },\n  transition: { duration: 0.15 },\n};\n\nfunction barPresenceOf(\n  shouldReduceMotion: boolean | null,\n  isDemonstrated: boolean\n) {\n  if (shouldReduceMotion) {\n    return BAR_FADE;\n  }\n  if (isDemonstrated) {\n    return BAR_AFTER_SWEEP;\n  }\n  return BAR_PRESENCE;\n}\n\nfunction rangeOfReview(review: RewriteReview | undefined): Range | null {\n  if (!review) {\n    return null;\n  }\n  return { start: review.start, end: review.end };\n}\n\nfunction modeOfReview(review: RewriteReview | undefined): Mode {\n  if (review) {\n    return 'review';\n  }\n  return 'idle';\n}\n\nfunction announcementOf(mode: Mode, proposal: string, isUnchanged: boolean) {\n  if (mode === 'rewriting') {\n    return 'Rewriting the phrase';\n  }\n  if (mode === 'review') {\n    if (isUnchanged) {\n      return 'No change suggested. Try again or discard';\n    }\n    return `Suggested: ${proposal}. Tab accepts, Escape discards`;\n  }\n  if (mode === 'settling') {\n    return 'Rewrite accepted';\n  }\n  if (mode === 'failed') {\n    return 'The rewrite failed. Try again or discard';\n  }\n  return '';\n}\n\nexport type RewriteInPlaceProps = {\n  value: string;\n  onValueChange: (value: string) => void;\n  rewrite: (request: RewriteRequest, signal: AbortSignal) => Promise<string>;\n  label: string;\n  /** Opens on a suggestion already made, waiting to be accepted or discarded. */\n  defaultReview?: RewriteReview;\n  /** Runs what the pointer and the bar do, for a demonstration or a control beside the text. */\n  handleRef?: React.Ref<RewriteHandle>;\n  /** A demonstration drives the piece: nothing takes the focus and nothing is read aloud. */\n  isDemonstrated?: boolean;\n  className?: string;\n};\n\nexport function RewriteInPlace({\n  value,\n  onValueChange,\n  rewrite,\n  label,\n  defaultReview,\n  handleRef,\n  isDemonstrated = false,\n  className,\n}: RewriteInPlaceProps) {\n  const [selection, setSelection] = useState<Range | null>(() =>\n    rangeOfReview(defaultReview)\n  );\n  const [mode, setMode] = useState<Mode>(() => modeOfReview(defaultReview));\n  const [instruction, setInstruction] = useState('');\n  const [lastInstruction, setLastInstruction] = useState(\n    defaultReview?.instruction ?? ''\n  );\n  const [proposal, setProposal] = useState(defaultReview?.proposal ?? '');\n  const [attempt, setAttempt] = useState(1);\n  const [settledRange, setSettledRange] = useState<Range | null>(null);\n  const { schedule, clearAll } = useTimeouts();\n  const { pressed, press } = usePress<QuickAsk | 'accept'>();\n  const containerRef = useRef<HTMLDivElement>(null);\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const barRef = useRef<HTMLDivElement>(null);\n  const phraseRef = useRef<HTMLSpanElement>(null);\n  const fieldRef = useRef<HTMLInputElement>(null);\n  const acceptRef = useRef<HTMLButtonElement>(null);\n  const request = useRef<AbortController | null>(null);\n  const hintId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const barPresence = barPresenceOf(shouldReduceMotion, isDemonstrated);\n  const canMoveFocus = !isDemonstrated;\n  const isReviewing = mode === 'review';\n  const isAccepting = mode === 'accepting';\n  const isSettling = mode === 'settling';\n  const showsChange = isReviewing || isAccepting;\n  const showsTextarea = !showsChange && !isSettling;\n  const isRewriting = mode === 'rewriting';\n  const isFailed = mode === 'failed';\n  const hasSelection = selection !== null;\n  const showsBar = hasSelection && !isSettling;\n  const before = sliceBefore(value, selection);\n  const phrase = sliceOf(value, selection);\n  const after = sliceAfter(value, selection);\n  const parts = diffWords(phrase, proposal);\n  const isUnchanged = proposal.trim() === phrase.trim();\n  const announcement = announcementOf(mode, proposal, isUnchanged);\n  useAutosize(textareaRef, value, 1000, showsTextarea);\n\n  useLayoutEffect(() => {\n    const container = containerRef.current;\n    const bar = barRef.current;\n    const phraseElement = phraseRef.current;\n    if (!container || !bar || !phraseElement) {\n      return;\n    }\n    placeBar(container, bar, phraseElement);\n    const observer = new ResizeObserver(() => {\n      placeBar(container, bar, phraseElement);\n    });\n    observer.observe(container);\n    observer.observe(bar);\n    return () => observer.disconnect();\n  }, [selection, mode, proposal, value]);\n\n  useEffect(() => {\n    return () => request.current?.abort();\n  }, []);\n\n  useEffect(() => {\n    const textarea = textareaRef.current;\n    if (!textarea) {\n      return;\n    }\n    textarea.addEventListener('beforeinput', refuseEdit);\n    return () => textarea.removeEventListener('beforeinput', refuseEdit);\n  }, [showsTextarea]);\n\n  function askFor(text: string, take: number) {\n    if (!selection) {\n      return;\n    }\n    const trimmed = text.trim();\n    if (trimmed === '') {\n      return;\n    }\n    request.current?.abort();\n    const controller = new AbortController();\n    request.current = controller;\n    setLastInstruction(trimmed);\n    setAttempt(take);\n    setMode('rewriting');\n    if (canMoveFocus) {\n      barRef.current?.focus();\n    }\n    rewrite(\n      { phrase, instruction: trimmed, before, after, attempt: take },\n      controller.signal\n    )\n      .then((next) => {\n        if (controller.signal.aborted) {\n          return;\n        }\n        setProposal(next);\n        setMode('review');\n        if (canMoveFocus) {\n          requestAnimationFrame(() => focusReview(next));\n        }\n      })\n      .catch(() => {\n        if (controller.signal.aborted) {\n          return;\n        }\n        setMode('failed');\n      });\n  }\n\n  function focusReview(next: string) {\n    const isSame = next.trim() === phrase.trim();\n    if (isSame) {\n      barRef.current?.focus();\n      return;\n    }\n    acceptRef.current?.focus();\n  }\n\n  function submitField(event: React.FormEvent<HTMLFormElement>) {\n    event.preventDefault();\n    askFor(instruction, 1);\n  }\n\n  function tryAgain() {\n    const nextAttempt = attempt + 1;\n    askFor(lastInstruction, nextAttempt);\n  }\n\n  function closeBar() {\n    request.current?.abort();\n    clearAll();\n    const end = selection?.end ?? 0;\n    setSelection(null);\n    setMode('idle');\n    setProposal('');\n    setInstruction('');\n    if (!canMoveFocus) {\n      return;\n    }\n    requestAnimationFrame(() => {\n      const textarea = textareaRef.current;\n      textarea?.focus();\n      textarea?.setSelectionRange(end, end);\n    });\n  }\n\n  function discard() {\n    request.current?.abort();\n    setMode('idle');\n    setProposal('');\n    if (!canMoveFocus) {\n      return;\n    }\n    requestAnimationFrame(() => fieldRef.current?.focus());\n  }\n\n  function accept() {\n    const canAccept = isReviewing && !isUnchanged;\n    if (!canAccept) {\n      return;\n    }\n    if (!selection) {\n      return;\n    }\n    const start = selection.start;\n    const end = start + proposal.length;\n    setMode('accepting');\n    schedule(() => {\n      onValueChange(`${before}${proposal}${after}`);\n      setSettledRange({ start, end });\n      setMode('settling');\n    }, ACCEPT_FADE_MS);\n    schedule(() => {\n      setSettledRange(null);\n      setSelection(null);\n      setProposal('');\n      setInstruction('');\n      setMode('idle');\n      if (!canMoveFocus) {\n        return;\n      }\n      requestAnimationFrame(() => {\n        const textarea = textareaRef.current;\n        textarea?.focus();\n        textarea?.setSelectionRange(end, end);\n      });\n    }, ACCEPT_FADE_MS + SETTLE_MS);\n  }\n\n  function selectPhrase(start: number, end: number) {\n    if (mode !== 'idle') {\n      return;\n    }\n    const range = phraseRangeOf(value, start, end);\n    if (sameRange(range, selection)) {\n      return;\n    }\n    setSelection(range);\n  }\n\n  function readSelection(event: React.SyntheticEvent<HTMLTextAreaElement>) {\n    const textarea = event.currentTarget;\n    selectPhrase(textarea.selectionStart, textarea.selectionEnd);\n  }\n\n  function showReview(review: RewriteReview) {\n    request.current?.abort();\n    clearAll();\n    setSelection({ start: review.start, end: review.end });\n    setLastInstruction(review.instruction);\n    setProposal(review.proposal);\n    setInstruction('');\n    setAttempt(1);\n    setSettledRange(null);\n    setMode('review');\n  }\n\n  function askFirstTake(text: string) {\n    askFor(text, 1);\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (!isOwnKey(event)) {\n      return;\n    }\n    const isEscape = event.key === 'Escape';\n    const isTab = event.key === 'Tab' && !event.shiftKey;\n    const isOnAccept = event.target === acceptRef.current;\n    const isAcceptKey = isTab && isOnAccept;\n    const isWaitingOnAnswer = isRewriting || isFailed;\n    if (isReviewing && isEscape) {\n      event.preventDefault();\n      discard();\n      return;\n    }\n    if (isReviewing && isAcceptKey) {\n      event.preventDefault();\n      accept();\n      return;\n    }\n    if (isWaitingOnAnswer && isEscape) {\n      event.preventDefault();\n      discard();\n      return;\n    }\n    if (hasSelection && isEscape) {\n      event.preventDefault();\n      closeBar();\n    }\n  }\n\n  const bar = (\n    <motion.div\n      key='bar'\n      ref={barRef}\n      tabIndex={-1}\n      role='group'\n      aria-label='Rewrite the selected phrase'\n      className='surface-raised absolute z-20 w-[19rem] max-w-full rounded-xl p-1.5 outline-none'\n      {...barPresence}\n    >\n      <AnimatedSize>\n        {isReviewing && (\n          <div className='flex flex-wrap items-center gap-1'>\n            {isUnchanged && (\n              <p className='text-muted-foreground w-full px-1.5 pb-1 text-xs'>\n                This already reads well\n              </p>\n            )}\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              onClick={discard}\n              aria-keyshortcuts='Escape'\n              className='text-muted-foreground'\n            >\n              <XIcon />\n              Discard\n            </Button>\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              onClick={tryAgain}\n              className='text-muted-foreground'\n            >\n              <RotateCcwIcon />\n              Try again\n            </Button>\n            {!isUnchanged && (\n              <Button\n                ref={acceptRef}\n                type='button'\n                size='sm'\n                onClick={accept}\n                aria-keyshortcuts='Tab'\n                className={cn('ms-auto', pressedSolidOf(pressed === 'accept'))}\n              >\n                <CheckIcon />\n                Accept\n                <span className='text-primary-foreground/70 text-[11px] font-normal'>\n                  Tab\n                </span>\n              </Button>\n            )}\n          </div>\n        )}\n        {isAccepting && (\n          <p className='text-muted-foreground flex h-7 items-center gap-2 px-2 text-xs'>\n            <CheckIcon className='text-success-foreground size-3.5' />\n            Accepted\n          </p>\n        )}\n        {isRewriting && (\n          <p\n            aria-hidden={hiddenIf(isDemonstrated)}\n            className='flex h-7 items-center px-2'\n          >\n            <TextLoader text='Rewriting' size='sm' />\n          </p>\n        )}\n        {isFailed && (\n          <div className='flex items-center gap-2 ps-2'>\n            <CircleAlertIcon className='text-destructive-ink size-3.5 shrink-0' />\n            <p className='text-destructive-ink min-w-0 flex-1 text-xs'>\n              Could not rewrite this phrase\n            </p>\n            <Button type='button' variant='ghost' size='sm' onClick={tryAgain}>\n              <RotateCcwIcon />\n              Try again\n            </Button>\n          </div>\n        )}\n        {mode === 'idle' && (\n          <div className='flex flex-col gap-1.5'>\n            <div className='flex flex-wrap gap-1'>\n              {QUICK_ASKS.map((ask) => (\n                <Button\n                  key={ask}\n                  type='button'\n                  variant='outline'\n                  size='sm'\n                  onClick={() => askFirstTake(ask)}\n                  className={pressedQuietOf(pressed === ask)}\n                >\n                  {ask}\n                </Button>\n              ))}\n            </div>\n            <form onSubmit={submitField} className='relative'>\n              <Input\n                ref={fieldRef}\n                value={instruction}\n                onChange={(event) => setInstruction(event.target.value)}\n                aria-label='How should it read?'\n                placeholder='How should it read?'\n                className='pe-9'\n              />\n              <Button\n                type='submit'\n                size='icon-sm'\n                aria-label='Rewrite'\n                disabled={instruction.trim() === ''}\n                className='absolute end-0.5 top-1/2 size-7 -translate-y-1/2'\n              >\n                <ArrowUpIcon />\n              </Button>\n            </form>\n          </div>\n        )}\n      </AnimatedSize>\n    </motion.div>\n  );\n\n  useImperativeHandle(handleRef, () => ({\n    select: selectPhrase,\n    press,\n    ask: askFirstTake,\n    accept,\n    discard,\n    review: showReview,\n  }));\n\n  return (\n    <div\n      ref={containerRef}\n      onKeyDown={handleKeys}\n      className={cn('relative', className)}\n    >\n      <AnimatedSize>\n        {showsTextarea && (\n          <div className='relative'>\n            <div\n              aria-hidden='true'\n              className={cn(\n                TEXT_BOX,\n                'pointer-events-none absolute inset-0 break-words whitespace-pre-wrap text-transparent'\n              )}\n            >\n              {before}\n              {hasSelection && (\n                <motion.span\n                  ref={phraseRef}\n                  animate={{ opacity: highlightPulseOf(isRewriting) }}\n                  transition={highlightTransitionOf(isRewriting)}\n                  className={PHRASE_TINT}\n                >\n                  {phrase}\n                </motion.span>\n              )}\n              {after}\n            </div>\n            <textarea\n              ref={textareaRef}\n              aria-readonly='true'\n              inputMode='none'\n              value={value}\n              onChange={keepValue}\n              onSelect={readSelection}\n              aria-label={label}\n              aria-describedby={hintId}\n              className={cn(\n                TEXT_BOX,\n                'focus-visible:ring-ring/25 relative block w-full resize-none overflow-hidden rounded-md bg-transparent outline-none focus-visible:ring-[3px]'\n              )}\n            />\n          </div>\n        )}\n        {!showsTextarea && (\n          <div className={cn(TEXT_BOX, 'break-words whitespace-pre-wrap')}>\n            {showsChange && (\n              <>\n                {before}\n                <TrackedChange\n                  parts={parts}\n                  isAccepting={isAccepting}\n                  phraseRef={phraseRef}\n                />\n                {after}\n              </>\n            )}\n            {isSettling && <SettledText value={value} range={settledRange} />}\n          </div>\n        )}\n      </AnimatedSize>\n      <AnimatePresence initial={false}>{showsBar && bar}</AnimatePresence>\n      <p id={hintId} className='sr-only'>\n        Select a phrase with the mouse or with Shift and the arrow keys, then\n        press Tab to reach the rewrite bar.\n      </p>\n      <LiveRegion message={spokenUnless(isDemonstrated, announcement)} />\n    </div>\n  );\n}\n\nfunction highlightPulseOf(isRewriting: boolean) {\n  if (isRewriting) {\n    return [1, 0.45, 1];\n  }\n  return 1;\n}\n\nfunction highlightTransitionOf(isRewriting: boolean) {\n  if (isRewriting) {\n    return { duration: 1.2, repeat: Infinity, ease: 'easeInOut' } as const;\n  }\n  return { duration: 0.2 };\n}\n\nfunction sliceBefore(text: string, range: Range | null) {\n  if (!range) {\n    return text;\n  }\n  return text.slice(0, range.start);\n}\n\nfunction sliceOf(text: string, range: Range | null) {\n  if (!range) {\n    return '';\n  }\n  return text.slice(range.start, range.end);\n}\n\nfunction sliceAfter(text: string, range: Range | null) {\n  if (!range) {\n    return '';\n  }\n  return text.slice(range.end);\n}\n\nfunction SettledText({ value, range }: { value: string; range: Range | null }) {\n  if (!range) {\n    return <>{value}</>;\n  }\n  const before = value.slice(0, range.start);\n  const accepted = value.slice(range.start, range.end);\n  const after = value.slice(range.end);\n\n  return (\n    <>\n      {before}\n      <span className='text-foreground starting:text-primary-ink starting:decoration-primary-ink/50 underline decoration-transparent underline-offset-[3px] transition-[color,text-decoration-color] duration-700 ease-(--ease-out-strong)'>\n        {accepted}\n      </span>\n      {after}\n    </>\n  );\n}\n\ntype RewriteKind = 'shorter' | 'friendlier' | 'direct' | 'formal';\n\nconst KIND_WORDS: { kind: RewriteKind; pattern: RegExp }[] = [\n  { kind: 'shorter', pattern: /short|brief|concise|trim|tight/i },\n  { kind: 'friendlier', pattern: /friend|warm|kind|polite|soft|nice/i },\n  { kind: 'formal', pattern: /formal|professional/i },\n  { kind: 'direct', pattern: /direct|clear|firm|plain|assertive|blunt/i },\n];\n\nfunction kindOf(instruction: string): RewriteKind {\n  const match = KIND_WORDS.find((entry) => entry.pattern.test(instruction));\n  return match?.kind ?? 'direct';\n}\n\ntype PreparedRewrite = {\n  phrase: string;\n  takes: Record<RewriteKind, string[]>;\n};\n\n/** Hand-written takes for the phrases of the demo letter; any other phrase falls back on the rules below. */\nconst PREPARED: PreparedRewrite[] = [\n  {\n    phrase:\n      'I just wanted to reach out because we were wondering if it might be possible to get a credit for the October order',\n    takes: {\n      shorter: [\n        'Could we get a credit for the October order',\n        'We would like a credit for the October order',\n      ],\n      friendlier: [\n        'I hope you are well. We would love to ask whether a credit for the October order is possible',\n        'Hope all is well. Would a credit for the October order be possible',\n      ],\n      direct: [\n        'Please issue a credit for the October order',\n        'We need a credit for the October order',\n      ],\n      formal: [\n        'We are writing to request a credit for the October order',\n        'We kindly request a credit for the October order',\n      ],\n    },\n  },\n  {\n    phrase:\n      'since a few of the lines seem to have been billed above the price we agreed on',\n    takes: {\n      shorter: [\n        'since some lines were billed above our agreed price',\n        'as some lines exceed the agreed price',\n      ],\n      friendlier: [\n        'since a few lines look like they were billed a little above the price we agreed on',\n        'because a few lines seem to have slipped above our agreed price',\n      ],\n      direct: [\n        'because several lines were billed above the agreed price',\n        'because lines 4, 7 and 9 exceed the agreed price',\n      ],\n      formal: [\n        'as several lines were invoiced above the agreed price',\n        'given that several lines exceed the contracted price',\n      ],\n    },\n  },\n  {\n    phrase: 'Please let us know at your earliest convenience',\n    takes: {\n      shorter: ['Please reply soon', 'Let us know soon'],\n      friendlier: [\n        'Let us know whenever you get a chance, thank you',\n        'Thanks so much for looking into it',\n      ],\n      direct: ['Please reply by Friday', 'Please confirm the credit by Friday'],\n      formal: [\n        'We look forward to your reply',\n        'We would appreciate your prompt reply',\n      ],\n    },\n  },\n];\n\ntype Rule = [RegExp, string];\n\nconst RULES: Record<RewriteKind, Rule[]> = {\n  shorter: [\n    [/\\bI just wanted to reach out because\\s*/gi, ''],\n    [/\\bwe were wondering if it might be possible to\\b/gi, 'could we'],\n    [/\\bat your earliest convenience\\b/gi, 'soon'],\n    [/\\bseem to have been\\b/gi, 'were'],\n    [/\\ba few of the\\b/gi, 'some'],\n    [/\\bin order to\\b/gi, 'to'],\n    [/\\b(just|really|very|actually|basically|quite) /gi, ''],\n  ],\n  friendlier: [\n    [/\\bPlease let us know\\b/g, 'Could you let us know'],\n    [/\\bat your earliest convenience\\b/gi, 'whenever you get a chance'],\n    [/\\bwe were wondering if\\b/gi, 'we would love to know if'],\n    [/\\bbilled above\\b/gi, 'billed a little above'],\n  ],\n  direct: [\n    [/\\bI just wanted to reach out because\\s*/gi, ''],\n    [/\\bwe were wondering if it might be possible to get\\b/gi, 'please issue'],\n    [/\\bseem to have been\\b/gi, 'were'],\n    [/\\b(I think|perhaps|maybe) /gi, ''],\n    [/\\bmight\\b/gi, 'will'],\n    [/\\bat your earliest convenience\\b/gi, 'by Friday'],\n  ],\n  formal: [\n    [/\\bHi\\b/g, 'Dear'],\n    [/\\blet us know\\b/gi, 'advise us'],\n    [/\\bget\\b/gi, 'obtain'],\n    [/\\bsince\\b/gi, 'as'],\n  ],\n};\n\nconst SECOND_TAKE_RULES: Record<RewriteKind, Rule[]> = {\n  shorter: [[/\\bthat /gi, '']],\n  friendlier: [[/\\bplease\\b/gi, 'kindly']],\n  direct: [[/\\bcould\\b/gi, 'please']],\n  formal: [[/\\bwe\\b/g, 'our team']],\n};\n\nconst TRAILING_MARKS = /[.,;:!?]+$/;\n\nfunction normalized(text: string) {\n  const trimmed = text.trim();\n  const withoutMarks = trimmed.replace(TRAILING_MARKS, '');\n  return withoutMarks.toLowerCase();\n}\n\nfunction trailingMarksOf(text: string) {\n  const match = text.trim().match(TRAILING_MARKS);\n  return match?.[0] ?? '';\n}\n\nfunction applyRules(text: string, rules: Rule[]) {\n  let next = text;\n  for (const [pattern, replacement] of rules) {\n    next = next.replace(pattern, replacement);\n  }\n  return next;\n}\n\nfunction capitalizedLike(original: string, next: string) {\n  const startsUpper = /^\\p{Lu}/u.test(original.trim());\n  if (!startsUpper) {\n    return next;\n  }\n  const firstLetter = next.charAt(0);\n  const first = firstLetter.toUpperCase();\n  const rest = next.slice(1);\n  return `${first}${rest}`;\n}\n\nfunction ruleTake(phrase: string, kind: RewriteKind, attempt: number) {\n  const marks = trailingMarksOf(phrase);\n  const core = phrase.trim().replace(TRAILING_MARKS, '');\n  const firstTake = applyRules(core, RULES[kind]);\n  const isSecondTake = attempt > 1;\n  let take = firstTake;\n  if (isSecondTake) {\n    take = applyRules(firstTake, SECOND_TAKE_RULES[kind]);\n  }\n  const tidy = take.replace(/\\s{2,}/g, ' ').trim();\n  const cased = capitalizedLike(core, tidy);\n  return `${cased}${marks}`;\n}\n\nfunction preparedTake(phrase: string, kind: RewriteKind, attempt: number) {\n  const key = normalized(phrase);\n  const entry = PREPARED.find(\n    (candidate) => normalized(candidate.phrase) === key\n  );\n  if (!entry) {\n    return null;\n  }\n  const takes = entry.takes[kind];\n  const index = (attempt - 1) % takes.length;\n  const marks = trailingMarksOf(phrase);\n  return `${takes[index]}${marks}`;\n}\n\nconst THINKING_MS = 900;\n\nfunction wait(milliseconds: number, signal: AbortSignal) {\n  return new Promise<void>((resolve, reject) => {\n    const timeout = setTimeout(resolve, milliseconds);\n    signal.addEventListener('abort', () => {\n      clearTimeout(timeout);\n      reject(new DOMException('The rewrite was cancelled', 'AbortError'));\n    });\n  });\n}\n\nasync function demoRewrite(request: RewriteRequest, signal: AbortSignal) {\n  await wait(THINKING_MS, signal);\n  const kind = kindOf(request.instruction);\n  const prepared = preparedTake(request.phrase, kind, request.attempt);\n  if (prepared) {\n    return prepared;\n  }\n  return ruleTake(request.phrase, kind, request.attempt);\n}\n\nconst LETTER =\n  'Hi Dana,\\n\\nI just wanted to reach out because we were wondering if it might be possible to get a credit for the October order, since a few of the lines seem to have been billed above the price we agreed on. Please let us know at your earliest convenience.';\n\nconst [OPENING, REASON, CLOSING] = PREPARED;\n\nconst OPENING_START = LETTER.indexOf(OPENING.phrase);\n\n/** The piece opens on its best picture: the first sentence already rewritten, waiting for an answer. */\nconst FIRST_REVIEW: RewriteReview = {\n  start: OPENING_START,\n  end: OPENING_START + OPENING.phrase.length,\n  instruction: 'Shorter',\n  proposal: OPENING.takes.shorter[0],\n};\n\ntype DemoRewrite = {\n  phrase: string;\n  ask: QuickAsk;\n};\n\n/** After the first sentence, a round rewrites one of these, a different one each time. */\nconst NEXT_REWRITES: DemoRewrite[] = [\n  { phrase: REASON.phrase, ask: 'More direct' },\n  { phrase: CLOSING.phrase, ask: 'Friendlier' },\n];\n\nexport default function Prompt06() {\n  const [letter, setLetter] = useState(LETTER);\n  const [round, setRound] = useState(0);\n  const rewriter = useRef<RewriteHandle>(null);\n  const { pressed, press } = usePress<'start-over'>();\n  const isEdited = letter !== LETTER;\n  const next = NEXT_REWRITES[round % NEXT_REWRITES.length];\n\n  function startOver() {\n    setLetter(LETTER);\n  }\n\n  function selectNext() {\n    const start = letter.indexOf(next.phrase);\n    if (start < 0) {\n      return;\n    }\n    const end = start + next.phrase.length;\n    rewriter.current?.select(start, end);\n  }\n\n  function resetDemo() {\n    setLetter(LETTER);\n    rewriter.current?.review(FIRST_REVIEW);\n    setRound((current) => current + 1);\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 2200, run: () => rewriter.current?.press('accept') },\n    { after: PRESS_LEAD_MS, run: () => rewriter.current?.accept() },\n    { after: 2000, run: selectNext },\n    { after: 1300, run: () => rewriter.current?.press(next.ask) },\n    { after: PRESS_LEAD_MS, run: () => rewriter.current?.ask(next.ask) },\n    {\n      after: THINKING_MS + 2600,\n      run: () => rewriter.current?.press('accept'),\n    },\n    { after: PRESS_LEAD_MS, run: () => rewriter.current?.accept() },\n    { after: 2000, run: () => press('start-over') },\n    { after: PRESS_LEAD_MS, run: startOver },\n    { after: 300, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2200,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='flex w-full max-w-[30rem] flex-col gap-3'>\n      <div className='bg-card hairline-ring ring-border flex flex-col gap-3 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n        <div className='flex items-baseline justify-between gap-3'>\n          <p className='text-sm font-medium'>Credit request to Brightmoor</p>\n          <p className='text-muted-foreground text-xs'>Draft</p>\n        </div>\n        <RewriteInPlace\n          value={letter}\n          onValueChange={setLetter}\n          rewrite={demoRewrite}\n          label='Credit request to Brightmoor'\n          defaultReview={FIRST_REVIEW}\n          handleRef={rewriter}\n          isDemonstrated={isAutoplaying}\n          className='-mx-1'\n        />\n      </div>\n      <div className='flex min-h-7 items-center justify-between gap-3 px-1'>\n        <p className='text-muted-foreground text-xs'>\n          Select a phrase, or use Shift and the arrows\n        </p>\n        {isEdited && (\n          <Button\n            type='button'\n            variant='ghost'\n            size='sm'\n            onClick={startOver}\n            className={cn(\n              'text-muted-foreground',\n              pressedQuietOf(pressed === 'start-over')\n            )}\n          >\n            <RotateCcwIcon />\n            Start over\n          </Button>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/prompt/prompt-06.tsx"
    },
    {
      "path": "registry/ndeko/components/prompt/_parts/use-autosize.ts",
      "content": "'use client';\n\nimport { useLayoutEffect } from 'react';\n\nfunction fitHeight(textarea: HTMLTextAreaElement, maxHeight: number) {\n  textarea.style.height = 'auto';\n  const height = Math.min(textarea.scrollHeight, maxHeight);\n  textarea.style.height = `${height}px`;\n}\n\n/** Also fits again when the width changes, and when `remountKey` changes for a textarea shown again. */\nexport function useAutosize(\n  ref: React.RefObject<HTMLTextAreaElement | null>,\n  value: string,\n  maxHeight: number,\n  remountKey?: unknown\n) {\n  useLayoutEffect(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    fitHeight(textarea, maxHeight);\n    let lastWidth = textarea.offsetWidth;\n    const observer = new ResizeObserver(() => {\n      const width = textarea.offsetWidth;\n      if (width === lastWidth) {\n        return;\n      }\n      lastWidth = width;\n      fitHeight(textarea, maxHeight);\n    });\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [ref, value, maxHeight, remountKey]);\n}\n\nexport function isSendKey(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n  const isEnter = event.key === 'Enter';\n  const isNewLine = event.shiftKey;\n  const isComposing = event.nativeEvent.isComposing;\n  const isPlainEnter = isEnter && !isNewLine;\n  return isPlainEnter && !isComposing;\n}\n\n/** Puts the caret after the last character once React has committed the new text. */\nexport function caretToEnd(ref: React.RefObject<HTMLTextAreaElement | null>) {\n  requestAnimationFrame(() => {\n    const textarea = ref.current;\n    if (!textarea) {\n      return;\n    }\n    const end = textarea.value.length;\n    textarea.focus();\n    textarea.setSelectionRange(end, end);\n  });\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",
      "type": "registry:component",
      "target": "components/prompt/_parts/use-autosize.ts"
    }
  ],
  "categories": [
    "components",
    "prompt"
  ],
  "type": "registry:component"
}