@ds-hu/dsh-bvi-input 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/NOTICE +31 -0
- package/icon.svg +6 -0
- package/lib/client.js +1364 -0
- package/lib/index.js +2 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +47 -4
- package/README.md +0 -3
package/lib/client.js
ADDED
|
@@ -0,0 +1,1364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Better voice input — browser half.
|
|
3
|
+
*
|
|
4
|
+
* One long-press gesture on the composer card starts speech capture, a full-screen
|
|
5
|
+
* overlay reproduces the DeepSeek App recording surface, and the transcript is written
|
|
6
|
+
* back through the composer's public `inputActions`. Audio and policy come from our own
|
|
7
|
+
* service component over same-origin HTTP; no Harness client package is imported.
|
|
8
|
+
*/
|
|
9
|
+
window.__ModuleLoader__.load({
|
|
10
|
+
id: '@ds-hu/dsh-bvi-input',
|
|
11
|
+
factory: (require) => {
|
|
12
|
+
var module = { exports: {} };
|
|
13
|
+
var exports = module.exports;
|
|
14
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
15
|
+
|
|
16
|
+
const react = require('react');
|
|
17
|
+
const reactDom = require('react-dom');
|
|
18
|
+
const { useCallback, useEffect, useRef, useState } = react;
|
|
19
|
+
const h = react.createElement;
|
|
20
|
+
const createPortal = reactDom.createPortal;
|
|
21
|
+
|
|
22
|
+
const NS = 'betterVoiceInput';
|
|
23
|
+
const API_BASE = '/api/better-voice-input';
|
|
24
|
+
const CSS_ID = '@ds-hu/dsh-bvi-input';
|
|
25
|
+
const OVERLAY_CLASS = 'bvi-overlay';
|
|
26
|
+
const HOLD_CLASS = 'bvi-holding';
|
|
27
|
+
const HINT_ATTR = 'data-bvi-hint';
|
|
28
|
+
|
|
29
|
+
/** Gesture defaults mirror the service preference defaults in the host contract. */
|
|
30
|
+
const DEFAULTS = {
|
|
31
|
+
releaseAction: 'insert',
|
|
32
|
+
holdDelayMs: 280,
|
|
33
|
+
cancelDistancePx: 72,
|
|
34
|
+
hintDismissed: false,
|
|
35
|
+
};
|
|
36
|
+
const MOVE_TOLERANCE_PX = 8;
|
|
37
|
+
const CANCEL_RELEASE_RATIO = 0.6;
|
|
38
|
+
const MIN_RECORDING_MS = 300;
|
|
39
|
+
const STATE_TTL_MS = 4_000;
|
|
40
|
+
const PREPARE_POLL_MS = 800;
|
|
41
|
+
const TOAST_MS = 5_200;
|
|
42
|
+
const WAVE_PITCH_PX = 22;
|
|
43
|
+
const WAVE_MAX_BARS = 56;
|
|
44
|
+
|
|
45
|
+
/* ================================================================ */
|
|
46
|
+
/* dictionaries */
|
|
47
|
+
/* ================================================================ */
|
|
48
|
+
|
|
49
|
+
const zh = {
|
|
50
|
+
'status.insert': '松手插入,上滑取消',
|
|
51
|
+
'status.send': '松手发送,上滑取消',
|
|
52
|
+
'status.cancel': '松手取消',
|
|
53
|
+
'status.preparing': '正在准备模型…',
|
|
54
|
+
'status.transcribing': '正在转写…',
|
|
55
|
+
'status.tooShort': '说话时间太短',
|
|
56
|
+
'preparing.hint': '首次使用需要下载,本轮结束后会自动开始识别',
|
|
57
|
+
'preparing.percent': '已完成 {percent}%',
|
|
58
|
+
'cancelPrepare': '取消准备',
|
|
59
|
+
'cancelTranscribe': '取消转写',
|
|
60
|
+
'composerHint': '发消息或按住说话',
|
|
61
|
+
'feedback.unavailable': '语音服务不可用:请确认「更好的语音输入」插件已启用。',
|
|
62
|
+
'feedback.missingDependency': '语音转写尚未就绪:请先启用官方「语音输入」插件。',
|
|
63
|
+
'feedback.noProvider': '尚未选择语音识别服务:请到插件设置里选择。',
|
|
64
|
+
'feedback.empty': '没有识别到内容,请再说一次。',
|
|
65
|
+
'feedback.tooLarge': '录音太长了,请缩短后重试。',
|
|
66
|
+
'feedback.tooShort': '说话时间太短,请按住多说一会儿。',
|
|
67
|
+
'feedback.failed': '转写失败:{message}',
|
|
68
|
+
'feedback.conflict': '草稿已更新,识别结果没有插入。',
|
|
69
|
+
'feedback.permission': '麦克风权限被拒绝:请在浏览器地址栏允许后重试。',
|
|
70
|
+
'feedback.deviceMissing': '没有找到可用的麦克风。',
|
|
71
|
+
'feedback.microphone': '无法使用麦克风:{message}',
|
|
72
|
+
'feedback.prepareFailed': '模型准备失败:{message}',
|
|
73
|
+
'feedback.cancelled': '已取消。',
|
|
74
|
+
'feedback.ready': '本地模型已就绪,现在可以按住输入框说话。',
|
|
75
|
+
'feedback.preparing': '本地模型正在准备,请稍候…',
|
|
76
|
+
'feedback.recordingFailed': '录音失败:{message}',
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const en = {
|
|
80
|
+
'status.insert': 'Release to insert · slide up to cancel',
|
|
81
|
+
'status.send': 'Release to send · slide up to cancel',
|
|
82
|
+
'status.cancel': 'Release to cancel',
|
|
83
|
+
'status.preparing': 'Preparing model…',
|
|
84
|
+
'status.transcribing': 'Transcribing…',
|
|
85
|
+
'status.tooShort': 'Too short',
|
|
86
|
+
'preparing.hint': 'The first run downloads the model; recognition starts afterwards',
|
|
87
|
+
'preparing.percent': '{percent}% complete',
|
|
88
|
+
'cancelPrepare': 'Cancel preparation',
|
|
89
|
+
'cancelTranscribe': 'Cancel transcription',
|
|
90
|
+
'composerHint': 'Message, or hold to talk',
|
|
91
|
+
'feedback.unavailable': 'Voice service unavailable: enable the “Better voice input” plugin.',
|
|
92
|
+
'feedback.missingDependency': 'Speech-to-text is offline: enable the official Voice input plugin first.',
|
|
93
|
+
'feedback.noProvider': 'No speech service selected yet: choose one in the plugin settings.',
|
|
94
|
+
'feedback.empty': 'No speech detected. Please try again.',
|
|
95
|
+
'feedback.tooLarge': 'The recording is too long. Please shorten it and retry.',
|
|
96
|
+
'feedback.tooShort': 'Recording too short. Hold and speak a little longer.',
|
|
97
|
+
'feedback.failed': 'Transcription failed: {message}',
|
|
98
|
+
'feedback.conflict': 'The draft changed, so the transcript was not inserted.',
|
|
99
|
+
'feedback.permission': 'Microphone permission denied. Allow it in the address bar and retry.',
|
|
100
|
+
'feedback.deviceMissing': 'No microphone was found.',
|
|
101
|
+
'feedback.microphone': 'The microphone is unavailable: {message}',
|
|
102
|
+
'feedback.prepareFailed': 'Model preparation failed: {message}',
|
|
103
|
+
'feedback.cancelled': 'Cancelled.',
|
|
104
|
+
'feedback.ready': 'The local model is ready. Hold the composer to talk.',
|
|
105
|
+
'feedback.preparing': 'The local model is still preparing…',
|
|
106
|
+
'feedback.recordingFailed': 'Recording failed: {message}',
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/* ================================================================ */
|
|
110
|
+
/* small utilities */
|
|
111
|
+
/* ================================================================ */
|
|
112
|
+
|
|
113
|
+
function clamp(value, min, max) {
|
|
114
|
+
if (!Number.isFinite(value)) return min;
|
|
115
|
+
if (value < min) return min;
|
|
116
|
+
if (value > max) return max;
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isAbort(failure) {
|
|
121
|
+
return Boolean(failure && (failure.name === 'AbortError' || failure.code === 20));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function now() {
|
|
125
|
+
return typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function clampInteger(value, min, max, fallback) {
|
|
129
|
+
return Number.isInteger(value) ? clamp(value, min, max) : fallback;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** @returns {typeof DEFAULTS} normalized preferences from the service state. */
|
|
133
|
+
function readPreferences(state) {
|
|
134
|
+
const preferences = state && typeof state === 'object' && state.preferences && typeof state.preferences === 'object' ? state.preferences : {};
|
|
135
|
+
return {
|
|
136
|
+
releaseAction: preferences.releaseAction === 'send' ? 'send' : 'insert',
|
|
137
|
+
holdDelayMs: clampInteger(preferences.holdDelayMs, 150, 1000, DEFAULTS.holdDelayMs),
|
|
138
|
+
cancelDistancePx: clampInteger(preferences.cancelDistancePx, 40, 200, DEFAULTS.cancelDistancePx),
|
|
139
|
+
hintDismissed: preferences.hintDismissed === true,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** @returns {{maxAudioBytes: number, maxDurationSeconds: number}} service limits with safe fallbacks. */
|
|
144
|
+
function readLimits(state) {
|
|
145
|
+
const limits = state && typeof state === 'object' && state.limits && typeof state.limits === 'object' ? state.limits : {};
|
|
146
|
+
return {
|
|
147
|
+
maxAudioBytes: clampInteger(limits.maxAudioBytes, 64 * 1024, 16 * 1024 * 1024, 4 * 1024 * 1024),
|
|
148
|
+
maxDurationSeconds: clampInteger(limits.maxDurationSeconds, 5, 600, 120),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Hold-gesture state machine. Pure so the gesture rules are unit-testable without
|
|
154
|
+
* a browser: `event.time` is only carried for diagnostics, callers own the timer.
|
|
155
|
+
*
|
|
156
|
+
* Phases: idle -> pressing -> recording <-> cancel -> (finished | cancelled)
|
|
157
|
+
*/
|
|
158
|
+
function holdStart() {
|
|
159
|
+
return { phase: 'idle', pointerId: null, startX: 0, startY: 0, armed: false };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Advance the gesture state.
|
|
164
|
+
* @param {ReturnType<typeof holdStart>} state - current state.
|
|
165
|
+
* @param {{ type: string, pointerId?: number, x?: number, y?: number }} event - input event.
|
|
166
|
+
* @param {{ cancelDistancePx: number, moveTolerancePx?: number }} options - thresholds.
|
|
167
|
+
* @returns {{ state: ReturnType<typeof holdStart>, action: string }} next state and side effect.
|
|
168
|
+
*/
|
|
169
|
+
function holdStep(state, event, options) {
|
|
170
|
+
const tolerance = options && Number.isFinite(options.moveTolerancePx) ? options.moveTolerancePx : MOVE_TOLERANCE_PX;
|
|
171
|
+
const cancelDistance = options && Number.isFinite(options.cancelDistancePx) ? options.cancelDistancePx : DEFAULTS.cancelDistancePx;
|
|
172
|
+
switch (event.type) {
|
|
173
|
+
case 'press': {
|
|
174
|
+
if (state.phase !== 'idle') return { state, action: 'ignore' };
|
|
175
|
+
return { state: { phase: 'pressing', pointerId: event.pointerId, startX: event.x, startY: event.y, armed: false }, action: 'none' };
|
|
176
|
+
}
|
|
177
|
+
case 'hold': {
|
|
178
|
+
if (state.phase !== 'pressing') return { state, action: 'ignore' };
|
|
179
|
+
return { state: { ...state, phase: 'recording', armed: false }, action: 'start' };
|
|
180
|
+
}
|
|
181
|
+
case 'move': {
|
|
182
|
+
if (state.phase === 'pressing') {
|
|
183
|
+
const moved = Math.hypot(event.x - state.startX, event.y - state.startY);
|
|
184
|
+
if (moved > tolerance) return { state: holdStart(), action: 'abort' };
|
|
185
|
+
return { state, action: 'none' };
|
|
186
|
+
}
|
|
187
|
+
if (state.phase === 'recording' || state.phase === 'cancel') {
|
|
188
|
+
const risen = state.startY - event.y;
|
|
189
|
+
if (state.phase === 'recording' && risen >= cancelDistance) return { state: { ...state, phase: 'cancel', armed: true }, action: 'arm' };
|
|
190
|
+
if (state.phase === 'cancel' && risen < cancelDistance * CANCEL_RELEASE_RATIO) return { state: { ...state, phase: 'recording', armed: false }, action: 'disarm' };
|
|
191
|
+
return { state, action: 'none' };
|
|
192
|
+
}
|
|
193
|
+
return { state, action: 'ignore' };
|
|
194
|
+
}
|
|
195
|
+
case 'release': {
|
|
196
|
+
if (state.phase === 'recording') return { state: holdStart(), action: 'finish' };
|
|
197
|
+
if (state.phase === 'cancel') return { state: holdStart(), action: 'cancel' };
|
|
198
|
+
if (state.phase === 'pressing') return { state: holdStart(), action: 'abort' };
|
|
199
|
+
return { state, action: 'ignore' };
|
|
200
|
+
}
|
|
201
|
+
case 'cancel': {
|
|
202
|
+
if (state.phase === 'recording' || state.phase === 'cancel') return { state: holdStart(), action: 'cancel' };
|
|
203
|
+
if (state.phase === 'pressing') return { state: holdStart(), action: 'abort' };
|
|
204
|
+
return { state, action: 'ignore' };
|
|
205
|
+
}
|
|
206
|
+
default:
|
|
207
|
+
return { state, action: 'ignore' };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** @returns {boolean} whether the keyboard event should cancel the current overlay. */
|
|
212
|
+
function isEscape(event) {
|
|
213
|
+
return Boolean(event && event.key === 'Escape');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** @returns {number} waveform bar count for a viewport width. */
|
|
217
|
+
function barCountFor(viewportWidth) {
|
|
218
|
+
const width = Number.isFinite(viewportWidth) && viewportWidth > 0 ? viewportWidth : 1024;
|
|
219
|
+
return clampInteger(Math.round(width / WAVE_PITCH_PX), 16, WAVE_MAX_BARS, 40);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** @returns {number} bar height in px for one level sample. */
|
|
223
|
+
function barHeight(level) {
|
|
224
|
+
const safe = Number.isFinite(level) ? clamp(level, 0, 1) : 0;
|
|
225
|
+
return Math.round(6 + safe * 34);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Encode mono float samples as a canonical 16 kHz PCM16 WAV.
|
|
230
|
+
* @param {Float32Array} samples - mono samples in [-1, 1].
|
|
231
|
+
* @param {number} sampleRate - sample rate of `samples` (must already be 16000 for uploads).
|
|
232
|
+
* @returns {Uint8Array} complete little-endian WAV bytes.
|
|
233
|
+
*/
|
|
234
|
+
function encodeWav(samples, sampleRate) {
|
|
235
|
+
const rate = Number.isFinite(sampleRate) && sampleRate > 0 ? Math.round(sampleRate) : 16000;
|
|
236
|
+
const bytes = new Uint8Array(44 + samples.length * 2);
|
|
237
|
+
const view = new DataView(bytes.buffer);
|
|
238
|
+
const text = (at, value) => {
|
|
239
|
+
for (let index = 0; index < value.length; index += 1) bytes[at + index] = value.charCodeAt(index);
|
|
240
|
+
};
|
|
241
|
+
text(0, 'RIFF');
|
|
242
|
+
view.setUint32(4, bytes.length - 8, true);
|
|
243
|
+
text(8, 'WAVE');
|
|
244
|
+
text(12, 'fmt ');
|
|
245
|
+
view.setUint32(16, 16, true);
|
|
246
|
+
view.setUint16(20, 1, true);
|
|
247
|
+
view.setUint16(22, 1, true);
|
|
248
|
+
view.setUint32(24, rate, true);
|
|
249
|
+
view.setUint32(28, rate * 2, true);
|
|
250
|
+
view.setUint16(32, 2, true);
|
|
251
|
+
view.setUint16(34, 16, true);
|
|
252
|
+
text(36, 'data');
|
|
253
|
+
view.setUint32(40, samples.length * 2, true);
|
|
254
|
+
for (let index = 0; index < samples.length; index += 1) {
|
|
255
|
+
const sample = clamp(samples[index], -1, 1);
|
|
256
|
+
view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true);
|
|
257
|
+
}
|
|
258
|
+
return bytes;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/* ================================================================ */
|
|
262
|
+
/* microphone capture */
|
|
263
|
+
/* ================================================================ */
|
|
264
|
+
|
|
265
|
+
/** Capture failures whose kind is localized by the caller. */
|
|
266
|
+
class CaptureError extends Error {
|
|
267
|
+
constructor(kind) {
|
|
268
|
+
super(kind);
|
|
269
|
+
this.name = 'CaptureError';
|
|
270
|
+
this.kind = kind;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* One microphone acquisition: MediaRecorder for the payload, an AnalyserNode for
|
|
276
|
+
* the live waveform, and an OfflineAudioContext to resample to 16 kHz mono WAV.
|
|
277
|
+
*/
|
|
278
|
+
class MicrophoneCapture {
|
|
279
|
+
constructor() {
|
|
280
|
+
this.stream = undefined;
|
|
281
|
+
this.recorder = undefined;
|
|
282
|
+
this.context = undefined;
|
|
283
|
+
this.analyser = undefined;
|
|
284
|
+
this.chunks = [];
|
|
285
|
+
this.samples = new Float32Array(256);
|
|
286
|
+
this.stopped = false;
|
|
287
|
+
this.disposal = undefined;
|
|
288
|
+
this.onInterrupted = undefined;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Acquire the microphone and start recording.
|
|
293
|
+
* @param {() => void} onInterrupted - fired when the device disappears mid-capture.
|
|
294
|
+
* @returns {Promise<void>} resolves once frames are flowing.
|
|
295
|
+
*/
|
|
296
|
+
async start(onInterrupted) {
|
|
297
|
+
if (typeof MediaRecorder === 'undefined') throw new CaptureError('unavailable');
|
|
298
|
+
const devices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;
|
|
299
|
+
if (!devices || typeof devices.getUserMedia !== 'function') throw new CaptureError('unavailable');
|
|
300
|
+
this.onInterrupted = onInterrupted;
|
|
301
|
+
let stream;
|
|
302
|
+
try {
|
|
303
|
+
stream = await devices.getUserMedia({
|
|
304
|
+
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
|
|
305
|
+
video: false,
|
|
306
|
+
});
|
|
307
|
+
} catch (failure) {
|
|
308
|
+
if (failure instanceof DOMException) {
|
|
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');
|
|
313
|
+
}
|
|
314
|
+
if (this.stopped) {
|
|
315
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
316
|
+
throw new CaptureError('cancelled');
|
|
317
|
+
}
|
|
318
|
+
this.stream = stream;
|
|
319
|
+
try {
|
|
320
|
+
this.context = new AudioContext();
|
|
321
|
+
if (this.context.state === 'suspended') await this.context.resume();
|
|
322
|
+
this.analyser = this.context.createAnalyser();
|
|
323
|
+
this.analyser.fftSize = this.samples.length;
|
|
324
|
+
this.context.createMediaStreamSource(stream).connect(this.analyser);
|
|
325
|
+
for (const track of stream.getTracks()) {
|
|
326
|
+
track.addEventListener('ended', () => {
|
|
327
|
+
if (!this.stopped) this.onInterrupted?.();
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
this.recorder = new MediaRecorder(stream);
|
|
331
|
+
this.recorder.ondataavailable = (event) => {
|
|
332
|
+
if (!this.stopped && event.data && event.data.size > 0) this.chunks.push(event.data);
|
|
333
|
+
};
|
|
334
|
+
this.recorder.onerror = () => {
|
|
335
|
+
if (!this.stopped) this.onInterrupted?.();
|
|
336
|
+
};
|
|
337
|
+
this.recorder.start();
|
|
338
|
+
} catch (failure) {
|
|
339
|
+
await this.dispose();
|
|
340
|
+
if (failure instanceof CaptureError) throw failure;
|
|
341
|
+
throw new CaptureError('unavailable');
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** @returns {number} current RMS level in [0, 1]. */
|
|
346
|
+
amplitude() {
|
|
347
|
+
if (!this.analyser) return 0;
|
|
348
|
+
this.analyser.getFloatTimeDomainData(this.samples);
|
|
349
|
+
let sum = 0;
|
|
350
|
+
for (const sample of this.samples) sum += sample * sample;
|
|
351
|
+
return Math.min(1, Math.sqrt(sum / this.samples.length) * 4);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Stop capture and return canonical 16 kHz mono PCM16 WAV bytes.
|
|
356
|
+
* @param {number} maxDurationSeconds - hard truncation limit.
|
|
357
|
+
* @returns {Promise<Uint8Array>} the complete WAV payload.
|
|
358
|
+
*/
|
|
359
|
+
async stop(maxDurationSeconds) {
|
|
360
|
+
const recorder = this.recorder;
|
|
361
|
+
const context = this.context;
|
|
362
|
+
if (!recorder || !context || recorder.state !== 'recording') {
|
|
363
|
+
await this.dispose();
|
|
364
|
+
throw new CaptureError('empty');
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
await new Promise((resolve, reject) => {
|
|
368
|
+
recorder.onstop = () => resolve();
|
|
369
|
+
recorder.onerror = () => reject(new CaptureError('empty'));
|
|
370
|
+
recorder.stop();
|
|
371
|
+
});
|
|
372
|
+
this.stream?.getTracks().forEach((track) => track.stop());
|
|
373
|
+
const blob = new Blob(this.chunks, { type: recorder.mimeType });
|
|
374
|
+
if (blob.size === 0) throw new CaptureError('empty');
|
|
375
|
+
const decoded = await context.decodeAudioData(await blob.arrayBuffer());
|
|
376
|
+
const seconds = Math.max(0.05, Math.min(decoded.duration, maxDurationSeconds));
|
|
377
|
+
const frames = Math.max(1, Math.floor(seconds * 16000));
|
|
378
|
+
const offline = new OfflineAudioContext(1, frames, 16000);
|
|
379
|
+
const source = offline.createBufferSource();
|
|
380
|
+
source.buffer = decoded;
|
|
381
|
+
source.connect(offline.destination);
|
|
382
|
+
source.start();
|
|
383
|
+
const rendered = await offline.startRendering();
|
|
384
|
+
return encodeWav(rendered.getChannelData(0), 16000);
|
|
385
|
+
} finally {
|
|
386
|
+
await this.dispose();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** @returns {Promise<void>} idempotent resource release. */
|
|
391
|
+
dispose() {
|
|
392
|
+
if (!this.disposal) {
|
|
393
|
+
this.disposal = this.release();
|
|
394
|
+
}
|
|
395
|
+
return this.disposal;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async release() {
|
|
399
|
+
this.stopped = true;
|
|
400
|
+
try {
|
|
401
|
+
if (this.recorder && this.recorder.state === 'recording') this.recorder.stop();
|
|
402
|
+
} catch {
|
|
403
|
+
/* a stopped recorder is already silent */
|
|
404
|
+
}
|
|
405
|
+
this.stream?.getTracks().forEach((track) => track.stop());
|
|
406
|
+
this.stream = undefined;
|
|
407
|
+
this.analyser = undefined;
|
|
408
|
+
const context = this.context;
|
|
409
|
+
this.context = undefined;
|
|
410
|
+
this.chunks = [];
|
|
411
|
+
try {
|
|
412
|
+
if (context && context.state !== 'closed') await context.close();
|
|
413
|
+
} catch {
|
|
414
|
+
/* closing an already interrupted context is harmless */
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/* ================================================================ */
|
|
420
|
+
/* service HTTP client */
|
|
421
|
+
/* ================================================================ */
|
|
422
|
+
|
|
423
|
+
class ServiceError extends Error {
|
|
424
|
+
constructor(code, message) {
|
|
425
|
+
super(message || code);
|
|
426
|
+
this.name = 'ServiceError';
|
|
427
|
+
this.code = code;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Service request helper shared by the overlay runtime; no credentials are needed. */
|
|
432
|
+
const service = {
|
|
433
|
+
stateCache: null,
|
|
434
|
+
stateAt: 0,
|
|
435
|
+
pending: null,
|
|
436
|
+
inflight: null,
|
|
437
|
+
|
|
438
|
+
/** @returns {Promise<any|null>} a fresh-enough `/state` payload, or null when unreachable. */
|
|
439
|
+
async state(force) {
|
|
440
|
+
const fresh = this.stateCache !== null && now() - this.stateAt < STATE_TTL_MS;
|
|
441
|
+
if (fresh && !force) return this.stateCache;
|
|
442
|
+
if (this.inflight) return this.inflight;
|
|
443
|
+
this.inflight = (async () => {
|
|
444
|
+
try {
|
|
445
|
+
const response = await fetch(API_BASE + '/state', { credentials: 'same-origin', headers: { accept: 'application/json' } });
|
|
446
|
+
if (!response.ok) return null;
|
|
447
|
+
const payload = await response.json();
|
|
448
|
+
this.stateCache = payload;
|
|
449
|
+
this.stateAt = now();
|
|
450
|
+
return payload;
|
|
451
|
+
} catch {
|
|
452
|
+
return null;
|
|
453
|
+
} finally {
|
|
454
|
+
this.inflight = null;
|
|
455
|
+
}
|
|
456
|
+
})();
|
|
457
|
+
return this.inflight;
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
/** @returns {Promise<any>} decoded JSON of a mutation. */
|
|
461
|
+
async post(path, body, signal) {
|
|
462
|
+
const response = await fetch(API_BASE + path, {
|
|
463
|
+
method: 'POST',
|
|
464
|
+
credentials: 'same-origin',
|
|
465
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
466
|
+
body: JSON.stringify(body ?? {}),
|
|
467
|
+
signal,
|
|
468
|
+
});
|
|
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
|
+
},
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Send one WAV payload for recognition.
|
|
479
|
+
* @param {Uint8Array} wav - canonical WAV bytes.
|
|
480
|
+
* @param {AbortSignal} signal - caller cancellation.
|
|
481
|
+
* @param {string} language - selected recognition language.
|
|
482
|
+
* @returns {Promise<any>} decoded transcript response.
|
|
483
|
+
*/
|
|
484
|
+
async transcribe(wav, signal, language) {
|
|
485
|
+
const query = language ? '?language=' + encodeURIComponent(language) : '';
|
|
486
|
+
const response = await fetch(API_BASE + '/transcribe' + query, {
|
|
487
|
+
method: 'POST',
|
|
488
|
+
credentials: 'same-origin',
|
|
489
|
+
headers: { 'content-type': 'audio/wav', accept: 'application/json' },
|
|
490
|
+
body: wav,
|
|
491
|
+
signal,
|
|
492
|
+
});
|
|
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
|
+
},
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
/* ================================================================ */
|
|
503
|
+
/* overlay + toast rendering */
|
|
504
|
+
/* ================================================================ */
|
|
505
|
+
|
|
506
|
+
/** @returns {string} the overlay sub-state used for styling. */
|
|
507
|
+
function overlayState(phase, armed) {
|
|
508
|
+
if (phase === 'preparing') return 'preparing';
|
|
509
|
+
if (phase === 'transcribing') return 'transcribing';
|
|
510
|
+
if (phase === 'cancel' || armed) return 'cancel';
|
|
511
|
+
return 'recording';
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function Waveform(props) {
|
|
515
|
+
const { live, getLevel } = props;
|
|
516
|
+
const barsRef = useRef([]);
|
|
517
|
+
const historyRef = useRef(new Float32Array(WAVE_MAX_BARS));
|
|
518
|
+
const [count, setCount] = useState(() => barCountFor(typeof innerWidth === 'number' ? innerWidth : 1024));
|
|
519
|
+
|
|
520
|
+
useEffect(() => {
|
|
521
|
+
const onResize = () => setCount(barCountFor(typeof innerWidth === 'number' ? innerWidth : 1024));
|
|
522
|
+
window.addEventListener('resize', onResize, { passive: true });
|
|
523
|
+
return () => window.removeEventListener('resize', onResize);
|
|
524
|
+
}, []);
|
|
525
|
+
|
|
526
|
+
useEffect(() => {
|
|
527
|
+
if (!live) {
|
|
528
|
+
for (let index = 0; index < barsRef.current.length; index += 1) {
|
|
529
|
+
const element = barsRef.current[index];
|
|
530
|
+
if (element) element.style.height = barHeight(0.06 + (index % 5) * 0.03) + 'px';
|
|
531
|
+
}
|
|
532
|
+
return undefined;
|
|
533
|
+
}
|
|
534
|
+
let frame = 0;
|
|
535
|
+
const step = () => {
|
|
536
|
+
const level = typeof getLevel === 'function' ? clamp(getLevel(), 0, 1) * 9 : 0;
|
|
537
|
+
const history = historyRef.current;
|
|
538
|
+
for (let index = history.length - 1; index > 0; index -= 1) history[index] = history[index - 1];
|
|
539
|
+
history[0] = level;
|
|
540
|
+
const visible = Math.min(count, history.length);
|
|
541
|
+
for (let index = 0; index < barsRef.current.length; index += 1) {
|
|
542
|
+
const element = barsRef.current[index];
|
|
543
|
+
if (!element) continue;
|
|
544
|
+
const sample = index < visible ? history[Math.floor(index * (history.length / Math.max(1, count)))] : 0;
|
|
545
|
+
element.style.height = barHeight(Math.min(1, sample * 1.2)) + 'px';
|
|
546
|
+
}
|
|
547
|
+
frame = requestAnimationFrame(step);
|
|
548
|
+
};
|
|
549
|
+
frame = requestAnimationFrame(step);
|
|
550
|
+
return () => cancelAnimationFrame(frame);
|
|
551
|
+
}, [live, count, getLevel]);
|
|
552
|
+
|
|
553
|
+
const bars = [];
|
|
554
|
+
for (let index = 0; index < count; index += 1) {
|
|
555
|
+
bars.push(h('span', {
|
|
556
|
+
key: index,
|
|
557
|
+
className: 'bvi-bar',
|
|
558
|
+
ref: (element) => { barsRef.current[index] = element; },
|
|
559
|
+
}));
|
|
560
|
+
}
|
|
561
|
+
return h('div', { className: 'bvi-wave', 'data-live': live ? 'true' : 'false', 'aria-hidden': 'true' }, bars);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function Overlay(props) {
|
|
565
|
+
const { phase, armed, progress, statusText, live, getLevel, onCancel, cancelLabel } = props;
|
|
566
|
+
const state = overlayState(phase, armed);
|
|
567
|
+
const layer = h('div', { className: OVERLAY_CLASS, 'data-state': state, role: 'dialog', 'aria-modal': 'true', 'aria-live': 'polite', 'aria-label': statusText },
|
|
568
|
+
h('div', { className: 'bvi-overlay__blue', 'aria-hidden': 'true' }),
|
|
569
|
+
h('div', { className: 'bvi-overlay__red', 'aria-hidden': 'true' }),
|
|
570
|
+
h('div', { className: 'bvi-overlay__vignette', 'aria-hidden': 'true' }),
|
|
571
|
+
h('div', { className: 'bvi-status' }, statusText),
|
|
572
|
+
phase === 'preparing'
|
|
573
|
+
? h('div', { className: 'bvi-progress', 'aria-hidden': 'true' },
|
|
574
|
+
h('div', { className: 'bvi-progress__track' }, h('div', { className: 'bvi-progress__fill', style: { width: (progress ?? 0) + '%' } })),
|
|
575
|
+
typeof progress === 'number' ? h('div', { className: 'bvi-progress__label' }, progress + '%') : null)
|
|
576
|
+
: null,
|
|
577
|
+
h(Waveform, { live, getLevel }),
|
|
578
|
+
onCancel
|
|
579
|
+
? h('button', { type: 'button', className: 'bvi-cancel', onClick: onCancel }, cancelLabel)
|
|
580
|
+
: null);
|
|
581
|
+
return createPortal(layer, document.body);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function ToastLayer(props) {
|
|
585
|
+
const { toast } = props;
|
|
586
|
+
if (!toast) return null;
|
|
587
|
+
return createPortal(
|
|
588
|
+
h('div', { className: 'bvi-toast', 'data-tone': toast.tone || 'info', role: 'status', 'aria-live': 'polite' }, toast.text),
|
|
589
|
+
document.body,
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/* ================================================================ */
|
|
594
|
+
/* composer glue */
|
|
595
|
+
/* ================================================================ */
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* One runtime owns every effect of one composer occurrence: gesture listeners,
|
|
599
|
+
* capture, HTTP, timers and the placeholder hint. React only re-renders the
|
|
600
|
+
* overlay and toast; the waveform updates through DOM refs.
|
|
601
|
+
*/
|
|
602
|
+
function createRuntime(deps) {
|
|
603
|
+
const { propsRef, setView, setToast } = deps;
|
|
604
|
+
const controller = {
|
|
605
|
+
card: null,
|
|
606
|
+
anchor: null,
|
|
607
|
+
hintObserver: null,
|
|
608
|
+
placeholderOriginal: null,
|
|
609
|
+
disposed: false,
|
|
610
|
+
finishing: false,
|
|
611
|
+
generation: 0,
|
|
612
|
+
pointerType: 'mouse',
|
|
613
|
+
span: undefined,
|
|
614
|
+
recordingStartedAt: 0,
|
|
615
|
+
preferences: { ...DEFAULTS },
|
|
616
|
+
limits: readLimits(null),
|
|
617
|
+
};
|
|
618
|
+
let hold = holdStart();
|
|
619
|
+
let holdTimer = 0;
|
|
620
|
+
let capture = null;
|
|
621
|
+
let abort = null;
|
|
622
|
+
let preparePoll = 0;
|
|
623
|
+
let maxTimer = 0;
|
|
624
|
+
let toastTimer = 0;
|
|
625
|
+
let busy = false;
|
|
626
|
+
let pointerDown = false;
|
|
627
|
+
let stopRequested = false;
|
|
628
|
+
let hintText = '';
|
|
629
|
+
|
|
630
|
+
const translate = () => (propsRef.current && typeof propsRef.current.t === 'function' ? propsRef.current.t : (key) => key);
|
|
631
|
+
const t = (key, params) => {
|
|
632
|
+
let text = String(translate()(key));
|
|
633
|
+
if (params) {
|
|
634
|
+
for (const name of Object.keys(params)) text = text.split('{' + name + '}').join(String(params[name]));
|
|
635
|
+
}
|
|
636
|
+
if (text === key) text = String((zh[key] ?? en[key] ?? key));
|
|
637
|
+
return text;
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
function safeSetView(next) {
|
|
641
|
+
if (!controller.disposed) setView(next);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function showToast(text, tone) {
|
|
645
|
+
if (controller.disposed) return;
|
|
646
|
+
if (toastTimer) clearTimeout(toastTimer);
|
|
647
|
+
setToast({ text, tone: tone || 'info', at: Date.now() });
|
|
648
|
+
toastTimer = setTimeout(() => {
|
|
649
|
+
toastTimer = 0;
|
|
650
|
+
setToast(null);
|
|
651
|
+
}, TOAST_MS);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function releaseView() {
|
|
655
|
+
safeSetView({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '' });
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function overlayFor(phase, armed, progress) {
|
|
659
|
+
const prefs = controller.preferences;
|
|
660
|
+
const statusText = phase === 'cancel' || armed
|
|
661
|
+
? t('status.cancel')
|
|
662
|
+
: phase === 'recording'
|
|
663
|
+
? t(prefs.releaseAction === 'send' ? 'status.send' : 'status.insert')
|
|
664
|
+
: phase === 'preparing' ? t('status.preparing')
|
|
665
|
+
: phase === 'transcribing' ? t('status.transcribing')
|
|
666
|
+
: '';
|
|
667
|
+
const cancelLabel = phase === 'preparing' ? t('cancelPrepare') : phase === 'transcribing' ? t('cancelTranscribe') : '';
|
|
668
|
+
safeSetView({
|
|
669
|
+
visible: true,
|
|
670
|
+
phase: phase === 'cancel' ? 'cancel' : phase,
|
|
671
|
+
armed: Boolean(armed),
|
|
672
|
+
progress: typeof progress === 'number' ? Math.round(progress) : null,
|
|
673
|
+
action: prefs.releaseAction,
|
|
674
|
+
statusText,
|
|
675
|
+
cancelLabel,
|
|
676
|
+
hint: phase === 'preparing' ? t('preparing.hint') : '',
|
|
677
|
+
onCancel: phase === 'preparing' || phase === 'transcribing' ? cancelCurrent : undefined,
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
function editor() {
|
|
682
|
+
return controller.card ? controller.card.querySelector('[data-composer-input]') : null;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function focusEditor() {
|
|
686
|
+
const element = editor();
|
|
687
|
+
if (element && typeof element.focus === 'function') {
|
|
688
|
+
try {
|
|
689
|
+
element.focus({ preventScroll: true });
|
|
690
|
+
} catch {
|
|
691
|
+
/* focusing is best effort */
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function setHolding(on) {
|
|
697
|
+
if (!controller.card) return;
|
|
698
|
+
controller.card.classList.toggle(HOLD_CLASS, on);
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function clearTimers() {
|
|
702
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
703
|
+
if (maxTimer) { clearTimeout(maxTimer); maxTimer = 0; }
|
|
704
|
+
if (preparePoll) { clearTimeout(preparePoll); preparePoll = 0; }
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function abortInFlight() {
|
|
708
|
+
if (abort) { abort.abort(); abort = null; }
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function disposeCapture() {
|
|
712
|
+
const current = capture;
|
|
713
|
+
capture = null;
|
|
714
|
+
if (current) void current.dispose().catch(() => undefined);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** @returns {Promise<void>} cancel the current operation without transcribing. */
|
|
718
|
+
async function cancelCurrent(options) {
|
|
719
|
+
const silent = Boolean(options && options.silent);
|
|
720
|
+
controller.generation += 1;
|
|
721
|
+
if (typeof controller.disposePrepare === 'function') {
|
|
722
|
+
controller.disposePrepare();
|
|
723
|
+
controller.disposePrepare = undefined;
|
|
724
|
+
}
|
|
725
|
+
abortInFlight();
|
|
726
|
+
clearTimers();
|
|
727
|
+
disposeCapture();
|
|
728
|
+
busy = false;
|
|
729
|
+
controller.finishing = false;
|
|
730
|
+
stopRequested = false;
|
|
731
|
+
hold = holdStart();
|
|
732
|
+
setHolding(false);
|
|
733
|
+
releaseView();
|
|
734
|
+
if (!silent) {
|
|
735
|
+
const state = service.stateCache;
|
|
736
|
+
const providerId = state && state.selection ? state.selection.providerId : undefined;
|
|
737
|
+
if (state && providerId && state.local && Array.isArray(state.local)) {
|
|
738
|
+
const local = state.local.find((entry) => entry.id === providerId);
|
|
739
|
+
if (local && local.install && local.install.phase === 'preparing') {
|
|
740
|
+
void service.post('/cancel-preparation', { providerId }).catch(() => undefined);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** @returns {Promise<boolean>} whether the selected provider can recognize right now. */
|
|
747
|
+
async function ensureReady(state) {
|
|
748
|
+
const providerId = state && state.selection ? state.selection.providerId : undefined;
|
|
749
|
+
const provider = state && Array.isArray(state.providers) ? state.providers.find((entry) => entry.id === providerId) : undefined;
|
|
750
|
+
if (!provider) {
|
|
751
|
+
const errorProvider = t('feedback.noProvider');
|
|
752
|
+
showToast(errorProvider, 'error');
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
const phase = provider.preparation && typeof provider.preparation.phase === 'string' ? provider.preparation.phase : 'ready';
|
|
756
|
+
if (phase === 'ready' || phase === 'standby' || phase === 'waking') return true;
|
|
757
|
+
if (phase === 'preparing') {
|
|
758
|
+
showToast(t('feedback.preparing'));
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
busy = true;
|
|
762
|
+
overlayFor('preparing', false, 0);
|
|
763
|
+
try {
|
|
764
|
+
await service.post('/prepare', { providerId });
|
|
765
|
+
} catch (failure) {
|
|
766
|
+
busy = false;
|
|
767
|
+
releaseView();
|
|
768
|
+
showToast(t('feedback.prepareFailed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
return await new Promise((resolve) => {
|
|
772
|
+
const poll = async () => {
|
|
773
|
+
preparePoll = 0;
|
|
774
|
+
const latest = await service.state(true);
|
|
775
|
+
const current = latest && Array.isArray(latest.providers) ? latest.providers.find((entry) => entry.id === providerId) : undefined;
|
|
776
|
+
const currentPhase = current && current.preparation ? current.preparation.phase : 'ready';
|
|
777
|
+
const progress = current && current.preparation && Number.isFinite(current.preparation.progress) ? current.preparation.progress : 0;
|
|
778
|
+
if (currentPhase === 'ready' || currentPhase === 'standby' || currentPhase === 'waking') {
|
|
779
|
+
busy = false;
|
|
780
|
+
releaseView();
|
|
781
|
+
showToast(t('feedback.ready'));
|
|
782
|
+
resolve(true);
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
if (currentPhase === 'failed' || currentPhase === 'cancelled') {
|
|
786
|
+
busy = false;
|
|
787
|
+
releaseView();
|
|
788
|
+
showToast(t('feedback.prepareFailed', { message: (current.preparation && current.preparation.error) || currentPhase }), 'error');
|
|
789
|
+
resolve(false);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
overlayFor('preparing', false, progress);
|
|
793
|
+
preparePoll = setTimeout(() => { void poll(); }, PREPARE_POLL_MS);
|
|
794
|
+
};
|
|
795
|
+
void poll();
|
|
796
|
+
controller.disposePrepare = () => {
|
|
797
|
+
clearTimeout(preparePoll);
|
|
798
|
+
preparePoll = 0;
|
|
799
|
+
busy = false;
|
|
800
|
+
resolve(false);
|
|
801
|
+
};
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function startMaxTimer() {
|
|
806
|
+
if (maxTimer) clearTimeout(maxTimer);
|
|
807
|
+
const seconds = controller.limits.maxDurationSeconds;
|
|
808
|
+
maxTimer = setTimeout(() => {
|
|
809
|
+
maxTimer = 0;
|
|
810
|
+
if (hold.phase === 'recording' || hold.phase === 'cancel') void finish();
|
|
811
|
+
}, Math.max(1000, seconds * 1000));
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
async function startRecording() {
|
|
815
|
+
if (busy || controller.disposed) return;
|
|
816
|
+
const inputActions = propsRef.current && propsRef.current.inputActions;
|
|
817
|
+
const span = inputActions && typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : undefined;
|
|
818
|
+
controller.span = span;
|
|
819
|
+
controller.recordingStartedAt = now();
|
|
820
|
+
busy = true;
|
|
821
|
+
stopRequested = false;
|
|
822
|
+
setHolding(true);
|
|
823
|
+
try { editor()?.blur?.(); } catch { /* optional */ }
|
|
824
|
+
overlayFor('recording', false, 0);
|
|
825
|
+
capture = new MicrophoneCapture();
|
|
826
|
+
try {
|
|
827
|
+
await capture.start(() => {
|
|
828
|
+
showToast(t('feedback.recordingFailed', { message: 'device interrupted' }), 'error');
|
|
829
|
+
void cancelCurrent({ silent: true });
|
|
830
|
+
});
|
|
831
|
+
} catch (failure) {
|
|
832
|
+
busy = false;
|
|
833
|
+
disposeCapture();
|
|
834
|
+
setHolding(false);
|
|
835
|
+
releaseView();
|
|
836
|
+
const kind = failure && failure.kind ? failure.kind : 'unavailable';
|
|
837
|
+
const message = kind === 'permission' ? t('feedback.permission') : kind === 'deviceMissing' ? t('feedback.deviceMissing') : t('feedback.microphone', { message: failure && failure.message ? failure.message : String(failure) });
|
|
838
|
+
showToast(message, 'error');
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (stopRequested) {
|
|
842
|
+
stopRequested = false;
|
|
843
|
+
if (now() - controller.recordingStartedAt < MIN_RECORDING_MS) {
|
|
844
|
+
void cancelCurrent({ silent: true });
|
|
845
|
+
showToast(t('feedback.tooShort'));
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
void finish();
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
if (controller.disposed || (hold.phase !== 'recording' && hold.phase !== 'cancel')) {
|
|
852
|
+
void cancelCurrent({ silent: true });
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
startMaxTimer();
|
|
856
|
+
overlayFor(hold.phase === 'cancel' ? 'cancel' : 'recording', hold.phase === 'cancel', 0);
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async function finish() {
|
|
860
|
+
if (controller.finishing) return;
|
|
861
|
+
if (!capture) {
|
|
862
|
+
busy = false;
|
|
863
|
+
releaseView();
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
controller.finishing = true;
|
|
867
|
+
const generation = controller.generation;
|
|
868
|
+
const inputActions = propsRef.current && propsRef.current.inputActions;
|
|
869
|
+
const span = controller.span;
|
|
870
|
+
const startedAt = controller.recordingStartedAt;
|
|
871
|
+
setHolding(false);
|
|
872
|
+
clearTimers();
|
|
873
|
+
abort = new AbortController();
|
|
874
|
+
overlayFor('transcribing', false, 0);
|
|
875
|
+
let bytes;
|
|
876
|
+
try {
|
|
877
|
+
bytes = await capture.stop(controller.limits.maxDurationSeconds);
|
|
878
|
+
} catch (failure) {
|
|
879
|
+
busy = false;
|
|
880
|
+
controller.finishing = false;
|
|
881
|
+
disposeCapture();
|
|
882
|
+
releaseView();
|
|
883
|
+
const kind = failure && failure.kind ? failure.kind : 'unknown';
|
|
884
|
+
if (kind === 'cancelled') return;
|
|
885
|
+
showToast(t('feedback.recordingFailed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
disposeCapture();
|
|
889
|
+
if (controller.disposed || generation !== controller.generation) return;
|
|
890
|
+
if (!bytes || bytes.byteLength <= 44) {
|
|
891
|
+
busy = false;
|
|
892
|
+
controller.finishing = false;
|
|
893
|
+
releaseView();
|
|
894
|
+
showToast(t('feedback.tooShort'));
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
if (bytes.byteLength > controller.limits.maxAudioBytes) {
|
|
898
|
+
busy = false;
|
|
899
|
+
controller.finishing = false;
|
|
900
|
+
releaseView();
|
|
901
|
+
showToast(t('feedback.tooLarge'), 'error');
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
if (now() - startedAt < MIN_RECORDING_MS) {
|
|
905
|
+
busy = false;
|
|
906
|
+
controller.finishing = false;
|
|
907
|
+
releaseView();
|
|
908
|
+
showToast(t('feedback.tooShort'));
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
let payload;
|
|
912
|
+
try {
|
|
913
|
+
const state = service.stateCache;
|
|
914
|
+
const language = state && state.selection && typeof state.selection.language === 'string' ? state.selection.language : 'auto';
|
|
915
|
+
payload = await service.transcribe(bytes, abort.signal, language);
|
|
916
|
+
} catch (failure) {
|
|
917
|
+
busy = false;
|
|
918
|
+
controller.finishing = false;
|
|
919
|
+
releaseView();
|
|
920
|
+
if (isAbort(failure)) return;
|
|
921
|
+
showToast(t('feedback.failed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
|
|
922
|
+
return;
|
|
923
|
+
} finally {
|
|
924
|
+
abort = null;
|
|
925
|
+
}
|
|
926
|
+
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
927
|
+
if (text === '') {
|
|
928
|
+
busy = false;
|
|
929
|
+
controller.finishing = false;
|
|
930
|
+
releaseView();
|
|
931
|
+
showToast(t('feedback.empty'));
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
const action = controller.preferences.releaseAction;
|
|
935
|
+
busy = false;
|
|
936
|
+
controller.finishing = false;
|
|
937
|
+
releaseView();
|
|
938
|
+
if (generation !== controller.generation) return;
|
|
939
|
+
const inserted = tryInsert(inputActions, text, span);
|
|
940
|
+
if (inserted === 'failed') {
|
|
941
|
+
showToast(t('feedback.conflict'), 'error');
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (action === 'send') {
|
|
945
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
946
|
+
try {
|
|
947
|
+
inputActions && typeof inputActions.submit === 'function' && inputActions.submit();
|
|
948
|
+
} catch (failure) {
|
|
949
|
+
showToast(t('feedback.failed', { message: failure && failure.message ? failure.message : String(failure) }), 'error');
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
// Touch users expect the keyboard to stay hidden, like the App; a missed
|
|
953
|
+
// insertion is a hard error, so mouse/keyboard users get the caret back.
|
|
954
|
+
if (controller.pointerType !== 'touch') focusEditor();
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Insert the transcript through the public input actions.
|
|
959
|
+
* @returns {'inserted'|'fallback'|'failed'} outcome used for the follow-up behavior.
|
|
960
|
+
*/
|
|
961
|
+
function tryInsert(inputActions, text, span) {
|
|
962
|
+
if (!inputActions || typeof inputActions.insertText !== 'function') return 'failed';
|
|
963
|
+
try {
|
|
964
|
+
if (span !== undefined && inputActions.insertText(text, span)) return 'inserted';
|
|
965
|
+
const fresh = typeof inputActions.captureInsertion === 'function' ? inputActions.captureInsertion() : undefined;
|
|
966
|
+
if (fresh !== undefined && inputActions.insertText(text, fresh)) return 'inserted';
|
|
967
|
+
} catch {
|
|
968
|
+
/* fall through to the whole-draft fallback */
|
|
969
|
+
}
|
|
970
|
+
const draft = propsRef.current && typeof propsRef.current.getDraft === 'function' ? propsRef.current.getDraft() : '';
|
|
971
|
+
try {
|
|
972
|
+
if (typeof inputActions.setDraft === 'function') {
|
|
973
|
+
inputActions.setDraft((draft ? draft + ' ' : '') + text);
|
|
974
|
+
return 'fallback';
|
|
975
|
+
}
|
|
976
|
+
} catch {
|
|
977
|
+
/* a rejected fallback is reported to the user */
|
|
978
|
+
}
|
|
979
|
+
return 'failed';
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
async function beginHoldAttempt() {
|
|
983
|
+
if (busy || controller.disposed) return;
|
|
984
|
+
const state = await service.state(false);
|
|
985
|
+
if (controller.disposed) return;
|
|
986
|
+
if (!pointerDown || (hold.phase !== 'pressing' && hold.phase !== 'recording')) return;
|
|
987
|
+
if (!state) {
|
|
988
|
+
showToast(t('feedback.unavailable'), 'error');
|
|
989
|
+
hold = holdStart();
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
controller.preferences = readPreferences(state);
|
|
993
|
+
controller.limits = readLimits(state);
|
|
994
|
+
if (state.dependency && state.dependency.speechToText === false) {
|
|
995
|
+
hold = holdStart();
|
|
996
|
+
showToast(t('feedback.missingDependency'), 'error');
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
const ready = await ensureReady(state);
|
|
1000
|
+
if (!ready || controller.disposed) return;
|
|
1001
|
+
if (!pointerDown) {
|
|
1002
|
+
busy = false;
|
|
1003
|
+
releaseView();
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
await startRecording();
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/* ---------------- gesture listeners ---------------- */
|
|
1010
|
+
|
|
1011
|
+
function onPointerDown(event) {
|
|
1012
|
+
if (controller.disposed || busy) return;
|
|
1013
|
+
if (event.pointerType === 'mouse' && event.button !== 0) return;
|
|
1014
|
+
const target = event.target;
|
|
1015
|
+
if (!target || typeof target.closest !== 'function') return;
|
|
1016
|
+
const card = controller.card;
|
|
1017
|
+
if (!card || !card.contains(target)) return;
|
|
1018
|
+
if (!target.closest('[data-input-scroll]')) return;
|
|
1019
|
+
if (target.closest('button, a, input, select, textarea, [role="button"], [contenteditable="false"]')) return;
|
|
1020
|
+
if (typeof window !== 'undefined' && window.getSelection && String(window.getSelection() || '').length > 0) return;
|
|
1021
|
+
const props = propsRef.current;
|
|
1022
|
+
if (props && typeof props.getPhase === 'function' && props.getPhase() !== 'plain') return;
|
|
1023
|
+
const pressed = holdStep(hold, { type: 'press', pointerId: event.pointerId, x: event.clientX, y: event.clientY }, controller.preferences);
|
|
1024
|
+
if (pressed.action === 'ignore') return;
|
|
1025
|
+
hold = pressed.state;
|
|
1026
|
+
pointerDown = true;
|
|
1027
|
+
controller.pointerType = event.pointerType || 'mouse';
|
|
1028
|
+
if (holdTimer) clearTimeout(holdTimer);
|
|
1029
|
+
holdTimer = setTimeout(() => {
|
|
1030
|
+
holdTimer = 0;
|
|
1031
|
+
if (!pointerDown) return;
|
|
1032
|
+
const next = holdStep(hold, { type: 'hold' });
|
|
1033
|
+
hold = next.state;
|
|
1034
|
+
if (next.action === 'start') {
|
|
1035
|
+
setHolding(true);
|
|
1036
|
+
if (controller.card && typeof controller.card.setPointerCapture === 'function') {
|
|
1037
|
+
try { controller.card.setPointerCapture(event.pointerId); } catch { /* capture is an optimization */ }
|
|
1038
|
+
}
|
|
1039
|
+
void beginHoldAttempt();
|
|
1040
|
+
}
|
|
1041
|
+
}, controller.preferences.holdDelayMs);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
function onPointerMove(event) {
|
|
1045
|
+
if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
|
|
1046
|
+
const options = { cancelDistancePx: controller.preferences.cancelDistancePx, moveTolerancePx: MOVE_TOLERANCE_PX };
|
|
1047
|
+
const next = holdStep(hold, { type: 'move', x: event.clientX, y: event.clientY }, options);
|
|
1048
|
+
if (next.action === 'abort') {
|
|
1049
|
+
pointerDown = false;
|
|
1050
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
1051
|
+
setHolding(false);
|
|
1052
|
+
}
|
|
1053
|
+
hold = next.state;
|
|
1054
|
+
if (next.action === 'arm' || next.action === 'disarm') {
|
|
1055
|
+
const phase = hold.phase === 'cancel' ? 'cancel' : 'recording';
|
|
1056
|
+
overlayFor(phase, hold.phase === 'cancel', 0);
|
|
1057
|
+
setHolding(true);
|
|
1058
|
+
try { event.preventDefault(); } catch { /* passive listeners cannot prevent */ }
|
|
1059
|
+
}
|
|
1060
|
+
if ((hold.phase === 'recording' || hold.phase === 'cancel') && event.cancelable) {
|
|
1061
|
+
try { event.preventDefault(); } catch { /* selection is already prevented by the CSS class */ }
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
function onPointerUp(event) {
|
|
1066
|
+
if (event.pointerId !== undefined && hold.pointerId !== null && event.pointerId !== hold.pointerId) return;
|
|
1067
|
+
pointerDown = false;
|
|
1068
|
+
if (holdTimer) { clearTimeout(holdTimer); holdTimer = 0; }
|
|
1069
|
+
const next = holdStep(hold, { type: 'release' });
|
|
1070
|
+
hold = next.state;
|
|
1071
|
+
if (next.action === 'finish') {
|
|
1072
|
+
stopRequested = true;
|
|
1073
|
+
if (capture && busy) void finish();
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
if (next.action === 'cancel') {
|
|
1077
|
+
void cancelCurrent({ silent: true });
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
if (next.action === 'abort') {
|
|
1081
|
+
setHolding(false);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
function onPointerCancel() {
|
|
1086
|
+
pointerDown = false;
|
|
1087
|
+
const next = holdStep(hold, { type: 'cancel' });
|
|
1088
|
+
hold = next.state;
|
|
1089
|
+
if (next.action === 'cancel') void cancelCurrent({ silent: true });
|
|
1090
|
+
else setHolding(false);
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function onKeyDown(event) {
|
|
1094
|
+
if (!isEscape(event)) return;
|
|
1095
|
+
if (hold.phase === 'recording' || hold.phase === 'cancel' || busy) {
|
|
1096
|
+
event.preventDefault();
|
|
1097
|
+
void cancelCurrent({ silent: true });
|
|
1098
|
+
showToast(t('feedback.cancelled'));
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function onDocumentHidden() {
|
|
1103
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden' && (hold.phase === 'recording' || hold.phase === 'cancel')) {
|
|
1104
|
+
void cancelCurrent({ silent: true });
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function onWindowBlur() {
|
|
1109
|
+
if (hold.phase === 'recording' || hold.phase === 'cancel') void cancelCurrent({ silent: true });
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function onContextMenu(event) {
|
|
1113
|
+
if (hold.phase === 'pressing' || hold.phase === 'recording' || hold.phase === 'cancel') event.preventDefault();
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/* ---------------- placeholder hint ---------------- */
|
|
1117
|
+
|
|
1118
|
+
function setPlaceholderHint(text) {
|
|
1119
|
+
if (!controller.card) return;
|
|
1120
|
+
const placeholder = controller.card.querySelector('[data-composer-placeholder]');
|
|
1121
|
+
if (!placeholder) return;
|
|
1122
|
+
if (controller.placeholderOriginal === null) controller.placeholderOriginal = placeholder.textContent;
|
|
1123
|
+
if (placeholder.textContent !== text) placeholder.textContent = text;
|
|
1124
|
+
placeholder.setAttribute(HINT_ATTR, 'true');
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
function restorePlaceholderHint() {
|
|
1128
|
+
if (!controller.card) return;
|
|
1129
|
+
const placeholder = controller.card.querySelector('[data-composer-placeholder]');
|
|
1130
|
+
if (!placeholder) return;
|
|
1131
|
+
if (placeholder.hasAttribute(HINT_ATTR) && controller.placeholderOriginal !== null) {
|
|
1132
|
+
placeholder.textContent = controller.placeholderOriginal;
|
|
1133
|
+
placeholder.removeAttribute(HINT_ATTR);
|
|
1134
|
+
}
|
|
1135
|
+
controller.placeholderOriginal = null;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
function refreshHint() {
|
|
1139
|
+
if (!controller.card) return;
|
|
1140
|
+
const enabled = Boolean(controller.preferences && controller.preferences.composerHint !== false);
|
|
1141
|
+
const text = hintText || t('composerHint');
|
|
1142
|
+
if (enabled) setPlaceholderHint(text);
|
|
1143
|
+
else restorePlaceholderHint();
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/* ---------------- lifecycle ---------------- */
|
|
1147
|
+
|
|
1148
|
+
function attach(anchor) {
|
|
1149
|
+
controller.anchor = anchor;
|
|
1150
|
+
const card = anchor && typeof anchor.closest === 'function' ? anchor.closest('[data-composer-card]') : null;
|
|
1151
|
+
if (!card) return;
|
|
1152
|
+
controller.card = card;
|
|
1153
|
+
card.addEventListener('pointerdown', onPointerDown, { capture: true, passive: true });
|
|
1154
|
+
card.addEventListener('contextmenu', onContextMenu, { capture: true, passive: false });
|
|
1155
|
+
window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
|
|
1156
|
+
window.addEventListener('pointerup', onPointerUp, { capture: true, passive: true });
|
|
1157
|
+
window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: true });
|
|
1158
|
+
window.addEventListener('blur', onWindowBlur);
|
|
1159
|
+
window.addEventListener('keydown', onKeyDown, true);
|
|
1160
|
+
document.addEventListener('visibilitychange', onDocumentHidden);
|
|
1161
|
+
controller.hintObserver = new MutationObserver(() => refreshHint());
|
|
1162
|
+
controller.hintObserver.observe(card, { childList: true, subtree: true, characterData: true });
|
|
1163
|
+
void service.state(false).then((state) => {
|
|
1164
|
+
if (controller.disposed) return;
|
|
1165
|
+
if (state) {
|
|
1166
|
+
controller.preferences = { ...readPreferences(state), composerHint: state.preferences ? state.preferences.composerHint !== false : true };
|
|
1167
|
+
controller.limits = readLimits(state);
|
|
1168
|
+
}
|
|
1169
|
+
hintText = t('composerHint');
|
|
1170
|
+
refreshHint();
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function dispose() {
|
|
1175
|
+
if (controller.disposed) return;
|
|
1176
|
+
controller.disposed = true;
|
|
1177
|
+
clearTimers();
|
|
1178
|
+
abortInFlight();
|
|
1179
|
+
disposeCapture();
|
|
1180
|
+
setHolding(false);
|
|
1181
|
+
restorePlaceholderHint();
|
|
1182
|
+
if (controller.hintObserver) controller.hintObserver.disconnect();
|
|
1183
|
+
const card = controller.card;
|
|
1184
|
+
if (card) {
|
|
1185
|
+
card.removeEventListener('pointerdown', onPointerDown, { capture: true });
|
|
1186
|
+
card.removeEventListener('contextmenu', onContextMenu, { capture: true });
|
|
1187
|
+
}
|
|
1188
|
+
window.removeEventListener('pointermove', onPointerMove, { capture: true });
|
|
1189
|
+
window.removeEventListener('pointerup', onPointerUp, { capture: true });
|
|
1190
|
+
window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
|
|
1191
|
+
window.removeEventListener('blur', onWindowBlur);
|
|
1192
|
+
window.removeEventListener('keydown', onKeyDown, true);
|
|
1193
|
+
document.removeEventListener('visibilitychange', onDocumentHidden);
|
|
1194
|
+
if (toastTimer) { clearTimeout(toastTimer); toastTimer = 0; }
|
|
1195
|
+
releaseView();
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
return {
|
|
1199
|
+
attach,
|
|
1200
|
+
dispose,
|
|
1201
|
+
getLevel: () => (capture ? capture.amplitude() : 0),
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/* ================================================================ */
|
|
1206
|
+
/* React component */
|
|
1207
|
+
/* ================================================================ */
|
|
1208
|
+
|
|
1209
|
+
function HoldToTalkOverlay(props) {
|
|
1210
|
+
const anchorRef = useRef(null);
|
|
1211
|
+
const propsRef = useRef(null);
|
|
1212
|
+
const inputActionsRef = useRef(props.inputActions);
|
|
1213
|
+
inputActionsRef.current = props.inputActions;
|
|
1214
|
+
const runtimeRef = useRef(null);
|
|
1215
|
+
const [view, setView] = useState({ visible: false, phase: 'idle', armed: false, progress: null, action: 'insert', statusText: '', cancelLabel: '', hint: '', onCancel: undefined });
|
|
1216
|
+
const [toast, setToast] = useState(null);
|
|
1217
|
+
|
|
1218
|
+
const useInput = props.useInput;
|
|
1219
|
+
const draft = useInput ? useInput((state) => state.draft) : '';
|
|
1220
|
+
const phase = useInput ? useInput((state) => state.phase) : 'plain';
|
|
1221
|
+
const draftRef = useRef(draft);
|
|
1222
|
+
draftRef.current = draft;
|
|
1223
|
+
const phaseRef = useRef(phase);
|
|
1224
|
+
phaseRef.current = phase;
|
|
1225
|
+
|
|
1226
|
+
const getDraft = useCallback(() => draftRef.current, []);
|
|
1227
|
+
const getPhase = useCallback(() => phaseRef.current, []);
|
|
1228
|
+
propsRef.current = { ...props, getDraft, getPhase };
|
|
1229
|
+
|
|
1230
|
+
useEffect(() => {
|
|
1231
|
+
const runtime = createRuntime({ propsRef, setView, setToast });
|
|
1232
|
+
runtimeRef.current = runtime;
|
|
1233
|
+
runtime.attach(anchorRef.current);
|
|
1234
|
+
return () => {
|
|
1235
|
+
runtimeRef.current = null;
|
|
1236
|
+
runtime.dispose();
|
|
1237
|
+
};
|
|
1238
|
+
}, []);
|
|
1239
|
+
|
|
1240
|
+
const live = view.phase === 'recording' || view.phase === 'cancel';
|
|
1241
|
+
return h(react.Fragment, null,
|
|
1242
|
+
h('span', { ref: anchorRef, className: 'bvi-anchor', 'aria-hidden': 'true' }),
|
|
1243
|
+
view.visible
|
|
1244
|
+
? h(Overlay, {
|
|
1245
|
+
phase: view.phase,
|
|
1246
|
+
armed: view.armed,
|
|
1247
|
+
progress: view.progress,
|
|
1248
|
+
statusText: view.statusText,
|
|
1249
|
+
live,
|
|
1250
|
+
getLevel: () => (runtimeRef.current ? runtimeRef.current.getLevel() : 0),
|
|
1251
|
+
onCancel: view.onCancel,
|
|
1252
|
+
cancelLabel: view.cancelLabel,
|
|
1253
|
+
})
|
|
1254
|
+
: null,
|
|
1255
|
+
h(ToastLayer, { toast }));
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/* ================================================================ */
|
|
1259
|
+
/* styles */
|
|
1260
|
+
/* ================================================================ */
|
|
1261
|
+
|
|
1262
|
+
const CSS = [
|
|
1263
|
+
'.bvi-anchor{display:block;position:absolute;inset:0 auto auto 0;width:0;height:0;overflow:hidden;pointer-events:none}',
|
|
1264
|
+
'[data-composer-card].bvi-holding,[data-composer-card].bvi-holding [data-input-scroll],[data-composer-card].bvi-holding [contenteditable]{user-select:none!important;-webkit-user-select:none!important;-webkit-touch-callout:none!important}',
|
|
1265
|
+
'[data-composer-card].bvi-holding{cursor:default}',
|
|
1266
|
+
'.bvi-overlay{position:fixed;inset:0;z-index:9000;display:flex;flex-direction:column;align-items:center;justify-content:flex-start;overflow:hidden;touch-action:none;pointer-events:none;font-family:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif)}',
|
|
1267
|
+
'.bvi-overlay__blue,.bvi-overlay__red,.bvi-overlay__vignette{position:absolute;inset:0;pointer-events:none;transition:opacity 160ms ease}',
|
|
1268
|
+
'.bvi-overlay__blue{background:linear-gradient(180deg,#0f1112 0%,#0c141d 8%,#0b223d 18%,#04376a 29%,#004992 38%,#005ec0 50%,#0066d3 60%,#0169dc 70%,#006bda 82%,#006bd8 100%)}',
|
|
1269
|
+
'.bvi-overlay__blue::after{content:"";position:absolute;inset:0;background:radial-gradient(ellipse 68% 42% at 50% 74%,rgba(0,116,235,.55) 0%,rgba(0,116,235,0) 70%)}',
|
|
1270
|
+
'.bvi-overlay__red{background:linear-gradient(180deg,#0f0f0f 0%,#0f0f0f 12%,#151011 20%,#1d1314 30%,#391b1a 45%,#602728 61%,#772d31 70%,#873235 80%,#903538 90%,#953535 100%);opacity:0}',
|
|
1271
|
+
'.bvi-overlay__red::after{content:"";position:absolute;inset:0;background:radial-gradient(ellipse 62% 40% at 50% 76%,rgba(190,45,50,.45) 0%,rgba(190,45,50,0) 72%)}',
|
|
1272
|
+
'.bvi-overlay__vignette{background:radial-gradient(ellipse 78% 70% at 50% 50%,rgba(0,0,0,0) 42%,rgba(0,0,0,.34) 100%);transition:opacity 160ms ease}',
|
|
1273
|
+
'.bvi-overlay[data-state="cancel"] .bvi-overlay__blue{opacity:0}',
|
|
1274
|
+
'.bvi-overlay[data-state="cancel"] .bvi-overlay__red{opacity:1}',
|
|
1275
|
+
'.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
|
+
'.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)}',
|
|
1277
|
+
'.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
|
+
'.bvi-wave[data-live="false"]{opacity:.9}',
|
|
1279
|
+
'.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}',
|
|
1280
|
+
'.bvi-overlay[data-state="cancel"] .bvi-bar{background:#e06770;box-shadow:0 0 9px rgba(255,95,105,.75)}',
|
|
1281
|
+
'.bvi-overlay[data-state="preparing"] .bvi-wave,.bvi-overlay[data-state="transcribing"] .bvi-wave{opacity:.55}',
|
|
1282
|
+
'.bvi-overlay[data-state="transcribing"] .bvi-bar{animation:bvi-pulse 1.15s ease-in-out infinite}',
|
|
1283
|
+
'.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n){animation-delay:.18s}',
|
|
1284
|
+
'.bvi-overlay[data-state="transcribing"] .bvi-bar:nth-child(3n+1){animation-delay:.36s}',
|
|
1285
|
+
'@keyframes bvi-pulse{0%,100%{opacity:.5}50%{opacity:1}}',
|
|
1286
|
+
'.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
|
+
'.bvi-progress__track{width:100%;height:3px;border-radius:2px;background:rgba(207,230,255,.22);overflow:hidden}',
|
|
1288
|
+
'.bvi-progress__fill{height:100%;border-radius:2px;background:#cfe6ff;transition:width 300ms ease}',
|
|
1289
|
+
'.bvi-progress__label{color:rgba(207,230,255,.82);font-size:12px;letter-spacing:.08em}',
|
|
1290
|
+
'.bvi-cancel{position:absolute;left:50%;bottom:12vh;transform:translateX(-50%);pointer-events:auto;appearance:none;border:1px solid rgba(207,230,255,.28);background:rgba(8,18,38,.28);color:rgba(207,230,255,.9);font-size:13px;letter-spacing:.06em;padding:7px 16px;border-radius:999px;cursor:pointer;backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px)}',
|
|
1291
|
+
'.bvi-overlay[data-state="cancel"] .bvi-cancel{border-color:rgba(255,160,165,.35);color:rgba(255,205,208,.92)}',
|
|
1292
|
+
'.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
|
+
'.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}}',
|
|
1296
|
+
].join('\n');
|
|
1297
|
+
|
|
1298
|
+
function mountCss() {
|
|
1299
|
+
const existing = document.getElementById(CSS_ID);
|
|
1300
|
+
if (existing) existing.remove();
|
|
1301
|
+
const style = document.createElement('style');
|
|
1302
|
+
style.id = CSS_ID;
|
|
1303
|
+
style.setAttribute('data-plugin', '@ds-hu/dsh-bvi-input');
|
|
1304
|
+
style.textContent = CSS;
|
|
1305
|
+
document.head.appendChild(style);
|
|
1306
|
+
return () => style.remove();
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/* ================================================================ */
|
|
1310
|
+
/* plugin */
|
|
1311
|
+
/* ================================================================ */
|
|
1312
|
+
|
|
1313
|
+
let appCtx = null;
|
|
1314
|
+
|
|
1315
|
+
function currentLang() {
|
|
1316
|
+
try {
|
|
1317
|
+
const locale = appCtx && appCtx.locale;
|
|
1318
|
+
const snapshot = locale && typeof locale.getLocale === 'function' ? locale.getLocale() : undefined;
|
|
1319
|
+
const active = snapshot && typeof snapshot.active === 'string' ? snapshot.active : undefined;
|
|
1320
|
+
if (active !== undefined && active.toLowerCase().startsWith('en')) return 'en';
|
|
1321
|
+
} catch {
|
|
1322
|
+
/* fall back to the project default */
|
|
1323
|
+
}
|
|
1324
|
+
return 'zh';
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
function apply(ctx) {
|
|
1328
|
+
appCtx = ctx;
|
|
1329
|
+
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'better-voice-input: dictionaries');
|
|
1330
|
+
ctx.effect(() => mountCss(), 'better-voice-input: stylesheet');
|
|
1331
|
+
ctx.effect(() => ctx.slots.inject('conversation.input.overlay', () => ctx.slots.register({
|
|
1332
|
+
name: 'conversation.input.overlay',
|
|
1333
|
+
id: 'bvi-input',
|
|
1334
|
+
locale: NS,
|
|
1335
|
+
}, HoldToTalkOverlay)), 'better-voice-input: composer hold-to-talk');
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
exports.name = 'better-voice-input';
|
|
1339
|
+
exports.inject = ['slots', 'locale'];
|
|
1340
|
+
exports.apply = apply;
|
|
1341
|
+
exports.__bviTest = {
|
|
1342
|
+
holdStart,
|
|
1343
|
+
holdStep,
|
|
1344
|
+
barCountFor,
|
|
1345
|
+
barHeight,
|
|
1346
|
+
encodeWav,
|
|
1347
|
+
readPreferences,
|
|
1348
|
+
readLimits,
|
|
1349
|
+
overlayState,
|
|
1350
|
+
isEscape,
|
|
1351
|
+
clampInteger,
|
|
1352
|
+
DEFAULTS,
|
|
1353
|
+
API_BASE,
|
|
1354
|
+
NS,
|
|
1355
|
+
zh,
|
|
1356
|
+
en,
|
|
1357
|
+
currentLang,
|
|
1358
|
+
setTestRuntime(ctx) { appCtx = ctx; },
|
|
1359
|
+
HoldToTalkOverlay,
|
|
1360
|
+
createRuntime,
|
|
1361
|
+
};
|
|
1362
|
+
return module.exports;
|
|
1363
|
+
},
|
|
1364
|
+
});
|