{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "textarea-20",
  "title": "Rewind",
  "description": "A textarea that records versions as you write: drag the scrubber back and the words you deleted later return in colour, then keep that version or press Escape to return to now.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/label.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/recipes.json",
    "https://ui.ndekocode.dev/r/textarea.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/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/textarea/textarea-20.tsx",
      "content": "'use client';\n\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ChangeEvent,\n  type KeyboardEvent,\n  type PointerEvent,\n} from 'react';\nimport { flushSync } from 'react-dom';\n\nimport {\n  typingSteps,\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { HistoryIcon } from '@/registry/ndeko/lib/icons';\nimport { CONTROL_RECIPE } from '@/registry/ndeko/lib/recipes';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { Label } from '@/registry/ndeko/ui/label';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nconst SNAPSHOT_MS = 450;\nconst MAX_VERSIONS = 40;\nconst HELD_UNDO_REPEATS_PER_STEP = 4;\n\nconst FIRST_SENTENCE = 'Ship the export on Friday.';\nconst SECOND_SENTENCE = 'Ask Mei about the totals row.';\nconst THIRD_SENTENCE = 'Hold the release until Monday.';\n\nconst VERSIONS = [\n  FIRST_SENTENCE,\n  `${FIRST_SENTENCE} ${SECOND_SENTENCE}`,\n  SECOND_SENTENCE,\n  `${SECOND_SENTENCE} ${THIRD_SENTENCE}`,\n];\n\nconst FINAL_TEXT = VERSIONS[VERSIONS.length - 1];\n\nconst VIEW =\n  'whitespace-pre-wrap wrap-break-word field-sizing-content max-h-[12lh] min-h-16 overflow-hidden px-2.5 py-2 leading-normal';\n\nconst RETURNING_WORD =\n  'text-primary-ink transition-[color,opacity] duration-200 ease-(--ease-out-strong) starting:opacity-0';\n\ntype Token = {\n  text: string;\n  isReturning: boolean;\n};\n\nfunction framesOf(history: string[], text: string) {\n  const last = history[history.length - 1];\n  if (last === text) {\n    return history;\n  }\n  return [...history, text];\n}\n\nfunction withSnapshot(history: string[], text: string) {\n  const last = history[history.length - 1];\n  const isNew = last !== text;\n  const hasContent = text !== '';\n  if (!isNew || !hasContent) {\n    return history;\n  }\n  return [...history, text].slice(-MAX_VERSIONS);\n}\n\nfunction countOfWords(text: string) {\n  const counts = new Map<string, number>();\n  const words = text.split(/\\s+/).filter((word) => word !== '');\n  for (const word of words) {\n    const seen = counts.get(word) ?? 0;\n    counts.set(word, seen + 1);\n  }\n  return counts;\n}\n\nfunction tokensOf(shownText: string, nowText: string): Token[] {\n  const remaining = countOfWords(nowText);\n  return shownText.split(/(\\s+)/).map((text) => {\n    const isSpace = text.trim() === '';\n    if (isSpace) {\n      return { text, isReturning: false };\n    }\n    const left = remaining.get(text) ?? 0;\n    if (left > 0) {\n      remaining.set(text, left - 1);\n      return { text, isReturning: false };\n    }\n    return { text, isReturning: true };\n  });\n}\n\nfunction shareOf(index: number, count: number) {\n  const lastIndex = count - 1;\n  if (lastIndex <= 0) {\n    return 1;\n  }\n  return index / lastIndex;\n}\n\nfunction versionLabelOf(index: number, count: number) {\n  const isNow = index === count - 1;\n  if (isNow) {\n    return 'Now';\n  }\n  return `Version ${index + 1} of ${count}`;\n}\n\nfunction clampedIndex(index: number, count: number) {\n  return Math.min(count - 1, Math.max(0, index));\n}\n\nfunction indexAtPointer(event: PointerEvent<HTMLElement>, count: number) {\n  const box = event.currentTarget.getBoundingClientRect();\n  const share = (event.clientX - box.left) / box.width;\n  const boundedShare = Math.min(1, Math.max(0, share));\n  return Math.round(boundedShare * (count - 1));\n}\n\nfunction isUndoKey(event: KeyboardEvent<HTMLElement>) {\n  const hasModifier = event.metaKey || event.ctrlKey;\n  const isZ = event.key.toLowerCase() === 'z';\n  return hasModifier && isZ;\n}\n\nfunction RewindView({\n  shownText,\n  nowText,\n}: {\n  shownText: string;\n  nowText: string;\n}) {\n  const tokens = tokensOf(shownText, nowText);\n\n  return (\n    <div\n      aria-hidden='true'\n      className={cn(\n        CONTROL_RECIPE,\n        VIEW,\n        'border-foreground/30 ring-ring/25 col-start-1 row-start-1 ring-[3px]'\n      )}\n    >\n      {tokens.map((token, index) => {\n        if (!token.isReturning) {\n          return <span key={`${index}-${token.text}`}>{token.text}</span>;\n        }\n        return (\n          <span key={`${index}-${token.text}`} className={RETURNING_WORD}>\n            {token.text}\n          </span>\n        );\n      })}\n    </div>\n  );\n}\n\ntype ScrubberProps = {\n  index: number;\n  count: number;\n  sliderRef: React.RefObject<HTMLDivElement | null>;\n  onIndexChange: (index: number) => void;\n  onKeep: () => void;\n  onCancel: () => void;\n};\n\nfunction Scrubber({\n  index,\n  count,\n  sliderRef,\n  onIndexChange,\n  onKeep,\n  onCancel,\n}: ScrubberProps) {\n  const isDragging = useRef(false);\n  const share = shareOf(index, count);\n  const thumbStyle = { translate: `${share * 100}cqw 0` };\n  const label = versionLabelOf(index, count);\n\n  function startDrag(event: PointerEvent<HTMLDivElement>) {\n    isDragging.current = true;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    onIndexChange(indexAtPointer(event, count));\n  }\n\n  function drag(event: PointerEvent<HTMLDivElement>) {\n    if (!isDragging.current) {\n      return;\n    }\n    onIndexChange(indexAtPointer(event, count));\n  }\n\n  function endDrag() {\n    if (!isDragging.current) {\n      return;\n    }\n    isDragging.current = false;\n    onKeep();\n  }\n\n  function moveWithKeys(event: KeyboardEvent<HTMLDivElement>) {\n    const lastIndex = count - 1;\n    if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {\n      onIndexChange(clampedIndex(index - 1, count));\n    }\n    if (event.key === 'ArrowRight' || event.key === 'ArrowUp') {\n      onIndexChange(clampedIndex(index + 1, count));\n    }\n    if (event.key === 'Home') {\n      onIndexChange(0);\n    }\n    if (event.key === 'End') {\n      onIndexChange(lastIndex);\n    }\n    if (event.key === 'Enter') {\n      onKeep();\n    }\n    if (event.key === 'Escape') {\n      onCancel();\n    }\n    const isHandled = [\n      'ArrowLeft',\n      'ArrowRight',\n      'ArrowUp',\n      'ArrowDown',\n      'Home',\n      'End',\n      'Enter',\n      'Escape',\n    ].includes(event.key);\n    if (isHandled) {\n      event.preventDefault();\n    }\n  }\n\n  return (\n    <div className='flex flex-col gap-3 pt-3'>\n      <div\n        ref={sliderRef}\n        role='slider'\n        tabIndex={0}\n        aria-label='Version history'\n        aria-valuemin={1}\n        aria-valuemax={count}\n        aria-valuenow={index + 1}\n        aria-valuetext={label}\n        onPointerDown={startDrag}\n        onPointerMove={drag}\n        onPointerUp={endDrag}\n        onPointerCancel={onCancel}\n        onKeyDown={moveWithKeys}\n        className='focus-visible:ring-ring/25 @container relative flex h-6 cursor-ew-resize touch-none items-center rounded-full outline-none focus-visible:ring-[3px]'\n      >\n        <span className='bg-foreground/10 h-1 w-full rounded-full' />\n        {Array.from({ length: count }, (_, tick) => (\n          <span\n            key={tick}\n            aria-hidden='true'\n            style={{ left: `${shareOf(tick, count) * 100}%` }}\n            className='bg-foreground/25 absolute top-1/2 -mt-[3px] -ml-[3px] size-1.5 rounded-full'\n          />\n        ))}\n        <span\n          aria-hidden='true'\n          style={thumbStyle}\n          className='keycap-3d absolute top-1/2 left-0 -mt-2 -ml-2 size-4 rounded-full transition-[translate] duration-150 ease-(--ease-out-strong)'\n        />\n      </div>\n      <div className='flex flex-wrap items-center justify-between gap-2'>\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          {label}\n        </span>\n        <div className='flex items-center gap-1.5'>\n          <Button variant='ghost' size='sm' onClick={onCancel}>\n            Back to now\n            <Kbd>Esc</Kbd>\n          </Button>\n          <Button size='sm' onClick={onKeep}>\n            Keep this version\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default function Textarea20() {\n  const id = useId();\n  const [text, setText] = useState(FINAL_TEXT);\n  const [history, setHistory] = useState(VERSIONS);\n  const [rewindIndex, setRewindIndex] = useState<number | null>(null);\n  const [announcement, setAnnouncement] = useState('');\n  const sliderRef = useRef<HTMLDivElement>(null);\n  const heldUndo = useRef({ isHeld: false, repeats: 0 });\n  const { pressed, press } = usePress<'rewind'>();\n  const frames = framesOf(history, text);\n  const count = frames.length;\n  const isRewinding = rewindIndex !== null;\n  const shownIndex = rewindIndex ?? count - 1;\n  const shownText = frames[shownIndex];\n  const canRewind = count > 1;\n\n  useEffect(() => {\n    if (isRewinding) {\n      return;\n    }\n    const timer = window.setTimeout(() => {\n      setHistory((current) => withSnapshot(current, text));\n    }, SNAPSHOT_MS);\n    return () => window.clearTimeout(timer);\n  }, [text, isRewinding]);\n\n  function openRewind(index: number) {\n    setRewindIndex(clampedIndex(index, count));\n  }\n\n  function keepVersion() {\n    if (rewindIndex === null) {\n      return;\n    }\n    setText(frames[rewindIndex]);\n    setRewindIndex(null);\n  }\n\n  function cancelRewind() {\n    setRewindIndex(null);\n  }\n\n  function openFromButton() {\n    if (isRewinding) {\n      cancelRewind();\n      return;\n    }\n    flushSync(() => openRewind(count - 2));\n    sliderRef.current?.focus();\n    setAnnouncement(versionLabelOf(count - 2, count));\n  }\n\n  function changeText(event: ChangeEvent<HTMLTextAreaElement>) {\n    setText(event.currentTarget.value);\n  }\n\n  function holdUndo(event: KeyboardEvent<HTMLTextAreaElement>) {\n    if (event.key === 'Escape' && isRewinding) {\n      event.preventDefault();\n      cancelRewind();\n      return;\n    }\n    if (!isUndoKey(event)) {\n      return;\n    }\n    event.preventDefault();\n    if (event.shiftKey || !canRewind) {\n      return;\n    }\n    const held = heldUndo.current;\n    if (!held.isHeld) {\n      held.isHeld = true;\n      held.repeats = 0;\n      openRewind(count - 2);\n      return;\n    }\n    held.repeats += 1;\n    const isStepDue = held.repeats % HELD_UNDO_REPEATS_PER_STEP === 0;\n    if (isStepDue && rewindIndex !== null) {\n      openRewind(rewindIndex - 1);\n    }\n  }\n\n  function releaseUndo(event: KeyboardEvent<HTMLTextAreaElement>) {\n    const held = heldUndo.current;\n    if (!held.isHeld) {\n      return;\n    }\n    const releasesUndo =\n      isUndoKey(event) || event.key === 'Meta' || event.key === 'Control';\n    if (!releasesUndo) {\n      return;\n    }\n    held.isHeld = false;\n    keepVersion();\n  }\n\n  function startWriting() {\n    setHistory([]);\n    setRewindIndex(null);\n    setText('');\n  }\n\n  function startOver() {\n    setHistory(VERSIONS);\n    setRewindIndex(null);\n    setText(FINAL_TEXT);\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 2600, run: startWriting },\n    ...typingSteps(FIRST_SENTENCE, setText, {\n      startAfter: 500,\n      characterMs: 34,\n    }),\n    { after: 1100, run: hold },\n    ...typingSteps(\n      ` ${SECOND_SENTENCE}`,\n      (typed) => setText(`${FIRST_SENTENCE}${typed}`),\n      { startAfter: 200, characterMs: 30 }\n    ),\n    { after: 1100, run: hold },\n    { after: 200, run: () => setText(SECOND_SENTENCE) },\n    { after: 1100, run: hold },\n    ...typingSteps(\n      ` ${THIRD_SENTENCE}`,\n      (typed) => setText(`${SECOND_SENTENCE}${typed}`),\n      { startAfter: 200, characterMs: 30 }\n    ),\n    { after: 1200, run: hold },\n    { after: 400, run: () => press('rewind') },\n    { after: PRESS_LEAD_MS, run: () => openRewind(count - 2) },\n    { after: 900, run: () => setRewindIndex(count - 3) },\n    { after: 900, run: () => setRewindIndex(count - 4) },\n    { after: 2600, run: cancelRewind },\n  ];\n  const { ref } = useAutoplay(steps, {\n    loopAfter: 3000,\n    onReset: startOver,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[15rem] w-full max-w-sm flex-col gap-2'\n    >\n      <div className='flex items-center justify-between gap-2'>\n        <Label htmlFor={id}>Standup notes</Label>\n        <Button\n          variant='ghost'\n          size='sm'\n          disabled={!canRewind}\n          aria-expanded={isRewinding}\n          onClick={openFromButton}\n          className={cn(\n            'text-muted-foreground hover:text-foreground -me-2',\n            pressedQuietOf(pressed === 'rewind')\n          )}\n        >\n          <HistoryIcon className='size-3.5' />\n          Rewind\n        </Button>\n      </div>\n      <div className='grid'>\n        <Textarea\n          id={id}\n          value={text}\n          readOnly={isRewinding}\n          onChange={changeText}\n          onKeyDown={holdUndo}\n          onKeyUp={releaseUndo}\n          placeholder='Write a note'\n          className={cn('col-start-1 row-start-1', isRewinding && 'opacity-0')}\n        />\n        {isRewinding && <RewindView shownText={shownText} nowText={text} />}\n      </div>\n      <Fold open={isRewinding}>\n        <Scrubber\n          index={shownIndex}\n          count={count}\n          sliderRef={sliderRef}\n          onIndexChange={setRewindIndex}\n          onKeep={keepVersion}\n          onCancel={cancelRewind}\n        />\n      </Fold>\n      <LiveRegion message={announcement} />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "textarea"
  ],
  "type": "registry:component"
}