@ds-hu/dsh-bvi-input 0.1.0 → 0.2.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/lib/client.js +1389 -84
- package/package.json +1 -1
package/lib/client.js
CHANGED
|
@@ -5,6 +5,17 @@
|
|
|
5
5
|
* overlay reproduces the DeepSeek App recording surface, and the transcript is written
|
|
6
6
|
* back through the composer's public `inputActions`. Audio and policy come from our own
|
|
7
7
|
* service component over same-origin HTTP; no Harness client package is imported.
|
|
8
|
+
*
|
|
9
|
+
* v0.2 adds three behaviours on top of the original batch hold-to-talk:
|
|
10
|
+
* - a focused-editor / virtual-keyboard guard so a touch long-press never starts while
|
|
11
|
+
* the user is typing (the desktop mouse gesture keeps working);
|
|
12
|
+
* - an optional configurable keyboard shortcut that drives the very same hold state
|
|
13
|
+
* machine (`preferences.shortcut`);
|
|
14
|
+
* - live streaming transcription for providers that declare `streaming: true`: an
|
|
15
|
+
* AudioWorklet (ScriptProcessor fallback) taps the microphone, PCM16LE 16 kHz chunks
|
|
16
|
+
* are POSTed every ~200 ms, the cumulative partial is rendered above the waveform and
|
|
17
|
+
* the final line flies from the overlay into the composer before it is inserted.
|
|
18
|
+
* The whole-WAV `MediaRecorder` batch path is unchanged when streaming is unavailable.
|
|
8
19
|
*/
|
|
9
20
|
window.__ModuleLoader__.load({
|
|
10
21
|
id: '@ds-hu/dsh-bvi-input',
|
|
@@ -26,12 +37,25 @@ window.__ModuleLoader__.load({
|
|
|
26
37
|
const HOLD_CLASS = 'bvi-holding';
|
|
27
38
|
const HINT_ATTR = 'data-bvi-hint';
|
|
28
39
|
|
|
40
|
+
/** The suggested shortcut echoed by the settings page when the user has not chosen one. */
|
|
41
|
+
const DEFAULT_SHORTCUT = {
|
|
42
|
+
enabled: false,
|
|
43
|
+
code: 'Space',
|
|
44
|
+
ctrl: true,
|
|
45
|
+
alt: false,
|
|
46
|
+
shift: true,
|
|
47
|
+
meta: false,
|
|
48
|
+
};
|
|
49
|
+
|
|
29
50
|
/** Gesture defaults mirror the service preference defaults in the host contract. */
|
|
30
51
|
const DEFAULTS = {
|
|
31
52
|
releaseAction: 'insert',
|
|
32
53
|
holdDelayMs: 280,
|
|
33
54
|
cancelDistancePx: 72,
|
|
34
55
|
hintDismissed: false,
|
|
56
|
+
composerHint: true,
|
|
57
|
+
streaming: true,
|
|
58
|
+
shortcut: DEFAULT_SHORTCUT,
|
|
35
59
|
};
|
|
36
60
|
const MOVE_TOLERANCE_PX = 8;
|
|
37
61
|
const CANCEL_RELEASE_RATIO = 0.6;
|
|
@@ -42,6 +66,38 @@ window.__ModuleLoader__.load({
|
|
|
42
66
|
const WAVE_PITCH_PX = 22;
|
|
43
67
|
const WAVE_MAX_BARS = 56;
|
|
44
68
|
|
|
69
|
+
/** Keyboard guard: a viewport at least 25 % shorter than the window means a keyboard is up. */
|
|
70
|
+
const VIRTUAL_KEYBOARD_RATIO = 0.75;
|
|
71
|
+
|
|
72
|
+
/** Canonical streaming audio: PCM16LE, mono, 16 kHz, ~200 ms per chunk. */
|
|
73
|
+
const LIVE_SAMPLE_RATE = 16_000;
|
|
74
|
+
const STREAM_CHUNK_MS = 200;
|
|
75
|
+
const MAX_STREAM_CHUNK_BYTES = 1024 * 1024;
|
|
76
|
+
const LIVE_TEXT_MAX_CHARS = 600;
|
|
77
|
+
const LIVE_WORKLET_NAME = 'bvi-live-capture';
|
|
78
|
+
const LIVE_WORKLET_SOURCE = [
|
|
79
|
+
'class BviLiveCaptureProcessor extends AudioWorkletProcessor {',
|
|
80
|
+
' process(inputs) {',
|
|
81
|
+
' const channel = inputs[0] && inputs[0][0];',
|
|
82
|
+
' if (channel && channel.length) this.port.postMessage(channel.slice(0));',
|
|
83
|
+
' return true;',
|
|
84
|
+
' }',
|
|
85
|
+
'}',
|
|
86
|
+
'registerProcessor("' + LIVE_WORKLET_NAME + '", BviLiveCaptureProcessor);',
|
|
87
|
+
].join('\n');
|
|
88
|
+
|
|
89
|
+
/** Final-line flight into the composer (DOM only; skipped for reduced motion). */
|
|
90
|
+
const FLIGHT_MS = 360;
|
|
91
|
+
const FLIGHT_SCALE = 0.6;
|
|
92
|
+
const FLIGHT_EASING = 'cubic-bezier(.2,.8,.2,1)';
|
|
93
|
+
const FLIGHT_TIMEOUT_MS = FLIGHT_MS + 160;
|
|
94
|
+
|
|
95
|
+
/** Keyboard codes that may end a shortcut hold and may never be a bare shortcut. */
|
|
96
|
+
const MODIFIER_KEY_CODES = [
|
|
97
|
+
'AltLeft', 'AltRight', 'ControlLeft', 'ControlRight',
|
|
98
|
+
'MetaLeft', 'MetaRight', 'ShiftLeft', 'ShiftRight', 'OSLeft', 'OSRight',
|
|
99
|
+
];
|
|
100
|
+
|
|
45
101
|
/* ================================================================ */
|
|
46
102
|
/* dictionaries */
|
|
47
103
|
/* ================================================================ */
|
|
@@ -49,6 +105,9 @@ window.__ModuleLoader__.load({
|
|
|
49
105
|
const zh = {
|
|
50
106
|
'status.insert': '松手插入,上滑取消',
|
|
51
107
|
'status.send': '松手发送,上滑取消',
|
|
108
|
+
'status.insertKeyboard': '松开按键插入,按 Esc 取消',
|
|
109
|
+
'status.sendKeyboard': '松开按键发送,按 Esc 取消',
|
|
110
|
+
'status.streaming': '实时识别中…',
|
|
52
111
|
'status.cancel': '松手取消',
|
|
53
112
|
'status.preparing': '正在准备模型…',
|
|
54
113
|
'status.transcribing': '正在转写…',
|
|
@@ -65,6 +124,8 @@ window.__ModuleLoader__.load({
|
|
|
65
124
|
'feedback.tooLarge': '录音太长了,请缩短后重试。',
|
|
66
125
|
'feedback.tooShort': '说话时间太短,请按住多说一会儿。',
|
|
67
126
|
'feedback.failed': '转写失败:{message}',
|
|
127
|
+
'feedback.streamFallback': '实时识别已中断,本轮改用整段识别。',
|
|
128
|
+
'feedback.keyboardGuard': '键盘打开时长按不会录音,请先收起键盘再按住说话。',
|
|
68
129
|
'feedback.conflict': '草稿已更新,识别结果没有插入。',
|
|
69
130
|
'feedback.permission': '麦克风权限被拒绝:请在浏览器地址栏允许后重试。',
|
|
70
131
|
'feedback.deviceMissing': '没有找到可用的麦克风。',
|
|
@@ -79,6 +140,9 @@ window.__ModuleLoader__.load({
|
|
|
79
140
|
const en = {
|
|
80
141
|
'status.insert': 'Release to insert · slide up to cancel',
|
|
81
142
|
'status.send': 'Release to send · slide up to cancel',
|
|
143
|
+
'status.insertKeyboard': 'Release to insert · Esc to cancel',
|
|
144
|
+
'status.sendKeyboard': 'Release to send · Esc to cancel',
|
|
145
|
+
'status.streaming': 'Listening live…',
|
|
82
146
|
'status.cancel': 'Release to cancel',
|
|
83
147
|
'status.preparing': 'Preparing model…',
|
|
84
148
|
'status.transcribing': 'Transcribing…',
|
|
@@ -95,6 +159,8 @@ window.__ModuleLoader__.load({
|
|
|
95
159
|
'feedback.tooLarge': 'The recording is too long. Please shorten it and retry.',
|
|
96
160
|
'feedback.tooShort': 'Recording too short. Hold and speak a little longer.',
|
|
97
161
|
'feedback.failed': 'Transcription failed: {message}',
|
|
162
|
+
'feedback.streamFallback': 'Live recognition stopped; the whole take is being transcribed instead.',
|
|
163
|
+
'feedback.keyboardGuard': 'Long-press stays quiet while the keyboard is open. Close it, then hold to talk.',
|
|
98
164
|
'feedback.conflict': 'The draft changed, so the transcript was not inserted.',
|
|
99
165
|
'feedback.permission': 'Microphone permission denied. Allow it in the address bar and retry.',
|
|
100
166
|
'feedback.deviceMissing': 'No microphone was found.',
|
|
@@ -129,7 +195,85 @@ window.__ModuleLoader__.load({
|
|
|
129
195
|
return Number.isInteger(value) ? clamp(value, min, max) : fallback;
|
|
130
196
|
}
|
|
131
197
|
|
|
132
|
-
|
|
198
|
+
/* ================================================================ */
|
|
199
|
+
/* preferences + optional keyboard shortcut */
|
|
200
|
+
/* ================================================================ */
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* A shortcut is exactly `{ enabled, code, ctrl, alt, shift, meta }` where `code` is a
|
|
204
|
+
* `KeyboardEvent.code` of 1–32 alphanumerics, never a bare modifier, and the combination
|
|
205
|
+
* carries ctrl/alt/meta (or is a function key) so a plain letter can never hijack typing.
|
|
206
|
+
* This tolerant normalizer mirrors the host's strict `sanitizePreferences` reader.
|
|
207
|
+
* @param {any} value - the `preferences.shortcut` value from `/state`.
|
|
208
|
+
* @returns {{enabled: boolean, code: string, ctrl: boolean, alt: boolean, shift: boolean, meta: boolean}} normalized shortcut.
|
|
209
|
+
*/
|
|
210
|
+
function normalizeShortcut(value) {
|
|
211
|
+
if (!value || typeof value !== 'object') return { ...DEFAULT_SHORTCUT };
|
|
212
|
+
const rawCode = typeof value.code === 'string' ? value.code : '';
|
|
213
|
+
const validCode = /^[A-Za-z0-9]{1,32}$/u.test(rawCode) && !MODIFIER_KEY_CODES.includes(rawCode);
|
|
214
|
+
if (!validCode) return { ...DEFAULT_SHORTCUT };
|
|
215
|
+
const modifiers = {
|
|
216
|
+
ctrl: value.ctrl === true,
|
|
217
|
+
alt: value.alt === true,
|
|
218
|
+
shift: value.shift === true,
|
|
219
|
+
meta: value.meta === true,
|
|
220
|
+
};
|
|
221
|
+
return {
|
|
222
|
+
enabled: value.enabled === true && shortcutComboAllowed(rawCode, modifiers),
|
|
223
|
+
code: rawCode,
|
|
224
|
+
...modifiers,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** @returns {boolean} whether a code+modifier combination may ever be saved as a shortcut. */
|
|
229
|
+
function shortcutComboAllowed(code, modifiers) {
|
|
230
|
+
if (typeof code !== 'string' || !/^[A-Za-z0-9]{1,32}$/u.test(code)) return false;
|
|
231
|
+
if (MODIFIER_KEY_CODES.includes(code)) return false;
|
|
232
|
+
if (modifiers.ctrl || modifiers.alt || modifiers.meta) return true;
|
|
233
|
+
return /^F([1-9]|1[0-2])$/u.test(code);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Compare one keyboard event against a normalized shortcut. Repeats and IME composition
|
|
238
|
+
* events never match; modifiers are compared exactly so `Ctrl+Shift+Space` is not
|
|
239
|
+
* triggered by `Ctrl+Space`.
|
|
240
|
+
* @param {any} event - a `KeyboardEvent`.
|
|
241
|
+
* @param {any} shortcut - normalized shortcut.
|
|
242
|
+
* @returns {boolean} whether this event is the configured shortcut.
|
|
243
|
+
*/
|
|
244
|
+
function matchesShortcut(event, shortcut) {
|
|
245
|
+
if (!event || !shortcut || shortcut.enabled !== true) return false;
|
|
246
|
+
if (event.repeat === true || event.isComposing === true) return false;
|
|
247
|
+
if (typeof event.code !== 'string' || event.code !== shortcut.code) return false;
|
|
248
|
+
if (Boolean(event.ctrlKey) !== shortcut.ctrl) return false;
|
|
249
|
+
if (Boolean(event.altKey) !== shortcut.alt) return false;
|
|
250
|
+
if (Boolean(event.shiftKey) !== shortcut.shift) return false;
|
|
251
|
+
if (Boolean(event.metaKey) !== shortcut.meta) return false;
|
|
252
|
+
return true;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** @returns {boolean} whether a key code is a modifier key (used to end a shortcut hold). */
|
|
256
|
+
function isModifierCode(code) {
|
|
257
|
+
return typeof code === 'string' && MODIFIER_KEY_CODES.includes(code);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Shortcut events only fire while focus sits on the composer editor, the composer card
|
|
262
|
+
* itself or the document body — settings forms and other inputs keep typing normally.
|
|
263
|
+
* @param {{hasComposer: boolean, activeIsComposer: boolean, activeIsCard: boolean, activeIsBody: boolean}} input - focus facts.
|
|
264
|
+
* @returns {boolean} whether the shortcut may start a hold.
|
|
265
|
+
*/
|
|
266
|
+
function shortcutAllowed(input) {
|
|
267
|
+
if (!input || input.hasComposer !== true) return false;
|
|
268
|
+
return input.activeIsComposer === true || input.activeIsCard === true || input.activeIsBody === true;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Normalize the service preferences document (tolerant reads; each invalid field falls
|
|
273
|
+
* back to its default). v0.2 adds `composerHint`, `streaming` and `shortcut`.
|
|
274
|
+
* @param {any} state - the `/state` payload.
|
|
275
|
+
* @returns {typeof DEFAULTS} normalized preferences.
|
|
276
|
+
*/
|
|
133
277
|
function readPreferences(state) {
|
|
134
278
|
const preferences = state && typeof state === 'object' && state.preferences && typeof state.preferences === 'object' ? state.preferences : {};
|
|
135
279
|
return {
|
|
@@ -137,6 +281,9 @@ window.__ModuleLoader__.load({
|
|
|
137
281
|
holdDelayMs: clampInteger(preferences.holdDelayMs, 150, 1000, DEFAULTS.holdDelayMs),
|
|
138
282
|
cancelDistancePx: clampInteger(preferences.cancelDistancePx, 40, 200, DEFAULTS.cancelDistancePx),
|
|
139
283
|
hintDismissed: preferences.hintDismissed === true,
|
|
284
|
+
composerHint: preferences.composerHint !== false,
|
|
285
|
+
streaming: preferences.streaming !== false,
|
|
286
|
+
shortcut: normalizeShortcut(preferences.shortcut),
|
|
140
287
|
};
|
|
141
288
|
}
|
|
142
289
|
|
|
@@ -149,6 +296,52 @@ window.__ModuleLoader__.load({
|
|
|
149
296
|
};
|
|
150
297
|
}
|
|
151
298
|
|
|
299
|
+
/* ================================================================ */
|
|
300
|
+
/* trigger guards + capture mode selection */
|
|
301
|
+
/* ================================================================ */
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* @param {number|undefined} viewportHeight - `visualViewport.height`.
|
|
305
|
+
* @param {number|undefined} windowHeight - `innerHeight`.
|
|
306
|
+
* @returns {boolean} whether the visual viewport shrank enough to be a software keyboard.
|
|
307
|
+
*/
|
|
308
|
+
function isVirtualKeyboardOpen(viewportHeight, windowHeight) {
|
|
309
|
+
if (!Number.isFinite(viewportHeight) || !Number.isFinite(windowHeight)) return false;
|
|
310
|
+
if (viewportHeight <= 0 || windowHeight <= 0) return false;
|
|
311
|
+
return viewportHeight < windowHeight * VIRTUAL_KEYBOARD_RATIO;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Touch and pen long-presses never start while the composer editor owns focus or the
|
|
316
|
+
* virtual keyboard is open: the keyboard would be pushed away mid-gesture and the
|
|
317
|
+
* overlay would move the user's cursor. The desktop mouse keeps the gesture.
|
|
318
|
+
* @param {{pointerType?: string, editorFocused?: boolean, keyboardOpen?: boolean}} input - guard facts.
|
|
319
|
+
* @returns {boolean} whether the pointer hold may start.
|
|
320
|
+
*/
|
|
321
|
+
function shouldStartPointerHold(input) {
|
|
322
|
+
const pointerType = input && typeof input.pointerType === 'string' && input.pointerType !== '' ? input.pointerType : 'mouse';
|
|
323
|
+
if (pointerType === 'mouse') return true;
|
|
324
|
+
if (input && input.editorFocused === true) return false;
|
|
325
|
+
if (input && input.keyboardOpen === true) return false;
|
|
326
|
+
return true;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Per-recording capture mode. Streaming only when the preference is on, the selected
|
|
331
|
+
* provider declares `streaming: true` in `/state` and live PCM capture is available.
|
|
332
|
+
* @param {{preferences?: any, state?: any, liveSupported?: boolean}} input - selection facts.
|
|
333
|
+
* @returns {'stream'|'batch'} capture mode for the next take.
|
|
334
|
+
*/
|
|
335
|
+
function captureModeFor(input) {
|
|
336
|
+
const preferences = input && input.preferences && typeof input.preferences === 'object' ? input.preferences : {};
|
|
337
|
+
if (preferences.streaming !== true) return 'batch';
|
|
338
|
+
if (input && input.liveSupported === false) return 'batch';
|
|
339
|
+
const state = input ? input.state : undefined;
|
|
340
|
+
const providerId = state && state.selection && typeof state.selection.providerId === 'string' ? state.selection.providerId : undefined;
|
|
341
|
+
const provider = state && Array.isArray(state.providers) ? state.providers.find((entry) => entry && entry.id === providerId) : undefined;
|
|
342
|
+
return provider && provider.streaming === true ? 'stream' : 'batch';
|
|
343
|
+
}
|
|
344
|
+
|
|
152
345
|
/**
|
|
153
346
|
* Hold-gesture state machine. Pure so the gesture rules are unit-testable without
|
|
154
347
|
* a browser: `event.time` is only carried for diagnostics, callers own the timer.
|
|
@@ -225,15 +418,19 @@ window.__ModuleLoader__.load({
|
|
|
225
418
|
return Math.round(6 + safe * 34);
|
|
226
419
|
}
|
|
227
420
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
421
|
+
/* ================================================================ */
|
|
422
|
+
/* PCM / WAV helpers */
|
|
423
|
+
/* ================================================================ */
|
|
424
|
+
|
|
425
|
+
/** @returns {number} the canonical PCM16 value of a float sample in [-1, 1]. */
|
|
426
|
+
function sampleToInt16(sample) {
|
|
427
|
+
const value = clamp(sample, -1, 1);
|
|
428
|
+
return Math.round(value * (value < 0 ? 32768 : 32767));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Write the canonical 44-byte mono PCM16 RIFF header. */
|
|
432
|
+
function writeWavHeader(bytes, dataBytes, sampleRate) {
|
|
235
433
|
const rate = Number.isFinite(sampleRate) && sampleRate > 0 ? Math.round(sampleRate) : 16000;
|
|
236
|
-
const bytes = new Uint8Array(44 + samples.length * 2);
|
|
237
434
|
const view = new DataView(bytes.buffer);
|
|
238
435
|
const text = (at, value) => {
|
|
239
436
|
for (let index = 0; index < value.length; index += 1) bytes[at + index] = value.charCodeAt(index);
|
|
@@ -250,14 +447,190 @@ window.__ModuleLoader__.load({
|
|
|
250
447
|
view.setUint16(32, 2, true);
|
|
251
448
|
view.setUint16(34, 16, true);
|
|
252
449
|
text(36, 'data');
|
|
253
|
-
view.setUint32(40,
|
|
450
|
+
view.setUint32(40, dataBytes, true);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Encode mono float samples as a canonical 16 kHz PCM16 WAV.
|
|
455
|
+
* @param {Float32Array} samples - mono samples in [-1, 1].
|
|
456
|
+
* @param {number} sampleRate - sample rate of `samples` (must already be 16000 for uploads).
|
|
457
|
+
* @returns {Uint8Array} complete little-endian WAV bytes.
|
|
458
|
+
*/
|
|
459
|
+
function encodeWav(samples, sampleRate) {
|
|
460
|
+
const bytes = new Uint8Array(44 + samples.length * 2);
|
|
461
|
+
writeWavHeader(bytes, samples.length * 2, sampleRate);
|
|
462
|
+
const view = new DataView(bytes.buffer);
|
|
254
463
|
for (let index = 0; index < samples.length; index += 1) {
|
|
255
|
-
|
|
256
|
-
view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true);
|
|
464
|
+
view.setInt16(44 + index * 2, sampleToInt16(samples[index]), true);
|
|
257
465
|
}
|
|
258
466
|
return bytes;
|
|
259
467
|
}
|
|
260
468
|
|
|
469
|
+
/**
|
|
470
|
+
* Wrap already-16 kHz PCM16LE bytes in a canonical WAV container (batch fallback after
|
|
471
|
+
* a broken live stream keeps the take without re-resampling).
|
|
472
|
+
* @param {Uint8Array} pcm - PCM16LE mono 16 kHz bytes.
|
|
473
|
+
* @returns {Uint8Array} complete little-endian WAV bytes.
|
|
474
|
+
*/
|
|
475
|
+
function encodeWavFromPcm16(pcm) {
|
|
476
|
+
const samples = pcm && typeof pcm.byteLength === 'number' ? pcm : new Uint8Array(0);
|
|
477
|
+
const bytes = new Uint8Array(44 + samples.byteLength);
|
|
478
|
+
writeWavHeader(bytes, samples.byteLength, LIVE_SAMPLE_RATE);
|
|
479
|
+
bytes.set(samples, 44);
|
|
480
|
+
return bytes;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Linear-interpolation resampler used by the live streaming path (the batch path keeps
|
|
485
|
+
* using OfflineAudioContext, which is already exact for whole recordings).
|
|
486
|
+
* @param {ArrayLike<number>} samples - input mono samples.
|
|
487
|
+
* @param {number} fromRate - input sample rate.
|
|
488
|
+
* @param {number} toRate - output sample rate.
|
|
489
|
+
* @returns {Float32Array} resampled mono samples.
|
|
490
|
+
*/
|
|
491
|
+
function resampleFloat32(samples, fromRate, toRate) {
|
|
492
|
+
const input = samples && Number.isFinite(samples.length) ? samples : new Float32Array(0);
|
|
493
|
+
const from = Number.isFinite(fromRate) && fromRate > 0 ? fromRate : LIVE_SAMPLE_RATE;
|
|
494
|
+
const to = Number.isFinite(toRate) && toRate > 0 ? toRate : LIVE_SAMPLE_RATE;
|
|
495
|
+
if (input.length === 0) return new Float32Array(0);
|
|
496
|
+
const ratio = from / to;
|
|
497
|
+
const length = Math.max(1, Math.round(input.length / ratio));
|
|
498
|
+
const output = new Float32Array(length);
|
|
499
|
+
for (let index = 0; index < length; index += 1) {
|
|
500
|
+
const position = index * ratio;
|
|
501
|
+
const low = Math.floor(position);
|
|
502
|
+
const fraction = position - low;
|
|
503
|
+
const a = input[Math.min(low, input.length - 1)];
|
|
504
|
+
const b = input[Math.min(low + 1, input.length - 1)];
|
|
505
|
+
output[index] = a + (b - a) * fraction;
|
|
506
|
+
}
|
|
507
|
+
return output;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** @returns {Float32Array} samples downsampled to the 16 kHz streaming rate. */
|
|
511
|
+
function downsampleTo16k(samples, sampleRate) {
|
|
512
|
+
return resampleFloat32(samples, sampleRate, LIVE_SAMPLE_RATE);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** @returns {Uint8Array} PCM16LE bytes for float samples in [-1, 1]. */
|
|
516
|
+
function floatToPcm16(samples) {
|
|
517
|
+
const input = samples && Number.isFinite(samples.length) ? samples : new Float32Array(0);
|
|
518
|
+
const bytes = new Uint8Array(input.length * 2);
|
|
519
|
+
const view = new DataView(bytes.buffer);
|
|
520
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
521
|
+
view.setInt16(index * 2, sampleToInt16(input[index]), true);
|
|
522
|
+
}
|
|
523
|
+
return bytes;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** @returns {Float32Array} mono float samples decoded from PCM16LE bytes. */
|
|
527
|
+
function pcm16ToFloat32(pcm) {
|
|
528
|
+
const bytes = pcm && typeof pcm.byteLength === 'number' ? pcm : new Uint8Array(0);
|
|
529
|
+
const length = Math.floor(bytes.byteLength / 2);
|
|
530
|
+
const output = new Float32Array(length);
|
|
531
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
532
|
+
for (let index = 0; index < length; index += 1) {
|
|
533
|
+
const sample = view.getInt16(index * 2, true);
|
|
534
|
+
output[index] = sample < 0 ? sample / 32768 : sample / 32767;
|
|
535
|
+
}
|
|
536
|
+
return output;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Concatenate byte parts, optionally trusting a precomputed total length. */
|
|
540
|
+
function concatBytes(parts, totalLength) {
|
|
541
|
+
const list = Array.isArray(parts) ? parts : [];
|
|
542
|
+
let length = Number.isFinite(totalLength) ? Math.max(0, Math.floor(totalLength)) : 0;
|
|
543
|
+
if (!Number.isFinite(totalLength)) {
|
|
544
|
+
for (const part of list) length += part && typeof part.byteLength === 'number' ? part.byteLength : 0;
|
|
545
|
+
}
|
|
546
|
+
const output = new Uint8Array(length);
|
|
547
|
+
let offset = 0;
|
|
548
|
+
for (const part of list) {
|
|
549
|
+
if (!part || part.byteLength === 0 || offset >= length) continue;
|
|
550
|
+
const view = part instanceof Uint8Array ? part : new Uint8Array(part);
|
|
551
|
+
output.set(view.subarray(0, Math.max(0, length - offset)), offset);
|
|
552
|
+
offset += view.byteLength;
|
|
553
|
+
}
|
|
554
|
+
return output;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Take at most `maxBytes` whole PCM16 frames off the front of a stream buffer. Keeping
|
|
559
|
+
* the cut on an even byte keeps every chunk a valid PCM16LE payload.
|
|
560
|
+
* @param {Uint8Array} buffer - pending PCM16LE bytes.
|
|
561
|
+
* @param {number} [maxBytes] - hard chunk ceiling (defaults to the service's 1 MiB cap).
|
|
562
|
+
* @returns {{chunk: Uint8Array, rest: Uint8Array}} one chunk and the remaining bytes.
|
|
563
|
+
*/
|
|
564
|
+
function splitStreamingChunk(buffer, maxBytes) {
|
|
565
|
+
const source = buffer && typeof buffer.subarray === 'function' ? buffer : new Uint8Array(0);
|
|
566
|
+
const limit = Number.isFinite(maxBytes) && maxBytes >= 2 ? Math.floor(maxBytes / 2) * 2 : MAX_STREAM_CHUNK_BYTES;
|
|
567
|
+
if (source.byteLength < 2) return { chunk: new Uint8Array(0), rest: new Uint8Array(source) };
|
|
568
|
+
const size = Math.min(source.byteLength, limit);
|
|
569
|
+
const even = size % 2 === 0 ? size : size - 1;
|
|
570
|
+
if (even < 2) return { chunk: new Uint8Array(0), rest: new Uint8Array(source) };
|
|
571
|
+
return { chunk: source.subarray(0, even), rest: source.subarray(even) };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Keep the live overlay line small: the newest {@link LIVE_TEXT_MAX_CHARS} characters of
|
|
576
|
+
* the cumulative partial (the overlay itself clamps to three visual lines).
|
|
577
|
+
* @param {string} text - cumulative partial.
|
|
578
|
+
* @returns {string} the display text.
|
|
579
|
+
*/
|
|
580
|
+
function trimLiveText(text) {
|
|
581
|
+
const value = typeof text === 'string' ? text : '';
|
|
582
|
+
if (value.length <= LIVE_TEXT_MAX_CHARS) return value;
|
|
583
|
+
return '…' + value.slice(value.length - LIVE_TEXT_MAX_CHARS);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/* ================================================================ */
|
|
587
|
+
/* final-line flight animation (pure planning) */
|
|
588
|
+
/* ================================================================ */
|
|
589
|
+
|
|
590
|
+
/** @returns {{left: number, top: number, width: number, height: number}|null} a usable viewport rect. */
|
|
591
|
+
function usableRect(rect) {
|
|
592
|
+
if (!rect || typeof rect !== 'object') return null;
|
|
593
|
+
const left = Number(rect.left);
|
|
594
|
+
const top = Number(rect.top);
|
|
595
|
+
const width = Number(rect.width);
|
|
596
|
+
const height = Number(rect.height);
|
|
597
|
+
if (!Number.isFinite(left) || !Number.isFinite(top) || !Number.isFinite(width) || !Number.isFinite(height)) return null;
|
|
598
|
+
if (width <= 0 || height <= 0) return null;
|
|
599
|
+
return { left, top, width, height };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Plan the DOM-only flight of the final transcript from the overlay line to the composer
|
|
604
|
+
* target. A `null` plan means "insert immediately": reduced motion, empty text or a
|
|
605
|
+
* missing rect all skip the animation.
|
|
606
|
+
* @param {{text?: string, from?: any, to?: any, reducedMotion?: boolean}} input - flight facts.
|
|
607
|
+
* @returns {{text: string, left: number, top: number, width: number, height: number, dx: number, dy: number, scale: number, durationMs: number, easing: string, transform: string, opacity: number}|null} plan.
|
|
608
|
+
*/
|
|
609
|
+
function planFlight(input) {
|
|
610
|
+
const source = input && typeof input === 'object' ? input : {};
|
|
611
|
+
const text = typeof source.text === 'string' ? source.text.trim() : '';
|
|
612
|
+
if (text === '' || source.reducedMotion === true) return null;
|
|
613
|
+
const from = usableRect(source.from);
|
|
614
|
+
const to = usableRect(source.to);
|
|
615
|
+
if (!from || !to) return null;
|
|
616
|
+
const dx = Math.round((to.left + to.width / 2) - (from.left + from.width / 2));
|
|
617
|
+
const dy = Math.round((to.top + to.height / 2) - (from.top + from.height / 2));
|
|
618
|
+
return {
|
|
619
|
+
text,
|
|
620
|
+
left: from.left,
|
|
621
|
+
top: from.top,
|
|
622
|
+
width: from.width,
|
|
623
|
+
height: from.height,
|
|
624
|
+
dx,
|
|
625
|
+
dy,
|
|
626
|
+
scale: FLIGHT_SCALE,
|
|
627
|
+
durationMs: FLIGHT_MS,
|
|
628
|
+
easing: FLIGHT_EASING,
|
|
629
|
+
transform: 'translate(' + dx + 'px,' + dy + 'px) scale(' + FLIGHT_SCALE + ')',
|
|
630
|
+
opacity: 0,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
261
634
|
/* ================================================================ */
|
|
262
635
|
/* microphone capture */
|
|
263
636
|
/* ================================================================ */
|
|
@@ -271,9 +644,42 @@ window.__ModuleLoader__.load({
|
|
|
271
644
|
}
|
|
272
645
|
}
|
|
273
646
|
|
|
647
|
+
/** @returns {'permission'|'deviceMissing'|'unavailable'} localized kind of a media failure. */
|
|
648
|
+
function classifyMediaError(failure) {
|
|
649
|
+
if (failure instanceof DOMException) {
|
|
650
|
+
if (failure.name === 'NotAllowedError' || failure.name === 'SecurityError') return 'permission';
|
|
651
|
+
if (failure.name === 'NotFoundError' || failure.name === 'OverconstrainedError') return 'deviceMissing';
|
|
652
|
+
}
|
|
653
|
+
return 'unavailable';
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** @returns {any} the platform AudioContext constructor, if any. */
|
|
657
|
+
function audioContextConstructor() {
|
|
658
|
+
if (typeof window === 'undefined') return null;
|
|
659
|
+
if (typeof window.AudioContext === 'function') return window.AudioContext;
|
|
660
|
+
if (typeof window.webkitAudioContext === 'function') return window.webkitAudioContext;
|
|
661
|
+
return null;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* @returns {boolean} whether live PCM capture (AudioWorklet or ScriptProcessor) can run
|
|
666
|
+
* in this browser. Authored as a pure capability check so the capture mode decision is
|
|
667
|
+
* testable without a microphone.
|
|
668
|
+
*/
|
|
669
|
+
function liveCaptureSupported() {
|
|
670
|
+
if (typeof window === 'undefined') return false;
|
|
671
|
+
const hasWorklet = typeof window.AudioWorkletNode === 'function';
|
|
672
|
+
const hasProcessor = typeof window.ScriptProcessorNode === 'function';
|
|
673
|
+
if (!hasWorklet && !hasProcessor) return false;
|
|
674
|
+
if (typeof window.AudioContext !== 'function' && typeof window.webkitAudioContext !== 'function') return false;
|
|
675
|
+
const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
|
|
676
|
+
return Boolean(devices && typeof devices.getUserMedia === 'function');
|
|
677
|
+
}
|
|
678
|
+
|
|
274
679
|
/**
|
|
275
680
|
* One microphone acquisition: MediaRecorder for the payload, an AnalyserNode for
|
|
276
681
|
* the live waveform, and an OfflineAudioContext to resample to 16 kHz mono WAV.
|
|
682
|
+
* The batch path is unchanged from v0.1; streaming uses {@link LivePcmCapture}.
|
|
277
683
|
*/
|
|
278
684
|
class MicrophoneCapture {
|
|
279
685
|
constructor() {
|
|
@@ -305,11 +711,7 @@ window.__ModuleLoader__.load({
|
|
|
305
711
|
video: false,
|
|
306
712
|
});
|
|
307
713
|
} catch (failure) {
|
|
308
|
-
|
|
309
|
-
if (failure.name === 'NotAllowedError' || failure.name === 'SecurityError') throw new CaptureError('permission');
|
|
310
|
-
if (failure.name === 'NotFoundError' || failure.name === 'OverconstrainedError') throw new CaptureError('deviceMissing');
|
|
311
|
-
}
|
|
312
|
-
throw new CaptureError('unavailable');
|
|
714
|
+
throw new CaptureError(classifyMediaError(failure));
|
|
313
715
|
}
|
|
314
716
|
if (this.stopped) {
|
|
315
717
|
stream.getTracks().forEach((track) => track.stop());
|
|
@@ -416,6 +818,179 @@ window.__ModuleLoader__.load({
|
|
|
416
818
|
}
|
|
417
819
|
}
|
|
418
820
|
|
|
821
|
+
/**
|
|
822
|
+
* Live PCM capture for the streaming path: the same microphone acquisition and analyser
|
|
823
|
+
* meter as {@link MicrophoneCapture}, but Float32 frames flow to `onFrames` instead of into
|
|
824
|
+
* a MediaRecorder. AudioWorklet first (inline blob module), ScriptProcessor fallback.
|
|
825
|
+
*/
|
|
826
|
+
class LivePcmCapture {
|
|
827
|
+
constructor() {
|
|
828
|
+
this.stream = undefined;
|
|
829
|
+
this.context = undefined;
|
|
830
|
+
this.analyser = undefined;
|
|
831
|
+
this.worklet = undefined;
|
|
832
|
+
this.processor = undefined;
|
|
833
|
+
this.mute = undefined;
|
|
834
|
+
this.source = undefined;
|
|
835
|
+
this.samples = new Float32Array(256);
|
|
836
|
+
this.stopped = false;
|
|
837
|
+
this.disposal = undefined;
|
|
838
|
+
this.onInterrupted = undefined;
|
|
839
|
+
this.onFrames = undefined;
|
|
840
|
+
this.usingWorklet = false;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Acquire the microphone and start producing Float32 frames.
|
|
845
|
+
* @param {() => void} onInterrupted - fired when the device disappears mid-capture.
|
|
846
|
+
* @param {(samples: Float32Array, sampleRate: number) => void} onFrames - frame sink.
|
|
847
|
+
* @returns {Promise<void>} resolves once frames are flowing.
|
|
848
|
+
*/
|
|
849
|
+
async start(onInterrupted, onFrames) {
|
|
850
|
+
const Context = audioContextConstructor();
|
|
851
|
+
const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
|
|
852
|
+
if (!Context || !devices || typeof devices.getUserMedia !== 'function') throw new CaptureError('unavailable');
|
|
853
|
+
this.onInterrupted = onInterrupted;
|
|
854
|
+
this.onFrames = onFrames;
|
|
855
|
+
let stream;
|
|
856
|
+
try {
|
|
857
|
+
stream = await devices.getUserMedia({
|
|
858
|
+
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
|
|
859
|
+
video: false,
|
|
860
|
+
});
|
|
861
|
+
} catch (failure) {
|
|
862
|
+
throw new CaptureError(classifyMediaError(failure));
|
|
863
|
+
}
|
|
864
|
+
if (this.stopped) {
|
|
865
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
866
|
+
throw new CaptureError('cancelled');
|
|
867
|
+
}
|
|
868
|
+
this.stream = stream;
|
|
869
|
+
try {
|
|
870
|
+
this.context = new Context();
|
|
871
|
+
if (this.context.state === 'suspended') await this.context.resume();
|
|
872
|
+
this.analyser = this.context.createAnalyser();
|
|
873
|
+
this.analyser.fftSize = this.samples.length;
|
|
874
|
+
this.source = this.context.createMediaStreamSource(stream);
|
|
875
|
+
this.source.connect(this.analyser);
|
|
876
|
+
this.mute = this.context.createGain();
|
|
877
|
+
this.mute.gain.value = 0;
|
|
878
|
+
this.mute.connect(this.context.destination);
|
|
879
|
+
for (const track of stream.getTracks()) {
|
|
880
|
+
track.addEventListener('ended', () => {
|
|
881
|
+
if (!this.stopped) this.onInterrupted?.();
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
const emit = (frames) => {
|
|
885
|
+
if (this.stopped || !this.onFrames || !frames) return;
|
|
886
|
+
this.onFrames(frames, this.context ? this.context.sampleRate : LIVE_SAMPLE_RATE);
|
|
887
|
+
};
|
|
888
|
+
const canWorklet = typeof window !== 'undefined'
|
|
889
|
+
&& typeof window.AudioWorkletNode === 'function'
|
|
890
|
+
&& this.context.audioWorklet
|
|
891
|
+
&& typeof this.context.audioWorklet.addModule === 'function'
|
|
892
|
+
&& typeof Blob !== 'undefined'
|
|
893
|
+
&& typeof URL !== 'undefined'
|
|
894
|
+
&& typeof URL.createObjectURL === 'function';
|
|
895
|
+
if (canWorklet) {
|
|
896
|
+
try {
|
|
897
|
+
const objectUrl = URL.createObjectURL(new Blob([LIVE_WORKLET_SOURCE], { type: 'application/javascript' }));
|
|
898
|
+
try {
|
|
899
|
+
await this.context.audioWorklet.addModule(objectUrl);
|
|
900
|
+
} finally {
|
|
901
|
+
URL.revokeObjectURL(objectUrl);
|
|
902
|
+
}
|
|
903
|
+
this.worklet = new window.AudioWorkletNode(this.context, LIVE_WORKLET_NAME);
|
|
904
|
+
this.worklet.port.onmessage = (event) => {
|
|
905
|
+
const frames = event && event.data;
|
|
906
|
+
if (frames && typeof frames.length === 'number') emit(frames);
|
|
907
|
+
};
|
|
908
|
+
this.source.connect(this.worklet);
|
|
909
|
+
this.worklet.connect(this.mute);
|
|
910
|
+
this.usingWorklet = true;
|
|
911
|
+
} catch {
|
|
912
|
+
/* insecure context or a rejected worklet module: reuse the ScriptProcessor below */
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
const canProcessor = typeof window !== 'undefined' && typeof window.ScriptProcessorNode === 'function';
|
|
916
|
+
if (!this.usingWorklet && canProcessor) {
|
|
917
|
+
this.processor = this.context.createScriptProcessor(4096, 1, 1);
|
|
918
|
+
this.processor.onaudioprocess = (event) => {
|
|
919
|
+
const channel = event && event.inputBuffer ? event.inputBuffer.getChannelData(0) : null;
|
|
920
|
+
if (channel) emit(new Float32Array(channel));
|
|
921
|
+
};
|
|
922
|
+
this.source.connect(this.processor);
|
|
923
|
+
this.processor.connect(this.mute);
|
|
924
|
+
}
|
|
925
|
+
if (!this.usingWorklet && !this.processor) throw new CaptureError('unavailable');
|
|
926
|
+
} catch (failure) {
|
|
927
|
+
await this.dispose();
|
|
928
|
+
if (failure instanceof CaptureError) throw failure;
|
|
929
|
+
throw new CaptureError('unavailable');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/** @returns {number} current RMS level in [0, 1]. */
|
|
934
|
+
amplitude() {
|
|
935
|
+
if (!this.analyser) return 0;
|
|
936
|
+
this.analyser.getFloatTimeDomainData(this.samples);
|
|
937
|
+
let sum = 0;
|
|
938
|
+
for (const sample of this.samples) sum += sample * sample;
|
|
939
|
+
return Math.min(1, Math.sqrt(sum / this.samples.length) * 4);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/** @returns {Promise<void>} stop and release the microphone (no payload is built here). */
|
|
943
|
+
async stop() {
|
|
944
|
+
await this.dispose();
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/** @returns {Promise<void>} idempotent resource release. */
|
|
948
|
+
dispose() {
|
|
949
|
+
if (!this.disposal) {
|
|
950
|
+
this.disposal = this.release();
|
|
951
|
+
}
|
|
952
|
+
return this.disposal;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
async release() {
|
|
956
|
+
this.stopped = true;
|
|
957
|
+
try {
|
|
958
|
+
if (this.worklet) {
|
|
959
|
+
this.worklet.port.onmessage = null;
|
|
960
|
+
this.worklet.disconnect();
|
|
961
|
+
}
|
|
962
|
+
} catch {
|
|
963
|
+
/* disconnecting an interrupted node is harmless */
|
|
964
|
+
}
|
|
965
|
+
try {
|
|
966
|
+
if (this.processor) {
|
|
967
|
+
this.processor.onaudioprocess = null;
|
|
968
|
+
this.processor.disconnect();
|
|
969
|
+
}
|
|
970
|
+
} catch {
|
|
971
|
+
/* disconnecting an interrupted node is harmless */
|
|
972
|
+
}
|
|
973
|
+
try { if (this.source) this.source.disconnect(); } catch { /* optional */ }
|
|
974
|
+
try { if (this.analyser) this.analyser.disconnect(); } catch { /* optional */ }
|
|
975
|
+
try { if (this.mute) this.mute.disconnect(); } catch { /* optional */ }
|
|
976
|
+
this.stream?.getTracks().forEach((track) => track.stop());
|
|
977
|
+
this.stream = undefined;
|
|
978
|
+
this.analyser = undefined;
|
|
979
|
+
this.worklet = undefined;
|
|
980
|
+
this.processor = undefined;
|
|
981
|
+
this.mute = undefined;
|
|
982
|
+
this.source = undefined;
|
|
983
|
+
this.onFrames = undefined;
|
|
984
|
+
const context = this.context;
|
|
985
|
+
this.context = undefined;
|
|
986
|
+
try {
|
|
987
|
+
if (context && context.state !== 'closed') await context.close();
|
|
988
|
+
} catch {
|
|
989
|
+
/* closing an already interrupted context is harmless */
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
419
994
|
/* ================================================================ */
|
|
420
995
|
/* service HTTP client */
|
|
421
996
|
/* ================================================================ */
|
|
@@ -428,6 +1003,19 @@ window.__ModuleLoader__.load({
|
|
|
428
1003
|
}
|
|
429
1004
|
}
|
|
430
1005
|
|
|
1006
|
+
/** @returns {Promise<any>} decoded JSON of a service mutation; throws {@link ServiceError} on failure. */
|
|
1007
|
+
async function serviceJson(fetchImpl, path, init) {
|
|
1008
|
+
const response = await fetchImpl(API_BASE + path, init);
|
|
1009
|
+
const payload = await response.json().catch(() => null);
|
|
1010
|
+
if (!response.ok || !payload || payload.ok === false) {
|
|
1011
|
+
const detail = payload && typeof payload.message === 'string' ? payload.message : 'HTTP ' + response.status;
|
|
1012
|
+
const error = new ServiceError(payload && typeof payload.code === 'string' ? payload.code : 'http', detail);
|
|
1013
|
+
error.status = response.status;
|
|
1014
|
+
throw error;
|
|
1015
|
+
}
|
|
1016
|
+
return payload;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
431
1019
|
/** Service request helper shared by the overlay runtime; no credentials are needed. */
|
|
432
1020
|
const service = {
|
|
433
1021
|
stateCache: null,
|
|
@@ -459,19 +1047,13 @@ window.__ModuleLoader__.load({
|
|
|
459
1047
|
|
|
460
1048
|
/** @returns {Promise<any>} decoded JSON of a mutation. */
|
|
461
1049
|
async post(path, body, signal) {
|
|
462
|
-
|
|
1050
|
+
return serviceJson(fetch, path, {
|
|
463
1051
|
method: 'POST',
|
|
464
1052
|
credentials: 'same-origin',
|
|
465
1053
|
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
466
1054
|
body: JSON.stringify(body ?? {}),
|
|
467
1055
|
signal,
|
|
468
1056
|
});
|
|
469
|
-
const payload = await response.json().catch(() => null);
|
|
470
|
-
if (!response.ok || !payload || payload.ok === false) {
|
|
471
|
-
const detail = payload && typeof payload.message === 'string' ? payload.message : `HTTP ${response.status}`;
|
|
472
|
-
throw new ServiceError(payload && typeof payload.code === 'string' ? payload.code : 'http', detail);
|
|
473
|
-
}
|
|
474
|
-
return payload;
|
|
475
1057
|
},
|
|
476
1058
|
|
|
477
1059
|
/**
|
|
@@ -483,22 +1065,189 @@ window.__ModuleLoader__.load({
|
|
|
483
1065
|
*/
|
|
484
1066
|
async transcribe(wav, signal, language) {
|
|
485
1067
|
const query = language ? '?language=' + encodeURIComponent(language) : '';
|
|
486
|
-
|
|
1068
|
+
return serviceJson(fetch, '/transcribe' + query, {
|
|
487
1069
|
method: 'POST',
|
|
488
1070
|
credentials: 'same-origin',
|
|
489
1071
|
headers: { 'content-type': 'audio/wav', accept: 'application/json' },
|
|
490
1072
|
body: wav,
|
|
491
1073
|
signal,
|
|
492
1074
|
});
|
|
493
|
-
const payload = await response.json().catch(() => null);
|
|
494
|
-
if (!response.ok || !payload || payload.ok === false) {
|
|
495
|
-
const detail = payload && typeof payload.message === 'string' ? payload.message : `HTTP ${response.status}`;
|
|
496
|
-
throw new ServiceError(payload && typeof payload.code === 'string' ? payload.code : 'http', detail);
|
|
497
|
-
}
|
|
498
|
-
return payload;
|
|
499
1075
|
},
|
|
500
1076
|
};
|
|
501
1077
|
|
|
1078
|
+
/**
|
|
1079
|
+
* One live streaming relay session owned by the browser. The overlay runtime drives the
|
|
1080
|
+
* ~200 ms cadence through {@link flush}; chunks never overlap (a second flush while one is
|
|
1081
|
+
* in flight reuses the same promise), partials are cumulative and every request carries the
|
|
1082
|
+
* caller's abort signal. `fetchImpl` is injectable so the HTTP contract is unit-testable.
|
|
1083
|
+
*/
|
|
1084
|
+
class StreamingSession {
|
|
1085
|
+
constructor(options) {
|
|
1086
|
+
const settings = options && typeof options === 'object' ? options : {};
|
|
1087
|
+
const providedFetch = typeof settings.fetchImpl === 'function' ? settings.fetchImpl : null;
|
|
1088
|
+
this.fetchImpl = providedFetch || ((url, init) => fetch(url, init));
|
|
1089
|
+
this.providerId = typeof settings.providerId === 'string' && settings.providerId !== '' ? settings.providerId : undefined;
|
|
1090
|
+
this.language = typeof settings.language === 'string' && settings.language !== '' ? settings.language : undefined;
|
|
1091
|
+
this.signal = settings.signal;
|
|
1092
|
+
this.onPartial = typeof settings.onPartial === 'function' ? settings.onPartial : undefined;
|
|
1093
|
+
this.maxChunkBytes = Number.isFinite(settings.maxChunkBytes) && settings.maxChunkBytes >= 2 ? settings.maxChunkBytes : MAX_STREAM_CHUNK_BYTES;
|
|
1094
|
+
this.sessionId = null;
|
|
1095
|
+
this.sampleRate = null;
|
|
1096
|
+
this.pending = new Uint8Array(0);
|
|
1097
|
+
this.opening = null;
|
|
1098
|
+
this.flushing = null;
|
|
1099
|
+
this.failed = false;
|
|
1100
|
+
this.cancelled = false;
|
|
1101
|
+
this.finished = false;
|
|
1102
|
+
this.bytesSent = 0;
|
|
1103
|
+
this.lastPartial = '';
|
|
1104
|
+
this.lastError = null;
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/** @returns {number} bytes captured but not yet accepted by `/stream/chunk`. */
|
|
1108
|
+
get pendingBytes() {
|
|
1109
|
+
return this.pending.length;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/** @returns {Promise<any>} open the relay session once; later calls share the same promise. */
|
|
1113
|
+
start() {
|
|
1114
|
+
if (this.opening === null) this.opening = this.open();
|
|
1115
|
+
return this.opening;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/** @returns {Promise<any>} the actual `/stream/start` request. */
|
|
1119
|
+
async open() {
|
|
1120
|
+
const body = {};
|
|
1121
|
+
if (this.providerId) body.providerId = this.providerId;
|
|
1122
|
+
if (this.language) body.language = this.language;
|
|
1123
|
+
const payload = await serviceJson(this.fetchImpl, '/stream/start', {
|
|
1124
|
+
method: 'POST',
|
|
1125
|
+
credentials: 'same-origin',
|
|
1126
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
1127
|
+
body: JSON.stringify(body),
|
|
1128
|
+
signal: this.signal,
|
|
1129
|
+
});
|
|
1130
|
+
if (!payload || typeof payload.sessionId !== 'string' || payload.sessionId === '') {
|
|
1131
|
+
throw new ServiceError('invalid-session', 'The streaming service returned no session id');
|
|
1132
|
+
}
|
|
1133
|
+
this.sessionId = payload.sessionId;
|
|
1134
|
+
this.sampleRate = Number.isFinite(payload.sampleRate) ? payload.sampleRate : null;
|
|
1135
|
+
return payload;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* Buffer one PCM16LE chunk for the next flush. Buffering starts as soon as capture
|
|
1140
|
+
* starts, so audio spoken while `/stream/start` is still opening (a cold local model can
|
|
1141
|
+
* take a moment to wake) is not lost: once the session id arrives, `flush()` sends it.
|
|
1142
|
+
*/
|
|
1143
|
+
enqueuePcm(pcm) {
|
|
1144
|
+
if (this.failed || this.cancelled || this.finished) return;
|
|
1145
|
+
if (!pcm || pcm.byteLength < 2) return;
|
|
1146
|
+
this.pending = concatBytes([this.pending, pcm]);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/**
|
|
1150
|
+
* Send at most one queued chunk (the runtime calls this every ~200 ms). Never runs two
|
|
1151
|
+
* requests at once: calls made while a chunk is in flight share that request, and newly
|
|
1152
|
+
* buffered bytes wait for the next tick (or for `finish`).
|
|
1153
|
+
* @returns {Promise<string|null>} the partial after this chunk, or null when nothing was sent.
|
|
1154
|
+
*/
|
|
1155
|
+
flush() {
|
|
1156
|
+
if (this.flushing) return this.flushing;
|
|
1157
|
+
if (!this.sessionId || this.failed || this.cancelled || this.finished) return Promise.resolve(null);
|
|
1158
|
+
if (this.pending.length < 2) return Promise.resolve(null);
|
|
1159
|
+
const split = splitStreamingChunk(this.pending, this.maxChunkBytes);
|
|
1160
|
+
if (split.chunk.length < 2) return Promise.resolve(null);
|
|
1161
|
+
this.pending = new Uint8Array(split.rest);
|
|
1162
|
+
const chunk = new Uint8Array(split.chunk);
|
|
1163
|
+
this.flushing = (async () => {
|
|
1164
|
+
try {
|
|
1165
|
+
const payload = await serviceJson(this.fetchImpl, '/stream/chunk?session=' + encodeURIComponent(this.sessionId), {
|
|
1166
|
+
method: 'POST',
|
|
1167
|
+
credentials: 'same-origin',
|
|
1168
|
+
headers: { 'content-type': 'application/octet-stream', accept: 'application/json' },
|
|
1169
|
+
body: chunk,
|
|
1170
|
+
signal: this.signal,
|
|
1171
|
+
});
|
|
1172
|
+
this.bytesSent += chunk.byteLength;
|
|
1173
|
+
const partial = payload && typeof payload.partial === 'string' ? payload.partial : this.lastPartial;
|
|
1174
|
+
this.lastPartial = partial;
|
|
1175
|
+
if (this.onPartial) {
|
|
1176
|
+
try {
|
|
1177
|
+
this.onPartial(partial);
|
|
1178
|
+
} catch {
|
|
1179
|
+
/* a broken listener must not break the relay */
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return partial;
|
|
1183
|
+
} catch (failure) {
|
|
1184
|
+
this.failed = true;
|
|
1185
|
+
this.lastError = failure;
|
|
1186
|
+
throw failure;
|
|
1187
|
+
} finally {
|
|
1188
|
+
this.flushing = null;
|
|
1189
|
+
}
|
|
1190
|
+
})();
|
|
1191
|
+
return this.flushing;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/** @returns {Promise<void>} keep flushing until the buffer is empty. */
|
|
1195
|
+
async flushAll() {
|
|
1196
|
+
while (!this.failed && !this.cancelled && this.pending.length >= 2) {
|
|
1197
|
+
await this.flush();
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
/**
|
|
1202
|
+
* Flush the tail and close the relay session.
|
|
1203
|
+
* @returns {Promise<any>} the final `{ text, audioSeconds, inferenceSeconds }` payload.
|
|
1204
|
+
*/
|
|
1205
|
+
async finish() {
|
|
1206
|
+
if (this.cancelled) throw new ServiceError('cancelled', 'The streaming session was cancelled');
|
|
1207
|
+
// A fast release can reach finish() while `/stream/start` is still in flight; waiting
|
|
1208
|
+
// here keeps the whole take (including the buffered pre-start audio) in the relay.
|
|
1209
|
+
if (this.opening !== null) await this.opening;
|
|
1210
|
+
await this.flushAll();
|
|
1211
|
+
if (this.failed) throw this.lastError || new ServiceError('stream-failed', 'The streaming session failed');
|
|
1212
|
+
if (this.finished) return { ok: true, text: this.lastPartial };
|
|
1213
|
+
if (!this.sessionId) throw new ServiceError('not-started', 'The streaming session was not started');
|
|
1214
|
+
const payload = await serviceJson(this.fetchImpl, '/stream/finish?session=' + encodeURIComponent(this.sessionId), {
|
|
1215
|
+
method: 'POST',
|
|
1216
|
+
credentials: 'same-origin',
|
|
1217
|
+
headers: { accept: 'application/json' },
|
|
1218
|
+
signal: this.signal,
|
|
1219
|
+
});
|
|
1220
|
+
this.finished = true;
|
|
1221
|
+
return payload;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** Abort and dispose the relay session (idempotent, best effort). */
|
|
1225
|
+
async cancel() {
|
|
1226
|
+
if (this.cancelled) return;
|
|
1227
|
+
this.cancelled = true;
|
|
1228
|
+
this.pending = new Uint8Array(0);
|
|
1229
|
+
// Cancelling while `/stream/start` is in flight must still close the host session.
|
|
1230
|
+
if (this.opening !== null) {
|
|
1231
|
+
try {
|
|
1232
|
+
await this.opening;
|
|
1233
|
+
} catch {
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const sessionId = this.sessionId;
|
|
1238
|
+
if (!sessionId || this.finished) return;
|
|
1239
|
+
try {
|
|
1240
|
+
await serviceJson(this.fetchImpl, '/stream/cancel?session=' + encodeURIComponent(sessionId), {
|
|
1241
|
+
method: 'POST',
|
|
1242
|
+
credentials: 'same-origin',
|
|
1243
|
+
headers: { accept: 'application/json' },
|
|
1244
|
+
});
|
|
1245
|
+
} catch {
|
|
1246
|
+
/* the host expires abandoned sessions on its own */
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
502
1251
|
/* ================================================================ */
|
|
503
1252
|
/* overlay + toast rendering */
|
|
504
1253
|
/* ================================================================ */
|
|
@@ -507,6 +1256,7 @@ window.__ModuleLoader__.load({
|
|
|
507
1256
|
function overlayState(phase, armed) {
|
|
508
1257
|
if (phase === 'preparing') return 'preparing';
|
|
509
1258
|
if (phase === 'transcribing') return 'transcribing';
|
|
1259
|
+
if (phase === 'settling') return 'settling';
|
|
510
1260
|
if (phase === 'cancel' || armed) return 'cancel';
|
|
511
1261
|
return 'recording';
|
|
512
1262
|
}
|
|
@@ -562,8 +1312,9 @@ window.__ModuleLoader__.load({
|
|
|
562
1312
|
}
|
|
563
1313
|
|
|
564
1314
|
function Overlay(props) {
|
|
565
|
-
const { phase, armed, progress, statusText, live, getLevel, onCancel, cancelLabel } = props;
|
|
1315
|
+
const { phase, armed, progress, statusText, liveText, live, getLevel, onCancel, cancelLabel } = props;
|
|
566
1316
|
const state = overlayState(phase, armed);
|
|
1317
|
+
const showLive = Boolean(liveText) && (state === 'recording' || state === 'cancel');
|
|
567
1318
|
const layer = h('div', { className: OVERLAY_CLASS, 'data-state': state, role: 'dialog', 'aria-modal': 'true', 'aria-live': 'polite', 'aria-label': statusText },
|
|
568
1319
|
h('div', { className: 'bvi-overlay__blue', 'aria-hidden': 'true' }),
|
|
569
1320
|
h('div', { className: 'bvi-overlay__red', 'aria-hidden': 'true' }),
|
|
@@ -574,6 +1325,8 @@ window.__ModuleLoader__.load({
|
|
|
574
1325
|
h('div', { className: 'bvi-progress__track' }, h('div', { className: 'bvi-progress__fill', style: { width: (progress ?? 0) + '%' } })),
|
|
575
1326
|
typeof progress === 'number' ? h('div', { className: 'bvi-progress__label' }, progress + '%') : null)
|
|
576
1327
|
: null,
|
|
1328
|
+
h('div', { className: 'bvi-live', 'data-visible': showLive ? 'true' : 'false', 'aria-hidden': 'true' },
|
|
1329
|
+
showLive ? h('div', { className: 'bvi-live__text' }, liveText) : null),
|
|
577
1330
|
h(Waveform, { live, getLevel }),
|
|
578
1331
|
onCancel
|
|
579
1332
|
? h('button', { type: 'button', className: 'bvi-cancel', onClick: onCancel }, cancelLabel)
|
|
@@ -594,10 +1347,22 @@ window.__ModuleLoader__.load({
|
|
|
594
1347
|
/* composer glue */
|
|
595
1348
|
/* ================================================================ */
|
|
596
1349
|
|
|
1350
|
+
/** @returns {boolean} whether the platform asks for reduced motion. */
|
|
1351
|
+
function prefersReducedMotion() {
|
|
1352
|
+
try {
|
|
1353
|
+
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
|
|
1354
|
+
const query = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
1355
|
+
return Boolean(query && query.matches === true);
|
|
1356
|
+
} catch {
|
|
1357
|
+
return false;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
|
|
597
1361
|
/**
|
|
598
|
-
* One runtime owns every effect of one composer occurrence: gesture listeners,
|
|
599
|
-
* capture, HTTP, timers
|
|
600
|
-
* overlay and toast; the waveform updates
|
|
1362
|
+
* One runtime owns every effect of one composer occurrence: gesture listeners, keyboard
|
|
1363
|
+
* shortcut, capture (batch or live PCM), HTTP, timers, the final-line flight and the
|
|
1364
|
+
* placeholder hint. React only re-renders the overlay and toast; the waveform updates
|
|
1365
|
+
* through DOM refs and live partials re-render through `setView`.
|
|
601
1366
|
*/
|
|
602
1367
|
function createRuntime(deps) {
|
|
603
1368
|
const { propsRef, setView, setToast } = deps;
|
|
@@ -612,16 +1377,32 @@ window.__ModuleLoader__.load({
|
|
|
612
1377
|
pointerType: 'mouse',
|
|
613
1378
|
span: undefined,
|
|
614
1379
|
recordingStartedAt: 0,
|
|
615
|
-
preferences:
|
|
1380
|
+
preferences: readPreferences(null),
|
|
616
1381
|
limits: readLimits(null),
|
|
1382
|
+
useStreaming: false,
|
|
1383
|
+
guardHintShown: false,
|
|
1384
|
+
releaseAnchorRect: null,
|
|
617
1385
|
};
|
|
618
1386
|
let hold = holdStart();
|
|
619
1387
|
let holdTimer = 0;
|
|
620
1388
|
let capture = null;
|
|
1389
|
+
let live = null;
|
|
1390
|
+
let streamSession = null;
|
|
1391
|
+
let streamTimer = 0;
|
|
1392
|
+
let streamBroken = false;
|
|
1393
|
+
let recordParts = [];
|
|
1394
|
+
let recordBytes = 0;
|
|
1395
|
+
let recordLimit = 0;
|
|
621
1396
|
let abort = null;
|
|
622
1397
|
let preparePoll = 0;
|
|
623
1398
|
let maxTimer = 0;
|
|
624
1399
|
let toastTimer = 0;
|
|
1400
|
+
let guardTimer = 0;
|
|
1401
|
+
let guardCandidate = false;
|
|
1402
|
+
let keyHeld = false;
|
|
1403
|
+
let shortcutCode = '';
|
|
1404
|
+
let liveText = '';
|
|
1405
|
+
let flightCancel = null;
|
|
625
1406
|
let busy = false;
|
|
626
1407
|
let pointerDown = false;
|
|
627
1408
|
let stopRequested = false;
|
|
@@ -652,18 +1433,36 @@ window.__ModuleLoader__.load({
|
|
|
652
1433
|
}
|
|
653
1434
|
|
|
654
1435
|
function releaseView() {
|
|
655
|
-
|
|
1436
|
+
liveText = '';
|
|
1437
|
+
controller.releaseAnchorRect = null;
|
|
1438
|
+
safeSetView({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', liveText: '', onCancel: undefined });
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
/** Merge a new live partial into the overlay without rebuilding the whole view. */
|
|
1442
|
+
function setLiveText(value) {
|
|
1443
|
+
const text = trimLiveText(value);
|
|
1444
|
+
if (text === liveText || controller.disposed) return;
|
|
1445
|
+
liveText = text;
|
|
1446
|
+
try {
|
|
1447
|
+
setView((previous) => ({ ...(previous && typeof previous === 'object' ? previous : {}), liveText }));
|
|
1448
|
+
} catch {
|
|
1449
|
+
/* a stale React setter while unmounting is harmless */
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
function recordingStatusText() {
|
|
1454
|
+
const send = controller.preferences.releaseAction === 'send';
|
|
1455
|
+
if (controller.pointerType === 'keyboard') return t(send ? 'status.sendKeyboard' : 'status.insertKeyboard');
|
|
1456
|
+
return t(send ? 'status.send' : 'status.insert');
|
|
656
1457
|
}
|
|
657
1458
|
|
|
658
1459
|
function overlayFor(phase, armed, progress) {
|
|
659
1460
|
const prefs = controller.preferences;
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
: phase === 'transcribing' ? t('status.transcribing')
|
|
666
|
-
: '';
|
|
1461
|
+
let statusText = '';
|
|
1462
|
+
if (phase === 'cancel' || armed) statusText = t('status.cancel');
|
|
1463
|
+
else if (phase === 'recording') statusText = recordingStatusText();
|
|
1464
|
+
else if (phase === 'preparing') statusText = t('status.preparing');
|
|
1465
|
+
else if (phase === 'transcribing') statusText = t('status.transcribing');
|
|
667
1466
|
const cancelLabel = phase === 'preparing' ? t('cancelPrepare') : phase === 'transcribing' ? t('cancelTranscribe') : '';
|
|
668
1467
|
safeSetView({
|
|
669
1468
|
visible: true,
|
|
@@ -674,6 +1473,7 @@ window.__ModuleLoader__.load({
|
|
|
674
1473
|
statusText,
|
|
675
1474
|
cancelLabel,
|
|
676
1475
|
hint: phase === 'preparing' ? t('preparing.hint') : '',
|
|
1476
|
+
liveText,
|
|
677
1477
|
onCancel: phase === 'preparing' || phase === 'transcribing' ? cancelCurrent : undefined,
|
|
678
1478
|
});
|
|
679
1479
|
}
|
|
@@ -693,6 +1493,36 @@ window.__ModuleLoader__.load({
|
|
|
693
1493
|
}
|
|
694
1494
|
}
|
|
695
1495
|
|
|
1496
|
+
function editorFocused() {
|
|
1497
|
+
const element = editor();
|
|
1498
|
+
return Boolean(element && typeof document !== 'undefined' && document.activeElement === element);
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
function keyboardOpen() {
|
|
1502
|
+
const viewport = typeof window !== 'undefined' ? window.visualViewport : undefined;
|
|
1503
|
+
const viewportHeight = viewport && Number.isFinite(viewport.height) ? viewport.height : undefined;
|
|
1504
|
+
const windowHeight = typeof window !== 'undefined' && Number.isFinite(window.innerHeight) ? window.innerHeight : undefined;
|
|
1505
|
+
return isVirtualKeyboardOpen(viewportHeight, windowHeight);
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function shortcutTargetFlags() {
|
|
1509
|
+
const active = typeof document !== 'undefined' ? document.activeElement : null;
|
|
1510
|
+
const element = editor();
|
|
1511
|
+
const card = controller.card;
|
|
1512
|
+
const body = typeof document !== 'undefined' ? document.body : null;
|
|
1513
|
+
const root = typeof document !== 'undefined' ? document.documentElement : null;
|
|
1514
|
+
return {
|
|
1515
|
+
hasComposer: Boolean(card),
|
|
1516
|
+
activeIsComposer: Boolean(active && element && (active === element || (typeof element.contains === 'function' && element.contains(active)))),
|
|
1517
|
+
activeIsCard: Boolean(active && card && active === card),
|
|
1518
|
+
activeIsBody: !active || active === body || Boolean(root && active === root),
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
function triggerActive() {
|
|
1523
|
+
return pointerDown || keyHeld;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
696
1526
|
function setHolding(on) {
|
|
697
1527
|
if (!controller.card) return;
|
|
698
1528
|
controller.card.classList.toggle(HOLD_CLASS, on);
|
|
@@ -702,6 +1532,8 @@ window.__ModuleLoader__.load({
|
|
|
702
1532
|
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
703
1533
|
if (maxTimer) { clearTimeout(maxTimer); maxTimer = 0; }
|
|
704
1534
|
if (preparePoll) { clearTimeout(preparePoll); preparePoll = 0; }
|
|
1535
|
+
if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
|
|
1536
|
+
if (guardTimer) { clearTimeout(guardTimer); guardTimer = 0; }
|
|
705
1537
|
}
|
|
706
1538
|
|
|
707
1539
|
function abortInFlight() {
|
|
@@ -714,6 +1546,50 @@ window.__ModuleLoader__.load({
|
|
|
714
1546
|
if (current) void current.dispose().catch(() => undefined);
|
|
715
1547
|
}
|
|
716
1548
|
|
|
1549
|
+
function disposeLive() {
|
|
1550
|
+
const current = live;
|
|
1551
|
+
live = null;
|
|
1552
|
+
if (current) void current.dispose().catch(() => undefined);
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
function cancelFlight() {
|
|
1556
|
+
const cancel = flightCancel;
|
|
1557
|
+
flightCancel = null;
|
|
1558
|
+
if (typeof cancel === 'function') cancel();
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/** Release every live-streaming resource (session first so `/stream/cancel` is not aborted). */
|
|
1562
|
+
function resetStreamingTake() {
|
|
1563
|
+
if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
|
|
1564
|
+
const session = streamSession;
|
|
1565
|
+
streamSession = null;
|
|
1566
|
+
if (session) void session.cancel().catch(() => undefined);
|
|
1567
|
+
disposeLive();
|
|
1568
|
+
recordParts = [];
|
|
1569
|
+
recordBytes = 0;
|
|
1570
|
+
recordLimit = 0;
|
|
1571
|
+
streamBroken = false;
|
|
1572
|
+
controller.useStreaming = false;
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
function clearGuardHint() {
|
|
1576
|
+
guardCandidate = false;
|
|
1577
|
+
if (guardTimer) { clearTimeout(guardTimer); guardTimer = 0; }
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/** Show the one-time keyboard guard hint when a touch long-press is deliberately ignored. */
|
|
1581
|
+
function scheduleGuardHint() {
|
|
1582
|
+
if (controller.guardHintShown || guardCandidate || controller.disposed) return;
|
|
1583
|
+
guardCandidate = true;
|
|
1584
|
+
guardTimer = setTimeout(() => {
|
|
1585
|
+
guardTimer = 0;
|
|
1586
|
+
if (!guardCandidate || controller.disposed) return;
|
|
1587
|
+
guardCandidate = false;
|
|
1588
|
+
controller.guardHintShown = true;
|
|
1589
|
+
showToast(t('feedback.keyboardGuard'));
|
|
1590
|
+
}, controller.preferences.holdDelayMs);
|
|
1591
|
+
}
|
|
1592
|
+
|
|
717
1593
|
/** @returns {Promise<void>} cancel the current operation without transcribing. */
|
|
718
1594
|
async function cancelCurrent(options) {
|
|
719
1595
|
const silent = Boolean(options && options.silent);
|
|
@@ -722,9 +1598,14 @@ window.__ModuleLoader__.load({
|
|
|
722
1598
|
controller.disposePrepare();
|
|
723
1599
|
controller.disposePrepare = undefined;
|
|
724
1600
|
}
|
|
1601
|
+
resetStreamingTake();
|
|
725
1602
|
abortInFlight();
|
|
726
1603
|
clearTimers();
|
|
727
1604
|
disposeCapture();
|
|
1605
|
+
cancelFlight();
|
|
1606
|
+
clearGuardHint();
|
|
1607
|
+
keyHeld = false;
|
|
1608
|
+
pointerDown = false;
|
|
728
1609
|
busy = false;
|
|
729
1610
|
controller.finishing = false;
|
|
730
1611
|
stopRequested = false;
|
|
@@ -748,8 +1629,7 @@ window.__ModuleLoader__.load({
|
|
|
748
1629
|
const providerId = state && state.selection ? state.selection.providerId : undefined;
|
|
749
1630
|
const provider = state && Array.isArray(state.providers) ? state.providers.find((entry) => entry.id === providerId) : undefined;
|
|
750
1631
|
if (!provider) {
|
|
751
|
-
|
|
752
|
-
showToast(errorProvider, 'error');
|
|
1632
|
+
showToast(t('feedback.noProvider'), 'error');
|
|
753
1633
|
return false;
|
|
754
1634
|
}
|
|
755
1635
|
const phase = provider.preparation && typeof provider.preparation.phase === 'string' ? provider.preparation.phase : 'ready';
|
|
@@ -811,17 +1691,14 @@ window.__ModuleLoader__.load({
|
|
|
811
1691
|
}, Math.max(1000, seconds * 1000));
|
|
812
1692
|
}
|
|
813
1693
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
setHolding(true);
|
|
823
|
-
try { editor()?.blur?.(); } catch { /* optional */ }
|
|
824
|
-
overlayFor('recording', false, 0);
|
|
1694
|
+
/** @returns {string} the localized microphone failure sentence. */
|
|
1695
|
+
function microphoneFailureMessage(kind, failure) {
|
|
1696
|
+
if (kind === 'permission') return t('feedback.permission');
|
|
1697
|
+
if (kind === 'deviceMissing') return t('feedback.deviceMissing');
|
|
1698
|
+
return t('feedback.microphone', { message: failure && failure.message ? failure.message : String(failure) });
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
async function startBatchCapture() {
|
|
825
1702
|
capture = new MicrophoneCapture();
|
|
826
1703
|
try {
|
|
827
1704
|
await capture.start(() => {
|
|
@@ -833,11 +1710,133 @@ window.__ModuleLoader__.load({
|
|
|
833
1710
|
disposeCapture();
|
|
834
1711
|
setHolding(false);
|
|
835
1712
|
releaseView();
|
|
1713
|
+
if (failure && failure.kind === 'cancelled') return false;
|
|
836
1714
|
const kind = failure && failure.kind ? failure.kind : 'unavailable';
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
return;
|
|
1715
|
+
showToast(microphoneFailureMessage(kind, failure), 'error');
|
|
1716
|
+
return false;
|
|
840
1717
|
}
|
|
1718
|
+
return true;
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
async function startStreamingCapture() {
|
|
1722
|
+
const captureInstance = new LivePcmCapture();
|
|
1723
|
+
live = captureInstance;
|
|
1724
|
+
try {
|
|
1725
|
+
await captureInstance.start(
|
|
1726
|
+
() => {
|
|
1727
|
+
showToast(t('feedback.recordingFailed', { message: 'device interrupted' }), 'error');
|
|
1728
|
+
void cancelCurrent({ silent: true });
|
|
1729
|
+
},
|
|
1730
|
+
handleLiveFrames,
|
|
1731
|
+
);
|
|
1732
|
+
} catch (failure) {
|
|
1733
|
+
busy = false;
|
|
1734
|
+
resetStreamingTake();
|
|
1735
|
+
setHolding(false);
|
|
1736
|
+
releaseView();
|
|
1737
|
+
if (failure && failure.kind === 'cancelled') return false;
|
|
1738
|
+
const kind = failure && failure.kind ? failure.kind : 'unavailable';
|
|
1739
|
+
showToast(microphoneFailureMessage(kind, failure), 'error');
|
|
1740
|
+
return false;
|
|
1741
|
+
}
|
|
1742
|
+
recordParts = [];
|
|
1743
|
+
recordBytes = 0;
|
|
1744
|
+
recordLimit = controller.limits.maxAudioBytes;
|
|
1745
|
+
streamBroken = false;
|
|
1746
|
+
abort = new AbortController();
|
|
1747
|
+
const state = service.stateCache;
|
|
1748
|
+
const providerId = state && state.selection ? state.selection.providerId : undefined;
|
|
1749
|
+
const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
|
|
1750
|
+
const session = new StreamingSession({
|
|
1751
|
+
providerId: typeof providerId === 'string' ? providerId : undefined,
|
|
1752
|
+
language,
|
|
1753
|
+
signal: abort.signal,
|
|
1754
|
+
onPartial: handleStreamingPartial,
|
|
1755
|
+
});
|
|
1756
|
+
streamSession = session;
|
|
1757
|
+
try {
|
|
1758
|
+
await session.start();
|
|
1759
|
+
} catch (failure) {
|
|
1760
|
+
if (streamSession === session) streamSession = null;
|
|
1761
|
+
streamBroken = true;
|
|
1762
|
+
if (isAbort(failure) || controller.disposed) return true;
|
|
1763
|
+
showToast(t('feedback.streamFallback'));
|
|
1764
|
+
return true;
|
|
1765
|
+
}
|
|
1766
|
+
// A release/cancel may land while the session was opening; the finish/cancel path
|
|
1767
|
+
// already owns the teardown, so do not start pumping a relay nobody is listening to.
|
|
1768
|
+
if (controller.disposed || controller.finishing || streamSession !== session) return true;
|
|
1769
|
+
setLiveText(t('status.streaming'));
|
|
1770
|
+
streamTimer = setInterval(() => { void pumpStreamChunk(); }, STREAM_CHUNK_MS);
|
|
1771
|
+
return true;
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
/** Convert one worklet block to 16 kHz PCM16, keep it for the batch fallback and relay it. */
|
|
1775
|
+
function handleLiveFrames(samples, sampleRate) {
|
|
1776
|
+
if (controller.disposed || !live) return;
|
|
1777
|
+
const pcm = floatToPcm16(downsampleTo16k(samples, sampleRate));
|
|
1778
|
+
if (pcm.byteLength === 0) return;
|
|
1779
|
+
if (recordLimit <= 0 || recordBytes + pcm.byteLength <= recordLimit) {
|
|
1780
|
+
recordParts.push(pcm);
|
|
1781
|
+
recordBytes += pcm.byteLength;
|
|
1782
|
+
}
|
|
1783
|
+
if (streamSession && !streamBroken) streamSession.enqueuePcm(pcm);
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
function handleStreamingPartial(partial) {
|
|
1787
|
+
if (controller.disposed || !streamSession) return;
|
|
1788
|
+
const text = typeof partial === 'string' ? partial : '';
|
|
1789
|
+
if (text === '') return;
|
|
1790
|
+
setLiveText(text);
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
async function pumpStreamChunk() {
|
|
1794
|
+
const session = streamSession;
|
|
1795
|
+
if (!session || streamBroken || controller.disposed) return;
|
|
1796
|
+
try {
|
|
1797
|
+
await session.flush();
|
|
1798
|
+
} catch (failure) {
|
|
1799
|
+
handleStreamFailure(failure);
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
/** A broken relay keeps the recording: the take is transcribed as one WAV at release. */
|
|
1804
|
+
function handleStreamFailure(failure) {
|
|
1805
|
+
if (streamBroken || controller.disposed) return;
|
|
1806
|
+
streamBroken = true;
|
|
1807
|
+
if (streamTimer) { clearInterval(streamTimer); streamTimer = 0; }
|
|
1808
|
+
const session = streamSession;
|
|
1809
|
+
streamSession = null;
|
|
1810
|
+
if (session) void session.cancel().catch(() => undefined);
|
|
1811
|
+
setLiveText('');
|
|
1812
|
+
if (!isAbort(failure)) showToast(t('feedback.streamFallback'));
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/** @returns {Promise<string>} transcribe the locally kept PCM16 as one canonical WAV. */
|
|
1816
|
+
async function transcribeRecordedPcm() {
|
|
1817
|
+
const pcm = concatBytes(recordParts, recordBytes);
|
|
1818
|
+
if (pcm.byteLength < 2) throw new ServiceError('empty-audio', 'No audio was captured');
|
|
1819
|
+
const wav = encodeWavFromPcm16(pcm);
|
|
1820
|
+
if (wav.byteLength > controller.limits.maxAudioBytes) throw new ServiceError('too-large', 'Recording too large');
|
|
1821
|
+
const state = service.stateCache;
|
|
1822
|
+
const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
|
|
1823
|
+
const payload = await service.transcribe(wav, abort ? abort.signal : undefined, language);
|
|
1824
|
+
return typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
async function startRecording(useStreaming) {
|
|
1828
|
+
if (busy || controller.disposed) return;
|
|
1829
|
+
const inputActions = propsRef.current && propsRef.current.inputActions;
|
|
1830
|
+
const span = inputActions && typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : undefined;
|
|
1831
|
+
controller.span = span;
|
|
1832
|
+
controller.recordingStartedAt = now();
|
|
1833
|
+
busy = true;
|
|
1834
|
+
stopRequested = false;
|
|
1835
|
+
setHolding(true);
|
|
1836
|
+
try { editor()?.blur?.(); } catch { /* optional */ }
|
|
1837
|
+
overlayFor('recording', false, 0);
|
|
1838
|
+
const started = useStreaming === true ? await startStreamingCapture() : await startBatchCapture();
|
|
1839
|
+
if (!started) return;
|
|
841
1840
|
if (stopRequested) {
|
|
842
1841
|
stopRequested = false;
|
|
843
1842
|
if (now() - controller.recordingStartedAt < MIN_RECORDING_MS) {
|
|
@@ -858,7 +1857,13 @@ window.__ModuleLoader__.load({
|
|
|
858
1857
|
|
|
859
1858
|
async function finish() {
|
|
860
1859
|
if (controller.finishing) return;
|
|
861
|
-
|
|
1860
|
+
const streamingMode = controller.useStreaming === true;
|
|
1861
|
+
if (!streamingMode && !capture) {
|
|
1862
|
+
busy = false;
|
|
1863
|
+
releaseView();
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1866
|
+
if (streamingMode && !live) {
|
|
862
1867
|
busy = false;
|
|
863
1868
|
releaseView();
|
|
864
1869
|
return;
|
|
@@ -868,8 +1873,19 @@ window.__ModuleLoader__.load({
|
|
|
868
1873
|
const inputActions = propsRef.current && propsRef.current.inputActions;
|
|
869
1874
|
const span = controller.span;
|
|
870
1875
|
const startedAt = controller.recordingStartedAt;
|
|
1876
|
+
// Snapshot where the live line sits before the overlay switches to `transcribing`;
|
|
1877
|
+
// the flight clone must start from the text the user was just reading.
|
|
1878
|
+
controller.releaseAnchorRect = overlayAnchorRect();
|
|
871
1879
|
setHolding(false);
|
|
872
1880
|
clearTimers();
|
|
1881
|
+
if (streamingMode) {
|
|
1882
|
+
await finishStreamingTake(generation, startedAt, inputActions, span);
|
|
1883
|
+
return;
|
|
1884
|
+
}
|
|
1885
|
+
await finishBatchTake(generation, startedAt, inputActions, span);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
async function finishBatchTake(generation, startedAt, inputActions, span) {
|
|
873
1889
|
abort = new AbortController();
|
|
874
1890
|
overlayFor('transcribing', false, 0);
|
|
875
1891
|
let bytes;
|
|
@@ -923,6 +1939,7 @@ window.__ModuleLoader__.load({
|
|
|
923
1939
|
} finally {
|
|
924
1940
|
abort = null;
|
|
925
1941
|
}
|
|
1942
|
+
if (controller.disposed || generation !== controller.generation) return;
|
|
926
1943
|
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
927
1944
|
if (text === '') {
|
|
928
1945
|
busy = false;
|
|
@@ -931,7 +1948,82 @@ window.__ModuleLoader__.load({
|
|
|
931
1948
|
showToast(t('feedback.empty'));
|
|
932
1949
|
return;
|
|
933
1950
|
}
|
|
934
|
-
|
|
1951
|
+
await deliverTranscript(text, generation, inputActions, span, false);
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
async function finishStreamingTake(generation, startedAt, inputActions, span) {
|
|
1955
|
+
const session = streamSession;
|
|
1956
|
+
if (now() - startedAt < MIN_RECORDING_MS) {
|
|
1957
|
+
resetStreamingTake();
|
|
1958
|
+
busy = false;
|
|
1959
|
+
controller.finishing = false;
|
|
1960
|
+
releaseView();
|
|
1961
|
+
showToast(t('feedback.tooShort'));
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
overlayFor('transcribing', false, 0);
|
|
1965
|
+
// Cut the microphone now: the relay only needs the frames captured during the hold.
|
|
1966
|
+
disposeLive();
|
|
1967
|
+
let text;
|
|
1968
|
+
try {
|
|
1969
|
+
if (session && !streamBroken) {
|
|
1970
|
+
const payload = await session.finish();
|
|
1971
|
+
text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
1972
|
+
} else {
|
|
1973
|
+
text = await transcribeRecordedPcm();
|
|
1974
|
+
}
|
|
1975
|
+
} catch (failure) {
|
|
1976
|
+
if (isAbort(failure) || controller.disposed || generation !== controller.generation) {
|
|
1977
|
+
resetStreamingTake();
|
|
1978
|
+
if (controller.disposed || generation !== controller.generation) return;
|
|
1979
|
+
busy = false;
|
|
1980
|
+
controller.finishing = false;
|
|
1981
|
+
releaseView();
|
|
1982
|
+
return;
|
|
1983
|
+
}
|
|
1984
|
+
try {
|
|
1985
|
+
text = await transcribeRecordedPcm();
|
|
1986
|
+
} catch (fallbackFailure) {
|
|
1987
|
+
resetStreamingTake();
|
|
1988
|
+
busy = false;
|
|
1989
|
+
controller.finishing = false;
|
|
1990
|
+
releaseView();
|
|
1991
|
+
const code = fallbackFailure && fallbackFailure.code;
|
|
1992
|
+
if (code === 'too-large') showToast(t('feedback.tooLarge'), 'error');
|
|
1993
|
+
else if (code === 'empty-audio') showToast(t('feedback.tooShort'));
|
|
1994
|
+
else showToast(t('feedback.failed', { message: fallbackFailure && fallbackFailure.message ? fallbackFailure.message : String(fallbackFailure) }), 'error');
|
|
1995
|
+
return;
|
|
1996
|
+
}
|
|
1997
|
+
} finally {
|
|
1998
|
+
abort = null;
|
|
1999
|
+
}
|
|
2000
|
+
resetStreamingTake();
|
|
2001
|
+
if (controller.disposed || generation !== controller.generation) return;
|
|
2002
|
+
if (typeof text !== 'string' || text === '') {
|
|
2003
|
+
busy = false;
|
|
2004
|
+
controller.finishing = false;
|
|
2005
|
+
releaseView();
|
|
2006
|
+
showToast(t('feedback.empty'));
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
await deliverTranscript(text, generation, inputActions, span, true);
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
async function deliverTranscript(text, generation, inputActions, span, withFlight) {
|
|
2013
|
+
if (generation !== controller.generation) return;
|
|
2014
|
+
if (withFlight) {
|
|
2015
|
+
const plan = planFlight({
|
|
2016
|
+
text,
|
|
2017
|
+
from: controller.releaseAnchorRect || overlayAnchorRect(),
|
|
2018
|
+
to: composerTargetRect(),
|
|
2019
|
+
reducedMotion: prefersReducedMotion(),
|
|
2020
|
+
});
|
|
2021
|
+
if (plan) {
|
|
2022
|
+
overlayFor('settling', false, 0);
|
|
2023
|
+
const completed = await playFlight(plan);
|
|
2024
|
+
if (!completed || controller.disposed || generation !== controller.generation) return;
|
|
2025
|
+
}
|
|
2026
|
+
}
|
|
935
2027
|
busy = false;
|
|
936
2028
|
controller.finishing = false;
|
|
937
2029
|
releaseView();
|
|
@@ -941,10 +2033,10 @@ window.__ModuleLoader__.load({
|
|
|
941
2033
|
showToast(t('feedback.conflict'), 'error');
|
|
942
2034
|
return;
|
|
943
2035
|
}
|
|
944
|
-
if (
|
|
2036
|
+
if (controller.preferences.releaseAction === 'send') {
|
|
945
2037
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
946
2038
|
try {
|
|
947
|
-
inputActions && typeof inputActions.submit === 'function'
|
|
2039
|
+
if (inputActions && typeof inputActions.submit === 'function') inputActions.submit();
|
|
948
2040
|
} catch (failure) {
|
|
949
2041
|
showToast(t('feedback.failed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
|
|
950
2042
|
}
|
|
@@ -979,34 +2071,121 @@ window.__ModuleLoader__.load({
|
|
|
979
2071
|
return 'failed';
|
|
980
2072
|
}
|
|
981
2073
|
|
|
2074
|
+
function overlayAnchorRect() {
|
|
2075
|
+
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') return null;
|
|
2076
|
+
const selectors = ['.bvi-overlay .bvi-live__text', '.bvi-overlay .bvi-live', '.bvi-overlay .bvi-status'];
|
|
2077
|
+
for (const selector of selectors) {
|
|
2078
|
+
let element;
|
|
2079
|
+
try {
|
|
2080
|
+
element = document.querySelector(selector);
|
|
2081
|
+
} catch {
|
|
2082
|
+
element = null;
|
|
2083
|
+
}
|
|
2084
|
+
if (!element || typeof element.getBoundingClientRect !== 'function') continue;
|
|
2085
|
+
const rect = usableRect(element.getBoundingClientRect());
|
|
2086
|
+
if (rect) return rect;
|
|
2087
|
+
}
|
|
2088
|
+
return null;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
function composerTargetRect() {
|
|
2092
|
+
const element = editor() || controller.card;
|
|
2093
|
+
if (!element || typeof element.getBoundingClientRect !== 'function') return null;
|
|
2094
|
+
return usableRect(element.getBoundingClientRect());
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
/** Pin the final-line clone over the overlay and transform it onto the composer target. */
|
|
2098
|
+
function playFlight(plan) {
|
|
2099
|
+
return new Promise((resolve) => {
|
|
2100
|
+
if (!plan || controller.disposed || typeof document === 'undefined' || !document.body || typeof document.createElement !== 'function') {
|
|
2101
|
+
resolve(false);
|
|
2102
|
+
return;
|
|
2103
|
+
}
|
|
2104
|
+
let node;
|
|
2105
|
+
try {
|
|
2106
|
+
node = document.createElement('div');
|
|
2107
|
+
} catch {
|
|
2108
|
+
resolve(false);
|
|
2109
|
+
return;
|
|
2110
|
+
}
|
|
2111
|
+
node.className = 'bvi-flight';
|
|
2112
|
+
if (typeof node.setAttribute === 'function') node.setAttribute('aria-hidden', 'true');
|
|
2113
|
+
node.textContent = plan.text;
|
|
2114
|
+
node.style.position = 'fixed';
|
|
2115
|
+
node.style.left = plan.left + 'px';
|
|
2116
|
+
node.style.top = plan.top + 'px';
|
|
2117
|
+
node.style.width = plan.width + 'px';
|
|
2118
|
+
node.style.opacity = '1';
|
|
2119
|
+
let settled = false;
|
|
2120
|
+
let timer = 0;
|
|
2121
|
+
const settle = (completed) => {
|
|
2122
|
+
if (settled) return;
|
|
2123
|
+
settled = true;
|
|
2124
|
+
if (timer) { clearTimeout(timer); timer = 0; }
|
|
2125
|
+
flightCancel = null;
|
|
2126
|
+
try {
|
|
2127
|
+
if (typeof node.remove === 'function') node.remove();
|
|
2128
|
+
else if (node.parentNode && typeof node.parentNode.removeChild === 'function') node.parentNode.removeChild(node);
|
|
2129
|
+
} catch {
|
|
2130
|
+
/* the clone may already be detached */
|
|
2131
|
+
}
|
|
2132
|
+
resolve(completed);
|
|
2133
|
+
};
|
|
2134
|
+
const cancel = () => settle(false);
|
|
2135
|
+
flightCancel = cancel;
|
|
2136
|
+
try {
|
|
2137
|
+
document.body.appendChild(node);
|
|
2138
|
+
} catch {
|
|
2139
|
+
settle(false);
|
|
2140
|
+
return;
|
|
2141
|
+
}
|
|
2142
|
+
try { void node.offsetHeight; } catch { /* forcing a reflow is only a transition hint */ }
|
|
2143
|
+
node.style.transition = 'transform ' + plan.durationMs + 'ms ' + plan.easing + ', opacity ' + plan.durationMs + 'ms ' + plan.easing;
|
|
2144
|
+
node.style.transform = plan.transform;
|
|
2145
|
+
node.style.opacity = String(plan.opacity);
|
|
2146
|
+
if (typeof node.addEventListener === 'function') {
|
|
2147
|
+
node.addEventListener('transitionend', () => settle(true), { once: true });
|
|
2148
|
+
}
|
|
2149
|
+
timer = setTimeout(() => settle(true), FLIGHT_TIMEOUT_MS);
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
|
|
982
2153
|
async function beginHoldAttempt() {
|
|
983
2154
|
if (busy || controller.disposed) return;
|
|
984
2155
|
const state = await service.state(false);
|
|
985
2156
|
if (controller.disposed) return;
|
|
986
|
-
if (!
|
|
2157
|
+
if (!triggerActive() || (hold.phase !== 'pressing' && hold.phase !== 'recording')) return;
|
|
987
2158
|
if (!state) {
|
|
988
|
-
showToast(t('feedback.unavailable'), 'error');
|
|
989
2159
|
hold = holdStart();
|
|
2160
|
+
keyHeld = false;
|
|
2161
|
+
showToast(t('feedback.unavailable'), 'error');
|
|
990
2162
|
return;
|
|
991
2163
|
}
|
|
992
2164
|
controller.preferences = readPreferences(state);
|
|
993
2165
|
controller.limits = readLimits(state);
|
|
2166
|
+
controller.useStreaming = captureModeFor({
|
|
2167
|
+
preferences: controller.preferences,
|
|
2168
|
+
state,
|
|
2169
|
+
liveSupported: liveCaptureSupported(),
|
|
2170
|
+
}) === 'stream';
|
|
994
2171
|
if (state.dependency && state.dependency.speechToText === false) {
|
|
995
2172
|
hold = holdStart();
|
|
2173
|
+
keyHeld = false;
|
|
996
2174
|
showToast(t('feedback.missingDependency'), 'error');
|
|
997
2175
|
return;
|
|
998
2176
|
}
|
|
999
2177
|
const ready = await ensureReady(state);
|
|
1000
2178
|
if (!ready || controller.disposed) return;
|
|
1001
|
-
if (!
|
|
2179
|
+
if (!triggerActive()) {
|
|
1002
2180
|
busy = false;
|
|
2181
|
+
setHolding(false);
|
|
1003
2182
|
releaseView();
|
|
1004
2183
|
return;
|
|
1005
2184
|
}
|
|
1006
|
-
await startRecording();
|
|
2185
|
+
await startRecording(controller.useStreaming);
|
|
1007
2186
|
}
|
|
1008
2187
|
|
|
1009
|
-
/* ---------------- gesture listeners ---------------- */
|
|
2188
|
+
/* ---------------- gesture + shortcut listeners ---------------- */
|
|
1010
2189
|
|
|
1011
2190
|
function onPointerDown(event) {
|
|
1012
2191
|
if (controller.disposed || busy) return;
|
|
@@ -1020,11 +2199,17 @@ window.__ModuleLoader__.load({
|
|
|
1020
2199
|
if (typeof window !== 'undefined' && window.getSelection && String(window.getSelection() || '').length > 0) return;
|
|
1021
2200
|
const props = propsRef.current;
|
|
1022
2201
|
if (props && typeof props.getPhase === 'function' && props.getPhase() !== 'plain') return;
|
|
2202
|
+
const pointerType = typeof event.pointerType === 'string' && event.pointerType !== '' ? event.pointerType : 'mouse';
|
|
2203
|
+
if (!shouldStartPointerHold({ pointerType, editorFocused: editorFocused(), keyboardOpen: keyboardOpen() })) {
|
|
2204
|
+
scheduleGuardHint();
|
|
2205
|
+
return;
|
|
2206
|
+
}
|
|
2207
|
+
clearGuardHint();
|
|
1023
2208
|
const pressed = holdStep(hold, { type: 'press', pointerId: event.pointerId, x: event.clientX, y: event.clientY }, controller.preferences);
|
|
1024
2209
|
if (pressed.action === 'ignore') return;
|
|
1025
2210
|
hold = pressed.state;
|
|
1026
2211
|
pointerDown = true;
|
|
1027
|
-
controller.pointerType =
|
|
2212
|
+
controller.pointerType = pointerType;
|
|
1028
2213
|
if (holdTimer) clearTimeout(holdTimer);
|
|
1029
2214
|
holdTimer = setTimeout(() => {
|
|
1030
2215
|
holdTimer = 0;
|
|
@@ -1042,6 +2227,10 @@ window.__ModuleLoader__.load({
|
|
|
1042
2227
|
}
|
|
1043
2228
|
|
|
1044
2229
|
function onPointerMove(event) {
|
|
2230
|
+
if (guardCandidate) {
|
|
2231
|
+
clearGuardHint();
|
|
2232
|
+
return;
|
|
2233
|
+
}
|
|
1045
2234
|
if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
|
|
1046
2235
|
const options = { cancelDistancePx: controller.preferences.cancelDistancePx, moveTolerancePx: MOVE_TOLERANCE_PX };
|
|
1047
2236
|
const next = holdStep(hold, { type: 'move', x: event.clientX, y: event.clientY }, options);
|
|
@@ -1063,6 +2252,10 @@ window.__ModuleLoader__.load({
|
|
|
1063
2252
|
}
|
|
1064
2253
|
|
|
1065
2254
|
function onPointerUp(event) {
|
|
2255
|
+
if (guardCandidate) {
|
|
2256
|
+
clearGuardHint();
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
1066
2259
|
if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
|
|
1067
2260
|
pointerDown = false;
|
|
1068
2261
|
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
@@ -1070,7 +2263,7 @@ window.__ModuleLoader__.load({
|
|
|
1070
2263
|
hold = next.state;
|
|
1071
2264
|
if (next.action === 'finish') {
|
|
1072
2265
|
stopRequested = true;
|
|
1073
|
-
if (capture && busy) void finish();
|
|
2266
|
+
if ((capture || live) && busy) void finish();
|
|
1074
2267
|
return;
|
|
1075
2268
|
}
|
|
1076
2269
|
if (next.action === 'cancel') {
|
|
@@ -1083,6 +2276,7 @@ window.__ModuleLoader__.load({
|
|
|
1083
2276
|
}
|
|
1084
2277
|
|
|
1085
2278
|
function onPointerCancel() {
|
|
2279
|
+
clearGuardHint();
|
|
1086
2280
|
pointerDown = false;
|
|
1087
2281
|
const next = holdStep(hold, { type: 'cancel' });
|
|
1088
2282
|
hold = next.state;
|
|
@@ -1091,12 +2285,68 @@ window.__ModuleLoader__.load({
|
|
|
1091
2285
|
}
|
|
1092
2286
|
|
|
1093
2287
|
function onKeyDown(event) {
|
|
1094
|
-
if (
|
|
1095
|
-
|
|
1096
|
-
|
|
2288
|
+
if (isEscape(event)) {
|
|
2289
|
+
if (keyHeld || (hold.phase === 'pressing' && holdTimer)) {
|
|
2290
|
+
if (typeof event.preventDefault === 'function') event.preventDefault();
|
|
2291
|
+
keyHeld = false;
|
|
2292
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
2293
|
+
const next = holdStep(hold, { type: 'cancel' });
|
|
2294
|
+
hold = next.state;
|
|
2295
|
+
if (next.action === 'cancel') {
|
|
2296
|
+
void cancelCurrent();
|
|
2297
|
+
showToast(t('feedback.cancelled'));
|
|
2298
|
+
} else {
|
|
2299
|
+
setHolding(false);
|
|
2300
|
+
}
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
if (hold.phase === 'recording' || hold.phase === 'cancel' || busy) {
|
|
2304
|
+
if (typeof event.preventDefault === 'function') event.preventDefault();
|
|
2305
|
+
void cancelCurrent({ silent: true });
|
|
2306
|
+
showToast(t('feedback.cancelled'));
|
|
2307
|
+
}
|
|
2308
|
+
return;
|
|
2309
|
+
}
|
|
2310
|
+
if (matchesShortcut(event, controller.preferences.shortcut) !== true) return;
|
|
2311
|
+
if (shortcutAllowed(shortcutTargetFlags()) !== true) return;
|
|
2312
|
+
if (hold.phase !== 'idle' || busy || holdTimer) return;
|
|
2313
|
+
if (typeof event.preventDefault === 'function') event.preventDefault();
|
|
2314
|
+
const pressed = holdStep(hold, { type: 'press', pointerId: 0, x: 0, y: 0 }, controller.preferences);
|
|
2315
|
+
if (pressed.action === 'ignore') return;
|
|
2316
|
+
hold = pressed.state;
|
|
2317
|
+
keyHeld = true;
|
|
2318
|
+
shortcutCode = event.code;
|
|
2319
|
+
controller.pointerType = 'keyboard';
|
|
2320
|
+
holdTimer = setTimeout(() => {
|
|
2321
|
+
holdTimer = 0;
|
|
2322
|
+
if (!keyHeld) return;
|
|
2323
|
+
const next = holdStep(hold, { type: 'hold' });
|
|
2324
|
+
hold = next.state;
|
|
2325
|
+
if (next.action === 'start') {
|
|
2326
|
+
setHolding(true);
|
|
2327
|
+
void beginHoldAttempt();
|
|
2328
|
+
}
|
|
2329
|
+
}, controller.preferences.holdDelayMs);
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
function onKeyUp(event) {
|
|
2333
|
+
if (!keyHeld) return;
|
|
2334
|
+
const code = typeof event.code === 'string' ? event.code : '';
|
|
2335
|
+
if (code !== shortcutCode && !isModifierCode(code)) return;
|
|
2336
|
+
keyHeld = false;
|
|
2337
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
2338
|
+
const next = holdStep(hold, { type: 'release' });
|
|
2339
|
+
hold = next.state;
|
|
2340
|
+
if (next.action === 'finish') {
|
|
2341
|
+
stopRequested = true;
|
|
2342
|
+
if ((capture || live) && busy) void finish();
|
|
2343
|
+
return;
|
|
2344
|
+
}
|
|
2345
|
+
if (next.action === 'cancel') {
|
|
1097
2346
|
void cancelCurrent({ silent: true });
|
|
1098
|
-
|
|
2347
|
+
return;
|
|
1099
2348
|
}
|
|
2349
|
+
if (next.action === 'abort') setHolding(false);
|
|
1100
2350
|
}
|
|
1101
2351
|
|
|
1102
2352
|
function onDocumentHidden() {
|
|
@@ -1106,7 +2356,18 @@ window.__ModuleLoader__.load({
|
|
|
1106
2356
|
}
|
|
1107
2357
|
|
|
1108
2358
|
function onWindowBlur() {
|
|
1109
|
-
if (hold.phase === 'recording' || hold.phase === 'cancel')
|
|
2359
|
+
if (hold.phase === 'recording' || hold.phase === 'cancel') {
|
|
2360
|
+
void cancelCurrent({ silent: true });
|
|
2361
|
+
return;
|
|
2362
|
+
}
|
|
2363
|
+
if (hold.phase === 'pressing') {
|
|
2364
|
+
keyHeld = false;
|
|
2365
|
+
pointerDown = false;
|
|
2366
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
2367
|
+
clearGuardHint();
|
|
2368
|
+
hold = holdStart();
|
|
2369
|
+
setHolding(false);
|
|
2370
|
+
}
|
|
1110
2371
|
}
|
|
1111
2372
|
|
|
1112
2373
|
function onContextMenu(event) {
|
|
@@ -1156,14 +2417,15 @@ window.__ModuleLoader__.load({
|
|
|
1156
2417
|
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: true });
|
|
1157
2418
|
window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: true });
|
|
1158
2419
|
window.addEventListener('blur', onWindowBlur);
|
|
1159
|
-
|
|
2420
|
+
document.addEventListener('keydown', onKeyDown, true);
|
|
2421
|
+
document.addEventListener('keyup', onKeyUp, true);
|
|
1160
2422
|
document.addEventListener('visibilitychange', onDocumentHidden);
|
|
1161
2423
|
controller.hintObserver = new MutationObserver(() => refreshHint());
|
|
1162
2424
|
controller.hintObserver.observe(card, { childList: true, subtree: true, characterData: true });
|
|
1163
2425
|
void service.state(false).then((state) => {
|
|
1164
2426
|
if (controller.disposed) return;
|
|
1165
2427
|
if (state) {
|
|
1166
|
-
controller.preferences =
|
|
2428
|
+
controller.preferences = readPreferences(state);
|
|
1167
2429
|
controller.limits = readLimits(state);
|
|
1168
2430
|
}
|
|
1169
2431
|
hintText = t('composerHint');
|
|
@@ -1174,9 +2436,12 @@ window.__ModuleLoader__.load({
|
|
|
1174
2436
|
function dispose() {
|
|
1175
2437
|
if (controller.disposed) return;
|
|
1176
2438
|
controller.disposed = true;
|
|
1177
|
-
|
|
2439
|
+
resetStreamingTake();
|
|
1178
2440
|
abortInFlight();
|
|
2441
|
+
cancelFlight();
|
|
1179
2442
|
disposeCapture();
|
|
2443
|
+
clearTimers();
|
|
2444
|
+
clearGuardHint();
|
|
1180
2445
|
setHolding(false);
|
|
1181
2446
|
restorePlaceholderHint();
|
|
1182
2447
|
if (controller.hintObserver) controller.hintObserver.disconnect();
|
|
@@ -1189,7 +2454,8 @@ window.__ModuleLoader__.load({
|
|
|
1189
2454
|
window.removeEventListener('pointerup', onPointerUp, { capture: true });
|
|
1190
2455
|
window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
|
|
1191
2456
|
window.removeEventListener('blur', onWindowBlur);
|
|
1192
|
-
|
|
2457
|
+
document.removeEventListener('keydown', onKeyDown, true);
|
|
2458
|
+
document.removeEventListener('keyup', onKeyUp, true);
|
|
1193
2459
|
document.removeEventListener('visibilitychange', onDocumentHidden);
|
|
1194
2460
|
if (toastTimer) { clearTimeout(toastTimer); toastTimer = 0; }
|
|
1195
2461
|
releaseView();
|
|
@@ -1198,7 +2464,7 @@ window.__ModuleLoader__.load({
|
|
|
1198
2464
|
return {
|
|
1199
2465
|
attach,
|
|
1200
2466
|
dispose,
|
|
1201
|
-
getLevel: () => (capture ? capture.amplitude() : 0),
|
|
2467
|
+
getLevel: () => (live ? live.amplitude() : capture ? capture.amplitude() : 0),
|
|
1202
2468
|
};
|
|
1203
2469
|
}
|
|
1204
2470
|
|
|
@@ -1212,7 +2478,7 @@ window.__ModuleLoader__.load({
|
|
|
1212
2478
|
const inputActionsRef = useRef(props.inputActions);
|
|
1213
2479
|
inputActionsRef.current = props.inputActions;
|
|
1214
2480
|
const runtimeRef = useRef(null);
|
|
1215
|
-
const [view, setView] = useState({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', onCancel: undefined });
|
|
2481
|
+
const [view, setView] = useState({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', liveText: '', onCancel: undefined });
|
|
1216
2482
|
const [toast, setToast] = useState(null);
|
|
1217
2483
|
|
|
1218
2484
|
const useInput = props.useInput;
|
|
@@ -1246,6 +2512,7 @@ window.__ModuleLoader__.load({
|
|
|
1246
2512
|
armed: view.armed,
|
|
1247
2513
|
progress: view.progress,
|
|
1248
2514
|
statusText: view.statusText,
|
|
2515
|
+
liveText: view.liveText,
|
|
1249
2516
|
live,
|
|
1250
2517
|
getLevel: () => (runtimeRef.current ? runtimeRef.current.getLevel() : 0),
|
|
1251
2518
|
onCancel: view.onCancel,
|
|
@@ -1274,6 +2541,10 @@ window.__ModuleLoader__.load({
|
|
|
1274
2541
|
'.bvi-overlay[data-state="cancel"] .bvi-overlay__red{opacity:1}',
|
|
1275
2542
|
'.bvi-status{position:absolute;left:50%;top:38%;transform:translate(-50%,-50%);margin:0;padding:0 4vw;max-width:92vw;color:#cfe6ff;font-size:clamp(21px,3.1vw,40px);font-weight:400;letter-spacing:.14em;line-height:1.4;text-align:center;white-space:nowrap;font-family:"Songti SC","Noto Serif SC","Source Han Serif SC","STSong",serif;text-shadow:0 0 22px rgba(120,180,255,.55),0 0 5px rgba(210,235,255,.45);transition:color 160ms ease,text-shadow 160ms ease}',
|
|
1276
2543
|
'.bvi-overlay[data-state="cancel"] .bvi-status{color:#d4525e;text-shadow:0 0 22px rgba(255,80,90,.42),0 0 5px rgba(255,150,155,.35)}',
|
|
2544
|
+
'.bvi-live{position:absolute;left:50%;top:48.5%;transform:translate(-50%,-50%);display:flex;align-items:flex-end;justify-content:center;width:min(86vw,980px);max-height:4.2em;overflow:hidden;pointer-events:none;opacity:0;transition:opacity 180ms ease}',
|
|
2545
|
+
'.bvi-live[data-visible="true"]{opacity:1}',
|
|
2546
|
+
'.bvi-live__text{color:#e8f2ff;font-size:clamp(16px,2.2vw,28px);line-height:1.4;letter-spacing:.02em;text-align:center;white-space:pre-wrap;word-break:break-word;text-shadow:0 0 16px rgba(120,180,255,.5),0 0 4px rgba(210,235,255,.4)}',
|
|
2547
|
+
'.bvi-overlay[data-state="cancel"] .bvi-live__text{color:#ffd9dc;text-shadow:0 0 16px rgba(255,90,100,.45)}',
|
|
1277
2548
|
'.bvi-wave{position:absolute;left:50%;top:61.5%;transform:translate(-50%,-50%);display:flex;align-items:center;justify-content:center;gap:9px;height:48px;width:min(72vw,900px);mask-image:linear-gradient(90deg,transparent 0%,#000 9%,#000 91%,transparent 100%);-webkit-mask-image:linear-gradient(90deg,transparent 0%,#000 9%,#000 91%,transparent 100%)}',
|
|
1278
2549
|
'.bvi-wave[data-live="false"]{opacity:.9}',
|
|
1279
2550
|
'.bvi-bar{display:block;width:4px;height:12px;border-radius:2px;background:#dde8ff;box-shadow:0 0 9px rgba(160,205,255,.85);transition:height 90ms linear,background 160ms ease,box-shadow 160ms ease;flex:0 0 auto}',
|
|
@@ -1282,6 +2553,8 @@ window.__ModuleLoader__.load({
|
|
|
1282
2553
|
'.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:bvi-pulse 1.15s ease-in-out infinite}',
|
|
1283
2554
|
'.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n){animation-delay:.18s}',
|
|
1284
2555
|
'.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n+1){animation-delay:.36s}',
|
|
2556
|
+
'.bvi-overlay[data-state="settling"] .bvi-status,.bvi-overlay[data-state="settling"] .bvi-live,.bvi-overlay[data-state="settling"] .bvi-wave{opacity:0}',
|
|
2557
|
+
'.bvi-flight{position:fixed;z-index:9002;pointer-events:none;transform-origin:50% 50%;color:#eaf3ff;font-size:clamp(17px,2.6vw,32px);line-height:1.4;letter-spacing:.02em;text-align:center;white-space:pre-wrap;word-break:break-word;text-shadow:0 0 18px rgba(120,180,255,.55),0 0 5px rgba(210,235,255,.45);transition:transform 360ms cubic-bezier(.2,.8,.2,1),opacity 360ms cubic-bezier(.2,.8,.2,1);will-change:transform,opacity}',
|
|
1285
2558
|
'@keyframes bvi-pulse{0%,100%{opacity:.5}50%{opacity:1}}',
|
|
1286
2559
|
'.bvi-progress{position:absolute;left:50%;top:calc(38% + 46px);transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;gap:8px;width:min(360px,64vw)}',
|
|
1287
2560
|
'.bvi-progress__track{width:100%;height:3px;border-radius:2px;background:rgba(207,230,255,.22);overflow:hidden}',
|
|
@@ -1291,8 +2564,8 @@ window.__ModuleLoader__.load({
|
|
|
1291
2564
|
'.bvi-overlay[data-state="cancel"] .bvi-cancel{border-color:rgba(255,160,165,.35);color:rgba(255,205,208,.92)}',
|
|
1292
2565
|
'.bvi-toast{position:fixed;left:50%;bottom:calc(env(safe-area-inset-bottom,0px) + 108px);transform:translateX(-50%);z-index:9001;pointer-events:none;max-width:min(520px,86vw);padding:10px 16px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,#242426);color:var(--dsw-alias-label-primary,#f2f2f2);border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.14));box-shadow:0 10px 30px rgba(0,0,0,.35);font-size:13px;line-height:1.5;text-align:center}',
|
|
1293
2566
|
'.bvi-toast[data-tone="error"]{border-color:var(--dsw-alias-state-error-primary,#e5484d);color:var(--dsw-alias-label-primary,#f2f2f2)}',
|
|
1294
|
-
'@media (max-width:520px){.bvi-wave{gap:6px;width:84vw}.bvi-bar{width:3px}.bvi-status{letter-spacing:.1em}.bvi-cancel{bottom:14vh}}',
|
|
1295
|
-
'@media (prefers-reduced-motion:reduce){.bvi-overlay__blue,.bvi-overlay__red,.bvi-status,.bvi-bar{transition:none}.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:none}}',
|
|
2567
|
+
'@media (max-width:520px){.bvi-wave{gap:6px;width:84vw}.bvi-bar{width:3px}.bvi-status{letter-spacing:.1em}.bvi-cancel{bottom:14vh}.bvi-live{width:90vw;top:48%}.bvi-live__text{font-size:15px}}',
|
|
2568
|
+
'@media (prefers-reduced-motion:reduce){.bvi-overlay__blue,.bvi-overlay__red,.bvi-status,.bvi-bar{transition:none}.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:none}.bvi-live,.bvi-flight{transition:none}}',
|
|
1296
2569
|
].join('\n');
|
|
1297
2570
|
|
|
1298
2571
|
function mountCss() {
|
|
@@ -1339,11 +2612,14 @@ window.__ModuleLoader__.load({
|
|
|
1339
2612
|
exports.inject = ['slots', 'locale'];
|
|
1340
2613
|
exports.apply = apply;
|
|
1341
2614
|
exports.__bviTest = {
|
|
2615
|
+
// gesture state machine
|
|
1342
2616
|
holdStart,
|
|
1343
2617
|
holdStep,
|
|
2618
|
+
// presentation helpers
|
|
1344
2619
|
barCountFor,
|
|
1345
2620
|
barHeight,
|
|
1346
2621
|
encodeWav,
|
|
2622
|
+
encodeWavFromPcm16,
|
|
1347
2623
|
readPreferences,
|
|
1348
2624
|
readLimits,
|
|
1349
2625
|
overlayState,
|
|
@@ -1358,6 +2634,35 @@ window.__ModuleLoader__.load({
|
|
|
1358
2634
|
setTestRuntime(ctx) { appCtx = ctx; },
|
|
1359
2635
|
HoldToTalkOverlay,
|
|
1360
2636
|
createRuntime,
|
|
2637
|
+
// v0.2: trigger guards, shortcut, streaming capture/session, flight animation
|
|
2638
|
+
DEFAULT_SHORTCUT,
|
|
2639
|
+
normalizeShortcut,
|
|
2640
|
+
shortcutComboAllowed,
|
|
2641
|
+
matchesShortcut,
|
|
2642
|
+
shortcutAllowed,
|
|
2643
|
+
isModifierCode,
|
|
2644
|
+
isVirtualKeyboardOpen,
|
|
2645
|
+
shouldStartPointerHold,
|
|
2646
|
+
captureModeFor,
|
|
2647
|
+
liveCaptureSupported,
|
|
2648
|
+
resampleFloat32,
|
|
2649
|
+
downsampleTo16k,
|
|
2650
|
+
floatToPcm16,
|
|
2651
|
+
pcm16ToFloat32,
|
|
2652
|
+
concatBytes,
|
|
2653
|
+
splitStreamingChunk,
|
|
2654
|
+
trimLiveText,
|
|
2655
|
+
usableRect,
|
|
2656
|
+
planFlight,
|
|
2657
|
+
prefersReducedMotion,
|
|
2658
|
+
StreamingSession,
|
|
2659
|
+
LIVE_SAMPLE_RATE,
|
|
2660
|
+
STREAM_CHUNK_MS,
|
|
2661
|
+
MAX_STREAM_CHUNK_BYTES,
|
|
2662
|
+
LIVE_TEXT_MAX_CHARS,
|
|
2663
|
+
FLIGHT_MS,
|
|
2664
|
+
FLIGHT_SCALE,
|
|
2665
|
+
FLIGHT_EASING,
|
|
1361
2666
|
};
|
|
1362
2667
|
return module.exports;
|
|
1363
2668
|
},
|