{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dtmf-keypad",
  "title": "DTMF Keypad",
  "description": "Telephone keypad that sends DTMF tones — buffered sequence entry or immediate per-key dialing, with synthesized press feedback.",
  "dependencies": [
    "@pipecat-ai/client-js@^1.14.0",
    "@pipecat-ai/client-react@^1.9.0",
    "lucide-react@^1.41.0"
  ],
  "registryDependencies": [
    "button",
    "input"
  ],
  "files": [
    {
      "path": "src/components/dtmf-keypad.tsx",
      "content": "\"use client\";\n\nimport { type DTMFButton } from \"@pipecat-ai/client-js\";\nimport {\n  useDTMF,\n  usePipecatClientTransportState,\n} from \"@pipecat-ai/client-react\";\nimport { DeleteIcon, PhoneIcon } from \"lucide-react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { cn } from \"@/lib/utils\";\n\ntype ButtonProps = React.ComponentProps<typeof Button>;\n\n/**\n * Ordered list of the twelve DTMF keys as they appear on a standard\n * telephone keypad, with the letters traditionally printed beneath each\n * digit. Rendered row by row into a 3-column grid.\n */\nconst DTMF_KEYS: { value: DTMFButton; sub?: string }[] = [\n  { value: \"1\" },\n  { value: \"2\", sub: \"ABC\" },\n  { value: \"3\", sub: \"DEF\" },\n  { value: \"4\", sub: \"GHI\" },\n  { value: \"5\", sub: \"JKL\" },\n  { value: \"6\", sub: \"MNO\" },\n  { value: \"7\", sub: \"PQRS\" },\n  { value: \"8\", sub: \"TUV\" },\n  { value: \"9\", sub: \"WXYZ\" },\n  { value: \"*\" },\n  { value: \"0\", sub: \"+\" },\n  { value: \"#\" },\n];\n\nconst sanitizeDTMF = (value: string): string => value.replace(/[^0-9*#]/g, \"\");\n\n/**\n * The (row, column) frequency pair defining each key's dual tone, per the\n * standard DTMF layout. Synthesized so no audio assets ship with the kit.\n */\nconst DTMF_FREQUENCIES: Record<DTMFButton, [number, number]> = {\n  \"1\": [697, 1209],\n  \"2\": [697, 1336],\n  \"3\": [697, 1477],\n  \"4\": [770, 1209],\n  \"5\": [770, 1336],\n  \"6\": [770, 1477],\n  \"7\": [852, 1209],\n  \"8\": [852, 1336],\n  \"9\": [852, 1477],\n  \"*\": [941, 1209],\n  \"0\": [941, 1336],\n  \"#\": [941, 1477],\n};\n\nconst TONE_DURATION = 0.12;\n/** Deliberately quiet: the tone plays over a live call. */\nconst DEFAULT_TONE_VOLUME = 0.15;\n/** Attack/release ramp; without it the tone clicks. */\nconst TONE_RAMP = 0.01;\n\n/**\n * Local press-feedback tone. Cosmetic sidetone only — the actual\n * signalling happens over the transport via sendTone.\n */\nfunction useDTMFTone(enabled: boolean, volume: number) {\n  const contextRef = useRef<AudioContext | null>(null);\n  const peakGain = Math.min(Math.max(volume, 0), 1);\n\n  useEffect(\n    () => () => {\n      void contextRef.current?.close();\n      contextRef.current = null;\n    },\n    [],\n  );\n\n  return useCallback(\n    (key: DTMFButton) => {\n      if (\n        !enabled ||\n        peakGain <= 0 ||\n        typeof window === \"undefined\" ||\n        !window.AudioContext\n      ) {\n        return;\n      }\n      // Created lazily on first press so it's tied to a user gesture\n      // (autoplay policy) and never constructed during SSR.\n      const context = (contextRef.current ??= new window.AudioContext());\n      if (context.state === \"suspended\") void context.resume();\n\n      const now = context.currentTime;\n      const gain = context.createGain();\n      gain.connect(context.destination);\n      gain.gain.setValueAtTime(0, now);\n      gain.gain.linearRampToValueAtTime(peakGain, now + TONE_RAMP);\n      gain.gain.setValueAtTime(peakGain, now + TONE_DURATION - TONE_RAMP);\n      gain.gain.linearRampToValueAtTime(0, now + TONE_DURATION);\n\n      const oscillators = DTMF_FREQUENCIES[key].map((frequency) => {\n        const oscillator = context.createOscillator();\n        oscillator.type = \"sine\";\n        oscillator.frequency.setValueAtTime(frequency, now);\n        oscillator.connect(gain);\n        oscillator.start(now);\n        oscillator.stop(now + TONE_DURATION);\n        return oscillator;\n      });\n\n      const last = oscillators[oscillators.length - 1];\n      if (last) {\n        last.onended = () => {\n          oscillators.forEach((oscillator) => oscillator.disconnect());\n          gain.disconnect();\n        };\n      }\n    },\n    [enabled, peakGain],\n  );\n}\n\n/**\n * - \"buffered\" (default): presses accumulate in an editable field and send\n *   as one sequence on submit — mistypes can be corrected before dialing.\n * - \"immediate\": each press sends right away — suits live IVR menus.\n */\nexport type DTMFKeypadMode = \"immediate\" | \"buffered\";\n\nexport interface DTMFKeypadViewProps {\n  mode?: DTMFKeypadMode;\n  variant?: ButtonProps[\"variant\"];\n  size?: ButtonProps[\"size\"];\n  disabled?: boolean;\n  /** Hide the letters printed beneath each digit. */\n  noSubLabels?: boolean;\n  /** Disable the audible press-feedback tone. */\n  noToneFeedback?: boolean;\n  /** Peak tone volume, 0–1 (clamped). */\n  toneVolume?: number;\n  placeholder?: string;\n  sendLabel?: string;\n  className?: string;\n  /** Called with each key as it is pressed (both modes). */\n  onPress?: (button: DTMFButton) => void;\n  /** Called with the full sequence on submit (buffered mode). */\n  onSend?: (sequence: string) => void;\n  /** Controlled buffer value (buffered mode). */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n}\n\n/**\n * Telephone keypad, props-driven. Buffered mode adds an editable sequence\n * field, backspace, and a send button.\n */\nexport function DTMFKeypadView({\n  mode = \"buffered\",\n  variant = \"secondary\",\n  size = \"lg\",\n  disabled = false,\n  noSubLabels = false,\n  noToneFeedback = false,\n  toneVolume = DEFAULT_TONE_VOLUME,\n  placeholder = \"Enter digits\",\n  sendLabel = \"Send\",\n  className,\n  onPress,\n  onSend,\n  value,\n  defaultValue,\n  onValueChange,\n}: DTMFKeypadViewProps) {\n  const buffered = mode === \"buffered\";\n\n  const isControlled = value !== undefined;\n  const [internalValue, setInternalValue] = useState(defaultValue ?? \"\");\n  const buffer = isControlled ? (value ?? \"\") : internalValue;\n\n  const setBuffer = useCallback(\n    (next: string) => {\n      if (!isControlled) setInternalValue(next);\n      onValueChange?.(next);\n    },\n    [isControlled, onValueChange],\n  );\n\n  const playTone = useDTMFTone(!noToneFeedback, toneVolume);\n\n  const handlePress = useCallback(\n    (key: DTMFButton) => {\n      playTone(key);\n      onPress?.(key);\n      if (buffered) setBuffer(buffer + key);\n    },\n    [buffered, buffer, onPress, setBuffer, playTone],\n  );\n\n  const handleSend = useCallback(() => {\n    // Sanitize at send time too: controlled values bypass the input's\n    // onChange sanitization.\n    const sequence = sanitizeDTMF(buffer);\n    if (!sequence) return;\n    onSend?.(sequence);\n    setBuffer(\"\");\n  }, [buffer, onSend, setBuffer]);\n\n  const grid = (\n    <div className=\"grid grid-cols-3 gap-2\">\n      {DTMF_KEYS.map(({ value: key, sub }) => (\n        <Button\n          key={key}\n          type=\"button\"\n          variant={variant}\n          size={size}\n          aria-label={`DTMF ${key}`}\n          disabled={disabled}\n          onClick={() => handlePress(key)}\n          className=\"flex h-auto flex-col items-center justify-center gap-0 py-1.5 tabular-nums\"\n        >\n          <span className=\"text-base font-semibold\">{key}</span>\n          {!noSubLabels && (\n            <span className=\"h-2.5 text-[0.6rem] leading-none tracking-widest opacity-60\">\n              {sub ?? \"\"}\n            </span>\n          )}\n        </Button>\n      ))}\n    </div>\n  );\n\n  if (!buffered) {\n    return (\n      <div data-slot=\"dtmf-keypad\" className={className}>\n        {grid}\n      </div>\n    );\n  }\n\n  return (\n    <div\n      data-slot=\"dtmf-keypad\"\n      className={cn(\"flex flex-col gap-2\", className)}\n    >\n      <div className=\"flex items-center gap-2\">\n        <Input\n          value={buffer}\n          onChange={(e) => setBuffer(sanitizeDTMF(e.target.value))}\n          onKeyDown={(e) => {\n            if (e.key === \"Enter\") {\n              // Enter should dispatch the sequence, not submit a form.\n              e.preventDefault();\n              handleSend();\n            }\n          }}\n          placeholder={placeholder}\n          disabled={disabled}\n          // The on-screen keypad is the intended input method on touch\n          // devices; typing/paste on desktop still works.\n          inputMode=\"none\"\n          aria-label=\"DTMF sequence\"\n          className=\"flex-1 tracking-widest tabular-nums\"\n        />\n        <Button\n          type=\"button\"\n          variant=\"secondary\"\n          size=\"icon\"\n          disabled={disabled || !buffer}\n          aria-label=\"Delete last digit\"\n          onClick={() => setBuffer(buffer.slice(0, -1))}\n        >\n          <DeleteIcon />\n        </Button>\n      </div>\n      {grid}\n      <Button\n        type=\"button\"\n        variant={variant}\n        size={size}\n        disabled={disabled || !buffer}\n        onClick={handleSend}\n        className=\"w-full\"\n      >\n        <PhoneIcon />\n        {sendLabel}\n      </Button>\n    </div>\n  );\n}\n\nexport interface DTMFKeypadProps extends Omit<DTMFKeypadViewProps, \"onSend\"> {\n  /** Called after tone(s) are successfully sent. */\n  onToneSent?: (sequence: string) => void;\n  /**\n   * Called if sending fails — sendTone throws when the transport isn't\n   * ready or the bot doesn't support DTMF (RTVI < 2.0.0).\n   */\n  onError?: (error: unknown) => void;\n}\n\n/** Requires PipecatClientProvider. Buffered mode sends on submit; immediate mode sends each press. */\nexport function DTMFKeypad({\n  mode = \"buffered\",\n  disabled,\n  onPress,\n  onToneSent,\n  onError,\n  ...props\n}: DTMFKeypadProps) {\n  const { sendTone } = useDTMF();\n  const transportState = usePipecatClientTransportState();\n  const isConnected = transportState === \"ready\";\n\n  const send = useCallback(\n    (sequence: string) => {\n      try {\n        sendTone(sequence);\n        onToneSent?.(sequence);\n      } catch (error) {\n        onError?.(error);\n      }\n    },\n    [sendTone, onToneSent, onError],\n  );\n\n  return (\n    <DTMFKeypadView\n      mode={mode}\n      disabled={disabled || !isConnected}\n      onPress={(button) => {\n        onPress?.(button);\n        if (mode === \"immediate\") send(button);\n      }}\n      onSend={mode === \"buffered\" ? send : undefined}\n      {...props}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/dtmf-keypad.tsx"
    }
  ],
  "docs": "Render inside a PipecatClientProvider. Disabled until the transport is ready; requires a bot with DTMF support (RTVI 2.0.0+).",
  "categories": [
    "voice"
  ],
  "type": "registry:component"
}