{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "text-effect-01",
  "title": "Typewriter",
  "description": "A line that types itself with human timing, cycling through phrases or clearing itself to type again, where a slip of two swapped letters is noticed, taken back and fixed while the caret blinks only when the hand rests.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/speech-envelope.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.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/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/text-effect/text-effect-01.tsx",
      "content": "'use client';\n\nimport { useEffect, useMemo, useRef, useState } 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 { noiseAt } from '@/registry/ndeko/lib/speech-envelope';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { usePlayWhileSeen } from './_parts/use-play-while-seen';\n\nexport type TypewriterMode = 'cycle' | 'retype';\n\nexport type TypewriterSlip = {\n  /** Where the slip starts in the phrase, counted in characters. */\n  at: number;\n  /** What is typed there in place of the right letters, before it is noticed and taken back. */\n  typed: string;\n};\n\n/** A state of the line, and how long it holds before the next one. */\ntype Beat = {\n  text: string;\n  holdMs: number;\n  /** The whole line is selected, the moment before it is cleared. */\n  isSelected: boolean;\n  /** The hand rests, so the caret blinks. */\n  isIdle: boolean;\n};\n\ntype Track = {\n  beats: readonly Beat[];\n  index: number;\n  isDone: boolean;\n};\n\n/** The time left on a beat that stopped playing, kept so it picks up where it stopped. */\ntype Pending = {\n  beats: readonly Beat[];\n  index: number;\n  remaining: number;\n  startedAt: number;\n};\n\ntype Word = {\n  start: number;\n  length: number;\n};\n\n/** A person does not type at a steady pace: each key waits between 60% and 150% of this. */\nconst KEY_MS = 70;\n\nconst KEY_STRETCH_MIN = 0.6;\n\nconst KEY_STRETCH_SPAN = 0.9;\n\nconst AFTER_SPACE_MS = 60;\n\nconst AFTER_PUNCTUATION_MS = 220;\n\nconst BACKSPACE_MS = 40;\n\nconst PHRASE_HOLD_MS = 2200;\n\nconst LINE_HOLD_MS = 2600;\n\nconst SELECTED_MS = 420;\n\nconst CLEARED_MS = 320;\n\n/** The slip is seen a moment after it was typed, not on the key that made it. */\nconst NOTICE_MS = 480;\n\nconst BEFORE_RETYPE_MS = 160;\n\nconst BEFORE_TYPING_MS = 280;\n\n/** A line that plays once blinks this long at the end, then its caret goes. */\nconst LAST_HOLD_MS = 2400;\n\nconst BLINK_MS = 1060;\n\nconst BLINK_KEYFRAMES: Keyframe[] = [\n  { offset: 0, opacity: 1 },\n  { offset: 0.45, opacity: 1 },\n  { offset: 0.55, opacity: 0 },\n  { offset: 0.95, opacity: 0 },\n  { offset: 1, opacity: 1 },\n];\n\nconst PUNCTUATION = ',.;:!?';\n\n/** The default slip swaps two letters of a word at least this long. */\nconst SLIP_WORD_LENGTH = 4;\n\n/** Joins the phrases into one key, so a new array with the same phrases keeps the line where it is. */\nconst PHRASE_SEPARATOR = '\\u001f';\n\nfunction charactersOf(text: string) {\n  return Array.from(text);\n}\n\nfunction commonLengthOf(first: readonly string[], second: readonly string[]) {\n  const shortest = Math.min(first.length, second.length);\n  for (let index = 0; index < shortest; index += 1) {\n    if (first[index] !== second[index]) {\n      return index;\n    }\n  }\n  return shortest;\n}\n\nfunction keyHoldOf(character: string, index: number, seed: number) {\n  const noise = noiseAt(index, seed);\n  const stretch = KEY_STRETCH_MIN + noise * KEY_STRETCH_SPAN;\n  const hold = KEY_MS * stretch;\n  if (character === ' ') {\n    return Math.round(hold + AFTER_SPACE_MS);\n  }\n  if (PUNCTUATION.includes(character)) {\n    return Math.round(hold + AFTER_PUNCTUATION_MS);\n  }\n  return Math.round(hold);\n}\n\nfunction idleBeat(text: string, holdMs: number): Beat {\n  return { text, holdMs, isSelected: false, isIdle: true };\n}\n\nfunction keyBeat(text: string, holdMs: number): Beat {\n  return { text, holdMs, isSelected: false, isIdle: false };\n}\n\n/** The line typed key by key from `start`, a beginning of `target`, to the whole of `target`. */\nfunction typedBeats(start: string, target: string, seed: number) {\n  const characters = charactersOf(target);\n  const startLength = charactersOf(start).length;\n  const beats: Beat[] = [];\n  for (let index = startLength; index < characters.length; index += 1) {\n    const end = index + 1;\n    const typed = characters.slice(0, end).join('');\n    const holdMs = keyHoldOf(characters[index], index, seed);\n    beats.push(keyBeat(typed, holdMs));\n  }\n  return beats;\n}\n\n/** The line taken back key by key from `start` to `target`, a beginning of it. */\nfunction deletedBeats(start: string, target: string) {\n  const characters = charactersOf(start);\n  const targetLength = charactersOf(target).length;\n  const beats: Beat[] = [];\n  for (\n    let length = characters.length - 1;\n    length >= targetLength;\n    length -= 1\n  ) {\n    const text = characters.slice(0, length).join('');\n    beats.push(keyBeat(text, BACKSPACE_MS));\n  }\n  return beats;\n}\n\nfunction withLastHold(beats: Beat[], holdMs: number) {\n  const last = beats.at(-1);\n  if (last) {\n    last.holdMs = holdMs;\n  }\n  return beats;\n}\n\n/** Each phrase rests, is taken back to what it shares with the next one, then the next is typed. */\nfunction cycleBeatsOf(phrases: readonly string[]) {\n  const beats: Beat[] = [];\n  const count = phrases.length;\n  for (let index = 0; index < count; index += 1) {\n    const phrase = phrases[index];\n    const nextIndex = (index + 1) % count;\n    const next = phrases[nextIndex];\n    const nextCharacters = charactersOf(next);\n    const keep = commonLengthOf(charactersOf(phrase), nextCharacters);\n    const kept = nextCharacters.slice(0, keep).join('');\n    const resting = idleBeat(phrase, PHRASE_HOLD_MS);\n    const deleting = withLastHold(deletedBeats(phrase, kept), BEFORE_TYPING_MS);\n    const typing = typedBeats(kept, next, nextIndex);\n    beats.push(resting, ...deleting, ...typing);\n  }\n  return beats;\n}\n\n/** The line rests, is selected and cleared, then typed again with a slip that is noticed, taken back and fixed. */\nfunction retypeBeatsOf(text: string, slip: TypewriterSlip | null) {\n  const beats: Beat[] = [\n    idleBeat(text, LINE_HOLD_MS),\n    { text, holdMs: SELECTED_MS, isSelected: true, isIdle: false },\n    keyBeat('', CLEARED_MS),\n  ];\n  if (!slip) {\n    beats.push(...typedBeats('', text, 1));\n    return beats;\n  }\n  const characters = charactersOf(text);\n  const before = characters.slice(0, slip.at).join('');\n  const wrongLine = before + slip.typed;\n  const typedWrong = charactersOf(slip.typed);\n  const slipEnd = slip.at + typedWrong.length;\n  const rightPart = characters.slice(slip.at, slipEnd);\n  const keep = commonLengthOf(typedWrong, rightPart);\n  const backTo = before + typedWrong.slice(0, keep).join('');\n  const slipping = withLastHold(typedBeats('', wrongLine, 1), NOTICE_MS);\n  const takingBack = withLastHold(\n    deletedBeats(wrongLine, backTo),\n    BEFORE_RETYPE_MS\n  );\n  const fixing = typedBeats(backTo, text, 2);\n  beats.push(...slipping, ...takingBack, ...fixing);\n  return beats;\n}\n\nfunction wordsOf(characters: readonly string[]) {\n  const words: Word[] = [];\n  let start = -1;\n  for (let index = 0; index <= characters.length; index += 1) {\n    const character = characters[index];\n    const isEnd = character === undefined;\n    const isGap = isEnd || character === ' ';\n    const isInWord = start >= 0;\n    if (isGap && isInWord) {\n      words.push({ start, length: index - start });\n      start = -1;\n    }\n    const startsWord = !isGap && !isInWord;\n    if (startsWord) {\n      start = index;\n    }\n  }\n  return words;\n}\n\n/** Two letters of a word swapped, as a fast hand does. */\nfunction swapSlipOf(characters: readonly string[], word: Word) {\n  const letters = characters.slice(word.start, word.start + word.length);\n  const swapped = [letters[2], letters[1], ...letters.slice(3)];\n  const typed = swapped.join('');\n  const right = letters.slice(1).join('');\n  if (typed === right) {\n    return null;\n  }\n  return { at: word.start + 1, typed };\n}\n\n/** The slip a line makes when none is given: two letters swapped in the word of four letters or more nearest its middle. */\nfunction defaultSlipOf(text: string): TypewriterSlip | null {\n  const characters = charactersOf(text);\n  const middle = characters.length / 2;\n  let best: TypewriterSlip | null = null;\n  let bestGap = Number.POSITIVE_INFINITY;\n  for (const word of wordsOf(characters)) {\n    const isLongEnough = word.length >= SLIP_WORD_LENGTH;\n    const gap = Math.abs(word.start - middle);\n    const isNearer = gap < bestGap;\n    if (!isLongEnough || !isNearer) {\n      continue;\n    }\n    const slip = swapSlipOf(characters, word);\n    if (slip) {\n      best = slip;\n      bestGap = gap;\n    }\n  }\n  return best;\n}\n\nfunction isUsableSlip(slip: TypewriterSlip, text: string) {\n  const length = charactersOf(text).length;\n  const isInside = slip.at >= 0 && slip.at <= length;\n  const hasLetters = slip.typed.length > 0;\n  return isInside && hasLetters;\n}\n\nfunction slipFor(text: string, slipAt: number, slipTyped: string) {\n  const isGiven = slipAt >= 0;\n  if (!isGiven) {\n    return defaultSlipOf(text);\n  }\n  const slip = { at: slipAt, typed: slipTyped };\n  if (isUsableSlip(slip, text)) {\n    return slip;\n  }\n  return null;\n}\n\nfunction nextTrackOf(\n  current: Track,\n  beats: readonly Beat[],\n  goesRound: boolean\n): Track {\n  if (current.beats !== beats) {\n    return current;\n  }\n  const nextIndex = current.index + 1;\n  if (nextIndex < beats.length) {\n    return { beats, index: nextIndex, isDone: false };\n  }\n  if (goesRound) {\n    return { beats, index: 0, isDone: false };\n  }\n  return { beats, index: current.index, isDone: true };\n}\n\n/**\n * Plays the beats one after another while `isPlaying`, and holds the beat it is on otherwise, with\n * the time it had left. The first beat is the resting line: it shows before playing and under\n * reduced motion.\n */\nfunction useBeats(\n  beats: readonly Beat[],\n  isPlaying: boolean,\n  goesRound: boolean\n) {\n  const [track, setTrack] = useState<Track>({\n    beats,\n    index: 0,\n    isDone: false,\n  });\n  const pending = useRef<Pending | null>(null);\n  const isCurrent = track.beats === beats;\n  if (!isCurrent) {\n    setTrack({ beats, index: 0, isDone: false });\n  }\n  let index = 0;\n  let isDone = false;\n  if (isCurrent) {\n    index = track.index;\n    isDone = track.isDone;\n  }\n  const beat = beats[index];\n  const holdMs = beat.holdMs;\n  const hasNext = beats.length > 1;\n  const canAdvance = isPlaying && hasNext && !isDone;\n\n  useEffect(() => {\n    if (!canAdvance) {\n      return;\n    }\n    const saved = pending.current;\n    const isSameBeats = saved?.beats === beats;\n    const isSameIndex = saved?.index === index;\n    let remaining = holdMs;\n    if (saved && isSameBeats && isSameIndex) {\n      remaining = saved.remaining;\n    }\n    pending.current = {\n      beats,\n      index,\n      remaining,\n      startedAt: performance.now(),\n    };\n    const timer = window.setTimeout(() => {\n      pending.current = null;\n      setTrack((current) => nextTrackOf(current, beats, goesRound));\n    }, remaining);\n    return () => {\n      window.clearTimeout(timer);\n      const left = pending.current;\n      if (!left) {\n        return;\n      }\n      const spent = performance.now() - left.startedAt;\n      const stillLeft = Math.max(0, left.remaining - spent);\n      pending.current = { ...left, remaining: stillLeft };\n    };\n  }, [canAdvance, beats, index, holdMs, goesRound]);\n\n  return { beat, isDone };\n}\n\nfunction beatsOf(\n  mode: TypewriterMode,\n  phrases: readonly string[],\n  slip: TypewriterSlip | null,\n  isLooping: boolean\n) {\n  if (mode === 'cycle') {\n    return cycleBeatsOf(phrases);\n  }\n  const text = phrases[0];\n  const beats = retypeBeatsOf(text, slip);\n  if (isLooping) {\n    return beats;\n  }\n  beats.push(idleBeat(text, LAST_HOLD_MS));\n  return beats;\n}\n\n/** Every line the effect can show is laid out unseen in the same place, so the box keeps the size of the longest and nothing around it moves. */\nfunction reservedLinesOf(\n  mode: TypewriterMode,\n  phrases: readonly string[],\n  slip: TypewriterSlip | null\n) {\n  if (mode === 'cycle') {\n    return phrases;\n  }\n  const text = phrases[0];\n  if (!slip) {\n    return [text];\n  }\n  const before = charactersOf(text).slice(0, slip.at).join('');\n  return [text, before + slip.typed];\n}\n\nfunction spokenTextOf(mode: TypewriterMode, phrases: readonly string[]) {\n  if (mode === 'cycle') {\n    return phrases.join(', ');\n  }\n  return phrases[0];\n}\n\nconst CARET =\n  'bg-primary ms-[0.04em] inline-block h-[1.05em] w-[max(2px,0.07em)] rounded-full align-[-0.16em]';\n\nexport type TypewriterProps = {\n  /** What the line types. `cycle` types each phrase in turn and goes round; `retype` takes the first phrase only. */\n  phrases: readonly string[];\n  mode?: TypewriterMode;\n  /** In `retype`, the slip it makes before it notices and fixes it. Left out, it swaps two letters of a word near the middle. */\n  slip?: TypewriterSlip;\n  /** Whether `retype` plays again after it rests. `cycle` always goes round. */\n  isLooping?: boolean;\n  /** What a screen reader reads in place of the phrases. */\n  label?: string;\n  className?: string;\n};\n\n/**\n * A line that types itself with human timing: it cycles through phrases, taking each back only as\n * far as it differs from the next, or it clears its line and types it again with a slip it fixes.\n * The caret blinks only while the hand rests. Screen readers read the text once, as plain text;\n * under reduced motion the line rests on its first phrase with no caret.\n */\nexport function Typewriter({\n  phrases,\n  mode = 'cycle',\n  slip,\n  isLooping = false,\n  label,\n  className,\n}: TypewriterProps) {\n  const { ref, isPlaying, isStill } = usePlayWhileSeen<HTMLSpanElement>();\n  const caretRef = useRef<HTMLSpanElement>(null);\n  const phrasesKey = phrases.join(PHRASE_SEPARATOR);\n  const slipAt = slip?.at ?? -1;\n  const slipTyped = slip?.typed ?? '';\n  const isCycling = mode === 'cycle';\n  const goesRound = isCycling || isLooping;\n  const lines = useMemo(() => phrasesKey.split(PHRASE_SEPARATOR), [phrasesKey]);\n  const chosenSlip = useMemo(\n    () => slipFor(lines[0], slipAt, slipTyped),\n    [lines, slipAt, slipTyped]\n  );\n  const beats = useMemo(\n    () => beatsOf(mode, lines, chosenSlip, isLooping),\n    [mode, lines, chosenSlip, isLooping]\n  );\n  const { beat, isDone } = useBeats(beats, isPlaying, goesRound);\n  const hasTyping = beats.length > 1;\n  const showsCaret = hasTyping && !isStill && !isDone;\n  const isBlinking = showsCaret && isPlaying && beat.isIdle;\n  const reserved = reservedLinesOf(mode, lines, chosenSlip);\n  const spoken = label ?? spokenTextOf(mode, lines);\n\n  useEffect(() => {\n    const caret = caretRef.current;\n    if (!caret || !isBlinking) {\n      return;\n    }\n    const blink = caret.animate(BLINK_KEYFRAMES, {\n      duration: BLINK_MS,\n      iterations: Number.POSITIVE_INFINITY,\n    });\n    return () => blink.cancel();\n  }, [isBlinking]);\n\n  return (\n    <span\n      ref={ref}\n      className={cn('relative inline-grid text-start', className)}\n    >\n      <span className='sr-only'>{spoken}</span>\n      {reserved.map((line, index) => (\n        <span\n          key={index}\n          aria-hidden='true'\n          className='invisible col-start-1 row-start-1 whitespace-pre-wrap'\n        >\n          {line}\n          <span className={CARET} />\n        </span>\n      ))}\n      <span\n        aria-hidden='true'\n        className='col-start-1 row-start-1 whitespace-pre-wrap'\n      >\n        <span\n          data-selected={beat.isSelected}\n          className='data-[selected=true]:bg-primary/20 rounded-[0.12em] transition-colors duration-100'\n        >\n          {beat.text}\n        </span>\n        <span\n          ref={caretRef}\n          data-shown={showsCaret}\n          className={cn(\n            CARET,\n            'transition-opacity duration-200 data-[shown=false]:opacity-0'\n          )}\n        />\n      </span>\n    </span>\n  );\n}\n\nconst PHRASES = ['standup', 'design review', 'launch', 'retro'];\n\nconst LINE = 'Draft the release notes before Friday';\n\nconst MODES: Segment<TypewriterMode>[] = [\n  { value: 'cycle', label: 'Phrases' },\n  { value: 'retype', label: 'Typo' },\n];\n\n/** The demonstration switches when each line has gone round once and rests again. */\nconst CYCLE_SHOWN_MS = 13600;\n\nconst RETYPE_SHOWN_MS = 9000;\n\nexport default function TextEffect01() {\n  const [mode, setMode] = useState<TypewriterMode>('cycle');\n  const steps: AutoplayStep[] = [\n    { after: CYCLE_SHOWN_MS, run: () => setMode('retype') },\n    { after: RETYPE_SHOWN_MS, run: () => setMode('cycle') },\n  ];\n  const { ref } = useAutoplay(steps, {\n    loopAfter: 0,\n    onReset: () => setMode('cycle'),\n  });\n  const isCycling = mode === 'cycle';\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='@container flex min-h-36 w-full max-w-[34rem] flex-col gap-5'\n    >\n      <p className='text-2xl leading-tight font-semibold text-balance @md:text-3xl'>\n        {isCycling && (\n          <>\n            Notes for every <Typewriter key='cycle' phrases={PHRASES} />\n          </>\n        )}\n        {!isCycling && (\n          <Typewriter key='retype' mode='retype' phrases={[LINE]} isLooping />\n        )}\n      </p>\n      <Segments\n        value={mode}\n        segments={MODES}\n        onValueChange={setMode}\n        label='Typewriter'\n        className='self-start'\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/text-effect/text-effect-01.tsx"
    },
    {
      "path": "registry/ndeko/components/text-effect/_parts/use-play-while-seen.ts",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useRef } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\n/**\n * A text effect plays only while someone can see it: on screen, in the tab that is shown, without\n * reduced motion. Everything that repeats hangs on `isPlaying`, and `isStill` asks for the still\n * frame, which must read as the finished text.\n */\nexport function usePlayWhileSeen<Element extends HTMLElement = HTMLElement>() {\n  const ref = useRef<Element>(null);\n  const isInView = useInView(ref);\n  const isTabVisible = useDocumentVisible();\n  const isStill = usePrefersReducedMotion();\n  const isOnScreen = isInView && isTabVisible;\n  const isPlaying = isOnScreen && !isStill;\n\n  return { ref, isPlaying, isStill };\n}\n",
      "type": "registry:component",
      "target": "components/text-effect/_parts/use-play-while-seen.ts"
    }
  ],
  "categories": [
    "components",
    "text-effect"
  ],
  "type": "registry:component"
}