{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "voice-03",
  "title": "Dictation",
  "description": "A field whose microphone key turns the footer into a recording strip, then transcribes the take and streams the words in at the caret.",
  "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/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/level-bars.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/media-clock.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/textarea.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/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/voice/voice-03.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport {\n  useContext,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react';\n\nimport { ClockGateContext, useNow } from '@/registry/ndeko/hooks/use-agent-run';\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  CheckIcon,\n  CircleAlertIcon,\n  LoaderIcon,\n  MicIcon,\n  RotateCcwIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { risePresenceOf } 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 { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport { formatClock } from '@/registry/ndeko/lib/media-clock';\nimport { LevelBars } from '@/registry/ndeko/ui/level-bars';\n\nexport type DictationTake = {\n  /** How long the person spoke, in milliseconds. */\n  durationMs: number;\n};\n\ntype Phase = 'idle' | 'recording' | 'transcribing' | 'writing' | 'failed';\n\ntype Failure = 'short' | 'error';\n\ntype Range = {\n  start: number;\n  end: number;\n};\n\nconst MIN_TAKE_MS = 1000;\n\nconst WORD_GAP_MS = 75;\n\nconst BAR_COUNT = 24;\n\nconst MAX_FIELD_HEIGHT = 220;\n\nconst FAILURE_TEXT: Record<Failure, string> = {\n  short: 'That was under a second. Record a little longer',\n  error: 'The words could not be transcribed. Try again',\n};\n\ntype KeyLook = {\n  key: string;\n  label: string;\n  glyph: React.ReactNode;\n};\n\nfunction keyLookOf(phase: Phase): KeyLook {\n  if (phase === 'recording') {\n    return {\n      key: 'done',\n      label: 'Stop and transcribe',\n      glyph: <CheckIcon />,\n    };\n  }\n  const isBusy = phase === 'transcribing' || phase === 'writing';\n  if (isBusy) {\n    return {\n      key: 'busy',\n      label: 'Transcribing',\n      glyph: <LoaderIcon className='animate-spin' />,\n    };\n  }\n  return { key: 'mic', label: 'Start dictation', glyph: <MicIcon /> };\n}\n\nfunction needsSpaceBetween(before: string, after: string) {\n  if (before === '') {\n    return false;\n  }\n  if (after === '') {\n    return false;\n  }\n  const endsWithSpace = /\\s$/.test(before);\n  const startsWithSpace = /^\\s/.test(after);\n  return !endsWithSpace && !startsWithSpace;\n}\n\nfunction spaceIf(isNeeded: boolean) {\n  if (isNeeded) {\n    return ' ';\n  }\n  return '';\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 Elapsed({ since }: { since: number }) {\n  const now = useNow(250, true);\n  const elapsed = now - since;\n  const text = formatClock(elapsed);\n\n  return (\n    <span className='text-muted-foreground w-9 shrink-0 text-end text-xs tabular-nums'>\n      {text}\n    </span>\n  );\n}\n\nfunction RecordingDot({ isBlinking }: { isBlinking: boolean }) {\n  return (\n    <span\n      aria-hidden='true'\n      className={cn(\n        'bg-destructive size-2 shrink-0 rounded-full',\n        isBlinking && 'animate-pulse'\n      )}\n    />\n  );\n}\n\nfunction announcementOf(phase: Phase, failure: Failure | null, added: string) {\n  if (phase === 'recording') {\n    return 'Recording. Press the key again or Space to stop, Escape to cancel';\n  }\n  if (phase === 'transcribing') {\n    return 'Transcribing';\n  }\n  if (phase === 'failed') {\n    return FAILURE_TEXT[failure ?? 'error'];\n  }\n  return added;\n}\n\nexport type DictationPressKey = 'key' | 'cancel';\n\nexport type DictationHandle = {\n  /** Shows the microphone key or Cancel held down. */\n  press: (key: DictationPressKey) => void;\n  /** Starts a take, or stops it and transcribes, as the microphone key does. */\n  pressKey: () => void;\n  /** Drops the take, as Escape does. */\n  cancel: () => void;\n};\n\nexport type DictationFieldProps = {\n  value: string;\n  onValueChange: (value: string) => void;\n  /** Turns a finished take into text; plug a speech service in here. It is called once Done is pressed. */\n  transcribe: (take: DictationTake, signal: AbortSignal) => Promise<string>;\n  /** The live microphone level between 0 and 1; left out, the bars follow a simulated voice. */\n  level?: () => number;\n  label: string;\n  placeholder?: string;\n  /** Runs what the microphone key and Escape do, for a demonstration or a control beside the field. */\n  handleRef?: React.Ref<DictationHandle>;\n  /** A demonstration drives the field: nothing takes the focus and nothing is read aloud. */\n  isDemonstrated?: boolean;\n  className?: string;\n};\n\nexport function DictationField({\n  value,\n  onValueChange,\n  transcribe,\n  level,\n  label,\n  placeholder,\n  handleRef,\n  isDemonstrated = false,\n  className,\n}: DictationFieldProps) {\n  const [phase, setPhase] = useState<Phase>('idle');\n  const [failure, setFailure] = useState<Failure | null>(null);\n  const [recordingSince, setRecordingSince] = useState(0);\n  const [added, setAdded] = useState('');\n  const { schedule, clearAll } = useTimeouts();\n  const { pressed, press } = usePress<DictationPressKey>();\n  const isOnScreen = useContext(ClockGateContext);\n  const canMoveFocus = !isDemonstrated;\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const keyRef = useRef<HTMLButtonElement>(null);\n  const selection = useRef<Range | null>(null);\n  const insertAt = useRef<Range>({ start: 0, end: 0 });\n  const lastTake = useRef<DictationTake | null>(null);\n  const request = useRef<AbortController | null>(null);\n  const fieldId = useId();\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const presence = risePresenceOf(shouldReduceMotion);\n  const keyLook = keyLookOf(phase);\n  const isRecording = phase === 'recording';\n  const isTranscribing = phase === 'transcribing';\n  const isWriting = phase === 'writing';\n  const isFailed = phase === 'failed';\n  const isBusy = isTranscribing || isWriting;\n  const canCancel = isRecording || isTranscribing;\n  const isLocked = isRecording || isBusy;\n  const canRetry = isFailed && failure === 'error';\n  const announcement = announcementOf(phase, failure, added);\n\n  useLayoutEffect(() => {\n    const textarea = textareaRef.current;\n    if (!textarea) {\n      return;\n    }\n    textarea.style.height = 'auto';\n    const height = Math.min(textarea.scrollHeight, MAX_FIELD_HEIGHT);\n    textarea.style.height = `${height}px`;\n  }, [value]);\n\n  useEffect(() => {\n    return () => request.current?.abort();\n  }, []);\n\n  function rememberSelection(event: React.SyntheticEvent<HTMLTextAreaElement>) {\n    const textarea = event.currentTarget;\n    selection.current = {\n      start: textarea.selectionStart,\n      end: textarea.selectionEnd,\n    };\n  }\n\n  function caretRange(): Range {\n    const saved = selection.current;\n    if (saved) {\n      return saved;\n    }\n    const end = value.length;\n    return { start: end, end };\n  }\n\n  function startRecording() {\n    clearAll();\n    request.current?.abort();\n    insertAt.current = caretRange();\n    setFailure(null);\n    setAdded('');\n    setRecordingSince(Date.now());\n    setPhase('recording');\n  }\n\n  function cancel() {\n    clearAll();\n    request.current?.abort();\n    setPhase('idle');\n    setAdded('Dictation cancelled');\n    if (canMoveFocus) {\n      keyRef.current?.focus();\n    }\n  }\n\n  function writeWords(text: string) {\n    const range = insertAt.current;\n    const before = value.slice(0, range.start);\n    const after = value.slice(range.end);\n    const leading = spaceIf(needsSpaceBetween(before, text));\n    const trailing = spaceIf(needsSpaceBetween(text, after));\n    const words = wordsIn(text);\n    const trimmedText = text.trim();\n    setPhase('writing');\n    words.forEach((_, index) => {\n      const count = index + 1;\n      const isLast = count === words.length;\n      const shownWords = words.slice(0, count);\n      const shown = shownWords.join(' ');\n      const tail = trailingIf(isLast, trailing);\n      const next = `${before}${leading}${shown}${tail}${after}`;\n      const delay = count * WORD_GAP_MS;\n      schedule(() => onValueChange(next), delay);\n    });\n    const caret = before.length + leading.length + trimmedText.length;\n    const doneAt = (words.length + 1) * WORD_GAP_MS;\n    schedule(() => {\n      setPhase('idle');\n      setAdded(`Added: ${trimmedText}`);\n      selection.current = { start: caret, end: caret };\n      if (!canMoveFocus) {\n        return;\n      }\n      const textarea = textareaRef.current;\n      textarea?.focus();\n      textarea?.setSelectionRange(caret, caret);\n    }, doneAt);\n  }\n\n  function runTranscription(take: DictationTake) {\n    const controller = new AbortController();\n    request.current = controller;\n    setPhase('transcribing');\n    transcribe(take, controller.signal)\n      .then((text) => {\n        if (controller.signal.aborted) {\n          return;\n        }\n        writeWords(text);\n      })\n      .catch(() => {\n        if (controller.signal.aborted) {\n          return;\n        }\n        setFailure('error');\n        setPhase('failed');\n      });\n  }\n\n  function finishRecording() {\n    const durationMs = Date.now() - recordingSince;\n    const take = { durationMs };\n    const isTooShort = durationMs < MIN_TAKE_MS;\n    if (isTooShort) {\n      setFailure('short');\n      setPhase('failed');\n      return;\n    }\n    lastTake.current = take;\n    runTranscription(take);\n  }\n\n  function retry() {\n    const take = lastTake.current;\n    if (!take) {\n      return;\n    }\n    runTranscription(take);\n  }\n\n  function dismiss() {\n    setPhase('idle');\n    setFailure(null);\n    keyRef.current?.focus();\n  }\n\n  function pressKey() {\n    if (isRecording) {\n      finishRecording();\n      return;\n    }\n    if (isBusy) {\n      return;\n    }\n    startRecording();\n  }\n\n  function handleEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key !== 'Escape') {\n      return;\n    }\n    if (!canCancel) {\n      return;\n    }\n    event.preventDefault();\n    cancel();\n  }\n\n  useImperativeHandle(handleRef, () => ({ press, pressKey, cancel }));\n\n  return (\n    <div\n      onKeyDown={handleEscape}\n      className={cn(\n        'bg-card hairline-ring ring-foreground/12 dark:ring-foreground/15 has-[textarea:focus]:ring-ring/25 @container flex flex-col rounded-xl p-1.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-shadow duration-150 has-[textarea:focus]:ring-[3px]',\n        className\n      )}\n    >\n      <label htmlFor={fieldId} className='sr-only'>\n        {label}\n      </label>\n      <Textarea\n        ref={textareaRef}\n        id={fieldId}\n        rows={2}\n        value={value}\n        onChange={(event) => onValueChange(event.target.value)}\n        onSelect={rememberSelection}\n        readOnly={isLocked}\n        placeholder={placeholder}\n        className='max-h-none min-h-14 border-0 bg-transparent px-2 py-1.5 shadow-none ring-0 focus-visible:ring-0 dark:bg-transparent'\n      />\n      <div className='flex min-h-8 items-center gap-2 ps-1.5'>\n        <div className='relative flex min-w-0 flex-1 items-center'>\n          <AnimatePresence initial={false} mode='popLayout'>\n            {isRecording && (\n              <motion.div\n                key='recording'\n                className='flex min-w-0 flex-1 items-center gap-2.5'\n                {...presence}\n              >\n                <RecordingDot isBlinking={isOnScreen} />\n                <LevelBars\n                  isActive={isOnScreen}\n                  level={level}\n                  count={BAR_COUNT}\n                  seed={0.8}\n                  className='min-w-0 flex-1 justify-end overflow-hidden'\n                />\n                <Elapsed since={recordingSince} />\n                <Button\n                  type='button'\n                  variant='ghost'\n                  size='sm'\n                  onClick={cancel}\n                  aria-keyshortcuts='Escape'\n                  className={cn(\n                    'text-muted-foreground gap-1.5',\n                    pressedQuietOf(pressed === 'cancel')\n                  )}\n                >\n                  Cancel\n                  <Kbd aria-hidden='true' className='hidden @xs:inline-flex'>\n                    Esc\n                  </Kbd>\n                </Button>\n              </motion.div>\n            )}\n            {isTranscribing && (\n              <motion.div\n                key='transcribing'\n                className='flex min-w-0 flex-1 items-center justify-between gap-2'\n                {...presence}\n              >\n                <span aria-hidden={hiddenIf(isDemonstrated)}>\n                  <TextLoader text='Transcribing' size='sm' />\n                </span>\n                <Button\n                  type='button'\n                  variant='ghost'\n                  size='sm'\n                  onClick={cancel}\n                  className='text-muted-foreground'\n                >\n                  Cancel\n                </Button>\n              </motion.div>\n            )}\n            {isWriting && (\n              <motion.p\n                key='writing'\n                className='text-muted-foreground flex-1 text-xs'\n                {...presence}\n              >\n                Adding the words at the caret\n              </motion.p>\n            )}\n            {isFailed && (\n              <motion.div\n                key='failed'\n                className='flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1'\n                {...presence}\n              >\n                <p className='text-destructive-ink flex min-w-0 flex-1 items-start gap-1.5 text-xs leading-5'>\n                  <CircleAlertIcon className='mt-0.5 size-3.5 shrink-0' />\n                  {FAILURE_TEXT[failure ?? 'error']}\n                </p>\n                <span className='flex items-center gap-1'>\n                  {canRetry && (\n                    <Button\n                      type='button'\n                      variant='ghost'\n                      size='sm'\n                      onClick={retry}\n                    >\n                      <RotateCcwIcon />\n                      Retry\n                    </Button>\n                  )}\n                  <Button\n                    type='button'\n                    variant='ghost'\n                    size='sm'\n                    onClick={dismiss}\n                    className='text-muted-foreground'\n                  >\n                    Dismiss\n                  </Button>\n                </span>\n              </motion.div>\n            )}\n            {phase === 'idle' && (\n              <motion.p\n                key='idle'\n                className='text-muted-foreground flex-1 truncate text-xs'\n                {...presence}\n              >\n                Press the microphone, or Space on it, to dictate\n              </motion.p>\n            )}\n          </AnimatePresence>\n        </div>\n        <Button\n          ref={keyRef}\n          type='button'\n          size='icon'\n          aria-label={keyLook.label}\n          disabled={isBusy}\n          focusableWhenDisabled\n          onClick={pressKey}\n          className={cn(busyClassOf(isBusy), pressedSolidOf(pressed === 'key'))}\n        >\n          <AnimatedSize as='span' axis='width'>\n            <Swap swapKey={keyLook.key}>{keyLook.glyph}</Swap>\n          </AnimatedSize>\n        </Button>\n      </div>\n      <LiveRegion message={spokenUnless(isDemonstrated, announcement)} />\n    </div>\n  );\n}\n\nfunction trailingIf(isLast: boolean, trailing: string) {\n  if (isLast) {\n    return trailing;\n  }\n  return '';\n}\n\n/** While it transcribes, the key keeps its colour: it is working, not unavailable. */\nfunction busyClassOf(isBusy: boolean) {\n  if (isBusy) {\n    return 'data-disabled:opacity-100 disabled:opacity-100';\n  }\n  return undefined;\n}\n\nconst SHORT_TAKE_MS = 3500;\n\nconst SHORT_PHRASE = 'Move the launch review to Thursday at ten';\n\nconst LONG_PHRASE =\n  'Move the launch review to Thursday at ten and ask Priya to bring the rollout numbers for the three pilot teams';\n\nconst TRANSCRIBE_MS = 1100;\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 transcription was cancelled', 'AbortError'));\n    });\n  });\n}\n\n/** A longer take gives a longer sentence, the way a real speech service would. */\nasync function demoTranscribe(take: DictationTake, signal: AbortSignal) {\n  await wait(TRANSCRIBE_MS, signal);\n  const isShort = take.durationMs < SHORT_TAKE_MS;\n  if (isShort) {\n    return SHORT_PHRASE;\n  }\n  return LONG_PHRASE;\n}\n\nconst START_TEXT = 'Notes for Monday: ask Priya for the rollout numbers. ';\n\n/** How long the demonstration speaks before it stops the take: short enough for the short sentence. */\nconst TAKE_MS = 2600;\n\n/** One take in three is dropped with Escape, so the strip shows how it folds back. */\nconst CANCEL_ROUND = 3;\n\nfunction writingMsOf(phrase: string) {\n  const words = wordsIn(phrase);\n  return (words.length + 1) * WORD_GAP_MS;\n}\n\nconst WRITING_MS = writingMsOf(SHORT_PHRASE);\n\nexport default function Voice03() {\n  const [notes, setNotes] = useState(START_TEXT);\n  const [round, setRound] = useState(0);\n  const field = useRef<DictationHandle>(null);\n  const isCancelRound = round % CANCEL_ROUND === CANCEL_ROUND - 1;\n\n  function resetDemo() {\n    setNotes(START_TEXT);\n    setRound((current) => current + 1);\n  }\n\n  const transcribing: AutoplayStep[] = [\n    { after: TAKE_MS, run: () => field.current?.press('key') },\n    { after: PRESS_LEAD_MS, run: () => field.current?.pressKey() },\n    { after: TRANSCRIBE_MS + WRITING_MS + 900, run: hold },\n  ];\n  const cancelling: AutoplayStep[] = [\n    { after: 1900, run: () => field.current?.press('cancel') },\n    { after: PRESS_LEAD_MS, run: () => field.current?.cancel() },\n    { after: 900, run: hold },\n  ];\n  let ending = transcribing;\n  if (isCancelRound) {\n    ending = cancelling;\n  }\n  const steps: AutoplayStep[] = [\n    { after: 1400, run: () => field.current?.press('key') },\n    { after: PRESS_LEAD_MS, run: () => field.current?.pressKey() },\n    ...ending,\n  ];\n  const { ref, isInView, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2600,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='flex w-full max-w-[26rem] flex-col gap-2'>\n      <ClockGate isActive={isInView}>\n        <p className='px-1 text-[13px] font-medium'>Meeting notes</p>\n        <DictationField\n          value={notes}\n          onValueChange={setNotes}\n          transcribe={demoTranscribe}\n          label='Meeting notes'\n          placeholder='Type or dictate your notes'\n          handleRef={field}\n          isDemonstrated={isAutoplaying}\n        />\n        <p className='text-muted-foreground px-1 text-[11px]'>\n          Illustrative: the levels and the words are simulated, no microphone is\n          used\n        </p>\n      </ClockGate>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "voice"
  ],
  "type": "registry:component"
}