@devicai/ui 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/ChatDrawer/ChatDrawer.js +2 -1
- package/dist/cjs/components/ChatDrawer/ChatDrawer.js.map +1 -1
- package/dist/cjs/components/ChatDrawer/ChatInput.js +168 -12
- package/dist/cjs/components/ChatDrawer/ChatInput.js.map +1 -1
- package/dist/cjs/hooks/useSpeechRecording.js +4 -0
- package/dist/cjs/hooks/useSpeechRecording.js.map +1 -1
- package/dist/cjs/styles.css +1 -1
- package/dist/esm/components/ChatDrawer/ChatDrawer.js +2 -1
- package/dist/esm/components/ChatDrawer/ChatDrawer.js.map +1 -1
- package/dist/esm/components/ChatDrawer/ChatDrawer.types.d.ts +11 -0
- package/dist/esm/components/ChatDrawer/ChatInput.d.ts +1 -1
- package/dist/esm/components/ChatDrawer/ChatInput.js +168 -12
- package/dist/esm/components/ChatDrawer/ChatInput.js.map +1 -1
- package/dist/esm/hooks/useSpeechRecording.d.ts +2 -0
- package/dist/esm/hooks/useSpeechRecording.js +4 -0
- package/dist/esm/hooks/useSpeechRecording.js.map +1 -1
- package/dist/esm/styles.css +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatInput.js","sources":["../../../../../src/components/ChatDrawer/ChatInput.tsx"],"sourcesContent":["import React, { useState, useRef, useCallback, useMemo, useEffect } from 'react';\nimport type { ChatInputProps } from './ChatDrawer.types';\nimport { useSpeechRecording } from '../../hooks/useSpeechRecording';\nimport { DevicApiClient } from '../../api/client';\n\nconst FILE_TYPE_ACCEPT: Record<string, string[]> = {\n images: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],\n documents: [\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/plain',\n 'text/csv',\n ],\n audio: ['audio/mpeg', 'audio/wav', 'audio/ogg'],\n video: ['video/mp4', 'video/webm', 'video/ogg'],\n};\n\n/**\n * Chat input component with file upload support\n */\nexport function ChatInput({\n onSend,\n disabled = false,\n placeholder = 'Type a message...',\n enableFileUploads = false,\n allowedFileTypes = { images: true, documents: true },\n maxFileSize = 10 * 1024 * 1024, // 10MB\n enableSpeechToText = false,\n speechLanguage,\n speechTenantId,\n speechAutoStop = true,\n speechAutoStopCountdownMs,\n apiKey,\n baseUrl,\n sendButtonContent,\n disabledMessage,\n isProcessing = false,\n onStop,\n stopButtonContent,\n pendingInputWidget,\n onSubmitWidget,\n onCancelWidget,\n references,\n onRemoveReference,\n}: ChatInputProps): JSX.Element {\n // When a widget is pending as 'input', render it in place of the textarea\n if (pendingInputWidget) {\n const WidgetComponent = pendingInputWidget.widget.component;\n return (\n <div className=\"devic-input-area\" data-widget-mode=\"input\">\n <div className=\"devic-input-widget\" data-tool-name={pendingInputWidget.toolName}>\n <WidgetComponent\n toolCall={pendingInputWidget.toolCall}\n params={pendingInputWidget.params}\n submit={(response) => onSubmitWidget?.(pendingInputWidget.toolCall.id, response)}\n cancel={(reason) => onCancelWidget?.(pendingInputWidget.toolCall.id, reason)}\n />\n </div>\n </div>\n );\n }\n const [message, setMessage] = useState('');\n const [files, setFiles] = useState<File[]>([]);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n // Speech-to-text state\n const [transcriptId, setTranscriptId] = useState<string | undefined>();\n const [isTranscribing, setIsTranscribing] = useState(false);\n const [speechError, setSpeechError] = useState<string | null>(null);\n // Holds the latest confirmRecording so the auto-stop callback (created before\n // confirmRecording is defined) always calls the current closure.\n const confirmRef = useRef<() => void>(() => {});\n const recording = useSpeechRecording({\n bars: 5,\n autoStop: speechAutoStop,\n ...(speechAutoStopCountdownMs != null && {\n autoStopCountdownMs: speechAutoStopCountdownMs,\n }),\n onAutoStop: () => confirmRef.current(),\n });\n\n // Client used only for the /whisper transcription call.\n const transcribeClient = useMemo(() => {\n if (!enableSpeechToText || !apiKey) return null;\n return new DevicApiClient({\n apiKey,\n baseUrl: baseUrl || 'https://api.devic.ai',\n });\n }, [enableSpeechToText, apiKey, baseUrl]);\n\n const speechEnabled =\n enableSpeechToText && recording.isSupported && !!transcribeClient;\n const isRecordingActive = recording.isRecording || recording.isPaused;\n\n // Calculate accepted file types\n const acceptedTypes = Object.entries(allowedFileTypes)\n .filter(([, enabled]) => enabled)\n .flatMap(([type]) => FILE_TYPE_ACCEPT[type] || [])\n .join(',');\n\n // Auto-resize textarea\n const handleInput = useCallback(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;\n }\n }, []);\n\n // Handle send\n const handleSend = useCallback(() => {\n const trimmedMessage = message.trim();\n if (!trimmedMessage && files.length === 0) return;\n\n onSend(\n trimmedMessage,\n files.length > 0 ? files : undefined,\n transcriptId ? { transcriptId } : undefined,\n );\n setMessage('');\n setFiles([]);\n setTranscriptId(undefined);\n\n // Reset textarea height\n if (textareaRef.current) {\n textareaRef.current.style.height = 'auto';\n }\n }, [message, files, onSend, transcriptId]);\n\n // --- Speech-to-text handlers ---\n\n const startRecording = useCallback(() => {\n setSpeechError(null);\n void recording.start();\n }, [recording]);\n\n const cancelRecording = useCallback(() => {\n recording.cancel();\n }, [recording]);\n\n // Stop recording, transcribe the audio and fill the input for review.\n const confirmRecording = useCallback(async () => {\n if (!transcribeClient) return;\n const blob = await recording.stop();\n if (!blob || blob.size === 0) return;\n\n setIsTranscribing(true);\n setSpeechError(null);\n try {\n const result = await transcribeClient.transcribeAudio(blob, {\n language: speechLanguage,\n tenantId: speechTenantId,\n });\n const text = (result.text || '').trim();\n setMessage((prev) => (prev ? `${prev} ${text}`.trim() : text));\n setTranscriptId(result.transcriptId);\n // Resize textarea and focus for review/edit.\n requestAnimationFrame(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;\n textarea.focus();\n }\n });\n } catch (e) {\n setSpeechError(\n `Could not transcribe the audio: ${(e as Error)?.message || 'unknown error'}`,\n );\n } finally {\n setIsTranscribing(false);\n }\n }, [transcribeClient, recording, speechLanguage, speechTenantId]);\n\n // Keep the auto-stop callback pointed at the latest confirmRecording.\n useEffect(() => {\n confirmRef.current = () => void confirmRecording();\n }, [confirmRecording]);\n\n // Handle key press\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n // Handle file selection\n const handleFileSelect = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => {\n const selectedFiles = Array.from(e.target.files || []);\n\n // Filter valid files\n const validFiles = selectedFiles.filter((file) => {\n if (file.size > maxFileSize) {\n console.warn(`File ${file.name} exceeds maximum size`);\n return false;\n }\n return true;\n });\n\n setFiles((prev) => [...prev, ...validFiles]);\n\n // Reset input\n if (fileInputRef.current) {\n fileInputRef.current.value = '';\n }\n },\n [maxFileSize]\n );\n\n // Remove file\n const removeFile = useCallback((index: number) => {\n setFiles((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n return (\n <div className=\"devic-input-area\">\n {disabledMessage && disabled && (\n <div className=\"devic-input-disabled-notice\">\n <WaitingIcon />\n {disabledMessage}\n </div>\n )}\n {speechError && (\n <div className=\"devic-speech-error\" role=\"alert\">\n {speechError}\n </div>\n )}\n {references && references.length > 0 && (\n <div className=\"devic-reference-chips\">\n {references.map((ref) => (\n <div key={ref.id} className=\"devic-reference-chip\" title={ref.label}>\n <ReferenceIcon />\n <span className=\"devic-reference-chip-label\">\"{ref.label}\"</span>\n <button\n type=\"button\"\n className=\"devic-reference-chip-remove\"\n onClick={() => onRemoveReference?.(ref.id)}\n aria-label=\"Quitar referencia\"\n >\n ×\n </button>\n </div>\n ))}\n </div>\n )}\n {files.length > 0 && (\n <div className=\"devic-file-preview\">\n {files.map((file, idx) => (\n <div key={idx} className=\"devic-file-preview-item\">\n <FileIcon />\n <span>{file.name}</span>\n <button\n className=\"devic-file-remove\"\n onClick={() => removeFile(idx)}\n type=\"button\"\n >\n ×\n </button>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"devic-input-wrapper\">\n {isTranscribing ? (\n <div className=\"devic-speech-panel\" data-state=\"processing\">\n <span className=\"devic-speech-spinner\" aria-hidden=\"true\" />\n <span className=\"devic-speech-status\">Transcribing…</span>\n </div>\n ) : isRecordingActive ? (\n <div className=\"devic-speech-panel\" data-state=\"recording\">\n <button\n className=\"devic-input-btn devic-speech-cancel\"\n onClick={cancelRecording}\n type=\"button\"\n title=\"Cancel recording\"\n >\n <CloseIcon />\n </button>\n <div className=\"devic-speech-live\">\n <Equalizer levels={recording.levels} paused={recording.isPaused} />\n <span className=\"devic-speech-timer\">\n {formatDuration(recording.durationMs)}\n </span>\n </div>\n <button\n className=\"devic-input-btn\"\n onClick={recording.isPaused ? recording.resume : recording.pause}\n type=\"button\"\n title={recording.isPaused ? 'Resume' : 'Pause'}\n >\n {recording.isPaused ? <PlayIcon /> : <PauseIcon />}\n </button>\n <div\n className=\"devic-speech-confirm-wrap\"\n data-autostop={recording.isAutoStopping ? 'true' : 'false'}\n >\n {recording.isAutoStopping && (\n <AutoStopRing progress={recording.autoStopProgress} />\n )}\n <button\n className=\"devic-input-btn devic-speech-confirm\"\n onClick={() => void confirmRecording()}\n type=\"button\"\n title={\n recording.isAutoStopping\n ? 'Auto-sending… keep talking to cancel'\n : 'Confirm'\n }\n >\n <CheckIcon />\n </button>\n </div>\n </div>\n ) : (\n <>\n {enableFileUploads && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={acceptedTypes}\n multiple\n onChange={handleFileSelect}\n style={{ display: 'none' }}\n />\n <button\n className=\"devic-input-btn\"\n onClick={() => fileInputRef.current?.click()}\n disabled={disabled}\n type=\"button\"\n title=\"Attach file\"\n >\n <AttachIcon />\n </button>\n </>\n )}\n\n {speechEnabled && (\n <button\n className=\"devic-input-btn devic-speech-mic\"\n onClick={startRecording}\n disabled={disabled || isProcessing}\n type=\"button\"\n title=\"Record voice message\"\n >\n <MicIcon />\n </button>\n )}\n\n <textarea\n ref={textareaRef}\n className=\"devic-input\"\n value={message}\n onChange={(e) => {\n const value = e.target.value;\n setMessage(value);\n // If the user clears the field, drop the transcript link so a fresh\n // message isn't wrongly attributed to the previous transcription.\n if (transcriptId && value.trim() === '') setTranscriptId(undefined);\n handleInput();\n }}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n disabled={disabled}\n rows={1}\n />\n\n {isProcessing ? (\n stopButtonContent ? (\n <div className=\"devic-send-btn-wrapper\">\n <div className=\"devic-send-btn-custom\" aria-hidden=\"true\">\n {stopButtonContent}\n </div>\n <button\n className=\"devic-send-btn-overlay\"\n onClick={onStop}\n type=\"button\"\n title=\"Stop\"\n />\n </div>\n ) : (\n <button\n className=\"devic-input-btn devic-stop-btn\"\n onClick={onStop}\n type=\"button\"\n title=\"Stop\"\n >\n <StopIcon />\n </button>\n )\n ) : sendButtonContent ? (\n <div className=\"devic-send-btn-wrapper\">\n <div className=\"devic-send-btn-custom\" aria-hidden=\"true\">\n {sendButtonContent}\n </div>\n <button\n className=\"devic-send-btn-overlay\"\n onClick={handleSend}\n disabled={disabled || (!message.trim() && files.length === 0)}\n type=\"button\"\n title=\"Send message\"\n />\n </div>\n ) : (\n <button\n className=\"devic-input-btn devic-send-btn\"\n onClick={handleSend}\n disabled={disabled || (!message.trim() && files.length === 0)}\n type=\"button\"\n title=\"Send message\"\n >\n <SendIcon />\n </button>\n )}\n </>\n )}\n </div>\n </div>\n );\n}\n\n/**\n * Live equalizer rendered from the recording amplitude levels (0..1 per bar).\n * When paused, bars collapse to a flat baseline.\n */\nfunction Equalizer({\n levels,\n paused,\n}: {\n levels: number[];\n paused: boolean;\n}): JSX.Element {\n return (\n <div className=\"devic-equalizer\" aria-hidden=\"true\" data-paused={paused}>\n {levels.map((level, i) => (\n <span\n key={i}\n className=\"devic-equalizer-bar\"\n style={{ height: `${Math.max(10, Math.round((paused ? 0 : level) * 100))}%` }}\n />\n ))}\n </div>\n );\n}\n\n// Geometry for the auto-stop ring drawn around the confirm button.\nconst AUTOSTOP_RING_R = 18;\nconst AUTOSTOP_RING_C = 2 * Math.PI * AUTOSTOP_RING_R;\n\n/**\n * Inverted circular progress drawn around the confirm button. Driven by\n * `progress` (1 → 0): a full ring that drains to empty over the countdown.\n */\nfunction AutoStopRing({ progress }: { progress: number }): JSX.Element {\n return (\n <svg className=\"devic-autostop-ring\" viewBox=\"0 0 40 40\" aria-hidden=\"true\">\n <circle\n className=\"devic-autostop-ring-track\"\n cx=\"20\"\n cy=\"20\"\n r={AUTOSTOP_RING_R}\n />\n <circle\n className=\"devic-autostop-ring-progress\"\n cx=\"20\"\n cy=\"20\"\n r={AUTOSTOP_RING_R}\n style={{\n strokeDasharray: AUTOSTOP_RING_C,\n strokeDashoffset: AUTOSTOP_RING_C * (1 - progress),\n }}\n />\n </svg>\n );\n}\n\n/** Formats milliseconds as m:ss. */\nfunction formatDuration(ms: number): string {\n const totalSeconds = Math.floor(ms / 1000);\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n}\n\n/**\n * Attach icon\n */\nfunction AttachIcon(): JSX.Element {\n return (\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48\" />\n </svg>\n );\n}\n\n/**\n * Send icon\n */\nfunction SendIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n >\n <path d=\"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z\" />\n </svg>\n );\n}\n\n/**\n * File icon\n */\nfunction FileIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14,2 14,8 20,8\" />\n </svg>\n );\n}\n\n/**\n * Microphone icon\n */\nfunction MicIcon(): JSX.Element {\n return (\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <line x1=\"12\" y1=\"19\" x2=\"12\" y2=\"23\" />\n <line x1=\"8\" y1=\"23\" x2=\"16\" y2=\"23\" />\n </svg>\n );\n}\n\n/**\n * Pause icon (two bars)\n */\nfunction PauseIcon(): JSX.Element {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <rect x=\"6\" y=\"4\" width=\"4\" height=\"16\" rx=\"1\" />\n <rect x=\"14\" y=\"4\" width=\"4\" height=\"16\" rx=\"1\" />\n </svg>\n );\n}\n\n/**\n * Play icon (triangle)\n */\nfunction PlayIcon(): JSX.Element {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <path d=\"M8 5v14l11-7z\" />\n </svg>\n );\n}\n\n/**\n * Check icon (confirm)\n */\nfunction CheckIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n );\n}\n\n/**\n * Close icon (cancel)\n */\nfunction CloseIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n );\n}\n\n/**\n * Stop icon (square)\n */\nfunction StopIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n >\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\" />\n </svg>\n );\n}\n\n/**\n * Reference icon (corner-down-right arrow)\n */\nfunction ReferenceIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <polyline points=\"15 10 20 15 15 20\" />\n <path d=\"M4 4v7a4 4 0 0 0 4 4h12\" />\n </svg>\n );\n}\n\n/**\n * Waiting icon (clock)\n */\nfunction WaitingIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <polyline points=\"12,6 12,12 16,14\" />\n </svg>\n );\n}\n"],"names":["_jsx","useState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cAAc,EAAC,OAAO,EAAA,QAAA,EAAA,CAEtBR,cAAA,CAAA,UAAA,EAAA,EAAU,MAAM,EAAC,mBAAmB,EAAA,CAAG,EACvCA,cAAA,CAAA,MAAA,EAAA,EAAM,CAAC,EAAC,yBAAyB,EAAA,CAAG,CAAA,EAAA,CAChC;AAEV;AAEA;;AAEG;AACH,SAAS,WAAW,GAAA;IAClB,QACEQ,eAAA,CAAA,KAAA,EAAA,EACE,KAAK,EAAC,IAAI,EACV,MAAM,EAAC,IAAI,EACX,OAAO,EAAC,WAAW,EACnB,IAAI,EAAC,MAAM,EACX,MAAM,EAAC,cAAc,EACrB,WAAW,EAAC,GAAG,EACf,aAAa,EAAC,OAAO,EACrB,cAAc,EAAC,OAAO,EAAA,QAAA,EAAA,CAEtBR,cAAA,CAAA,QAAA,EAAA,EAAQ,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,EAAA,CAAG,EACjCA,cAAA,CAAA,UAAA,EAAA,EAAU,MAAM,EAAC,kBAAkB,EAAA,CAAG,CAAA,EAAA,CAClC;AAEV;;;;"}
|
|
1
|
+
{"version":3,"file":"ChatInput.js","sources":["../../../../../src/components/ChatDrawer/ChatInput.tsx"],"sourcesContent":["import React, { useState, useRef, useCallback, useMemo, useEffect } from 'react';\nimport type { ChatInputProps } from './ChatDrawer.types';\nimport { useSpeechRecording } from '../../hooks/useSpeechRecording';\nimport { DevicApiClient } from '../../api/client';\n\nconst FILE_TYPE_ACCEPT: Record<string, string[]> = {\n images: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],\n documents: [\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'text/plain',\n 'text/csv',\n ],\n audio: ['audio/mpeg', 'audio/wav', 'audio/ogg'],\n video: ['video/mp4', 'video/webm', 'video/ogg'],\n};\n\n// Handoff (hands-free) loop timings.\nconst HANDOFF_PENDING_MS = 1000; // cancellable countdown before auto-send\nconst HANDOFF_INACTIVITY_MS = 6000; // silence (no speech) that ends the loop\n\n/**\n * Chat input component with file upload support\n */\nexport function ChatInput({\n onSend,\n disabled = false,\n placeholder = 'Type a message...',\n enableFileUploads = false,\n allowedFileTypes = { images: true, documents: true },\n maxFileSize = 10 * 1024 * 1024, // 10MB\n enableSpeechToText = false,\n speechLanguage,\n speechTenantId,\n speechAutoStop = true,\n speechAutoStopCountdownMs,\n speechHandoff = false,\n apiKey,\n baseUrl,\n sendButtonContent,\n disabledMessage,\n isProcessing = false,\n onStop,\n stopButtonContent,\n pendingInputWidget,\n onSubmitWidget,\n onCancelWidget,\n references,\n onRemoveReference,\n}: ChatInputProps): JSX.Element {\n // When a widget is pending as 'input', render it in place of the textarea\n if (pendingInputWidget) {\n const WidgetComponent = pendingInputWidget.widget.component;\n return (\n <div className=\"devic-input-area\" data-widget-mode=\"input\">\n <div className=\"devic-input-widget\" data-tool-name={pendingInputWidget.toolName}>\n <WidgetComponent\n toolCall={pendingInputWidget.toolCall}\n params={pendingInputWidget.params}\n submit={(response) => onSubmitWidget?.(pendingInputWidget.toolCall.id, response)}\n cancel={(reason) => onCancelWidget?.(pendingInputWidget.toolCall.id, reason)}\n />\n </div>\n </div>\n );\n }\n const [message, setMessage] = useState('');\n const [files, setFiles] = useState<File[]>([]);\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const fileInputRef = useRef<HTMLInputElement>(null);\n\n // Speech-to-text state\n const [transcriptId, setTranscriptId] = useState<string | undefined>();\n const [isTranscribing, setIsTranscribing] = useState(false);\n const [speechError, setSpeechError] = useState<string | null>(null);\n // Holds the latest confirmRecording so the auto-stop callback (created before\n // confirmRecording is defined) always calls the current closure.\n const confirmRef = useRef<() => void>(() => {});\n const recording = useSpeechRecording({\n bars: 5,\n autoStop: speechAutoStop,\n ...(speechAutoStopCountdownMs != null && {\n autoStopCountdownMs: speechAutoStopCountdownMs,\n }),\n onAutoStop: () => confirmRef.current(),\n });\n\n // --- Handoff (hands-free loop) state ---\n const [handoffActive, setHandoffActive] = useState(false);\n const [pendingSend, setPendingSend] = useState(false);\n const [pendingProgress, setPendingProgress] = useState(1);\n // Ref mirror so async callbacks (rAF, timers, document listeners) read the\n // live value without going stale.\n const handoffActiveRef = useRef(false);\n const pendingRafRef = useRef<number | null>(null);\n const inactivityTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const prevProcessingRef = useRef(isProcessing);\n // Always-fresh send fn so the deferred auto-send uses the latest message.\n const handleSendRef = useRef<() => void>(() => {});\n\n // Client used only for the /whisper transcription call.\n const transcribeClient = useMemo(() => {\n if (!enableSpeechToText || !apiKey) return null;\n return new DevicApiClient({\n apiKey,\n baseUrl: baseUrl || 'https://api.devic.ai',\n });\n }, [enableSpeechToText, apiKey, baseUrl]);\n\n const speechEnabled =\n enableSpeechToText && recording.isSupported && !!transcribeClient;\n const isRecordingActive = recording.isRecording || recording.isPaused;\n\n // Calculate accepted file types\n const acceptedTypes = Object.entries(allowedFileTypes)\n .filter(([, enabled]) => enabled)\n .flatMap(([type]) => FILE_TYPE_ACCEPT[type] || [])\n .join(',');\n\n // Auto-resize textarea\n const handleInput = useCallback(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;\n }\n }, []);\n\n // Handle send\n const handleSend = useCallback(() => {\n const trimmedMessage = message.trim();\n if (!trimmedMessage && files.length === 0) return;\n\n onSend(\n trimmedMessage,\n files.length > 0 ? files : undefined,\n transcriptId ? { transcriptId } : undefined,\n );\n setMessage('');\n setFiles([]);\n setTranscriptId(undefined);\n\n // Reset textarea height\n if (textareaRef.current) {\n textareaRef.current.style.height = 'auto';\n }\n }, [message, files, onSend, transcriptId]);\n // Keep a fresh send fn for the deferred handoff auto-send.\n handleSendRef.current = handleSend;\n\n // --- Speech-to-text handlers ---\n\n const clearPending = useCallback(() => {\n if (pendingRafRef.current !== null) {\n cancelAnimationFrame(pendingRafRef.current);\n pendingRafRef.current = null;\n }\n setPendingSend(false);\n setPendingProgress(1);\n }, []);\n\n // Fully exit the hands-free loop and stop any recording in progress.\n const cancelHandoff = useCallback(() => {\n handoffActiveRef.current = false;\n setHandoffActive(false);\n clearPending();\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n inactivityTimerRef.current = null;\n }\n recording.cancel();\n }, [clearPending, recording]);\n\n const startRecording = useCallback(() => {\n setSpeechError(null);\n if (speechHandoff) {\n handoffActiveRef.current = true;\n setHandoffActive(true);\n }\n void recording.start();\n }, [recording, speechHandoff]);\n\n const cancelRecording = useCallback(() => {\n cancelHandoff();\n }, [cancelHandoff]);\n\n // Stop recording, transcribe the audio and fill the input for review.\n // Returns the trimmed transcription (or null if nothing was transcribed) so\n // the handoff loop can decide whether to auto-send or end.\n const confirmRecording = useCallback(async (): Promise<string | null> => {\n if (!transcribeClient) return null;\n const blob = await recording.stop();\n if (!blob || blob.size === 0) return null;\n\n setIsTranscribing(true);\n setSpeechError(null);\n try {\n const result = await transcribeClient.transcribeAudio(blob, {\n language: speechLanguage,\n tenantId: speechTenantId,\n });\n const text = (result.text || '').trim();\n if (text) {\n setMessage((prev) => (prev ? `${prev} ${text}`.trim() : text));\n setTranscriptId(result.transcriptId);\n }\n // Resize textarea and focus for review/edit.\n requestAnimationFrame(() => {\n const textarea = textareaRef.current;\n if (textarea) {\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`;\n textarea.focus();\n }\n });\n return text;\n } catch (e) {\n setSpeechError(\n `Could not transcribe the audio: ${(e as Error)?.message || 'unknown error'}`,\n );\n return null;\n } finally {\n setIsTranscribing(false);\n }\n }, [transcribeClient, recording, speechLanguage, speechTenantId]);\n\n // Cancellable countdown, then auto-send. Handoff stays active across the send\n // so the loop can continue after the assistant replies.\n const startPendingSend = useCallback(() => {\n setPendingSend(true);\n setPendingProgress(1);\n const startedAt = Date.now();\n const step = () => {\n const elapsed = Date.now() - startedAt;\n setPendingProgress(Math.max(0, 1 - elapsed / HANDOFF_PENDING_MS));\n if (elapsed >= HANDOFF_PENDING_MS) {\n pendingRafRef.current = null;\n setPendingSend(false);\n setPendingProgress(1);\n handleSendRef.current(); // auto-send with the freshest message\n return;\n }\n pendingRafRef.current = requestAnimationFrame(step);\n };\n pendingRafRef.current = requestAnimationFrame(step);\n }, []);\n\n // Drives both the mic auto-stop and the manual confirm button, branching on\n // whether the hands-free loop is active.\n const handleConfirm = useCallback(async () => {\n const text = await confirmRecording();\n if (!handoffActiveRef.current) return; // normal mode: input already filled\n if (!text) {\n // Silent / empty turn → end the hands-free loop.\n cancelHandoff();\n setMessage('');\n setTranscriptId(undefined);\n return;\n }\n startPendingSend();\n }, [confirmRecording, cancelHandoff, startPendingSend]);\n\n // Auto-stop fires handleConfirm with the freshest closure.\n useEffect(() => {\n confirmRef.current = () => void handleConfirm();\n }, [handleConfirm]);\n\n // Any interaction during the pending countdown cancels the auto-send and\n // exits the loop (the user is taking manual control); text stays for editing.\n useEffect(() => {\n if (!pendingSend) return;\n const onInteract = () => {\n clearPending();\n handoffActiveRef.current = false;\n setHandoffActive(false);\n requestAnimationFrame(() => textareaRef.current?.focus());\n };\n document.addEventListener('mousedown', onInteract, true);\n document.addEventListener('keydown', onInteract, true);\n return () => {\n document.removeEventListener('mousedown', onInteract, true);\n document.removeEventListener('keydown', onInteract, true);\n };\n }, [pendingSend, clearPending]);\n\n // When the assistant finishes (isProcessing falls) while the loop is active,\n // re-activate listening for the next turn.\n useEffect(() => {\n const wasProcessing = prevProcessingRef.current;\n prevProcessingRef.current = isProcessing;\n if (\n handoffActive &&\n wasProcessing &&\n !isProcessing &&\n !disabled &&\n !pendingSend &&\n !isTranscribing &&\n !recording.isRecording &&\n !recording.isPaused\n ) {\n void recording.start();\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isProcessing, handoffActive, disabled, pendingSend, isTranscribing]);\n\n // While listening in handoff with no speech yet, end the loop after a silence\n // window (an open mic with nothing said means the user is done).\n useEffect(() => {\n if (!(handoffActive && recording.isRecording && !recording.speechDetected)) {\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n inactivityTimerRef.current = null;\n }\n return;\n }\n inactivityTimerRef.current = setTimeout(() => {\n if (handoffActiveRef.current && !recording.speechDetected) cancelHandoff();\n }, HANDOFF_INACTIVITY_MS);\n return () => {\n if (inactivityTimerRef.current) {\n clearTimeout(inactivityTimerRef.current);\n inactivityTimerRef.current = null;\n }\n };\n }, [handoffActive, recording.isRecording, recording.speechDetected, cancelHandoff]);\n\n // Cleanup deferred work on unmount.\n useEffect(() => {\n return () => {\n if (pendingRafRef.current !== null) cancelAnimationFrame(pendingRafRef.current);\n if (inactivityTimerRef.current) clearTimeout(inactivityTimerRef.current);\n };\n }, []);\n\n // Handle key press\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n // Handle file selection\n const handleFileSelect = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => {\n const selectedFiles = Array.from(e.target.files || []);\n\n // Filter valid files\n const validFiles = selectedFiles.filter((file) => {\n if (file.size > maxFileSize) {\n console.warn(`File ${file.name} exceeds maximum size`);\n return false;\n }\n return true;\n });\n\n setFiles((prev) => [...prev, ...validFiles]);\n\n // Reset input\n if (fileInputRef.current) {\n fileInputRef.current.value = '';\n }\n },\n [maxFileSize]\n );\n\n // Remove file\n const removeFile = useCallback((index: number) => {\n setFiles((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n return (\n <div className=\"devic-input-area\">\n {disabledMessage && disabled && (\n <div className=\"devic-input-disabled-notice\">\n <WaitingIcon />\n {disabledMessage}\n </div>\n )}\n {speechError && (\n <div className=\"devic-speech-error\" role=\"alert\">\n {speechError}\n </div>\n )}\n {handoffActive && (\n <div className=\"devic-handoff-bar\" data-waiting={isProcessing ? 'true' : 'false'}>\n <span className=\"devic-handoff-dot\" aria-hidden=\"true\" />\n <span className=\"devic-handoff-label\">\n {isProcessing ? 'Hands-free · waiting for reply' : 'Hands-free on'}\n </span>\n <button\n type=\"button\"\n className=\"devic-handoff-stop\"\n onClick={cancelHandoff}\n title=\"Stop hands-free\"\n aria-label=\"Stop hands-free\"\n >\n <CloseIcon />\n </button>\n </div>\n )}\n {references && references.length > 0 && (\n <div className=\"devic-reference-chips\">\n {references.map((ref) => (\n <div key={ref.id} className=\"devic-reference-chip\" title={ref.label}>\n <ReferenceIcon />\n <span className=\"devic-reference-chip-label\">\"{ref.label}\"</span>\n <button\n type=\"button\"\n className=\"devic-reference-chip-remove\"\n onClick={() => onRemoveReference?.(ref.id)}\n aria-label=\"Quitar referencia\"\n >\n ×\n </button>\n </div>\n ))}\n </div>\n )}\n {files.length > 0 && (\n <div className=\"devic-file-preview\">\n {files.map((file, idx) => (\n <div key={idx} className=\"devic-file-preview-item\">\n <FileIcon />\n <span>{file.name}</span>\n <button\n className=\"devic-file-remove\"\n onClick={() => removeFile(idx)}\n type=\"button\"\n >\n ×\n </button>\n </div>\n ))}\n </div>\n )}\n\n <div className=\"devic-input-wrapper\">\n {pendingSend ? (\n <div className=\"devic-speech-panel\" data-state=\"pending\">\n <div className=\"devic-handoff-pending\">\n <div className=\"devic-handoff-pending-icon\">\n <SendCountdownRing progress={pendingProgress} />\n <SendIcon />\n </div>\n <div className=\"devic-handoff-pending-text\">\n <span className=\"devic-handoff-pending-title\">\n Sending… interact to cancel\n </span>\n {message.trim() && (\n <span className=\"devic-handoff-pending-preview\">{message.trim()}</span>\n )}\n </div>\n </div>\n </div>\n ) : isTranscribing ? (\n <div className=\"devic-speech-panel\" data-state=\"processing\">\n <span className=\"devic-speech-spinner\" aria-hidden=\"true\" />\n <span className=\"devic-speech-status\">Transcribing…</span>\n </div>\n ) : isRecordingActive ? (\n <div className=\"devic-speech-panel\" data-state=\"recording\">\n <button\n className=\"devic-input-btn devic-speech-cancel\"\n onClick={cancelRecording}\n type=\"button\"\n title=\"Cancel recording\"\n >\n <CloseIcon />\n </button>\n <div className=\"devic-speech-live\">\n <Equalizer levels={recording.levels} paused={recording.isPaused} />\n <span className=\"devic-speech-timer\">\n {formatDuration(recording.durationMs)}\n </span>\n </div>\n <button\n className=\"devic-input-btn\"\n onClick={recording.isPaused ? recording.resume : recording.pause}\n type=\"button\"\n title={recording.isPaused ? 'Resume' : 'Pause'}\n >\n {recording.isPaused ? <PlayIcon /> : <PauseIcon />}\n </button>\n <div\n className=\"devic-speech-confirm-wrap\"\n data-autostop={recording.isAutoStopping ? 'true' : 'false'}\n >\n {recording.isAutoStopping && (\n <AutoStopRing progress={recording.autoStopProgress} />\n )}\n <button\n className=\"devic-input-btn devic-speech-confirm\"\n onClick={() => void handleConfirm()}\n type=\"button\"\n title={\n recording.isAutoStopping\n ? 'Auto-sending… keep talking to cancel'\n : 'Confirm'\n }\n >\n <CheckIcon />\n </button>\n </div>\n </div>\n ) : (\n <>\n {enableFileUploads && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n accept={acceptedTypes}\n multiple\n onChange={handleFileSelect}\n style={{ display: 'none' }}\n />\n <button\n className=\"devic-input-btn\"\n onClick={() => fileInputRef.current?.click()}\n disabled={disabled}\n type=\"button\"\n title=\"Attach file\"\n >\n <AttachIcon />\n </button>\n </>\n )}\n\n {speechEnabled && (\n <button\n className=\"devic-input-btn devic-speech-mic\"\n onClick={startRecording}\n disabled={disabled || isProcessing}\n type=\"button\"\n title=\"Record voice message\"\n >\n <MicIcon />\n </button>\n )}\n\n <textarea\n ref={textareaRef}\n className=\"devic-input\"\n value={message}\n onChange={(e) => {\n const value = e.target.value;\n setMessage(value);\n // If the user clears the field, drop the transcript link so a fresh\n // message isn't wrongly attributed to the previous transcription.\n if (transcriptId && value.trim() === '') setTranscriptId(undefined);\n handleInput();\n }}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n disabled={disabled}\n rows={1}\n />\n\n {isProcessing ? (\n stopButtonContent ? (\n <div className=\"devic-send-btn-wrapper\">\n <div className=\"devic-send-btn-custom\" aria-hidden=\"true\">\n {stopButtonContent}\n </div>\n <button\n className=\"devic-send-btn-overlay\"\n onClick={onStop}\n type=\"button\"\n title=\"Stop\"\n />\n </div>\n ) : (\n <button\n className=\"devic-input-btn devic-stop-btn\"\n onClick={onStop}\n type=\"button\"\n title=\"Stop\"\n >\n <StopIcon />\n </button>\n )\n ) : sendButtonContent ? (\n <div className=\"devic-send-btn-wrapper\">\n <div className=\"devic-send-btn-custom\" aria-hidden=\"true\">\n {sendButtonContent}\n </div>\n <button\n className=\"devic-send-btn-overlay\"\n onClick={handleSend}\n disabled={disabled || (!message.trim() && files.length === 0)}\n type=\"button\"\n title=\"Send message\"\n />\n </div>\n ) : (\n <button\n className=\"devic-input-btn devic-send-btn\"\n onClick={handleSend}\n disabled={disabled || (!message.trim() && files.length === 0)}\n type=\"button\"\n title=\"Send message\"\n >\n <SendIcon />\n </button>\n )}\n </>\n )}\n </div>\n </div>\n );\n}\n\n/**\n * Live equalizer rendered from the recording amplitude levels (0..1 per bar).\n * When paused, bars collapse to a flat baseline.\n */\nfunction Equalizer({\n levels,\n paused,\n}: {\n levels: number[];\n paused: boolean;\n}): JSX.Element {\n return (\n <div className=\"devic-equalizer\" aria-hidden=\"true\" data-paused={paused}>\n {levels.map((level, i) => (\n <span\n key={i}\n className=\"devic-equalizer-bar\"\n style={{ height: `${Math.max(10, Math.round((paused ? 0 : level) * 100))}%` }}\n />\n ))}\n </div>\n );\n}\n\n// Geometry for the auto-stop ring drawn around the confirm button.\nconst AUTOSTOP_RING_R = 18;\nconst AUTOSTOP_RING_C = 2 * Math.PI * AUTOSTOP_RING_R;\n\n/**\n * Inverted circular progress drawn around the confirm button. Driven by\n * `progress` (1 → 0): a full ring that drains to empty over the countdown.\n */\nfunction AutoStopRing({ progress }: { progress: number }): JSX.Element {\n return (\n <svg className=\"devic-autostop-ring\" viewBox=\"0 0 40 40\" aria-hidden=\"true\">\n <circle\n className=\"devic-autostop-ring-track\"\n cx=\"20\"\n cy=\"20\"\n r={AUTOSTOP_RING_R}\n />\n <circle\n className=\"devic-autostop-ring-progress\"\n cx=\"20\"\n cy=\"20\"\n r={AUTOSTOP_RING_R}\n style={{\n strokeDasharray: AUTOSTOP_RING_C,\n strokeDashoffset: AUTOSTOP_RING_C * (1 - progress),\n }}\n />\n </svg>\n );\n}\n\n/**\n * Draining ring around the send icon during the handoff pending countdown.\n * Visually distinct from the auto-stop ring (slate→primary track, larger).\n */\nfunction SendCountdownRing({ progress }: { progress: number }): JSX.Element {\n return (\n <svg className=\"devic-handoff-ring\" viewBox=\"0 0 44 44\" aria-hidden=\"true\">\n <circle className=\"devic-handoff-ring-track\" cx=\"22\" cy=\"22\" r={AUTOSTOP_RING_R} />\n <circle\n className=\"devic-handoff-ring-progress\"\n cx=\"22\"\n cy=\"22\"\n r={AUTOSTOP_RING_R}\n style={{\n strokeDasharray: AUTOSTOP_RING_C,\n strokeDashoffset: AUTOSTOP_RING_C * (1 - progress),\n }}\n />\n </svg>\n );\n}\n\n/** Formats milliseconds as m:ss. */\nfunction formatDuration(ms: number): string {\n const totalSeconds = Math.floor(ms / 1000);\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n return `${minutes}:${seconds.toString().padStart(2, '0')}`;\n}\n\n/**\n * Attach icon\n */\nfunction AttachIcon(): JSX.Element {\n return (\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48\" />\n </svg>\n );\n}\n\n/**\n * Send icon\n */\nfunction SendIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n >\n <path d=\"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z\" />\n </svg>\n );\n}\n\n/**\n * File icon\n */\nfunction FileIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\" />\n <polyline points=\"14,2 14,8 20,8\" />\n </svg>\n );\n}\n\n/**\n * Microphone icon\n */\nfunction MicIcon(): JSX.Element {\n return (\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <path d=\"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <line x1=\"12\" y1=\"19\" x2=\"12\" y2=\"23\" />\n <line x1=\"8\" y1=\"23\" x2=\"16\" y2=\"23\" />\n </svg>\n );\n}\n\n/**\n * Pause icon (two bars)\n */\nfunction PauseIcon(): JSX.Element {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <rect x=\"6\" y=\"4\" width=\"4\" height=\"16\" rx=\"1\" />\n <rect x=\"14\" y=\"4\" width=\"4\" height=\"16\" rx=\"1\" />\n </svg>\n );\n}\n\n/**\n * Play icon (triangle)\n */\nfunction PlayIcon(): JSX.Element {\n return (\n <svg width=\"18\" height=\"18\" viewBox=\"0 0 24 24\" fill=\"currentColor\">\n <path d=\"M8 5v14l11-7z\" />\n </svg>\n );\n}\n\n/**\n * Check icon (confirm)\n */\nfunction CheckIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <polyline points=\"20 6 9 17 4 12\" />\n </svg>\n );\n}\n\n/**\n * Close icon (cancel)\n */\nfunction CloseIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <line x1=\"18\" y1=\"6\" x2=\"6\" y2=\"18\" />\n <line x1=\"6\" y1=\"6\" x2=\"18\" y2=\"18\" />\n </svg>\n );\n}\n\n/**\n * Stop icon (square)\n */\nfunction StopIcon(): JSX.Element {\n return (\n <svg\n width=\"18\"\n height=\"18\"\n viewBox=\"0 0 24 24\"\n fill=\"currentColor\"\n >\n <rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\" />\n </svg>\n );\n}\n\n/**\n * Reference icon (corner-down-right arrow)\n */\nfunction ReferenceIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <polyline points=\"15 10 20 15 15 20\" />\n <path d=\"M4 4v7a4 4 0 0 0 4 4h12\" />\n </svg>\n );\n}\n\n/**\n * Waiting icon (clock)\n */\nfunction WaitingIcon(): JSX.Element {\n return (\n <svg\n width=\"14\"\n height=\"14\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <polyline points=\"12,6 12,12 16,14\" />\n </svg>\n );\n}\n"],"names":["_jsx","useState","useRef","useSpeechRecording","useMemo","DevicApiClient","useCallback","useEffect","_jsxs","_Fragment"],"mappings":";;;;;;;AAKA,MAAM,gBAAgB,GAA6B;IACjD,MAAM,EAAE,CAAC,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,CAAC;AAC9D,IAAA,SAAS,EAAE;QACT,iBAAiB;QACjB,oBAAoB;QACpB,yEAAyE;QACzE,YAAY;QACZ,UAAU;AACX,KAAA;AACD,IAAA,KAAK,EAAE,CAAC,YAAY,EAAE,WAAW,EAAE,WAAW,CAAC;AAC/C,IAAA,KAAK,EAAE,CAAC,WAAW,EAAE,YAAY,EAAE,WAAW,CAAC;CAChD;AAED;AACA,MAAM,kBAAkB,GAAG,IAAI,CAAC;AAChC,MAAM,qBAAqB,GAAG,IAAI,CAAC;AAEnC;;AAEG;SACa,SAAS,CAAC,EACxB,MAAM,EACN,QAAQ,GAAG,KAAK,EAChB,WAAW,GAAG,mBAAmB,EACjC,iBAAiB,GAAG,KAAK,EACzB,gBAAgB,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EACpD,WAAW,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI;AAC9B,kBAAkB,GAAG,KAAK,EAC1B,cAAc,EACd,cAAc,EACd,cAAc,GAAG,IAAI,EACrB,yBAAyB,EACzB,aAAa,GAAG,KAAK,EACrB,MAAM,EACN,OAAO,EACP,iBAAiB,EACjB,eAAe,EACf,YAAY,GAAG,KAAK,EACpB,MAAM,EACN,iBAAiB,EACjB,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,UAAU,EACV,iBAAiB,GACF,EAAA;;IAEf,IAAI,kBAAkB,EAAE;AACtB,QAAA,MAAM,eAAe,GAAG,kBAAkB,CAAC,MAAM,CAAC,SAAS;AAC3D,QAAA,QACEA,cAAA,CAAA,KAAA,EAAA,EAAK,SAAS,EAAC,kBAAkB,EAAA,kBAAA,EAAkB,OAAO,EAAA,QAAA,EACxD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K,EAAC,IAAI,EACV,MAAM,EAAC,IAAI,EACX,OAAO,EAAC,WAAW,EACnB,IAAI,EAAC,MAAM,EACX,MAAM,EAAC,cAAc,EACrB,WAAW,EAAC,GAAG,EACf,aAAa,EAAC,OAAO,EACrB,cAAc,EAAC,OAAO,EAAA,QAAA,EAAA,CAEtBR,cAAA,CAAA,QAAA,EAAA,EAAQ,EAAE,EAAC,IAAI,EAAC,EAAE,EAAC,IAAI,EAAC,CAAC,EAAC,IAAI,EAAA,CAAG,EACjCA,cAAA,CAAA,UAAA,EAAA,EAAU,MAAM,EAAC,kBAAkB,EAAA,CAAG,CAAA,EAAA,CAClC;AAEV;;;;"}
|
|
@@ -38,6 +38,7 @@ function useSpeechRecording(options = {}) {
|
|
|
38
38
|
const [error, setError] = React.useState(null);
|
|
39
39
|
const [isAutoStopping, setIsAutoStopping] = React.useState(false);
|
|
40
40
|
const [autoStopProgress, setAutoStopProgress] = React.useState(1);
|
|
41
|
+
const [speechDetected, setSpeechDetected] = React.useState(false);
|
|
41
42
|
const mediaRecorderRef = React.useRef(null);
|
|
42
43
|
const streamRef = React.useRef(null);
|
|
43
44
|
const chunksRef = React.useRef([]);
|
|
@@ -80,6 +81,7 @@ function useSpeechRecording(options = {}) {
|
|
|
80
81
|
if (!keepSpeech) {
|
|
81
82
|
hasSpeechRef.current = false;
|
|
82
83
|
loudestRef.current = 0;
|
|
84
|
+
setSpeechDetected(false);
|
|
83
85
|
}
|
|
84
86
|
silenceStartRef.current = null;
|
|
85
87
|
autoStopStartRef.current = null;
|
|
@@ -100,6 +102,7 @@ function useSpeechRecording(options = {}) {
|
|
|
100
102
|
if (peak >= cfg.autoStopSpeechLevel) {
|
|
101
103
|
hasSpeechRef.current = true;
|
|
102
104
|
loudestRef.current = peak;
|
|
105
|
+
setSpeechDetected(true);
|
|
103
106
|
}
|
|
104
107
|
return;
|
|
105
108
|
}
|
|
@@ -333,6 +336,7 @@ function useSpeechRecording(options = {}) {
|
|
|
333
336
|
error,
|
|
334
337
|
isAutoStopping,
|
|
335
338
|
autoStopProgress,
|
|
339
|
+
speechDetected,
|
|
336
340
|
start,
|
|
337
341
|
pause,
|
|
338
342
|
resume,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSpeechRecording.js","sources":["../../../../src/hooks/useSpeechRecording.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\n\n/**\n * Recording lifecycle state.\n * - `idle`: not recording\n * - `recording`: actively capturing audio\n * - `paused`: capture paused, can be resumed\n */\nexport type SpeechRecordingStatus = 'idle' | 'recording' | 'paused';\n\nexport interface UseSpeechRecordingOptions {\n /** Number of equalizer bars to expose in `levels`. @default 5 */\n bars?: number;\n /** Preferred MediaRecorder mime type. Falls back to a supported one. */\n mimeType?: string;\n /**\n * Auto-stop the recording after a short silence, but only once speech has\n * actually been detected. When it triggers, the countdown runs and then\n * `onAutoStop` is fired. Disable to require a manual confirm. @default true\n */\n autoStop?: boolean;\n /**\n * Continuous silence (ms) that must elapse — after speech was detected —\n * before the auto-stop countdown begins. @default 1000\n */\n autoStopSilenceMs?: number;\n /** Duration (ms) of the auto-stop countdown shown before firing. @default 1000 */\n autoStopCountdownMs?: number;\n /**\n * Silence is **adaptive**: the threshold is this fraction of the loudest\n * speech observed in the recording (e.g. 0.1 = 10% of peak voice). This makes\n * it robust to ambient noise — a quiet room and a loud one calibrate\n * differently. @default 0.1\n */\n autoStopSilenceRatio?: number;\n /**\n * Absolute floor (0..1) for the adaptive silence threshold, so it never drops\n * so low that background hiss reads as \"sound\". @default 0.02\n */\n autoStopSilenceLevel?: number;\n /**\n * Absolute floor (0..1) a peak must clear to first count as speech (arms the\n * detector / calibrates the reference loudness). @default 0.12\n */\n autoStopSpeechLevel?: number;\n /**\n * Fired when the silence countdown completes. The consumer decides what\n * \"stop\" means (e.g. confirm + transcribe). Read fresh on every frame, so it\n * does not need to be memoized.\n */\n onAutoStop?: () => void;\n}\n\nexport interface UseSpeechRecordingResult {\n status: SpeechRecordingStatus;\n isRecording: boolean;\n isPaused: boolean;\n /** Whether the browser supports audio recording. */\n isSupported: boolean;\n /** Normalized amplitude per bar (0..1), updated in real time for the equalizer. */\n levels: number[];\n /** Elapsed recording time in milliseconds (excludes paused time). */\n durationMs: number;\n /** Last error message, if any (e.g. permission denied). */\n error: string | null;\n /** True while the silence-triggered auto-stop countdown is running. */\n isAutoStopping: boolean;\n /** Auto-stop countdown progress, 1 (full) → 0 (empty), for an inverted ring. */\n autoStopProgress: number;\n /** Request mic access and start recording. */\n start: () => Promise<void>;\n /** Pause an active recording. */\n pause: () => void;\n /** Resume a paused recording. */\n resume: () => void;\n /** Stop and return the recorded audio as a Blob (null if nothing captured). */\n stop: () => Promise<Blob | null>;\n /** Stop and discard the recording without producing a Blob. */\n cancel: () => void;\n}\n\nconst PREFERRED_MIME_TYPES = [\n 'audio/webm;codecs=opus',\n 'audio/webm',\n 'audio/ogg;codecs=opus',\n 'audio/mp4',\n];\n\nfunction pickMimeType(preferred?: string): string | undefined {\n if (typeof MediaRecorder === 'undefined') return undefined;\n const candidates = preferred\n ? [preferred, ...PREFERRED_MIME_TYPES]\n : PREFERRED_MIME_TYPES;\n for (const type of candidates) {\n if (MediaRecorder.isTypeSupported(type)) return type;\n }\n return undefined;\n}\n\n/**\n * Encapsulates microphone capture via MediaRecorder plus a Web Audio analyser\n * that exposes live amplitude levels for an equalizer-style animation.\n *\n * The hook owns all teardown: stopping tracks, closing the AudioContext and\n * cancelling the animation frame on stop/cancel/unmount.\n */\nexport function useSpeechRecording(\n options: UseSpeechRecordingOptions = {},\n): UseSpeechRecordingResult {\n const {\n bars = 5,\n mimeType,\n autoStop = true,\n autoStopSilenceMs = 1000,\n autoStopCountdownMs = 1000,\n autoStopSilenceRatio = 0.1,\n autoStopSilenceLevel = 0.02,\n autoStopSpeechLevel = 0.12,\n onAutoStop,\n } = options;\n\n const isSupported =\n typeof navigator !== 'undefined' &&\n !!navigator.mediaDevices?.getUserMedia &&\n typeof MediaRecorder !== 'undefined';\n\n const [status, setStatus] = useState<SpeechRecordingStatus>('idle');\n const [levels, setLevels] = useState<number[]>(() => new Array(bars).fill(0));\n const [durationMs, setDurationMs] = useState(0);\n const [error, setError] = useState<string | null>(null);\n const [isAutoStopping, setIsAutoStopping] = useState(false);\n const [autoStopProgress, setAutoStopProgress] = useState(1);\n\n const mediaRecorderRef = useRef<MediaRecorder | null>(null);\n const streamRef = useRef<MediaStream | null>(null);\n const chunksRef = useRef<Blob[]>([]);\n const audioContextRef = useRef<AudioContext | null>(null);\n const analyserRef = useRef<AnalyserNode | null>(null);\n const rafRef = useRef<number | null>(null);\n const startedAtRef = useRef<number>(0);\n const accumulatedRef = useRef<number>(0);\n const stopResolveRef = useRef<((blob: Blob | null) => void) | null>(null);\n const discardRef = useRef<boolean>(false);\n\n // --- Auto-stop (silence detection) state, all kept in refs so the rAF loop\n // reads it without forcing `tick` to re-subscribe. ---\n const hasSpeechRef = useRef(false); // user has spoken at least once\n const loudestRef = useRef(0); // loudest peak seen (reference for adaptive silence)\n const silenceStartRef = useRef<number | null>(null); // when current silence began\n const autoStopStartRef = useRef<number | null>(null); // when the countdown started\n const autoStopFiredRef = useRef(false); // guard against re-firing before stop\n // Latest-config ref so the loop always sees fresh thresholds and callback.\n const autoStopCfgRef = useRef({\n autoStop,\n autoStopSilenceMs,\n autoStopCountdownMs,\n autoStopSilenceRatio,\n autoStopSilenceLevel,\n autoStopSpeechLevel,\n onAutoStop,\n });\n autoStopCfgRef.current = {\n autoStop,\n autoStopSilenceMs,\n autoStopCountdownMs,\n autoStopSilenceRatio,\n autoStopSilenceLevel,\n autoStopSpeechLevel,\n onAutoStop,\n };\n\n // Reset all auto-stop tracking. `keepSpeech` preserves the \"user has spoken\"\n // flag across a pause/resume so it doesn't re-arm from scratch.\n const resetAutoStop = useCallback((keepSpeech = false) => {\n if (!keepSpeech) {\n hasSpeechRef.current = false;\n loudestRef.current = 0;\n }\n silenceStartRef.current = null;\n autoStopStartRef.current = null;\n autoStopFiredRef.current = false;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n }, []);\n\n // Evaluate the current peak amplitude against the silence/speech thresholds\n // and drive the auto-stop countdown. Called once per animation frame.\n const evaluateAutoStop = useCallback((peak: number) => {\n const cfg = autoStopCfgRef.current;\n if (!cfg.autoStop || autoStopFiredRef.current) return;\n const now = Date.now();\n\n // 1) Arm only once a real voice peak (absolute floor) has been heard. This\n // also seeds the reference loudness so ambient noise alone can't arm it.\n if (!hasSpeechRef.current) {\n if (peak >= cfg.autoStopSpeechLevel) {\n hasSpeechRef.current = true;\n loudestRef.current = peak;\n }\n return;\n }\n\n // 2) Track the loudest voice so the silence threshold scales with how loud\n // the user actually speaks (robust to ambient noise).\n if (peak > loudestRef.current) loudestRef.current = peak;\n\n // 3) Adaptive thresholds: silence = ratio of the loudest voice (with an\n // absolute floor); activity sits above it for hysteresis, so background\n // noise between the two doesn't keep cancelling the countdown.\n const silenceThreshold = Math.max(\n cfg.autoStopSilenceLevel,\n cfg.autoStopSilenceRatio * loudestRef.current,\n );\n const activityThreshold = silenceThreshold * 1.8;\n\n if (peak >= activityThreshold) {\n // Talking again: reset silence and cancel any pending countdown.\n silenceStartRef.current = null;\n if (autoStopStartRef.current !== null) {\n autoStopStartRef.current = null;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n }\n return;\n }\n\n if (peak <= silenceThreshold) {\n if (silenceStartRef.current === null) silenceStartRef.current = now;\n\n if (autoStopStartRef.current === null) {\n // Waiting out the silence window before the countdown begins.\n if (now - silenceStartRef.current >= cfg.autoStopSilenceMs) {\n autoStopStartRef.current = now;\n setIsAutoStopping(true);\n setAutoStopProgress(1);\n }\n } else {\n // Countdown running: drain the ring 1 → 0, then fire.\n const elapsed = now - autoStopStartRef.current;\n const progress = Math.max(0, 1 - elapsed / cfg.autoStopCountdownMs);\n setAutoStopProgress(progress);\n if (elapsed >= cfg.autoStopCountdownMs) {\n autoStopFiredRef.current = true;\n autoStopStartRef.current = null;\n silenceStartRef.current = null;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n cfg.onAutoStop?.();\n }\n }\n }\n // Hysteresis deadzone (silence < peak < activity): keep timers running.\n }, []);\n\n const cleanupAudioGraph = useCallback(() => {\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n if (audioContextRef.current) {\n audioContextRef.current.close().catch(() => undefined);\n audioContextRef.current = null;\n }\n analyserRef.current = null;\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((t) => t.stop());\n streamRef.current = null;\n }\n }, []);\n\n // Drives both the equalizer levels and the duration counter.\n const tick = useCallback(() => {\n const analyser = analyserRef.current;\n if (analyser) {\n const data = new Uint8Array(analyser.frequencyBinCount);\n analyser.getByteFrequencyData(data);\n const bucketSize = Math.floor(data.length / bars) || 1;\n const next: number[] = [];\n let peak = 0;\n for (let i = 0; i < bars; i++) {\n let sum = 0;\n for (let j = 0; j < bucketSize; j++) {\n sum += data[i * bucketSize + j] ?? 0;\n }\n // Normalize 0..255 -> 0..1 with a small floor so bars stay visible.\n const level = Math.min(1, sum / bucketSize / 255);\n next.push(level);\n if (level > peak) peak = level;\n }\n setLevels(next);\n evaluateAutoStop(peak);\n }\n setDurationMs(accumulatedRef.current + (Date.now() - startedAtRef.current));\n rafRef.current = requestAnimationFrame(tick);\n }, [bars, evaluateAutoStop]);\n\n const start = useCallback(async () => {\n if (!isSupported) {\n setError('Audio recording is not supported in this browser');\n return;\n }\n if (mediaRecorderRef.current) return;\n\n setError(null);\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n streamRef.current = stream;\n\n const selectedType = pickMimeType(mimeType);\n const recorder = selectedType\n ? new MediaRecorder(stream, { mimeType: selectedType })\n : new MediaRecorder(stream);\n mediaRecorderRef.current = recorder;\n chunksRef.current = [];\n discardRef.current = false;\n resetAutoStop();\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size > 0) chunksRef.current.push(e.data);\n };\n recorder.onstop = () => {\n const type = recorder.mimeType || selectedType || 'audio/webm';\n const blob = discardRef.current\n ? null\n : new Blob(chunksRef.current, { type });\n chunksRef.current = [];\n cleanupAudioGraph();\n mediaRecorderRef.current = null;\n setStatus('idle');\n setLevels(new Array(bars).fill(0));\n setDurationMs(0);\n accumulatedRef.current = 0;\n resetAutoStop();\n const resolve = stopResolveRef.current;\n stopResolveRef.current = null;\n resolve?.(blob);\n };\n\n // Web Audio analyser for the equalizer animation.\n const AudioCtx =\n window.AudioContext ||\n (window as unknown as { webkitAudioContext: typeof AudioContext })\n .webkitAudioContext;\n const audioContext = new AudioCtx();\n const source = audioContext.createMediaStreamSource(stream);\n const analyser = audioContext.createAnalyser();\n analyser.fftSize = 64;\n source.connect(analyser);\n audioContextRef.current = audioContext;\n analyserRef.current = analyser;\n\n accumulatedRef.current = 0;\n startedAtRef.current = Date.now();\n recorder.start(100);\n setStatus('recording');\n rafRef.current = requestAnimationFrame(tick);\n } catch (e) {\n cleanupAudioGraph();\n mediaRecorderRef.current = null;\n const message =\n (e as Error)?.name === 'NotAllowedError'\n ? 'Microphone permission denied'\n : `Could not start recording: ${(e as Error)?.message || 'unknown error'}`;\n setError(message);\n setStatus('idle');\n }\n }, [isSupported, mimeType, bars, tick, cleanupAudioGraph, resetAutoStop]);\n\n const pause = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state === 'recording') {\n recorder.pause();\n accumulatedRef.current += Date.now() - startedAtRef.current;\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n setLevels(new Array(bars).fill(0));\n // Drop any in-flight silence/countdown but remember that speech happened.\n resetAutoStop(true);\n setStatus('paused');\n }\n }, [bars, resetAutoStop]);\n\n const resume = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state === 'paused') {\n recorder.resume();\n startedAtRef.current = Date.now();\n // Fresh silence timing on resume so it doesn't fire immediately.\n resetAutoStop(true);\n rafRef.current = requestAnimationFrame(tick);\n setStatus('recording');\n }\n }, [tick, resetAutoStop]);\n\n const stop = useCallback((): Promise<Blob | null> => {\n const recorder = mediaRecorderRef.current;\n if (!recorder) return Promise.resolve(null);\n discardRef.current = false;\n return new Promise<Blob | null>((resolve) => {\n stopResolveRef.current = resolve;\n recorder.stop();\n });\n }, []);\n\n const cancel = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (!recorder) {\n cleanupAudioGraph();\n setStatus('idle');\n setLevels(new Array(bars).fill(0));\n setDurationMs(0);\n resetAutoStop();\n return;\n }\n discardRef.current = true;\n recorder.stop();\n }, [bars, cleanupAudioGraph, resetAutoStop]);\n\n // Teardown on unmount.\n useEffect(() => {\n return () => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state !== 'inactive') {\n discardRef.current = true;\n try {\n recorder.stop();\n } catch {\n // ignore\n }\n }\n cleanupAudioGraph();\n };\n }, [cleanupAudioGraph]);\n\n return {\n status,\n isRecording: status === 'recording',\n isPaused: status === 'paused',\n isSupported,\n levels,\n durationMs,\n error,\n isAutoStopping,\n autoStopProgress,\n start,\n pause,\n resume,\n stop,\n cancel,\n };\n}\n"],"names":["useState","useRef","useCallback","useEffect"],"mappings":";;;;AAiFA,MAAM,oBAAoB,GAAG;IAC3B,wBAAwB;IACxB,YAAY;IACZ,uBAAuB;IACvB,WAAW;CACZ;AAED,SAAS,YAAY,CAAC,SAAkB,EAAA;IACtC,IAAI,OAAO,aAAa,KAAK,WAAW;AAAE,QAAA,OAAO,SAAS;IAC1D,MAAM,UAAU,GAAG;AACjB,UAAE,CAAC,SAAS,EAAE,GAAG,oBAAoB;UACnC,oBAAoB;AACxB,IAAA,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE;AAC7B,QAAA,IAAI,aAAa,CAAC,eAAe,CAAC,IAAI,CAAC;AAAE,YAAA,OAAO,IAAI;IACtD;AACA,IAAA,OAAO,SAAS;AAClB;AAEA;;;;;;AAMG;AACG,SAAU,kBAAkB,CAChC,OAAA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AAiB,EAAE,aAAa,CAAC,CAAC;;IAG5CC,eAAS,CAAC,MAAK;AACb,QAAA,OAAO,MAAK;AACV,YAAA,MAAM,QAAQ,GAAG,gBAAgB,CAAC,OAAO;YACzC,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK,KAAK,UAAU,EAAE;AAC7C,gBAAA,UAAU,CAAC,OAAO,GAAG,IAAI;AACzB,gBAAA,IAAI;oBACF,QAAQ,CAAC,IAAI,EAAE;gBACjB;AAAE,gBAAA,MAAM;;gBAER;YACF;AACA,YAAA,iBAAiB,EAAE;AACrB,QAAA,CAAC;AACH,IAAA,CAAC,EAAE,CAAC,iBAAiB,CAAC,CAAC;IAEvB,OAAO;QACL,MAAM;QACN,WAAW,EAAE,MAAM,KAAK,WAAW;QACnC,QAAQ,EAAE,MAAM,KAAK,QAAQ;QAC7B,WAAW;QACX,MAAM;QACN,UAAU;QACV,KAAK;QACL,cAAc;QACd,gBAAgB;QAChB,KAAK;QACL,KAAK;QACL,MAAM;QACN,IAAI;QACJ,MAAM;KACP;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"useSpeechRecording.js","sources":["../../../../src/hooks/useSpeechRecording.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react';\n\n/**\n * Recording lifecycle state.\n * - `idle`: not recording\n * - `recording`: actively capturing audio\n * - `paused`: capture paused, can be resumed\n */\nexport type SpeechRecordingStatus = 'idle' | 'recording' | 'paused';\n\nexport interface UseSpeechRecordingOptions {\n /** Number of equalizer bars to expose in `levels`. @default 5 */\n bars?: number;\n /** Preferred MediaRecorder mime type. Falls back to a supported one. */\n mimeType?: string;\n /**\n * Auto-stop the recording after a short silence, but only once speech has\n * actually been detected. When it triggers, the countdown runs and then\n * `onAutoStop` is fired. Disable to require a manual confirm. @default true\n */\n autoStop?: boolean;\n /**\n * Continuous silence (ms) that must elapse — after speech was detected —\n * before the auto-stop countdown begins. @default 1000\n */\n autoStopSilenceMs?: number;\n /** Duration (ms) of the auto-stop countdown shown before firing. @default 1000 */\n autoStopCountdownMs?: number;\n /**\n * Silence is **adaptive**: the threshold is this fraction of the loudest\n * speech observed in the recording (e.g. 0.1 = 10% of peak voice). This makes\n * it robust to ambient noise — a quiet room and a loud one calibrate\n * differently. @default 0.1\n */\n autoStopSilenceRatio?: number;\n /**\n * Absolute floor (0..1) for the adaptive silence threshold, so it never drops\n * so low that background hiss reads as \"sound\". @default 0.02\n */\n autoStopSilenceLevel?: number;\n /**\n * Absolute floor (0..1) a peak must clear to first count as speech (arms the\n * detector / calibrates the reference loudness). @default 0.12\n */\n autoStopSpeechLevel?: number;\n /**\n * Fired when the silence countdown completes. The consumer decides what\n * \"stop\" means (e.g. confirm + transcribe). Read fresh on every frame, so it\n * does not need to be memoized.\n */\n onAutoStop?: () => void;\n}\n\nexport interface UseSpeechRecordingResult {\n status: SpeechRecordingStatus;\n isRecording: boolean;\n isPaused: boolean;\n /** Whether the browser supports audio recording. */\n isSupported: boolean;\n /** Normalized amplitude per bar (0..1), updated in real time for the equalizer. */\n levels: number[];\n /** Elapsed recording time in milliseconds (excludes paused time). */\n durationMs: number;\n /** Last error message, if any (e.g. permission denied). */\n error: string | null;\n /** True while the silence-triggered auto-stop countdown is running. */\n isAutoStopping: boolean;\n /** Auto-stop countdown progress, 1 (full) → 0 (empty), for an inverted ring. */\n autoStopProgress: number;\n /** True once a real voice peak was detected in the current recording. */\n speechDetected: boolean;\n /** Request mic access and start recording. */\n start: () => Promise<void>;\n /** Pause an active recording. */\n pause: () => void;\n /** Resume a paused recording. */\n resume: () => void;\n /** Stop and return the recorded audio as a Blob (null if nothing captured). */\n stop: () => Promise<Blob | null>;\n /** Stop and discard the recording without producing a Blob. */\n cancel: () => void;\n}\n\nconst PREFERRED_MIME_TYPES = [\n 'audio/webm;codecs=opus',\n 'audio/webm',\n 'audio/ogg;codecs=opus',\n 'audio/mp4',\n];\n\nfunction pickMimeType(preferred?: string): string | undefined {\n if (typeof MediaRecorder === 'undefined') return undefined;\n const candidates = preferred\n ? [preferred, ...PREFERRED_MIME_TYPES]\n : PREFERRED_MIME_TYPES;\n for (const type of candidates) {\n if (MediaRecorder.isTypeSupported(type)) return type;\n }\n return undefined;\n}\n\n/**\n * Encapsulates microphone capture via MediaRecorder plus a Web Audio analyser\n * that exposes live amplitude levels for an equalizer-style animation.\n *\n * The hook owns all teardown: stopping tracks, closing the AudioContext and\n * cancelling the animation frame on stop/cancel/unmount.\n */\nexport function useSpeechRecording(\n options: UseSpeechRecordingOptions = {},\n): UseSpeechRecordingResult {\n const {\n bars = 5,\n mimeType,\n autoStop = true,\n autoStopSilenceMs = 1000,\n autoStopCountdownMs = 1000,\n autoStopSilenceRatio = 0.1,\n autoStopSilenceLevel = 0.02,\n autoStopSpeechLevel = 0.12,\n onAutoStop,\n } = options;\n\n const isSupported =\n typeof navigator !== 'undefined' &&\n !!navigator.mediaDevices?.getUserMedia &&\n typeof MediaRecorder !== 'undefined';\n\n const [status, setStatus] = useState<SpeechRecordingStatus>('idle');\n const [levels, setLevels] = useState<number[]>(() => new Array(bars).fill(0));\n const [durationMs, setDurationMs] = useState(0);\n const [error, setError] = useState<string | null>(null);\n const [isAutoStopping, setIsAutoStopping] = useState(false);\n const [autoStopProgress, setAutoStopProgress] = useState(1);\n const [speechDetected, setSpeechDetected] = useState(false);\n\n const mediaRecorderRef = useRef<MediaRecorder | null>(null);\n const streamRef = useRef<MediaStream | null>(null);\n const chunksRef = useRef<Blob[]>([]);\n const audioContextRef = useRef<AudioContext | null>(null);\n const analyserRef = useRef<AnalyserNode | null>(null);\n const rafRef = useRef<number | null>(null);\n const startedAtRef = useRef<number>(0);\n const accumulatedRef = useRef<number>(0);\n const stopResolveRef = useRef<((blob: Blob | null) => void) | null>(null);\n const discardRef = useRef<boolean>(false);\n\n // --- Auto-stop (silence detection) state, all kept in refs so the rAF loop\n // reads it without forcing `tick` to re-subscribe. ---\n const hasSpeechRef = useRef(false); // user has spoken at least once\n const loudestRef = useRef(0); // loudest peak seen (reference for adaptive silence)\n const silenceStartRef = useRef<number | null>(null); // when current silence began\n const autoStopStartRef = useRef<number | null>(null); // when the countdown started\n const autoStopFiredRef = useRef(false); // guard against re-firing before stop\n // Latest-config ref so the loop always sees fresh thresholds and callback.\n const autoStopCfgRef = useRef({\n autoStop,\n autoStopSilenceMs,\n autoStopCountdownMs,\n autoStopSilenceRatio,\n autoStopSilenceLevel,\n autoStopSpeechLevel,\n onAutoStop,\n });\n autoStopCfgRef.current = {\n autoStop,\n autoStopSilenceMs,\n autoStopCountdownMs,\n autoStopSilenceRatio,\n autoStopSilenceLevel,\n autoStopSpeechLevel,\n onAutoStop,\n };\n\n // Reset all auto-stop tracking. `keepSpeech` preserves the \"user has spoken\"\n // flag across a pause/resume so it doesn't re-arm from scratch.\n const resetAutoStop = useCallback((keepSpeech = false) => {\n if (!keepSpeech) {\n hasSpeechRef.current = false;\n loudestRef.current = 0;\n setSpeechDetected(false);\n }\n silenceStartRef.current = null;\n autoStopStartRef.current = null;\n autoStopFiredRef.current = false;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n }, []);\n\n // Evaluate the current peak amplitude against the silence/speech thresholds\n // and drive the auto-stop countdown. Called once per animation frame.\n const evaluateAutoStop = useCallback((peak: number) => {\n const cfg = autoStopCfgRef.current;\n if (!cfg.autoStop || autoStopFiredRef.current) return;\n const now = Date.now();\n\n // 1) Arm only once a real voice peak (absolute floor) has been heard. This\n // also seeds the reference loudness so ambient noise alone can't arm it.\n if (!hasSpeechRef.current) {\n if (peak >= cfg.autoStopSpeechLevel) {\n hasSpeechRef.current = true;\n loudestRef.current = peak;\n setSpeechDetected(true);\n }\n return;\n }\n\n // 2) Track the loudest voice so the silence threshold scales with how loud\n // the user actually speaks (robust to ambient noise).\n if (peak > loudestRef.current) loudestRef.current = peak;\n\n // 3) Adaptive thresholds: silence = ratio of the loudest voice (with an\n // absolute floor); activity sits above it for hysteresis, so background\n // noise between the two doesn't keep cancelling the countdown.\n const silenceThreshold = Math.max(\n cfg.autoStopSilenceLevel,\n cfg.autoStopSilenceRatio * loudestRef.current,\n );\n const activityThreshold = silenceThreshold * 1.8;\n\n if (peak >= activityThreshold) {\n // Talking again: reset silence and cancel any pending countdown.\n silenceStartRef.current = null;\n if (autoStopStartRef.current !== null) {\n autoStopStartRef.current = null;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n }\n return;\n }\n\n if (peak <= silenceThreshold) {\n if (silenceStartRef.current === null) silenceStartRef.current = now;\n\n if (autoStopStartRef.current === null) {\n // Waiting out the silence window before the countdown begins.\n if (now - silenceStartRef.current >= cfg.autoStopSilenceMs) {\n autoStopStartRef.current = now;\n setIsAutoStopping(true);\n setAutoStopProgress(1);\n }\n } else {\n // Countdown running: drain the ring 1 → 0, then fire.\n const elapsed = now - autoStopStartRef.current;\n const progress = Math.max(0, 1 - elapsed / cfg.autoStopCountdownMs);\n setAutoStopProgress(progress);\n if (elapsed >= cfg.autoStopCountdownMs) {\n autoStopFiredRef.current = true;\n autoStopStartRef.current = null;\n silenceStartRef.current = null;\n setIsAutoStopping(false);\n setAutoStopProgress(1);\n cfg.onAutoStop?.();\n }\n }\n }\n // Hysteresis deadzone (silence < peak < activity): keep timers running.\n }, []);\n\n const cleanupAudioGraph = useCallback(() => {\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n if (audioContextRef.current) {\n audioContextRef.current.close().catch(() => undefined);\n audioContextRef.current = null;\n }\n analyserRef.current = null;\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((t) => t.stop());\n streamRef.current = null;\n }\n }, []);\n\n // Drives both the equalizer levels and the duration counter.\n const tick = useCallback(() => {\n const analyser = analyserRef.current;\n if (analyser) {\n const data = new Uint8Array(analyser.frequencyBinCount);\n analyser.getByteFrequencyData(data);\n const bucketSize = Math.floor(data.length / bars) || 1;\n const next: number[] = [];\n let peak = 0;\n for (let i = 0; i < bars; i++) {\n let sum = 0;\n for (let j = 0; j < bucketSize; j++) {\n sum += data[i * bucketSize + j] ?? 0;\n }\n // Normalize 0..255 -> 0..1 with a small floor so bars stay visible.\n const level = Math.min(1, sum / bucketSize / 255);\n next.push(level);\n if (level > peak) peak = level;\n }\n setLevels(next);\n evaluateAutoStop(peak);\n }\n setDurationMs(accumulatedRef.current + (Date.now() - startedAtRef.current));\n rafRef.current = requestAnimationFrame(tick);\n }, [bars, evaluateAutoStop]);\n\n const start = useCallback(async () => {\n if (!isSupported) {\n setError('Audio recording is not supported in this browser');\n return;\n }\n if (mediaRecorderRef.current) return;\n\n setError(null);\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n streamRef.current = stream;\n\n const selectedType = pickMimeType(mimeType);\n const recorder = selectedType\n ? new MediaRecorder(stream, { mimeType: selectedType })\n : new MediaRecorder(stream);\n mediaRecorderRef.current = recorder;\n chunksRef.current = [];\n discardRef.current = false;\n resetAutoStop();\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data && e.data.size > 0) chunksRef.current.push(e.data);\n };\n recorder.onstop = () => {\n const type = recorder.mimeType || selectedType || 'audio/webm';\n const blob = discardRef.current\n ? null\n : new Blob(chunksRef.current, { type });\n chunksRef.current = [];\n cleanupAudioGraph();\n mediaRecorderRef.current = null;\n setStatus('idle');\n setLevels(new Array(bars).fill(0));\n setDurationMs(0);\n accumulatedRef.current = 0;\n resetAutoStop();\n const resolve = stopResolveRef.current;\n stopResolveRef.current = null;\n resolve?.(blob);\n };\n\n // Web Audio analyser for the equalizer animation.\n const AudioCtx =\n window.AudioContext ||\n (window as unknown as { webkitAudioContext: typeof AudioContext })\n .webkitAudioContext;\n const audioContext = new AudioCtx();\n const source = audioContext.createMediaStreamSource(stream);\n const analyser = audioContext.createAnalyser();\n analyser.fftSize = 64;\n source.connect(analyser);\n audioContextRef.current = audioContext;\n analyserRef.current = analyser;\n\n accumulatedRef.current = 0;\n startedAtRef.current = Date.now();\n recorder.start(100);\n setStatus('recording');\n rafRef.current = requestAnimationFrame(tick);\n } catch (e) {\n cleanupAudioGraph();\n mediaRecorderRef.current = null;\n const message =\n (e as Error)?.name === 'NotAllowedError'\n ? 'Microphone permission denied'\n : `Could not start recording: ${(e as Error)?.message || 'unknown error'}`;\n setError(message);\n setStatus('idle');\n }\n }, [isSupported, mimeType, bars, tick, cleanupAudioGraph, resetAutoStop]);\n\n const pause = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state === 'recording') {\n recorder.pause();\n accumulatedRef.current += Date.now() - startedAtRef.current;\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n setLevels(new Array(bars).fill(0));\n // Drop any in-flight silence/countdown but remember that speech happened.\n resetAutoStop(true);\n setStatus('paused');\n }\n }, [bars, resetAutoStop]);\n\n const resume = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state === 'paused') {\n recorder.resume();\n startedAtRef.current = Date.now();\n // Fresh silence timing on resume so it doesn't fire immediately.\n resetAutoStop(true);\n rafRef.current = requestAnimationFrame(tick);\n setStatus('recording');\n }\n }, [tick, resetAutoStop]);\n\n const stop = useCallback((): Promise<Blob | null> => {\n const recorder = mediaRecorderRef.current;\n if (!recorder) return Promise.resolve(null);\n discardRef.current = false;\n return new Promise<Blob | null>((resolve) => {\n stopResolveRef.current = resolve;\n recorder.stop();\n });\n }, []);\n\n const cancel = useCallback(() => {\n const recorder = mediaRecorderRef.current;\n if (!recorder) {\n cleanupAudioGraph();\n setStatus('idle');\n setLevels(new Array(bars).fill(0));\n setDurationMs(0);\n resetAutoStop();\n return;\n }\n discardRef.current = true;\n recorder.stop();\n }, [bars, cleanupAudioGraph, resetAutoStop]);\n\n // Teardown on unmount.\n useEffect(() => {\n return () => {\n const recorder = mediaRecorderRef.current;\n if (recorder && recorder.state !== 'inactive') {\n discardRef.current = true;\n try {\n recorder.stop();\n } catch {\n // ignore\n }\n }\n cleanupAudioGraph();\n };\n }, [cleanupAudioGraph]);\n\n return {\n status,\n isRecording: status === 'recording',\n isPaused: status === 'paused',\n isSupported,\n levels,\n durationMs,\n error,\n isAutoStopping,\n autoStopProgress,\n speechDetected,\n start,\n pause,\n resume,\n stop,\n cancel,\n };\n}\n"],"names":["useState","useRef","useCallback","useEffect"],"mappings":";;;;AAmFA,MAAM,oBAAoB,GAAG;IAC3B,wBAAwB;IACxB,YAAY;IACZ,uBAAuB;IACvB,WAAW;CACZ;AAED,SAAS,YAAY,CAAC,SAAkB,EAAA;IACtC,IAAI,OAAO,aAAa,KAAK,WAAW;AAAE,QAAA,OAAO,SAAS;IAC1D,MAAM,UAAU,GAAG;AACjB,UAAE,CAAC,SAAS,EAAE,GAAG,oBAAoB;UACnC,oBAAoB;AACxB,IAAA,KAAK,MAAM,IAAI,IAAI,UAAU,EAAE;AAC7B,QAAA,IAAI,aAAa,CAAC,eAAe,CAAC,IAAI,CAAC;AAAE,YAAA,OAAO,IAAI;IACtD;AACA,IAAA,OAAO,SAAS;AAClB;AAEA;;;;;;AAMG;AACG,SAAU,kBAAkB,CAChC,OAAA,GAAqC,EAAE,EAAA;AAEvC,IAAA,MAAM,EACJ,IAAI,GAAG,CAAC,EACR,QAAQ,EACR,QAAQ,GAAG,IAAI,EACf,iBAAiB,GAAG,IAAI,EACxB,mBAAmB,GAAG,IAAI,EAC1B,oBAAoB,GAAG,GAAG,EAC1B,oBAAoB,GAAG,IAAI,EAC3B,mBAAmB,GAAG,IAAI,EAC1B,UAAU,GACX,GAAG,OAAO;AAEX,IAAA,MAAM,WAAW,GACf,OAAO,SAAS,KAAK,WAAW;AAChC,QAAA,CAAC,CAAC,SAAS,CAAC,YAAY,EAAE,YAAY;QACtC,OAAO,aAAa,KAAK,WAAW;IAEtC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAGA,cAAQ,CAAwB,MAAM,CAAC;IACnE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAGA,cAAQ,CAAW,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,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