@umodeapporg/ui 0.32.1 → 0.33.1

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.
Files changed (28) hide show
  1. package/dist/components/Form/ControlledVoiceTextarea.js +5 -1
  2. package/dist/components/Form/ControlledVoiceTextarea.js.map +1 -1
  3. package/dist/components/UI/DataTable/DataTable.js +18 -3
  4. package/dist/components/UI/DataTable/DataTable.js.map +1 -1
  5. package/dist/components/UI/DataTable/DataTableBulkEditButton.d.ts +2 -0
  6. package/dist/components/UI/DataTable/DataTableBulkEditButton.js +2 -2
  7. package/dist/components/UI/DataTable/DataTableBulkEditButton.js.map +1 -1
  8. package/dist/components/UI/DataTable/DataTableColumnToggle.d.ts +5 -2
  9. package/dist/components/UI/DataTable/DataTableColumnToggle.js +7 -4
  10. package/dist/components/UI/DataTable/DataTableColumnToggle.js.map +1 -1
  11. package/dist/components/UI/DataTable/DataTableEditModeButton.d.ts +2 -0
  12. package/dist/components/UI/DataTable/DataTableEditModeButton.js +22 -15
  13. package/dist/components/UI/DataTable/DataTableEditModeButton.js.map +1 -1
  14. package/dist/helpers/speechSegmentRecorder.d.ts +25 -0
  15. package/dist/helpers/speechSegmentRecorder.js +171 -0
  16. package/dist/helpers/speechSegmentRecorder.js.map +1 -0
  17. package/dist/helpers/speechSegmenter.d.ts +16 -0
  18. package/dist/helpers/speechSegmenter.js +53 -0
  19. package/dist/helpers/speechSegmenter.js.map +1 -0
  20. package/dist/hooks/useVoiceTranscription.d.ts +19 -0
  21. package/dist/hooks/useVoiceTranscription.js +191 -13
  22. package/dist/hooks/useVoiceTranscription.js.map +1 -1
  23. package/dist/locales/en/ui.json.d.ts +3 -1
  24. package/dist/locales/en/ui.json.js +1 -1
  25. package/dist/locales/index.d.ts +4 -0
  26. package/dist/locales/pt/ui.json.d.ts +3 -1
  27. package/dist/locales/pt/ui.json.js +1 -1
  28. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"DataTableEditModeButton.js","sources":["../../../../src/components/UI/DataTable/DataTableEditModeButton.tsx"],"sourcesContent":["import React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\n\ninterface IDataTableEditModeButtonProps {\n active: boolean;\n onToggle: () => void;\n}\n\n/**\n * Liga e desliga a edição em célula. Fica junto do controle de colunas, no rodapé\n * da tabela: o modo pertence à tabela, não ao cabeçalho da página, e enquanto ele\n * está ativo o clique na linha deixa de abrir o registro.\n */\nconst DataTableEditModeButton: React.FC<IDataTableEditModeButtonProps> = ({ active, onToggle }) => {\n const { t } = useTranslation('ui');\n\n return (\n <ControlledTooltip content={active ? t('dataTable.editMode.activeHint') : t('dataTable.editMode.inactiveHint')}>\n <ControlledButton\n defaultHtmlButton\n onClick={onToggle}\n aria-pressed={active}\n className={classNames(\n 'inline-flex shrink-0 items-center gap-1.5 rounded-lg border p-2.5 text-sm font-medium shadow-sm transition-colors',\n active\n ? 'border-brand-border bg-brand text-brand-fg hover:bg-brand-hover'\n : 'border-border bg-surface text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted',\n )}\n >\n <MaterialSymbol icon={active ? 'edit_off' : 'edit'} size={18} />\n <span>{active ? t('dataTable.editMode.exit') : t('dataTable.editMode.enter')}</span>\n </ControlledButton>\n </ControlledTooltip>\n );\n};\n\nexport default DataTableEditModeButton;\n"],"names":[],"mappings":";;;;;;AAkBA,MAAM,0BAAmE,CAAC,EAAE,QAAQ,eAAe;AACjG,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,SACE,oBAAC,qBAAkB,SAAS,SAAS,EAAE,+BAA+B,IAAI,EAAE,iCAAiC,GAC3G,UAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,mBAAiB;AAAA,MACjB,SAAS;AAAA,MACT,gBAAc;AAAA,MACd,WAAW;AAAA,QACT;AAAA,QACA,SACI,oEACA;AAAA,MAAA;AAAA,MAGN,UAAA;AAAA,QAAA,oBAAC,kBAAe,MAAM,SAAS,aAAa,QAAQ,MAAM,IAAI;AAAA,QAC9D,oBAAC,UAAM,UAAA,SAAS,EAAE,yBAAyB,IAAI,EAAE,0BAA0B,EAAA,CAAE;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA,GAEjF;AAEJ;"}
1
+ {"version":3,"file":"DataTableEditModeButton.js","sources":["../../../../src/components/UI/DataTable/DataTableEditModeButton.tsx"],"sourcesContent":["import React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport type { TFloatingPlacement } from '@/hooks/useAnchoredFloating';\n\ninterface IDataTableEditModeButtonProps {\n active: boolean;\n onToggle: () => void;\n tooltipPlacement?: TFloatingPlacement;\n}\n\n/**\n * Liga e desliga a edição em célula. Fica junto do controle de colunas, no rodapé\n * da tabela: o modo pertence à tabela, não ao cabeçalho da página, e enquanto ele\n * está ativo o clique na linha deixa de abrir o registro.\n */\nconst DataTableEditModeButton: React.FC<IDataTableEditModeButtonProps> = ({ active, onToggle, tooltipPlacement }) => {\n const { t } = useTranslation('ui');\n\n return (\n <ControlledTooltip\n content={active ? t('dataTable.editMode.activeHint') : t('dataTable.editMode.inactiveHint')}\n placement={tooltipPlacement}\n >\n <ControlledButton\n defaultHtmlButton\n onClick={onToggle}\n aria-pressed={active}\n className={classNames(\n 'inline-flex shrink-0 items-center gap-1.5 rounded-lg border p-2.5 text-sm font-medium shadow-sm transition-colors',\n active\n ? 'border-brand-border bg-brand text-brand-fg hover:bg-brand-hover'\n : 'border-border bg-surface text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted',\n )}\n >\n <MaterialSymbol icon={active ? 'edit_off' : 'edit'} size={18} />\n <span>{active ? t('dataTable.editMode.exit') : t('dataTable.editMode.enter')}</span>\n </ControlledButton>\n </ControlledTooltip>\n );\n};\n\nexport default DataTableEditModeButton;\n"],"names":[],"mappings":";;;;;;AAoBA,MAAM,0BAAmE,CAAC,EAAE,QAAQ,UAAU,uBAAuB;AACnH,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,SAAS,SAAS,EAAE,+BAA+B,IAAI,EAAE,iCAAiC;AAAA,MAC1F,WAAW;AAAA,MAEX,UAAA;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,mBAAiB;AAAA,UACjB,SAAS;AAAA,UACT,gBAAc;AAAA,UACd,WAAW;AAAA,YACT;AAAA,YACA,SACI,oEACA;AAAA,UAAA;AAAA,UAGN,UAAA;AAAA,YAAA,oBAAC,kBAAe,MAAM,SAAS,aAAa,QAAQ,MAAM,IAAI;AAAA,YAC9D,oBAAC,UAAM,UAAA,SAAS,EAAE,yBAAyB,IAAI,EAAE,0BAA0B,EAAA,CAAE;AAAA,UAAA;AAAA,QAAA;AAAA,MAAA;AAAA,IAC/E;AAAA,EAAA;AAGN;"}
@@ -0,0 +1,25 @@
1
+ export type TSpeechRecorderFailure = 'permission' | 'microphone' | 'unavailable';
2
+ export declare class SpeechRecorderError extends Error {
3
+ readonly failure: TSpeechRecorderFailure;
4
+ constructor(failure: TSpeechRecorderFailure);
5
+ }
6
+ export interface ISpeechSegmentRecorderCallbacks {
7
+ onSegment: (segment: Blob) => void;
8
+ /** Nothing was said for a while; the recorder already stopped. */
9
+ onIdle: () => void;
10
+ /** The microphone went away (unplugged, permission revoked); the recorder already stopped. */
11
+ onInterrupted: () => void;
12
+ }
13
+ export interface ISpeechSegmentRecorder {
14
+ /** Stops listening and still delivers the phrase in progress; resolves once it was handed over. */
15
+ stop: () => Promise<void>;
16
+ /** Stops listening and drops the phrase in progress. */
17
+ abort: () => void;
18
+ }
19
+ export declare const canRecordSpeech: () => boolean;
20
+ /**
21
+ * Records dictation for browsers whose speech engine is missing or unreachable. The microphone is
22
+ * watched for pauses and every phrase becomes its own recording, handed over as soon as it ends.
23
+ * Only phrases with speech are handed over: silence is never sent anywhere.
24
+ */
25
+ export declare const startSpeechSegmentRecorder: (callbacks: ISpeechSegmentRecorderCallbacks) => Promise<ISpeechSegmentRecorder>;
@@ -0,0 +1,171 @@
1
+ import { createSpeechSegmenter } from "./speechSegmenter.js";
2
+ import { uiLogger } from "./uiLogger.js";
3
+ class SpeechRecorderError extends Error {
4
+ constructor(failure) {
5
+ super(`Speech recorder could not start: ${failure}`);
6
+ this.failure = failure;
7
+ this.name = "SpeechRecorderError";
8
+ }
9
+ }
10
+ const RECORDING_MIME_CANDIDATES = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/mp4", "audio/webm"];
11
+ const RECORDING_BITS_PER_SECOND = 32e3;
12
+ const LEVEL_SAMPLE_INTERVAL_MS = 50;
13
+ const SEGMENT_CLOSE_TIMEOUT_MS = 3e3;
14
+ const resolveAudioContextCtor = () => {
15
+ if (typeof window === "undefined") return null;
16
+ const audioWindow = window;
17
+ return audioWindow.AudioContext ?? audioWindow.webkitAudioContext ?? null;
18
+ };
19
+ const canRecordSpeech = () => typeof window !== "undefined" && typeof window.MediaRecorder !== "undefined" && typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getUserMedia === "function" && resolveAudioContextCtor() !== null;
20
+ const pickRecordingMime = () => RECORDING_MIME_CANDIDATES.find((candidate) => MediaRecorder.isTypeSupported?.(candidate)) ?? "";
21
+ const toContainerMime = (mimeType) => mimeType.split(";")[0]?.trim() || "audio/webm";
22
+ const classifyMicrophoneError = (error) => {
23
+ const errorName = error instanceof Error || error instanceof DOMException ? error.name : "";
24
+ if (errorName === "NotAllowedError" || errorName === "SecurityError") return "permission";
25
+ if (errorName === "NotFoundError" || errorName === "NotReadableError" || errorName === "OverconstrainedError") {
26
+ return "microphone";
27
+ }
28
+ return "unavailable";
29
+ };
30
+ const readLevel = (analyser, samples) => {
31
+ analyser.getFloatTimeDomainData(samples);
32
+ let sumOfSquares = 0;
33
+ for (let sampleIndex = 0; sampleIndex < samples.length; sampleIndex += 1) {
34
+ const sample = samples[sampleIndex] ?? 0;
35
+ sumOfSquares += sample * sample;
36
+ }
37
+ return Math.sqrt(sumOfSquares / samples.length);
38
+ };
39
+ const closeAudioContext = async (audioContext) => {
40
+ try {
41
+ await audioContext.close();
42
+ } catch (error) {
43
+ uiLogger.debug("[speechSegmentRecorder] audio context close failed", error);
44
+ }
45
+ };
46
+ const resumeAudioContext = async (audioContext) => {
47
+ try {
48
+ await audioContext.resume();
49
+ } catch (error) {
50
+ uiLogger.debug("[speechSegmentRecorder] audio context resume failed", error);
51
+ }
52
+ };
53
+ const startSpeechSegmentRecorder = async (callbacks) => {
54
+ const AudioContextCtor = resolveAudioContextCtor();
55
+ if (!AudioContextCtor || !canRecordSpeech()) throw new SpeechRecorderError("unavailable");
56
+ const audioContext = new AudioContextCtor();
57
+ const audioContextResumed = resumeAudioContext(audioContext);
58
+ let stream;
59
+ try {
60
+ stream = await navigator.mediaDevices.getUserMedia({
61
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
62
+ });
63
+ } catch (error) {
64
+ uiLogger.warn("[speechSegmentRecorder] microphone unavailable", error);
65
+ void closeAudioContext(audioContext);
66
+ throw new SpeechRecorderError(classifyMicrophoneError(error));
67
+ }
68
+ await audioContextResumed;
69
+ const source = audioContext.createMediaStreamSource(stream);
70
+ const analyser = audioContext.createAnalyser();
71
+ analyser.fftSize = 1024;
72
+ const silentOutput = audioContext.createGain();
73
+ silentOutput.gain.value = 0;
74
+ source.connect(analyser);
75
+ analyser.connect(silentOutput);
76
+ silentOutput.connect(audioContext.destination);
77
+ const samples = new Float32Array(analyser.fftSize);
78
+ const recordingMime = pickRecordingMime();
79
+ const recorderOptions = {
80
+ audioBitsPerSecond: RECORDING_BITS_PER_SECOND,
81
+ ...recordingMime ? { mimeType: recordingMime } : {}
82
+ };
83
+ let finished = false;
84
+ let closing = null;
85
+ let levelTimer = null;
86
+ const segmenter = createSpeechSegmenter(performance.now());
87
+ const releaseMicrophone = () => {
88
+ stream.getTracks().forEach((track) => track.stop());
89
+ source.disconnect();
90
+ void closeAudioContext(audioContext);
91
+ };
92
+ const openSegment = () => {
93
+ const recorder = new MediaRecorder(stream, recorderOptions);
94
+ const segment = { recorder, keepsSpeech: false, onClosed: null };
95
+ const chunks = [];
96
+ recorder.ondataavailable = (event) => {
97
+ if (event.data.size > 0) chunks.push(event.data);
98
+ };
99
+ recorder.onstop = () => {
100
+ if (segment.keepsSpeech && chunks.length > 0) {
101
+ callbacks.onSegment(new Blob(chunks, { type: toContainerMime(recorder.mimeType || recordingMime) }));
102
+ }
103
+ segment.onClosed?.();
104
+ };
105
+ recorder.start();
106
+ return segment;
107
+ };
108
+ const closeSegment = (segment, keepsSpeech, onClosed = null) => {
109
+ segment.keepsSpeech = keepsSpeech;
110
+ segment.onClosed = onClosed;
111
+ if (segment.recorder.state === "inactive") {
112
+ onClosed?.();
113
+ return;
114
+ }
115
+ segment.recorder.stop();
116
+ };
117
+ let currentSegment = openSegment();
118
+ const finish = (keepsSpeech) => {
119
+ if (closing) return closing;
120
+ finished = true;
121
+ if (levelTimer !== null) clearInterval(levelTimer);
122
+ stream.getAudioTracks().forEach((track) => track.removeEventListener("ended", handleTrackEnded));
123
+ const lastSegment = currentSegment;
124
+ const keepsLastPhrase = keepsSpeech && segmenter.segmentSpeechMs() > 0;
125
+ closing = new Promise((resolve) => {
126
+ let released = false;
127
+ const release = () => {
128
+ if (released) return;
129
+ released = true;
130
+ clearTimeout(closeTimeout);
131
+ releaseMicrophone();
132
+ resolve();
133
+ };
134
+ const closeTimeout = setTimeout(release, SEGMENT_CLOSE_TIMEOUT_MS);
135
+ closeSegment(lastSegment, keepsLastPhrase, release);
136
+ });
137
+ return closing;
138
+ };
139
+ function handleTrackEnded() {
140
+ void finish(true);
141
+ callbacks.onInterrupted();
142
+ }
143
+ stream.getAudioTracks().forEach((track) => track.addEventListener("ended", handleTrackEnded));
144
+ levelTimer = setInterval(() => {
145
+ if (finished) return;
146
+ const decision = segmenter.observe(readLevel(analyser, samples), performance.now());
147
+ if (decision === "idle") {
148
+ void finish(true);
149
+ callbacks.onIdle();
150
+ return;
151
+ }
152
+ if (decision === "close-with-speech" || decision === "close-silent") {
153
+ const closingSegment = currentSegment;
154
+ currentSegment = openSegment();
155
+ segmenter.openSegment(performance.now());
156
+ closeSegment(closingSegment, decision === "close-with-speech");
157
+ }
158
+ }, LEVEL_SAMPLE_INTERVAL_MS);
159
+ return {
160
+ stop: () => finish(true),
161
+ abort: () => {
162
+ void finish(false);
163
+ }
164
+ };
165
+ };
166
+ export {
167
+ SpeechRecorderError,
168
+ canRecordSpeech,
169
+ startSpeechSegmentRecorder
170
+ };
171
+ //# sourceMappingURL=speechSegmentRecorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speechSegmentRecorder.js","sources":["../../src/helpers/speechSegmentRecorder.ts"],"sourcesContent":["import { createSpeechSegmenter } from './speechSegmenter';\nimport { uiLogger } from './uiLogger';\n\nexport type TSpeechRecorderFailure = 'permission' | 'microphone' | 'unavailable';\n\nexport class SpeechRecorderError extends Error {\n constructor(readonly failure: TSpeechRecorderFailure) {\n super(`Speech recorder could not start: ${failure}`);\n this.name = 'SpeechRecorderError';\n }\n}\n\nexport interface ISpeechSegmentRecorderCallbacks {\n onSegment: (segment: Blob) => void;\n /** Nothing was said for a while; the recorder already stopped. */\n onIdle: () => void;\n /** The microphone went away (unplugged, permission revoked); the recorder already stopped. */\n onInterrupted: () => void;\n}\n\nexport interface ISpeechSegmentRecorder {\n /** Stops listening and still delivers the phrase in progress; resolves once it was handed over. */\n stop: () => Promise<void>;\n /** Stops listening and drops the phrase in progress. */\n abort: () => void;\n}\n\ntype TAudioContextCtor = new () => AudioContext;\n\n/** Opus first: a phrase stays in a few dozen kilobytes. Safari only records MP4. */\nconst RECORDING_MIME_CANDIDATES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm'];\nconst RECORDING_BITS_PER_SECOND = 32_000;\nconst LEVEL_SAMPLE_INTERVAL_MS = 50;\n/** A recorder that never reports its end must not hold the host waiting for a phrase forever. */\nconst SEGMENT_CLOSE_TIMEOUT_MS = 3_000;\n\nconst resolveAudioContextCtor = (): TAudioContextCtor | null => {\n if (typeof window === 'undefined') return null;\n const audioWindow = window as unknown as { AudioContext?: TAudioContextCtor; webkitAudioContext?: TAudioContextCtor };\n return audioWindow.AudioContext ?? audioWindow.webkitAudioContext ?? null;\n};\n\nexport const canRecordSpeech = (): boolean =>\n typeof window !== 'undefined' &&\n typeof window.MediaRecorder !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.mediaDevices?.getUserMedia === 'function' &&\n resolveAudioContextCtor() !== null;\n\nconst pickRecordingMime = (): string =>\n RECORDING_MIME_CANDIDATES.find((candidate) => MediaRecorder.isTypeSupported?.(candidate)) ?? '';\n\n/**\n * The container alone: a type with codec parameters (`audio/webm;codecs=opus`) is read as\n * `text/plain` by some multipart parsers, and the upload is refused as not audio.\n */\nconst toContainerMime = (mimeType: string): string => mimeType.split(';')[0]?.trim() || 'audio/webm';\n\nconst classifyMicrophoneError = (error: unknown): TSpeechRecorderFailure => {\n const errorName = error instanceof Error || error instanceof DOMException ? error.name : '';\n if (errorName === 'NotAllowedError' || errorName === 'SecurityError') return 'permission';\n if (errorName === 'NotFoundError' || errorName === 'NotReadableError' || errorName === 'OverconstrainedError') {\n return 'microphone';\n }\n return 'unavailable';\n};\n\nconst readLevel = (analyser: AnalyserNode, samples: Float32Array<ArrayBuffer>): number => {\n analyser.getFloatTimeDomainData(samples);\n let sumOfSquares = 0;\n for (let sampleIndex = 0; sampleIndex < samples.length; sampleIndex += 1) {\n const sample = samples[sampleIndex] ?? 0;\n sumOfSquares += sample * sample;\n }\n return Math.sqrt(sumOfSquares / samples.length);\n};\n\nconst closeAudioContext = async (audioContext: AudioContext): Promise<void> => {\n try {\n await audioContext.close();\n } catch (error) {\n uiLogger.debug('[speechSegmentRecorder] audio context close failed', error);\n }\n};\n\nconst resumeAudioContext = async (audioContext: AudioContext): Promise<void> => {\n try {\n await audioContext.resume();\n } catch (error) {\n uiLogger.debug('[speechSegmentRecorder] audio context resume failed', error);\n }\n};\n\ninterface IRecordingSegment {\n recorder: MediaRecorder;\n keepsSpeech: boolean;\n onClosed: (() => void) | null;\n}\n\n/**\n * Records dictation for browsers whose speech engine is missing or unreachable. The microphone is\n * watched for pauses and every phrase becomes its own recording, handed over as soon as it ends.\n * Only phrases with speech are handed over: silence is never sent anywhere.\n */\nexport const startSpeechSegmentRecorder = async (\n callbacks: ISpeechSegmentRecorderCallbacks,\n): Promise<ISpeechSegmentRecorder> => {\n const AudioContextCtor = resolveAudioContextCtor();\n if (!AudioContextCtor || !canRecordSpeech()) throw new SpeechRecorderError('unavailable');\n\n /* Created and resumed before the permission prompt, while the click that started dictation still\n counts as a user gesture: a context born after it can stay suspended and hear only silence. */\n const audioContext = new AudioContextCtor();\n const audioContextResumed = resumeAudioContext(audioContext);\n\n let stream: MediaStream;\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },\n });\n } catch (error) {\n uiLogger.warn('[speechSegmentRecorder] microphone unavailable', error);\n void closeAudioContext(audioContext);\n throw new SpeechRecorderError(classifyMicrophoneError(error));\n }\n\n await audioContextResumed;\n const source = audioContext.createMediaStreamSource(stream);\n const analyser = audioContext.createAnalyser();\n analyser.fftSize = 1024;\n const silentOutput = audioContext.createGain();\n silentOutput.gain.value = 0;\n // Some engines only process a graph that reaches the output; the gain keeps it inaudible.\n source.connect(analyser);\n analyser.connect(silentOutput);\n silentOutput.connect(audioContext.destination);\n const samples = new Float32Array(analyser.fftSize);\n\n const recordingMime = pickRecordingMime();\n const recorderOptions: MediaRecorderOptions = {\n audioBitsPerSecond: RECORDING_BITS_PER_SECOND,\n ...(recordingMime ? { mimeType: recordingMime } : {}),\n };\n\n let finished = false;\n let closing: Promise<void> | null = null;\n let levelTimer: ReturnType<typeof setInterval> | null = null;\n const segmenter = createSpeechSegmenter(performance.now());\n\n const releaseMicrophone = () => {\n stream.getTracks().forEach((track) => track.stop());\n source.disconnect();\n void closeAudioContext(audioContext);\n };\n\n const openSegment = (): IRecordingSegment => {\n const recorder = new MediaRecorder(stream, recorderOptions);\n const segment: IRecordingSegment = { recorder, keepsSpeech: false, onClosed: null };\n const chunks: Array<Blob> = [];\n\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = () => {\n if (segment.keepsSpeech && chunks.length > 0) {\n callbacks.onSegment(new Blob(chunks, { type: toContainerMime(recorder.mimeType || recordingMime) }));\n }\n segment.onClosed?.();\n };\n recorder.start();\n return segment;\n };\n\n const closeSegment = (segment: IRecordingSegment, keepsSpeech: boolean, onClosed: (() => void) | null = null) => {\n segment.keepsSpeech = keepsSpeech;\n segment.onClosed = onClosed;\n if (segment.recorder.state === 'inactive') {\n onClosed?.();\n return;\n }\n segment.recorder.stop();\n };\n\n let currentSegment = openSegment();\n\n const finish = (keepsSpeech: boolean): Promise<void> => {\n if (closing) return closing;\n finished = true;\n if (levelTimer !== null) clearInterval(levelTimer);\n stream.getAudioTracks().forEach((track) => track.removeEventListener('ended', handleTrackEnded));\n\n const lastSegment = currentSegment;\n const keepsLastPhrase = keepsSpeech && segmenter.segmentSpeechMs() > 0;\n closing = new Promise<void>((resolve) => {\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n clearTimeout(closeTimeout);\n releaseMicrophone();\n resolve();\n };\n const closeTimeout = setTimeout(release, SEGMENT_CLOSE_TIMEOUT_MS);\n closeSegment(lastSegment, keepsLastPhrase, release);\n });\n return closing;\n };\n\n function handleTrackEnded() {\n void finish(true);\n callbacks.onInterrupted();\n }\n\n stream.getAudioTracks().forEach((track) => track.addEventListener('ended', handleTrackEnded));\n\n levelTimer = setInterval(() => {\n if (finished) return;\n const decision = segmenter.observe(readLevel(analyser, samples), performance.now());\n\n if (decision === 'idle') {\n void finish(true);\n callbacks.onIdle();\n return;\n }\n\n if (decision === 'close-with-speech' || decision === 'close-silent') {\n const closingSegment = currentSegment;\n currentSegment = openSegment();\n segmenter.openSegment(performance.now());\n closeSegment(closingSegment, decision === 'close-with-speech');\n }\n }, LEVEL_SAMPLE_INTERVAL_MS);\n\n return {\n stop: () => finish(true),\n abort: () => {\n void finish(false);\n },\n };\n};\n"],"names":[],"mappings":";;AAKO,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAqB,SAAiC;AACpD,UAAM,oCAAoC,OAAO,EAAE;AADhC,SAAA,UAAA;AAEnB,SAAK,OAAO;AAAA,EACd;AACF;AAoBA,MAAM,4BAA4B,CAAC,0BAA0B,yBAAyB,aAAa,YAAY;AAC/G,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AAEjC,MAAM,2BAA2B;AAEjC,MAAM,0BAA0B,MAAgC;AAC9D,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,cAAc;AACpB,SAAO,YAAY,gBAAgB,YAAY,sBAAsB;AACvE;AAEO,MAAM,kBAAkB,MAC7B,OAAO,WAAW,eAClB,OAAO,OAAO,kBAAkB,eAChC,OAAO,cAAc,eACrB,OAAO,UAAU,cAAc,iBAAiB,cAChD,8BAA8B;AAEhC,MAAM,oBAAoB,MACxB,0BAA0B,KAAK,CAAC,cAAc,cAAc,kBAAkB,SAAS,CAAC,KAAK;AAM/F,MAAM,kBAAkB,CAAC,aAA6B,SAAS,MAAM,GAAG,EAAE,CAAC,GAAG,KAAA,KAAU;AAExF,MAAM,0BAA0B,CAAC,UAA2C;AAC1E,QAAM,YAAY,iBAAiB,SAAS,iBAAiB,eAAe,MAAM,OAAO;AACzF,MAAI,cAAc,qBAAqB,cAAc,gBAAiB,QAAO;AAC7E,MAAI,cAAc,mBAAmB,cAAc,sBAAs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ated speech breaks into segments that are sent to
3
+ * be transcribed. A segment closes on a pause, so each one is a whole phrase and the text arrives
4
+ * while the person keeps talking. Pure: the clock and the level come from outside.
5
+ */
6
+ /** Voiced time a segment needs before it is worth sending: shorter is a click or a breath. */
7
+ export declare const MIN_SEGMENT_SPEECH_MS = 200;
8
+ /** Nothing said for this long ends the dictation, like the browser engine does. */
9
+ export declare const IDLE_STOP_MS = 20000;
10
+ export type TSpeechSegmenterDecision = 'listen' | 'close-with-speech' | 'close-silent' | 'idle';
11
+ export interface ISpeechSegmenter {
12
+ observe: (level: number, now: number) => TSpeechSegmenterDecision;
13
+ openSegment: (now: number) => void;
14
+ segmentSpeechMs: () => number;
15
+ }
16
+ export declare const createSpeechSegmenter: (startedAt: number) => ISpeechSegmenter;
@@ -0,0 +1,53 @@
1
+ const MIN_SPEECH_LEVEL = 0.012;
2
+ const NOISE_FLOOR_MULTIPLIER = 3;
3
+ const INITIAL_NOISE_FLOOR = MIN_SPEECH_LEVEL / NOISE_FLOOR_MULTIPLIER;
4
+ const NOISE_WINDOW_MS = 2500;
5
+ const MIN_SEGMENT_SPEECH_MS = 200;
6
+ const PAUSE_TO_CLOSE_SEGMENT_MS = 900;
7
+ const LONG_SEGMENT_MS = 15e3;
8
+ const SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS = 300;
9
+ const MAX_SEGMENT_MS = 3e4;
10
+ const SILENT_SEGMENT_MS = 5e3;
11
+ const IDLE_STOP_MS = 2e4;
12
+ const createSpeechSegmenter = (startedAt) => {
13
+ const recentLevels = [];
14
+ let segmentStartedAt = startedAt;
15
+ let segmentVoicedMs = 0;
16
+ let lastVoiceAt = startedAt;
17
+ let lastObservedAt = startedAt;
18
+ const measureNoiseFloor = (now) => {
19
+ const quietestLevel = recentLevels.reduce((quietest, entry) => Math.min(quietest, entry.level), Infinity);
20
+ return now - startedAt < NOISE_WINDOW_MS ? Math.min(INITIAL_NOISE_FLOOR, quietestLevel) : quietestLevel;
21
+ };
22
+ const observe = (level, now) => {
23
+ const elapsedMs = Math.max(0, now - lastObservedAt);
24
+ lastObservedAt = now;
25
+ recentLevels.push({ at: now, level });
26
+ while (recentLevels.length > 0 && (recentLevels[0]?.at ?? now) < now - NOISE_WINDOW_MS) recentLevels.shift();
27
+ const isVoiced = level >= Math.max(MIN_SPEECH_LEVEL, measureNoiseFloor(now) * NOISE_FLOOR_MULTIPLIER);
28
+ if (isVoiced) {
29
+ segmentVoicedMs += elapsedMs;
30
+ lastVoiceAt = now;
31
+ }
32
+ const pauseMs = now - lastVoiceAt;
33
+ if (pauseMs >= IDLE_STOP_MS) return "idle";
34
+ const segmentAgeMs = now - segmentStartedAt;
35
+ if (segmentVoicedMs >= MIN_SEGMENT_SPEECH_MS) {
36
+ const isPhraseOver = pauseMs >= PAUSE_TO_CLOSE_SEGMENT_MS;
37
+ const isLongPhraseBreathing = segmentAgeMs >= LONG_SEGMENT_MS && pauseMs >= SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS;
38
+ return isPhraseOver || isLongPhraseBreathing || segmentAgeMs >= MAX_SEGMENT_MS ? "close-with-speech" : "listen";
39
+ }
40
+ return !isVoiced && segmentAgeMs >= SILENT_SEGMENT_MS ? "close-silent" : "listen";
41
+ };
42
+ const openSegment = (now) => {
43
+ segmentStartedAt = now;
44
+ segmentVoicedMs = 0;
45
+ };
46
+ return { observe, openSegment, segmentSpeechMs: () => segmentVoicedMs };
47
+ };
48
+ export {
49
+ IDLE_STOP_MS,
50
+ MIN_SEGMENT_SPEECH_MS,
51
+ createSpeechSegmenter
52
+ };
53
+ //# sourceMappingURL=speechSegmenter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speechSegmenter.js","sources":["../../src/helpers/speechSegmenter.ts"],"sourcesContent":["/**\n * Decides, from the microphone level, where dictated speech breaks into segments that are sent to\n * be transcribed. A segment closes on a pause, so each one is a whole phrase and the text arrives\n * while the person keeps talking. Pure: the clock and the level come from outside.\n */\n\n/** RMS below this is never speech, however quiet the room is. */\nconst MIN_SPEECH_LEVEL = 0.012;\n/** Speech has to stand this many times above the background noise. */\nconst NOISE_FLOOR_MULTIPLIER = 3;\nconst INITIAL_NOISE_FLOOR = MIN_SPEECH_LEVEL / NOISE_FLOOR_MULTIPLIER;\n/**\n * The background is the quietest level of the last moments. Speech always dips between syllables,\n * a fan or a street does not, so a steady noise becomes the floor and stops counting as speech.\n */\nconst NOISE_WINDOW_MS = 2_500;\n\n/** Voiced time a segment needs before it is worth sending: shorter is a click or a breath. */\nexport const MIN_SEGMENT_SPEECH_MS = 200;\nconst PAUSE_TO_CLOSE_SEGMENT_MS = 900;\nconst LONG_SEGMENT_MS = 15_000;\nconst SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS = 300;\nconst MAX_SEGMENT_MS = 30_000;\n/** A segment with no speech is restarted so silence never piles up in one recording. */\nconst SILENT_SEGMENT_MS = 5_000;\n/** Nothing said for this long ends the dictation, like the browser engine does. */\nexport const IDLE_STOP_MS = 20_000;\n\nexport type TSpeechSegmenterDecision = 'listen' | 'close-with-speech' | 'close-silent' | 'idle';\n\nexport interface ISpeechSegmenter {\n observe: (level: number, now: number) => TSpeechSegmenterDecision;\n openSegment: (now: number) => void;\n segmentSpeechMs: () => number;\n}\n\nexport const createSpeechSegmenter = (startedAt: number): ISpeechSegmenter => {\n const recentLevels: Array<{ at: number; level: number }> = [];\n let segmentStartedAt = startedAt;\n let segmentVoicedMs = 0;\n let lastVoiceAt = startedAt;\n let lastObservedAt = startedAt;\n\n /* Until a whole window was heard, someone who starts talking at once would become the floor. */\n const measureNoiseFloor = (now: number): number => {\n const quietestLevel = recentLevels.reduce((quietest, entry) => Math.min(quietest, entry.level), Infinity);\n return now - startedAt < NOISE_WINDOW_MS ? Math.min(INITIAL_NOISE_FLOOR, quietestLevel) : quietestLevel;\n };\n\n const observe = (level: number, now: number): TSpeechSegmenterDecision => {\n const elapsedMs = Math.max(0, now - lastObservedAt);\n lastObservedAt = now;\n\n recentLevels.push({ at: now, level });\n while (recentLevels.length > 0 && (recentLevels[0]?.at ?? now) < now - NOISE_WINDOW_MS) recentLevels.shift();\n\n const isVoiced = level >= Math.max(MIN_SPEECH_LEVEL, measureNoiseFloor(now) * NOISE_FLOOR_MULTIPLIER);\n if (isVoiced) {\n segmentVoicedMs += elapsedMs;\n lastVoiceAt = now;\n }\n\n const pauseMs = now - lastVoiceAt;\n if (pauseMs >= IDLE_STOP_MS) return 'idle';\n\n const segmentAgeMs = now - segmentStartedAt;\n if (segmentVoicedMs >= MIN_SEGMENT_SPEECH_MS) {\n const isPhraseOver = pauseMs >= PAUSE_TO_CLOSE_SEGMENT_MS;\n const isLongPhraseBreathing = segmentAgeMs >= LONG_SEGMENT_MS && pauseMs >= SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS;\n return isPhraseOver || isLongPhraseBreathing || segmentAgeMs >= MAX_SEGMENT_MS ? 'close-with-speech' : 'listen';\n }\n\n return !isVoiced && segmentAgeMs >= SILENT_SEGMENT_MS ? 'close-silent' : 'listen';\n };\n\n const openSegment = (now: number) => {\n segmentStartedAt = now;\n segmentVoicedMs = 0;\n };\n\n return { observe, openSegment, segmentSpeechMs: () => segmentVoicedMs };\n};\n"],"names":[],"mappings":"AAOA,MAAM,mBAAmB;AAEzB,MAAM,yBAAyB;AAC/B,MAAM,sBAAsB,mBAAmB;AAK/C,MAAM,kBAAkB;AAGjB,MAAM,wBAAwB;AACrC,MAAM,4BAA4B;AAClC,MAAM,kBAAkB;AACxB,MAAM,uCAAuC;AAC7C,MAAM,iBAAiB;AAEvB,MAAM,oBAAoB;AAEnB,MAAM,eAAe;AAUrB,MAAM,wBAAwB,CAAC,cAAwC;AAC5E,QAAM,eAAqD,CAAA;AAC3D,MAAI,mBAAmB;AACvB,MAAI,kBAAkB;AACtB,MAAI,cAAc;AAClB,MAAI,iBAAiB;AAGrB,QAAM,oBAAoB,CAAC,QAAwB;AACjD,UAAM,gBAAgB,aAAa,OAAO,CAAC,UAAU,UAAU,KAAK,IAAI,UAAU,MAAM,KAAK,GAAG,QAAQ;AACxG,WAAO,MAAM,YAAY,kBAAkB,KAAK,IAAI,qBAAqB,aAAa,IAAI;AAAA,EAC5F;AAEA,QAAM,UAAU,CAAC,OAAe,QAA0C;AACxE,UAAM,YAAY,KAAK,IAAI,GAAG,MAAM,cAAc;AAClD,qBAAiB;AAEjB,iBAAa,KAAK,EAAE,IAAI,KAAK,OAAO;AACpC,WAAO,aAAa,SAAS,MAAM,aAAa,CAAC,GAAG,MAAM,OAAO,MAAM,gBAAiB,cAAa,MAAA;AAErG,UAAM,WAAW,SAAS,KAAK,IAAI,kBAAkB,kBAAkB,GAAG,IAAI,sBAAsB;AACpG,QAAI,UAAU;AACZ,yBAAmB;AACnB,oBAAc;AAAA,IAChB;AAEA,UAAM,UAAU,MAAM;AACtB,QAAI,WAAW,aAAc,QAAO;AAEpC,UAAM,eAAe,MAAM;AAC3B,QAAI,mBAAmB,uBAAuB;AAC5C,YAAM,eAAe,WAAW;AAChC,YAAM,wBAAwB,gBAAgB,mBAAmB,WAAW;AAC5E,aAAO,gBAAgB,yBAAyB,gBAAgB,iBAAiB,sBAAsB;AAAA,IACzG;AAEA,WAAO,CAAC,YAAY,gBAAgB,oBAAoB,iBAAiB;AAAA,EAC3E;AAEA,QAAM,cAAc,CAAC,QAAgB;AACnC,uBAAmB;AACnB,sBAAkB;AAAA,EACpB;AAEA,SAAO,EAAE,SAAS,aAAa,iBAAiB,MAAM,gBAAA;AACxD;"}
@@ -1,3 +1,16 @@
1
+ export interface IVoiceTranscriberRequest {
2
+ /** BCP 47 tag of the language being spoken. */
3
+ lang: string;
4
+ signal: AbortSignal;
5
+ }
6
+ /** Turns one recorded phrase into text. Resolves with an empty string when nothing was said. */
7
+ export type TVoiceTranscriber = (audio: Blob, request: IVoiceTranscriberRequest) => Promise<string>;
8
+ /**
9
+ * The host registers how recorded speech becomes text. It backs the browsers that ship no speech
10
+ * engine (Firefox) or one that cannot reach its service (Arc, Brave, Opera): without it, those
11
+ * browsers cannot dictate at all.
12
+ */
13
+ export declare const configureVoiceTranscriber: (transcriber: TVoiceTranscriber | null) => void;
1
14
  export type TVoiceCommandKey = 'comma' | 'period' | 'newline' | 'space' | 'question' | 'exclamation' | 'deleteWord';
2
15
  interface IVoiceCommand {
3
16
  key: TVoiceCommandKey;
@@ -13,6 +26,8 @@ export interface IVoiceTranscriptionUpdate {
13
26
  export declare const applyVoiceUpdate: (current: string, update: IVoiceTranscriptionUpdate) => string;
14
27
  export declare const appendInterimTranscript: (committed: string, interim: string) => string;
15
28
  export type TVoiceTranscriptionError = 'permission' | 'microphone' | 'network' | 'unavailable';
29
+ /** `browser`: the browser's own engine, live text. `recorder`: recorded phrases sent to the host. */
30
+ export type TVoiceTranscriptionEngine = 'browser' | 'recorder';
16
31
  interface IUseVoiceTranscriptionParams {
17
32
  lang?: string;
18
33
  onCommit: (update: IVoiceTranscriptionUpdate) => void;
@@ -21,6 +36,10 @@ interface IUseVoiceTranscriptionParams {
21
36
  interface IUseVoiceTranscriptionResult {
22
37
  isSupported: boolean;
23
38
  isListening: boolean;
39
+ /** Recorded speech whose text has not arrived yet. Only the recorder engine waits for text. */
40
+ isTranscribing: boolean;
41
+ /** The engine of the current (or last) dictation. */
42
+ engine: TVoiceTranscriptionEngine | null;
24
43
  error: TVoiceTranscriptionError | null;
25
44
  toggle: () => void;
26
45
  stop: () => void;
@@ -1,12 +1,44 @@
1
1
  import { useState, useRef, useSyncExternalStore, useCallback, useEffect } from "react";
2
+ import { startSpeechSegmentRecorder, SpeechRecorderError, canRecordSpeech } from "../helpers/speechSegmentRecorder.js";
2
3
  import { uiLogger } from "../helpers/uiLogger.js";
4
+ import { writeUiPreference, readUiPreference } from "../helpers/uiPreferences.js";
3
5
  const getRecognitionCtor = () => {
4
6
  const w = window;
5
7
  return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
6
8
  };
7
- const subscribeToNothing = () => () => void 0;
8
- const isRecognitionAvailable = () => getRecognitionCtor() !== null;
9
+ let configuredTranscriber = null;
10
+ const transcriberListeners = /* @__PURE__ */ new Set();
11
+ const configureVoiceTranscriber = (transcriber) => {
12
+ configuredTranscriber = transcriber;
13
+ transcriberListeners.forEach((listener) => listener());
14
+ };
15
+ const canTranscribeRecordedSpeech = () => configuredTranscriber !== null && canRecordSpeech();
16
+ const subscribeToTranscriber = (listener) => {
17
+ transcriberListeners.add(listener);
18
+ return () => {
19
+ transcriberListeners.delete(listener);
20
+ };
21
+ };
22
+ const isVoiceInputAvailable = () => getRecognitionCtor() !== null || canTranscribeRecordedSpeech();
9
23
  const isUnavailableOnServer = () => false;
24
+ const BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY = "umode-ui.voiceInput.browserEngineUnreachableAt";
25
+ const BROWSER_ENGINE_RETRY_AFTER_MS = 7 * 24 * 60 * 60 * 1e3;
26
+ const BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD = /* @__PURE__ */ new Set([
27
+ "network",
28
+ "service-not-allowed",
29
+ "language-not-supported"
30
+ ]);
31
+ const BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD = /* @__PURE__ */ new Set(["audio-capture"]);
32
+ let browserEngineUnreachableThisPage = false;
33
+ const isBrowserEngineUnreachable = () => {
34
+ if (browserEngineUnreachableThisPage) return true;
35
+ const unreachableAt = readUiPreference(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY);
36
+ return typeof unreachableAt === "number" && Date.now() - unreachableAt < BROWSER_ENGINE_RETRY_AFTER_MS;
37
+ };
38
+ const rememberBrowserEngineUnreachable = () => {
39
+ browserEngineUnreachableThisPage = true;
40
+ writeUiPreference(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY, Date.now());
41
+ };
10
42
  const listensOneUtterancePerSession = () => {
11
43
  const { userAgent, maxTouchPoints } = navigator;
12
44
  return /Android|iPhone|iPad|iPod/i.test(userAgent) || /Macintosh/i.test(userAgent) && maxTouchPoints > 1;
@@ -85,6 +117,13 @@ const RECOGNITION_ERROR_TO_VOICE_ERROR = {
85
117
  "bad-grammar": "unavailable"
86
118
  };
87
119
  const MAX_SILENT_RESTARTS = 2;
120
+ const settleTranscript = async (transcriber, segment, request) => {
121
+ try {
122
+ return { ok: true, text: await transcriber(segment, request) };
123
+ } catch (error) {
124
+ return { ok: false, error };
125
+ }
126
+ };
88
127
  const detachRecognition = (recognition) => {
89
128
  recognition.onresult = null;
90
129
  recognition.onerror = null;
@@ -96,19 +135,121 @@ const useVoiceTranscription = ({
96
135
  onInterim
97
136
  }) => {
98
137
  const [isListening, setIsListening] = useState(false);
138
+ const [pendingSegmentCount, setPendingSegmentCount] = useState(0);
139
+ const [engine, setEngine] = useState(null);
99
140
  const [error, setError] = useState(null);
100
141
  const recognitionRef = useRef(null);
142
+ const segmentRecorderRef = useRef(null);
143
+ const activeEngineRef = useRef(null);
144
+ const recorderStartIdRef = useRef(0);
145
+ const commitQueueRef = useRef(Promise.resolve());
146
+ const unmountControllerRef = useRef(null);
147
+ const isMountedRef = useRef(true);
101
148
  const wantsListeningRef = useRef(false);
102
149
  const silentRestartCountRef = useRef(0);
103
150
  const onCommitRef = useRef(onCommit);
104
151
  const onInterimRef = useRef(onInterim);
105
152
  onCommitRef.current = onCommit;
106
153
  onInterimRef.current = onInterim;
107
- const isSupported = useSyncExternalStore(subscribeToNothing, isRecognitionAvailable, isUnavailableOnServer);
154
+ const isSupported = useSyncExternalStore(subscribeToTranscriber, isVoiceInputAvailable, isUnavailableOnServer);
155
+ const resolveUnmountSignal = () => {
156
+ if (!unmountControllerRef.current) unmountControllerRef.current = new AbortController();
157
+ return unmountControllerRef.current.signal;
158
+ };
159
+ const finishListening = useCallback(() => {
160
+ wantsListeningRef.current = false;
161
+ setIsListening(false);
162
+ }, []);
163
+ const detachSegmentRecorder = useCallback(() => {
164
+ recorderStartIdRef.current += 1;
165
+ const segmentRecorder = segmentRecorderRef.current;
166
+ segmentRecorderRef.current = null;
167
+ return segmentRecorder;
168
+ }, []);
169
+ const stopSegmentRecorder = useCallback(async () => {
170
+ const segmentRecorder = detachSegmentRecorder();
171
+ if (!segmentRecorder) return;
172
+ setPendingSegmentCount((count) => count + 1);
173
+ try {
174
+ await segmentRecorder.stop();
175
+ } finally {
176
+ if (isMountedRef.current) setPendingSegmentCount((count) => Math.max(0, count - 1));
177
+ }
178
+ }, [detachSegmentRecorder]);
179
+ const abortSegmentRecorder = useCallback(() => {
180
+ detachSegmentRecorder()?.abort();
181
+ }, [detachSegmentRecorder]);
182
+ const transcribeSegment = useCallback(
183
+ (segment) => {
184
+ const transcriber = configuredTranscriber;
185
+ if (!transcriber) return;
186
+ setPendingSegmentCount((count) => count + 1);
187
+ const outcome = settleTranscript(transcriber, segment, { lang, signal: resolveUnmountSignal() });
188
+ const previousCommit = commitQueueRef.current;
189
+ const commitInOrder = async () => {
190
+ await previousCommit;
191
+ const settled = await outcome;
192
+ if (!isMountedRef.current) return;
193
+ setPendingSegmentCount((count) => Math.max(0, count - 1));
194
+ if (!settled.ok) {
195
+ uiLogger.warn("[useVoiceTranscription] transcription failed", settled.error);
196
+ setError("network");
197
+ abortSegmentRecorder();
198
+ finishListening();
199
+ return;
200
+ }
201
+ if (!settled.text.trim()) return;
202
+ try {
203
+ onCommitRef.current(buildUpdateFromTranscript(settled.text));
204
+ } catch (commitError) {
205
+ uiLogger.error("[useVoiceTranscription] writing the transcript failed", commitError);
206
+ }
207
+ };
208
+ commitQueueRef.current = commitInOrder();
209
+ },
210
+ [abortSegmentRecorder, finishListening, lang]
211
+ );
212
+ const startSegmentRecorder = useCallback(async () => {
213
+ const startId = recorderStartIdRef.current + 1;
214
+ recorderStartIdRef.current = startId;
215
+ activeEngineRef.current = "recorder";
216
+ setEngine("recorder");
217
+ setIsListening(true);
218
+ try {
219
+ const segmentRecorder = await startSpeechSegmentRecorder({
220
+ onSegment: transcribeSegment,
221
+ onIdle: () => {
222
+ if (segmentRecorderRef.current !== segmentRecorder) return;
223
+ segmentRecorderRef.current = null;
224
+ finishListening();
225
+ },
226
+ onInterrupted: () => {
227
+ if (segmentRecorderRef.current !== segmentRecorder) return;
228
+ segmentRecorderRef.current = null;
229
+ setError("microphone");
230
+ finishListening();
231
+ }
232
+ });
233
+ if (recorderStartIdRef.current !== startId || !wantsListeningRef.current) {
234
+ segmentRecorder.abort();
235
+ return;
236
+ }
237
+ segmentRecorderRef.current = segmentRecorder;
238
+ } catch (startError) {
239
+ if (recorderStartIdRef.current !== startId || !isMountedRef.current) return;
240
+ uiLogger.warn("[useVoiceTranscription] recorder failed to start", startError);
241
+ setError(startError instanceof SpeechRecorderError ? startError.failure : "unavailable");
242
+ finishListening();
243
+ }
244
+ }, [finishListening, transcribeSegment]);
108
245
  const stop = useCallback(() => {
109
246
  wantsListeningRef.current = false;
110
247
  recognitionRef.current?.stop();
111
- }, []);
248
+ if (activeEngineRef.current === "recorder") {
249
+ void stopSegmentRecorder();
250
+ setIsListening(false);
251
+ }
252
+ }, [stopSegmentRecorder]);
112
253
  const startSession = useCallback(() => {
113
254
  const Ctor = getRecognitionCtor();
114
255
  if (!Ctor) return false;
@@ -147,6 +288,18 @@ const useVoiceTranscription = ({
147
288
  sessionEndedByError = true;
148
289
  if (event.error === "aborted") return;
149
290
  uiLogger.warn("[useVoiceTranscription] error", event.error);
291
+ const browserEngineIsUnreachable = BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD.has(event.error);
292
+ const recordsInstead = browserEngineIsUnreachable || BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD.has(event.error);
293
+ if (wantsListeningRef.current && recordsInstead && canTranscribeRecordedSpeech()) {
294
+ if (browserEngineIsUnreachable) rememberBrowserEngineUnreachable();
295
+ detachRecognition(recognition);
296
+ recognitionRef.current = null;
297
+ recognition.abort();
298
+ if (uncommittedTranscript) onCommitRef.current(buildUpdateFromTranscript(uncommittedTranscript));
299
+ onInterimRef.current?.("");
300
+ void startSegmentRecorder();
301
+ return;
302
+ }
150
303
  setError(RECOGNITION_ERROR_TO_VOICE_ERROR[event.error] ?? "unavailable");
151
304
  };
152
305
  recognition.onend = () => {
@@ -171,38 +324,63 @@ const useVoiceTranscription = ({
171
324
  setError("unavailable");
172
325
  return false;
173
326
  }
174
- }, [lang]);
327
+ }, [lang, startSegmentRecorder]);
175
328
  const start = useCallback(() => {
176
329
  setError(null);
177
330
  silentRestartCountRef.current = 0;
178
331
  wantsListeningRef.current = true;
179
- if (startSession()) {
332
+ const canRecordInstead = canTranscribeRecordedSpeech();
333
+ const prefersBrowserEngine = getRecognitionCtor() !== null && (!canRecordInstead || !isBrowserEngineUnreachable());
334
+ if (prefersBrowserEngine && startSession()) {
335
+ activeEngineRef.current = "browser";
336
+ setEngine("browser");
180
337
  setIsListening(true);
181
338
  return;
182
339
  }
340
+ if (canRecordInstead) {
341
+ setError(null);
342
+ void startSegmentRecorder();
343
+ return;
344
+ }
183
345
  wantsListeningRef.current = false;
184
- }, [startSession]);
346
+ if (!prefersBrowserEngine) setError("unavailable");
347
+ }, [startSegmentRecorder, startSession]);
185
348
  const toggle = useCallback(() => {
186
349
  if (isListening) stop();
187
350
  else start();
188
351
  }, [isListening, start, stop]);
189
- useEffect(
190
- () => () => {
352
+ useEffect(() => {
353
+ isMountedRef.current = true;
354
+ return () => {
355
+ isMountedRef.current = false;
191
356
  wantsListeningRef.current = false;
357
+ recorderStartIdRef.current += 1;
358
+ segmentRecorderRef.current?.abort();
359
+ segmentRecorderRef.current = null;
360
+ unmountControllerRef.current?.abort();
361
+ unmountControllerRef.current = null;
192
362
  const recognition = recognitionRef.current;
193
363
  if (!recognition) return;
194
364
  detachRecognition(recognition);
195
365
  recognitionRef.current = null;
196
366
  recognition.abort();
197
- },
198
- []
199
- );
200
- return { isSupported, isListening, error, toggle, stop };
367
+ };
368
+ }, []);
369
+ return {
370
+ isSupported,
371
+ isListening,
372
+ isTranscribing: pendingSegmentCount > 0,
373
+ engine,
374
+ error,
375
+ toggle,
376
+ stop
377
+ };
201
378
  };
202
379
  export {
203
380
  VOICE_COMMANDS,
204
381
  appendInterimTranscript,
205
382
  applyVoiceUpdate,
383
+ configureVoiceTranscriber,
206
384
  useVoiceTranscription
207
385
  };
208
386
  //# sourceMappingURL=useVoiceTranscription.js.map