{"version":3,"file":"useSpeechToText.mjs","names":[],"sources":["../../../../../../src/plugins/AIComponents/AIMessageComposer/hooks/useSpeechToText.ts"],"sourcesContent":["import { useEffect, useRef, useState } from 'react';\nimport { useStableCallback } from '../../../../utils/useStableCallback';\n\n// TypeScript declarations for Web Speech API\ninterface SpeechRecognition extends EventTarget {\n  lang: string;\n  continuous: boolean;\n  interimResults: boolean;\n  maxAlternatives: number;\n  start(): void;\n  stop(): void;\n  abort(): void;\n  onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => unknown) | null;\n  onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => unknown) | null;\n  onstart: ((this: SpeechRecognition, ev: Event) => unknown) | null;\n  onend: ((this: SpeechRecognition, ev: Event) => unknown) | null;\n}\n\ninterface SpeechRecognitionErrorEvent extends Event {\n  error:\n    | 'no-speech'\n    | 'aborted'\n    | 'audio-capture'\n    | 'network'\n    | 'not-allowed'\n    | 'service-not-allowed'\n    | 'bad-grammar'\n    | 'language-not-supported';\n  message: string;\n}\n\ninterface SpeechRecognitionEvent extends Event {\n  resultIndex: number;\n  results: SpeechRecognitionResultList;\n}\n\ninterface SpeechRecognitionResultList {\n  length: number;\n  item(index: number): SpeechRecognitionResult;\n  [index: number]: SpeechRecognitionResult;\n}\n\ninterface SpeechRecognitionResult {\n  isFinal: boolean;\n  length: number;\n  item(index: number): SpeechRecognitionAlternative;\n  [index: number]: SpeechRecognitionAlternative;\n}\n\ninterface SpeechRecognitionAlternative {\n  transcript: string;\n  confidence: number;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognition;\n\n// Module-local: augmenting the global `Window` interface would leak into every consumer's type\n// environment through the shipped .d.ts files.\ntype WindowWithSpeechRecognition = Window & {\n  SpeechRecognition?: SpeechRecognitionConstructor;\n  webkitSpeechRecognition?: SpeechRecognitionConstructor;\n};\n\nconst getSpeechRecognition = (): SpeechRecognitionConstructor | undefined => {\n  if (typeof window === 'undefined') return undefined;\n  const speechWindow = window as WindowWithSpeechRecognition;\n  return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition;\n};\n\nexport type UseSpeechToTextOptions = {\n  /**\n   * Recognition language, e.g. 'en-US' or 'es-ES'.\n   * @default 'en-US'\n   */\n  lang?: string;\n  /**\n   * Whether to return interim (partial) results.\n   * @default true\n   */\n  interimResults?: boolean;\n  /**\n   * Maximum number of alternative transcriptions.\n   * @default 1\n   */\n  maxAlternatives?: number;\n  /**\n   * Whether recognition continues after the user stops speaking.\n   * @default false\n   */\n  continuous?: boolean;\n  /** Called with the current transcript on every recognition result. */\n  onTranscript?: (text: string) => void;\n  /** Called with a readable message when recognition fails or cannot start. */\n  onError?: (error: string) => void;\n};\n\nexport const useSpeechToText = (options: UseSpeechToTextOptions = {}) => {\n  const {\n    continuous = false,\n    interimResults = true,\n    lang = 'en-US',\n    maxAlternatives = 1,\n    onError,\n    onTranscript,\n  } = options;\n\n  const [isListening, setIsListening] = useState(false);\n  // stable wrappers so inline callbacks do not re-create the recognizer on every render\n  const emitTranscript = useStableCallback((text: string) => onTranscript?.(text));\n  const emitError = useStableCallback((error: string) => onError?.(error));\n  const recognitionRef = useRef<SpeechRecognition | null>(null);\n\n  const isSupported = !!getSpeechRecognition();\n\n  useEffect(() => {\n    const SpeechRecognition = getSpeechRecognition();\n    if (!SpeechRecognition) {\n      return;\n    }\n\n    const recognition = new SpeechRecognition();\n    recognitionRef.current = recognition;\n    recognition.lang = lang;\n    recognition.interimResults = interimResults;\n    recognition.maxAlternatives = maxAlternatives;\n    recognition.continuous = continuous;\n\n    recognition.onresult = (event: SpeechRecognitionEvent) => {\n      const results = Array.from(event.results);\n\n      const text = results.reduce((accumulatedText, result) => {\n        const transcript = result[0]?.transcript || '';\n\n        if (result.isFinal) {\n          accumulatedText = transcript;\n        } else {\n          accumulatedText += transcript;\n        }\n\n        return accumulatedText;\n      }, '');\n\n      emitTranscript(text);\n    };\n\n    recognition.onerror = (event: SpeechRecognitionErrorEvent) => {\n      let errorMessage = 'Speech recognition error';\n\n      switch (event.error) {\n        case 'no-speech':\n          errorMessage = 'No speech detected. Please try again.';\n          break;\n        case 'audio-capture':\n          errorMessage = 'No microphone found. Please ensure a microphone is connected.';\n          break;\n        case 'not-allowed':\n          errorMessage =\n            'Microphone access denied. Please grant permission to use the microphone.';\n          break;\n        case 'network':\n          errorMessage = 'Network error occurred during speech recognition.';\n          break;\n        case 'aborted':\n          errorMessage = 'Speech recognition was aborted.';\n          break;\n        default:\n          errorMessage = `Speech recognition error: ${event.error}`;\n      }\n\n      emitError(errorMessage);\n    };\n\n    recognition.onend = () => {\n      setIsListening(false);\n    };\n\n    recognition.onstart = () => {\n      setIsListening(true);\n    };\n\n    return () => {\n      recognition.stop();\n      recognition.onresult = null;\n      recognition.onerror = null;\n      recognition.onend = null;\n      recognition.onstart = null;\n    };\n  }, [lang, interimResults, maxAlternatives, continuous, emitTranscript, emitError]);\n\n  const startListening = useStableCallback(() => {\n    if (!isSupported) {\n      throw new Error('Speech recognition is not supported in this browser');\n    }\n\n    if (recognitionRef.current && !isListening) {\n      try {\n        recognitionRef.current.start();\n      } catch {\n        emitError('Failed to start speech recognition');\n      }\n    }\n  });\n\n  const stopListening = useStableCallback(() => {\n    if (recognitionRef.current && isListening) {\n      recognitionRef.current.stop();\n    }\n  });\n\n  return {\n    isListening,\n    isSupported,\n    startListening,\n    stopListening,\n  } as const;\n};\n"],"mappings":";;;AA+DA,IAAM,6BAAuE;CAC3E,IAAI,OAAO,WAAW,aAAa,OAAO,KAAA;CAC1C,MAAM,eAAe;CACrB,OAAO,aAAa,qBAAqB,aAAa;AACxD;AA6BA,IAAa,mBAAmB,UAAkC,CAAC,MAAM;CACvE,MAAM,EACJ,aAAa,OACb,iBAAiB,MACjB,OAAO,SACP,kBAAkB,GAClB,SACA,iBACE;CAEJ,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CAEpD,MAAM,iBAAiB,mBAAmB,SAAiB,eAAe,IAAI,CAAC;CAC/E,M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