@shuning0128/dsh-voice-hotkey 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,2252 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@shuning0128/dsh-voice-hotkey',
3
+ factory(require) {
4
+ const React = require('react')
5
+ // Shell-provided design atoms (Button/Input exist since 0.2.1); fall back to
6
+ // plain elements if an older shell does not share the package.
7
+ let Primitives = {}
8
+ try { Primitives = require('@deepseek-ai/dsh-client-ui-primitives') } catch (error) { Primitives = {} }
9
+ // aria-label of the dictation control in every locale the voice-input plugin ships.
10
+ const START = /^(开始录音|Start recording|Empezar a grabar|Commencer l'enregistrement|Starten Sie die Aufnahme|Начать запись|Comece a gravar|録音を開始)$/
11
+ const STOP = /^(停止并识别|Stop and transcribe|Detener y transcribir|Arrêtez et transcrivez|Stoppen Sie und transkribieren Sie|Остановись и перепиши|Pare e transcreva|停止して文字起こし)$/
12
+ const DEFAULT_HOTKEY = 'primary+F8'
13
+ const ENTRY_IDS = ['voice-hotkey', 'include:voice-hotkey']
14
+ const IS_MAC = /mac/iu.test(navigator.platform || '') || /mac os/iu.test(navigator.userAgent)
15
+ // 桌面壳走 dsh-app:// 协议,浏览器里打开的 Web 版是 http(s)://;只有后者会
16
+ // 被浏览器抢走一部分快捷键,所以规则按这个信号收窄。
17
+ const IS_WEB = (() => {
18
+ try {
19
+ if (typeof location !== 'undefined' && location && typeof location.protocol === 'string') {
20
+ return /^https?:$/iu.test(location.protocol)
21
+ }
22
+ } catch (error) { /* ignore */ }
23
+ return false
24
+ })()
25
+
26
+ function findButton(pattern, root) {
27
+ const scope = root || document
28
+ const buttons = scope.querySelectorAll('button[aria-label]')
29
+ for (const button of buttons) {
30
+ const label = (button.getAttribute('aria-label') || '').trim()
31
+ if (pattern.test(label)) return button
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ function voiceRow(root) {
37
+ const scope = root || document
38
+ return scope.querySelector('[data-voice-activity]')
39
+ }
40
+
41
+ function buttonDisabled(button) {
42
+ return button.disabled === true || button.getAttribute('aria-disabled') === 'true'
43
+ }
44
+
45
+ // Find the nearest composer that contains both this slot and its editor. This
46
+ // avoids selecting an editor or send button from another open conversation.
47
+ function composerRoot(anchor) {
48
+ let node = anchor
49
+ while (node && node !== document) {
50
+ if (typeof node.querySelector === 'function' && node.querySelector('[data-composer-input]')) return node
51
+ node = node.parentElement
52
+ }
53
+ return undefined
54
+ }
55
+
56
+ function composerEditor(root) {
57
+ if (!root || typeof root.querySelectorAll !== 'function') return undefined
58
+ const editors = root.querySelectorAll('[data-composer-input][contenteditable="true"]')
59
+ return editors.length === 1 ? editors[0] : undefined
60
+ }
61
+
62
+ // Slots register the session they belong to. Global hotkeys use the active
63
+ // composer; focus and pointer activity update that selection.
64
+ const composerSessions = new Map()
65
+ let activeComposerId
66
+ function registerComposer(props, anchorRef, latest) {
67
+ const id = props.sessionId
68
+ if (id === undefined || id === null) return undefined
69
+ const record = {
70
+ id,
71
+ getInput: () => latest.current.input,
72
+ getInputActions: () => latest.current.inputActions,
73
+ getRoot: () => composerRoot(anchorRef.current),
74
+ }
75
+ composerSessions.set(id, record)
76
+ if (activeComposerId === undefined || !composerSessions.has(activeComposerId)) activeComposerId = id
77
+ return () => {
78
+ if (composerSessions.get(id) !== record) return
79
+ composerSessions.delete(id)
80
+ if (activeComposerId === id) activeComposerId = composerSessions.keys().next().value
81
+ }
82
+ }
83
+
84
+ function noteComposer(id) {
85
+ if (id !== undefined && composerSessions.has(id)) activeComposerId = id
86
+ }
87
+
88
+ function noteComposerActivity(target) {
89
+ if (!target) return
90
+ for (const [id, record] of composerSessions) {
91
+ const root = record.getRoot()
92
+ const editor = composerEditor(root)
93
+ if (!editor) continue
94
+ if (target === editor || (typeof editor.contains === 'function' && editor.contains(target))) {
95
+ activeComposerId = id
96
+ return
97
+ }
98
+ }
99
+ }
100
+
101
+ function currentComposer() {
102
+ let record = composerSessions.get(activeComposerId)
103
+ if (!record && composerSessions.size === 1) record = composerSessions.values().next().value
104
+ if (record) {
105
+ const root = record.getRoot()
106
+ const editor = composerEditor(root)
107
+ if (!root || !editor) return undefined
108
+ return { token: record, root, editor, getInput: record.getInput, getInputActions: record.getInputActions }
109
+ }
110
+ // Older shells can still use the hotkey when exactly one composer exists.
111
+ // They do not get auto-send without a registered input state and submit API.
112
+ const editors = document.querySelectorAll('[data-composer-input][contenteditable="true"]')
113
+ if (editors.length !== 1) return undefined
114
+ const editor = editors[0]
115
+ const root = composerRoot(editor)
116
+ if (!root) return undefined
117
+ return { token: editor, root, editor, getInput: () => undefined, getInputActions: () => undefined }
118
+ }
119
+
120
+ function sameComposer(session) {
121
+ const current = currentComposer()
122
+ return current !== undefined && current.token === session.token && current.editor === session.editor
123
+ }
124
+
125
+ // Returns undefined on success, or a user-readable reason when no safe action exists.
126
+ function toggle(session) {
127
+ if (!session) return '找不到当前会话的语音输入框,请先点击一个输入框。'
128
+ const row = voiceRow(session.root)
129
+ if (row) {
130
+ const phase = row.getAttribute('data-voice-activity')
131
+ if (phase === 'recording') {
132
+ const stop = findButton(STOP, session.root)
133
+ if (!stop) return '找不到停止录音按钮。'
134
+ if (buttonDisabled(stop)) return '停止录音按钮当前不可用。'
135
+ stop.click()
136
+ return undefined
137
+ }
138
+ if (phase === 'requesting') return '正在等待麦克风权限,请使用语音工具条上的取消按钮。'
139
+ if (phase === 'transcribing') return '正在识别语音,请稍候。'
140
+ if (phase === 'feedback') return '请先处理语音工具条上的识别结果或错误提示。'
141
+ return '语音输入正在处理,请稍候。'
142
+ }
143
+ const start = findButton(START, session.root)
144
+ if (!start) return '语音输入尚未就绪,请查看输入框中的麦克风状态。'
145
+ if (buttonDisabled(start)) return '语音输入当前不可用,请查看输入框状态。'
146
+ start.click()
147
+ return undefined
148
+ }
149
+
150
+ // ---- 识别完成后自动发送 ---------------------------------------------------
151
+ // Auto-send is deliberately fail-closed: an idle voice row alone is not proof
152
+ // that text was inserted. The session draft must advance after transcribing,
153
+ // then remain unchanged until the formal session submit API is called.
154
+ let autoSend = false
155
+ let autoSendDelaySeconds = 0
156
+ // 繁忙时的发送方式:'queue' 走会话官方提交接口(消息进队列);'enter' 合成回车,
157
+ // 与用户按回车同一条路径——繁忙时是排队还是插队由 DSH 设置「繁忙时的发送行为」决定。
158
+ let autoSendBusy = 'queue'
159
+ let autoSession
160
+ let autoSendTimer
161
+ let dictationWatcher
162
+ let pendingAutoSend = false
163
+
164
+ const MAX_AUTO_SEND_DELAY = 600
165
+ function clampDelay(value) {
166
+ const number = typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : 0
167
+ return number < 0 ? 0 : number > MAX_AUTO_SEND_DELAY ? MAX_AUTO_SEND_DELAY : number
168
+ }
169
+
170
+ function attachmentKey(input) {
171
+ return JSON.stringify(Array.isArray(input && input.attachmentIds) ? input.attachmentIds : [])
172
+ }
173
+
174
+ function hasDraft(input) {
175
+ return Boolean(input && ((typeof input.draft === 'string' && input.draft.trim() !== '')
176
+ || (Array.isArray(input.attachmentIds) && input.attachmentIds.length > 0)))
177
+ }
178
+
179
+ function inputCanSubmit(input) {
180
+ return input && (input.phase === undefined || input.phase === 'plain' || input.phase === 'claimed')
181
+ }
182
+
183
+ function autoSendSupported(session) {
184
+ const input = session.getInput()
185
+ const actions = session.getInputActions()
186
+ return Boolean(input && Number.isFinite(input.draftRev) && actions && typeof actions.submit === 'function')
187
+ }
188
+
189
+ function stopWatching() {
190
+ if (dictationWatcher !== undefined) { clearInterval(dictationWatcher); dictationWatcher = undefined }
191
+ }
192
+
193
+ function cancelAutoSend(announce) {
194
+ const hadPending = autoSession !== undefined || autoSendTimer !== undefined || pendingAutoSend
195
+ stopWatching()
196
+ if (autoSendTimer !== undefined) { clearTimeout(autoSendTimer); autoSendTimer = undefined }
197
+ autoSession = undefined
198
+ pendingAutoSend = false
199
+ if (hadPending && hintKind === 'autosend') clearHint()
200
+ if (hadPending && announce) showHint('已取消自动发送。', 'autosend')
201
+ }
202
+
203
+ // 合成键盘事件在没有 KeyboardEvent 的环境里退化成普通对象,方便单测。
204
+ function makeEnterEvent() {
205
+ const init = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }
206
+ try { return new KeyboardEvent('keydown', init) } catch (error) { return { type: 'keydown', ...init } }
207
+ }
208
+
209
+ function sendDraft(session) {
210
+ if (!autoSend || !sameComposer(session) || session.editor.isConnected === false) {
211
+ showHint('会话或输入框已切换,已取消自动发送。', 'status')
212
+ return false
213
+ }
214
+ const input = session.getInput()
215
+ const actions = session.getInputActions()
216
+ if (!input || !actions || typeof actions.submit !== 'function') {
217
+ showHint('当前版本无法确认草稿状态,未自动发送。', 'status')
218
+ return false
219
+ }
220
+ if (input.draftRev !== session.insertedRev || input.draft !== session.insertedDraft
221
+ || attachmentKey(input) !== session.insertedAttachments) {
222
+ showHint('草稿在延时期间发生变化,已取消自动发送。', 'status')
223
+ return false
224
+ }
225
+ if (!hasDraft(input) || !inputCanSubmit(input)) {
226
+ showHint('当前草稿或会话状态不允许自动发送。', 'status')
227
+ return false
228
+ }
229
+ try {
230
+ // 插队发送:走回车的原路,繁忙时是排队还是插队由 DSH 设置决定。
231
+ // 编辑器不在时退回官方提交接口——宁可排队,也不把识别结果丢掉。
232
+ if (autoSendBusy === 'enter' && session.editor
233
+ && typeof session.editor.dispatchEvent === 'function') {
234
+ try { if (typeof session.editor.focus === 'function') session.editor.focus() } catch (error) { /* ignore */ }
235
+ session.editor.dispatchEvent(makeEnterEvent())
236
+ return true
237
+ }
238
+ const result = actions.submit()
239
+ if (result && typeof result.catch === 'function') {
240
+ result.catch(() => showHint('自动发送失败,请手动发送。', 'status'))
241
+ }
242
+ return true
243
+ } catch (error) {
244
+ showHint('自动发送失败,请手动发送。', 'status')
245
+ return false
246
+ }
247
+ }
248
+
249
+ function scheduleAutoSend(session) {
250
+ if (!autoSend || autoSession !== session || autoSendTimer !== undefined) return
251
+ const seconds = autoSendDelaySeconds
252
+ pendingAutoSend = true
253
+ if (seconds > 0) showHint('将在 ' + seconds + ' 秒后自动发送,按 Esc 取消;修改草稿也会取消。', 'autosend')
254
+ autoSendTimer = setTimeout(() => {
255
+ autoSendTimer = undefined
256
+ if (!pendingAutoSend || autoSession !== session) return
257
+ pendingAutoSend = false
258
+ const sent = sendDraft(session)
259
+ autoSession = undefined
260
+ if (sent) clearHint()
261
+ }, seconds > 0 ? seconds * 1000 : 60)
262
+ if (autoSendTimer && typeof autoSendTimer.unref === 'function') autoSendTimer.unref()
263
+ }
264
+
265
+ function watchDictation(session) {
266
+ stopWatching()
267
+ autoSession = session
268
+ dictationWatcher = setInterval(() => {
269
+ if (autoSession !== session) { stopWatching(); return }
270
+ if (!autoSend || !sameComposer(session)) { cancelAutoSend(false); return }
271
+ const row = voiceRow(session.root)
272
+ if (row) {
273
+ const phase = row.getAttribute('data-voice-activity')
274
+ if (phase === 'feedback') { cancelAutoSend(false); return }
275
+ if (phase === 'transcribing') {
276
+ const input = session.getInput()
277
+ if (!input || !Number.isFinite(input.draftRev)) { cancelAutoSend(false); return }
278
+ // Freeze the baseline once. Upstream may insert the transcript while
279
+ // the row still says "transcribing"; advancing this baseline on every
280
+ // poll would then mistake that insertion for a pre-existing edit.
281
+ if (!session.sawTranscribing) {
282
+ session.sawTranscribing = true
283
+ session.beforeRev = input.draftRev
284
+ }
285
+ }
286
+ return
287
+ }
288
+
289
+ stopWatching()
290
+ if (!session.sawTranscribing || !Number.isFinite(session.beforeRev)) {
291
+ autoSession = undefined
292
+ return
293
+ }
294
+ const input = session.getInput()
295
+ if (!input || !Number.isFinite(input.draftRev) || input.draftRev <= session.beforeRev || !hasDraft(input)) {
296
+ autoSession = undefined
297
+ showHint('未确认识别结果已插入,未自动发送。', 'status')
298
+ return
299
+ }
300
+ session.insertedRev = input.draftRev
301
+ session.insertedDraft = input.draft
302
+ session.insertedAttachments = attachmentKey(input)
303
+ scheduleAutoSend(session)
304
+ }, 100)
305
+ if (dictationWatcher && typeof dictationWatcher.unref === 'function') dictationWatcher.unref()
306
+ }
307
+
308
+ // Keys without a printable character report a name in `event.key` ('ArrowUp',
309
+ // 'PageDown', ' '). Users may type that name or a short alias.
310
+ const NAMED_KEYS = {
311
+ up: 'ArrowUp', arrowup: 'ArrowUp',
312
+ down: 'ArrowDown', arrowdown: 'ArrowDown',
313
+ left: 'ArrowLeft', arrowleft: 'ArrowLeft',
314
+ right: 'ArrowRight', arrowright: 'ArrowRight',
315
+ home: 'Home', end: 'End',
316
+ pageup: 'PageUp', pgup: 'PageUp',
317
+ pagedown: 'PageDown', pgdn: 'PageDown',
318
+ insert: 'Insert', ins: 'Insert',
319
+ delete: 'Delete', del: 'Delete',
320
+ backspace: 'Backspace',
321
+ tab: 'Tab',
322
+ enter: 'Enter', return: 'Enter',
323
+ space: ' ',
324
+ }
325
+ const NAMED_LABELS = {
326
+ ArrowUp: '↑', ArrowDown: '↓', ArrowLeft: '←', ArrowRight: '→',
327
+ PageUp: 'PgUp', PageDown: 'PgDn', Insert: 'Ins', Delete: 'Del',
328
+ Backspace: 'Backspace', Tab: 'Tab', Enter: 'Enter', ' ': 'Space',
329
+ }
330
+ // Printable ASCII that is neither a letter nor a digit: the only keys that
331
+ // may be used without a modifier.
332
+ const SYMBOL_KEY = /^[!-/:-@[-`{-~]$/u
333
+ // What `event.key` becomes when Shift is held for those symbols (US layout).
334
+ const SHIFTED = {
335
+ '`': '~', '-': '_', '=': '+', '[': '{', ']': '}', '\\': '|',
336
+ ';': ':', "'": '"', ',': '<', '.': '>', '/': '?',
337
+ }
338
+ // 小键盘只能靠 event.code 分辨:NumLock 开着时它报的数字和主键区一样,关着时
339
+ // 又会报 Home/End/方向键,光看 event.key 永远分不开。
340
+ const NUMPAD_KEYS = {
341
+ num1: 'Numpad1', num2: 'Numpad2', num3: 'Numpad3', num4: 'Numpad4', num5: 'Numpad5',
342
+ num6: 'Numpad6', num7: 'Numpad7', num8: 'Numpad8', num9: 'Numpad9', num0: 'Numpad0',
343
+ numadd: 'NumpadAdd', numplus: 'NumpadAdd',
344
+ numsub: 'NumpadSubtract', numminus: 'NumpadSubtract',
345
+ nummul: 'NumpadMultiply', numstar: 'NumpadMultiply',
346
+ numdiv: 'NumpadDivide',
347
+ numdot: 'NumpadDecimal', numdecimal: 'NumpadDecimal',
348
+ }
349
+ const NUMPAD_LABELS = {
350
+ Numpad0: 'Num0', Numpad1: 'Num1', Numpad2: 'Num2', Numpad3: 'Num3', Numpad4: 'Num4',
351
+ Numpad5: 'Num5', Numpad6: 'Num6', Numpad7: 'Num7', Numpad8: 'Num8', Numpad9: 'Num9',
352
+ NumpadAdd: 'Num+', NumpadSubtract: 'Num-', NumpadMultiply: 'Num*',
353
+ NumpadDivide: 'Num/', NumpadDecimal: 'Num.',
354
+ }
355
+ // 浏览器自己吃掉的组合:网页里 preventDefault 拦不住(关标签页、切标签页、
356
+ // 刷新、开发者工具、缩放等)。桌面壳不受这些限制,只在 Web 上拒绝。
357
+ const BROWSER_RESERVED = new Set([
358
+ 'w', 'shift+w', 't', 'shift+t', 'n', 'shift+n',
359
+ 'tab', 'shift+tab', 'pageup', 'pagedown',
360
+ 'l', 'r', 'shift+r', 'f', 'p', 's', 'o', 'j', 'u', 'd', 'h', 'e', 'k', 'g', 'i',
361
+ 'shift+i', 'shift+j', 'shift+c',
362
+ 'f4', 'f5', 'f11', 'f12',
363
+ '=', '-', '0', 'shift+=',
364
+ '1', '2', '3', '4', '5', '6', '7', '8', '9',
365
+ ])
366
+ // 鼠标按键:DOM 的 mousedown 用 button 序号(0 左 1 中 2 右 3 后退 4 前进)。
367
+ // 留成一张表,以后要加别的输入源(数位板、遥控器)也在这里登记即可。
368
+ const MOUSE_KEYS = {
369
+ mouse1: 0, mouse2: 1, mouse3: 2, mouse4: 3, mouse5: 4,
370
+ m1: 0, m2: 1,
371
+ left: 0, middle: 1, right: 2, back: 3, forward: 4,
372
+ }
373
+ const MOUSE_LABELS = { 0: 'Mouse1', 1: 'Mouse2', 2: 'Mouse3', 3: 'Mouse4', 4: 'Mouse5' }
374
+
375
+ // 官方快捷键目录(@deepseek-ai/dsh-client-shortcuts)只认 event.code:
376
+ // 主键区 KeyX/DigitX/F1–F24 加一张命名键/符号键表。这里把本插件保存的写法
377
+ // 映射成官方 binding;映射不了的(小键盘、Home/End/PgUp/PgDn/Ins、表外符号)
378
+ // 返回 null,冲突检查对它们保持沉默——说不出确切结果就不要编一个。
379
+ const OFFICIAL_CODES = {
380
+ ArrowUp: 'ArrowUp', ArrowDown: 'ArrowDown', ArrowLeft: 'ArrowLeft', ArrowRight: 'ArrowRight',
381
+ Delete: 'Delete', Backspace: 'Backspace', Tab: 'Tab', Enter: 'Enter', ' ': 'Space',
382
+ '/': 'Slash', ',': 'Comma', '.': 'Period', '\\': 'Backslash', '`': 'Backquote',
383
+ '-': 'Minus', '=': 'Equal', '[': 'BracketLeft', ']': 'BracketRight',
384
+ ';': 'Semicolon', "'": 'Quote',
385
+ }
386
+ // Shift+符号录下来的是打出来的字符(? = / 键加 Shift),映射回同一枚物理键。
387
+ for (const [base, shifted] of Object.entries(SHIFTED)) {
388
+ if (OFFICIAL_CODES[base] !== undefined) OFFICIAL_CODES[shifted] = OFFICIAL_CODES[base]
389
+ }
390
+ function toOfficialBinding(binding) {
391
+ if (!binding || binding.mouse !== undefined || binding.code !== undefined) return null
392
+ const key = binding.key
393
+ let code
394
+ if (/^[a-z]$/u.test(key)) code = 'Key' + key.toUpperCase()
395
+ else if (/^[0-9]$/u.test(key)) code = 'Digit' + key
396
+ else if (/^f([1-9]|1[0-2])$/iu.test(key)) code = key.toUpperCase()
397
+ else code = OFFICIAL_CODES[key]
398
+ if (code === undefined) return null
399
+ const modifiers = []
400
+ if (binding.ctrl) modifiers.push('control')
401
+ if (binding.meta) modifiers.push('meta')
402
+ if (binding.alt) modifiers.push('alt')
403
+ if (binding.shift) modifiers.push('shift')
404
+ return { code, modifiers }
405
+ }
406
+ const FUNCTION_KEY = /^f([1-9]|1[0-2])$/u
407
+ // 反向表:录制按键时要先把浏览器报的 event 变回可保存的写法。
408
+ const NAME_BY_KEY = (() => {
409
+ const table = {}
410
+ for (const [alias, key] of Object.entries(NAMED_KEYS)) {
411
+ // 每个键只留最短的别名(up、pgup、space…)。
412
+ if (table[key] === undefined || alias.length < table[key].length) table[key] = alias
413
+ }
414
+ return table
415
+ })()
416
+ const NUMPAD_NAME_BY_CODE = (() => {
417
+ const table = {}
418
+ for (const [alias, code] of Object.entries(NUMPAD_KEYS)) {
419
+ if (/^num[0-9]$/u.test(alias) || code === 'NumpadAdd' || code === 'NumpadSubtract'
420
+ || code === 'NumpadMultiply' || code === 'NumpadDivide' || code === 'NumpadDecimal') {
421
+ if (table[code] === undefined) table[code] = alias
422
+ }
423
+ }
424
+ table.NumpadAdd = 'num+'
425
+ table.NumpadSubtract = 'num-'
426
+ table.NumpadMultiply = 'num*'
427
+ table.NumpadDivide = 'num/'
428
+ table.NumpadDecimal = 'num.'
429
+ return table
430
+ })()
431
+ const MOUSE_NAME_BY_BUTTON = { 0: 'mouse1', 1: 'mouse2', 2: 'mouse3', 3: 'mouse4', 4: 'mouse5' }
432
+ // 把一次真实按下翻译成可保存的键位字符串(录制用)。
433
+ function eventToHotkey(event, isMouse) {
434
+ const mods = []
435
+ if (event.ctrlKey) mods.push('ctrl')
436
+ if (event.metaKey) mods.push('meta')
437
+ if (event.altKey) mods.push('alt')
438
+ if (event.shiftKey) mods.push('shift')
439
+ let key
440
+ if (isMouse) {
441
+ key = MOUSE_NAME_BY_BUTTON[event.button]
442
+ } else {
443
+ const code = typeof event.code === 'string' ? event.code : ''
444
+ if (NUMPAD_NAME_BY_CODE[code] !== undefined) key = NUMPAD_NAME_BY_CODE[code]
445
+ else if (/^F([1-9]|1[0-2])$/u.test(event.key || '')) key = event.key.toLowerCase()
446
+ else if (NAME_BY_KEY[event.key] !== undefined) key = NAME_BY_KEY[event.key]
447
+ else if (typeof event.key === 'string' && event.key.length === 1) key = event.key.toLowerCase()
448
+ }
449
+ if (key === undefined) return undefined
450
+ return [...mods, key].join('+')
451
+ }
452
+
453
+
454
+ /**
455
+ * Parse a hotkey string like 'primary+F8' / 'ctrl+alt+F8' / 'meta+shift+D' / '/'.
456
+ * 'primary' means Command on macOS and Control elsewhere.
457
+ * Returns `{ binding }` or `{ error }` — the error is shown verbatim in the form.
458
+ */
459
+ function parseHotkeyDetailed(text) {
460
+ if (typeof text !== 'string') return { error: '键位必须是文本' }
461
+ // 空值是有意义的:表示不绑定任何键(网页版的默认状态)。
462
+ if (text.trim() === '') return { binding: null }
463
+ // 「num+」和主键区「+」本身都带加号,先换成不含分隔符的写法。
464
+ // 主键区加号可写成 ctrl++ 或 ctrl+plus。
465
+ const source = text.trim()
466
+ .replace(/num\+/giu, 'numadd')
467
+ .replace(/num-/giu, 'numsub')
468
+ .replace(/num\*/giu, 'nummul')
469
+ .replace(/num\//giu, 'numdiv')
470
+ .replace(/num\./giu, 'numdot')
471
+ .replace(/\+\s*$/u, ' plus ')
472
+ const parts = source.split('+').map((part) => part.trim().toLowerCase()).filter(Boolean)
473
+ if (parts.length === 0) return { error: '键位不能为空' }
474
+ const binding = { key: '', ctrl: false, meta: false, alt: false, shift: false }
475
+ let hasMainKey = false
476
+ for (const part of parts) {
477
+ const modifier = part === 'primary' || part === 'ctrl' || part === 'control'
478
+ || part === 'meta' || part === 'cmd' || part === 'command' || part === '⌘'
479
+ || part === 'alt' || part === 'option' || part === 'shift'
480
+ if (!modifier) {
481
+ if (hasMainKey) return { error: '一个快捷键只能有一个非修饰键,请检查 + 连接符' }
482
+ hasMainKey = true
483
+ }
484
+ if (part === 'primary') {
485
+ if (IS_MAC) binding.meta = true
486
+ else binding.ctrl = true
487
+ } else if (part === 'ctrl' || part === 'control') binding.ctrl = true
488
+ else if (part === 'meta' || part === 'cmd' || part === 'command' || part === '⌘') binding.meta = true
489
+ else if (part === 'alt' || part === 'option') binding.alt = true
490
+ else if (part === 'shift') binding.shift = true
491
+ else if (FUNCTION_KEY.test(part)) binding.key = part.toUpperCase()
492
+ else if (/^f(1[3-9]|2[0-4])$/u.test(part)) return { error: '不支持 F13 及以上的功能键,请改用 F1–F12' }
493
+ else if (MOUSE_KEYS[part] !== undefined) binding.mouse = MOUSE_KEYS[part]
494
+ else if (NUMPAD_KEYS[part] !== undefined) binding.code = NUMPAD_KEYS[part]
495
+ else if (NAMED_KEYS[part] !== undefined) binding.key = NAMED_KEYS[part]
496
+ else if (part === 'plus') binding.key = '+'
497
+ else if (/^[a-z0-9]$/u.test(part)) binding.key = part
498
+ else if (part.length === 1 && SYMBOL_KEY.test(part)) binding.key = part
499
+ else return { error: '看不懂这个按键:' + part }
500
+ }
501
+ if (binding.key === '' && binding.code === undefined && binding.mouse === undefined) {
502
+ return { error: '缺少按键,例如 ' + DEFAULT_INPUT }
503
+ }
504
+ // 每个键位都必须带 Ctrl / Alt / ⌘:Shift 单独当修饰键只会命中正常打字(Shift+字母、
505
+ // Shift+符号),而裸按功能键或符号键也会和编辑器、浏览器自带行为撞车。
506
+ // 例外是鼠标侧键(4 后退 / 5 前进):它们平时什么都不做,单按没有冲突。
507
+ // 桌面壳里右键(mouse3)同样闲置,允许单按;配套在触发后吞掉 contextmenu,
508
+ // 否则右键一按菜单就弹出来。网页版仍要求右键配修饰键(浏览器要留着开菜单)。
509
+ const bareMouse = binding.mouse !== undefined
510
+ && (binding.mouse >= 3 || (binding.mouse === 2 && !IS_WEB))
511
+ if (!bareMouse && !(binding.ctrl || binding.meta || binding.alt)) {
512
+ return { error: '键位必须带 Ctrl、Alt 或 ⌘;Shift 不算,光按会和打字/快捷键冲突('
513
+ + (IS_WEB ? '鼠标侧键可以单按' : '鼠标侧键、右键可以单按') + ')' }
514
+ }
515
+ if (IS_WEB) {
516
+ const reserved = browserReserved(binding)
517
+ if (reserved !== undefined) {
518
+ return { error: '这是浏览器自己保留的组合(' + reserved + '),网页里绑它不会生效。桌面端不受此限。' }
519
+ }
520
+ }
521
+ return { binding }
522
+ }
523
+
524
+ function parseHotkey(text) {
525
+ const parsed = parseHotkeyDetailed(text)
526
+ return parsed.error === undefined ? parsed.binding : null
527
+ }
528
+
529
+ // Returns a human hint when the binding collides with a combo the browser keeps
530
+ // for itself. Ctrl and Cmd carry the same actions; Alt alone is mostly free
531
+ // (Alt+F4 closes the window at the OS level, so that one is listed too).
532
+ function browserReserved(binding) {
533
+ if (binding.code !== undefined || binding.mouse !== undefined) return undefined
534
+ const base = binding.key.toLowerCase()
535
+ const token = (binding.shift ? 'shift+' : '') + base
536
+ const prettyKey = base.length === 1
537
+ ? base.toUpperCase()
538
+ : base.charAt(0).toUpperCase() + base.slice(1)
539
+ if (binding.alt && !binding.ctrl && !binding.meta) {
540
+ return base === 'f4' ? 'Alt+F4' : undefined
541
+ }
542
+ if (!binding.ctrl && !binding.meta) return undefined
543
+ if (!BROWSER_RESERVED.has(token)) return undefined
544
+ const mod = binding.ctrl ? 'Ctrl' : (IS_MAC ? '⌘' : 'Meta')
545
+ return [mod, binding.shift ? 'Shift' : '', prettyKey].filter(Boolean).join('+')
546
+ }
547
+
548
+ function keyLabel(binding) {
549
+ if (binding.mouse !== undefined) return MOUSE_LABELS[binding.mouse] || ('Mouse' + binding.mouse)
550
+ if (binding.code !== undefined && NUMPAD_LABELS[binding.code] !== undefined) return NUMPAD_LABELS[binding.code]
551
+ const key = binding.key
552
+ if (NAMED_LABELS[key] !== undefined) return NAMED_LABELS[key]
553
+ if (/^F\d+$/u.test(key)) return key
554
+ return key.toUpperCase()
555
+ }
556
+
557
+ function displayHotkey(binding) {
558
+ const mods = []
559
+ if (binding.ctrl) mods.push('Ctrl')
560
+ if (binding.meta) mods.push('⌘')
561
+ if (binding.alt) mods.push(IS_MAC ? '⌥' : 'Alt')
562
+ if (binding.shift) mods.push('Shift')
563
+ return [...mods, keyLabel(binding)].join('+')
564
+ }
565
+
566
+ function matchesMouse(event, binding) {
567
+ if (binding.mouse === undefined) return false
568
+ if (event.ctrlKey !== binding.ctrl || event.metaKey !== binding.meta) return false
569
+ if (event.altKey !== binding.alt || event.shiftKey !== binding.shift) return false
570
+ return event.button === binding.mouse
571
+ }
572
+
573
+ function matches(event, binding) {
574
+ if (binding.mouse !== undefined) return false
575
+ if (event.ctrlKey !== binding.ctrl || event.metaKey !== binding.meta) return false
576
+ if (event.altKey !== binding.alt || event.shiftKey !== binding.shift) return false
577
+ const code = typeof event.code === 'string' ? event.code : ''
578
+ if (binding.code !== undefined) return code === binding.code
579
+ // 没绑小键盘就不要被小键盘误触:NumLock 开时它的数字和主键区同名。
580
+ if (code.startsWith('Numpad')) return false
581
+ // With Shift held a symbol arrives shifted ('/' becomes '?'), so compare
582
+ // against what the browser actually reports.
583
+ const expected = binding.shift && SHIFTED[binding.key] !== undefined
584
+ ? SHIFTED[binding.key]
585
+ : binding.key
586
+ const key = event.key.length === 1 ? event.key.toLowerCase() : event.key
587
+ return key.toLowerCase() === expected.toLowerCase()
588
+ }
589
+
590
+ const BUNDLE_CONFIG_KEY = '@shuning0128/dsh-voice-hotkey'
591
+ // What the default key is called on this client, instead of the abstract 'primary+F8'.
592
+ const DEFAULT_INPUT = IS_MAC ? 'meta+F8' : 'ctrl+F8'
593
+ // 所有平台都不设默认键位:键位由用户自己录一次,免得替用户猜一个撞车的组合。
594
+ // 留空表示不绑定(功能停用,但也绝不抢键)。
595
+ const PLATFORM_DEFAULT_RAW = ''
596
+ const resolveRaw = (text) => (typeof text === 'string' && text.trim() !== '' ? text : PLATFORM_DEFAULT_RAW)
597
+ const SETUP_TEXT = '尚未设置快捷键,语音输入快捷键暂不可用。点击下方输入框录制组合(支持鼠标侧键),或点「手动输入」直接书写键位,然后点击「保存」。'
598
+ const PLATFORM_NOTICE = IS_WEB
599
+ ? '当前未绑定快捷键。网页版默认不绑定:浏览器自身占用大量组合键(如 Ctrl+W、Ctrl+T、Ctrl+Tab、F5、F11、F12 等),预置组合极易冲突。如需使用,请录制或手动输入键位并保存。'
600
+ : '当前未绑定快捷键。录制或手动输入键位并保存后即会生效。'
601
+
602
+ // The dictation UI lives in this bundle. Its browser half mounts a Remote
603
+ // namespace service, and that service is the only client-side proof that the
604
+ // button really loaded: it appears only when the plugin's client half ran.
605
+ const DEPENDENCY_SERVICE = 'remote.speech'
606
+
607
+ // ---- 依赖监测模块 ---------------------------------------------------------
608
+ // 语音插件能不能用,只由这里判断。界面(红字、红标、启用提示)、快捷键门控
609
+ // 和诊断都读同一份状态,不再各读各的。
610
+ //
611
+ // 判定依据是语音插件挂出来的客户端服务在不在,而不是页面上有没有麦克风按钮:
612
+ // 按钮会随会话视图变化,服务只随插件启停变化。
613
+ const GRACE_MS = 3000
614
+ const POLL_MS = 1500
615
+ const IDLE_STATE = { ready: undefined, settled: false, changes: 0, since: 0, reason: 'probe' }
616
+
617
+ function createDependencyMonitor(ctx) {
618
+ // ready: undefined = 尚未判定,true = 可用,false = 不可用。
619
+ // settled: 宽限期结束后才置位;置位前界面不报缺失,避免依赖稍后才挂载时闪一下红字。
620
+ const state = { ready: undefined, settled: false, changes: 0, since: 0, reason: 'probe' }
621
+ const listeners = new Set()
622
+ const emit = () => {
623
+ for (const listener of listeners) listener()
624
+ }
625
+ const read = () => {
626
+ try {
627
+ return ctx.get(DEPENDENCY_SERVICE) !== undefined
628
+ } catch (error) {
629
+ return false
630
+ }
631
+ }
632
+ const measure = (reason) => {
633
+ const ready = read()
634
+ if (ready === state.ready) return false
635
+ state.ready = ready
636
+ state.changes += 1
637
+ state.since = Date.now()
638
+ state.reason = reason
639
+ emit()
640
+ return true
641
+ }
642
+ return {
643
+ state,
644
+ snapshot: () => state,
645
+ subscribe(listener) {
646
+ listeners.add(listener)
647
+ return () => { listeners.delete(listener) }
648
+ },
649
+ // 快捷键这种同步判断直接读服务,不读快照:服务刚挂上就能用,不等下一次采样。
650
+ available: () => read(),
651
+ start() {
652
+ measure('probe')
653
+ // 宽限期:语音客户端可能比本插件晚挂载,这段时间里先不下结论。
654
+ const timer = setTimeout(() => {
655
+ state.settled = true
656
+ measure('probe')
657
+ emit()
658
+ }, GRACE_MS)
659
+ // Cordis 在服务挂载/撤下时会发这个事件,是快路径;轮询是兜底,
660
+ // 因为语音客户端在本插件之后挂载时不一定有我们能收到的事件。
661
+ let off
662
+ try {
663
+ off = ctx.on('internal/service', (name) => {
664
+ if (name === DEPENDENCY_SERVICE) measure('event')
665
+ })
666
+ } catch (error) {
667
+ off = undefined
668
+ }
669
+ const poll = setInterval(() => measure('poll'), POLL_MS)
670
+ // Node-only safety net for headless tests; a no-op in the browser.
671
+ if (poll && typeof poll.unref === 'function') poll.unref()
672
+ return () => {
673
+ clearTimeout(timer)
674
+ clearInterval(poll)
675
+ if (typeof off === 'function') off()
676
+ }
677
+ },
678
+ }
679
+ }
680
+
681
+ // apply() 创建,组件通过 useDependency 订阅同一实例。
682
+ let monitor
683
+ // apply() 写入,供弹窗查询语音插件的安装/启用状态(拿不到时静默降级)。
684
+ let appCtx
685
+ function useDependency() {
686
+ const [, bump] = React.useReducer((x) => x + 1, 0)
687
+ React.useEffect(() => (monitor ? monitor.subscribe(bump) : undefined), [])
688
+ return monitor ? monitor.state : IDLE_STATE
689
+ }
690
+
691
+ // 快捷键按下但语音插件不在时,往输入框下面说一句话;几秒后自己消失。
692
+ // 只做提示,不改任何状态。
693
+ const HINT_MS = 20000
694
+ let hintText = null
695
+ // 提示有两种来源:缺依赖(要带按钮、挂在输入框下面)和自动发送倒计时(纯文字)。
696
+ // ComposerHint 只渲染前者,倒计时只借同一个通道显示文字。
697
+ let hintKind = 'dependency'
698
+ let hintTimer
699
+ // 录制键位时,插件自己的触发逻辑要让路,否则按下的组合会同时去开关录音。
700
+ let recordingHotkey = false
701
+ const hintListeners = new Set()
702
+ function emitHint() {
703
+ for (const listener of hintListeners) {
704
+ try {
705
+ listener()
706
+ } catch (error) {
707
+ /* ignore */
708
+ }
709
+ }
710
+ }
711
+ function showHint(text, kind) {
712
+ hintText = text
713
+ hintKind = kind === 'autosend' || kind === 'status' ? kind : 'dependency'
714
+ emitHint()
715
+ if (hintTimer) clearTimeout(hintTimer)
716
+ hintTimer = setTimeout(() => {
717
+ hintTimer = undefined
718
+ hintText = null
719
+ emitHint()
720
+ }, HINT_MS)
721
+ if (hintTimer && typeof hintTimer.unref === 'function') hintTimer.unref()
722
+ }
723
+ function clearHint() {
724
+ if (hintText === null) return
725
+ hintText = null
726
+ hintKind = 'dependency'
727
+ if (hintTimer) {
728
+ clearTimeout(hintTimer)
729
+ hintTimer = undefined
730
+ }
731
+ emitHint()
732
+ }
733
+ function useHintKind() {
734
+ const [, bump] = React.useReducer((x) => x + 1, 0)
735
+ React.useEffect(() => {
736
+ hintListeners.add(bump)
737
+ return () => hintListeners.delete(bump)
738
+ }, [])
739
+ return hintKind
740
+ }
741
+ function useHint() {
742
+ const [, bump] = React.useReducer((x) => x + 1, 0)
743
+ React.useEffect(() => {
744
+ hintListeners.add(bump)
745
+ return () => hintListeners.delete(bump)
746
+ }, [])
747
+ return hintText
748
+ }
749
+
750
+ // 输入框工具栏里常驻的键位标签:证明本插件确实在跑。
751
+ let hotkeyLabel = '未绑定'
752
+ const labelListeners = new Set()
753
+ function setHotkeyLabel(next) {
754
+ if (typeof next !== 'string' || next === hotkeyLabel) return
755
+ hotkeyLabel = next
756
+ for (const listener of labelListeners) {
757
+ try {
758
+ listener()
759
+ } catch (error) {
760
+ /* ignore */
761
+ }
762
+ }
763
+ }
764
+ function useHotkeyLabel() {
765
+ const [, bump] = React.useReducer((x) => x + 1, 0)
766
+ React.useEffect(() => {
767
+ labelListeners.add(bump)
768
+ return () => labelListeners.delete(bump)
769
+ }, [])
770
+ return hotkeyLabel
771
+ }
772
+
773
+ // 官方快捷键目录冲突提示(读 @deepseek-ai/dsh-client-shortcuts 的活数据)。
774
+ // '' = 没有冲突或无法判断;非空 = 给用户看的一句话。只提示,不拦截:
775
+ // 键位仍按原样生效,冲突时两边都会响应,换不换键由用户决定。
776
+ let conflictText = ''
777
+ const conflictListeners = new Set()
778
+ function setConflictText(next) {
779
+ const text = typeof next === 'string' ? next : ''
780
+ if (text === conflictText) return
781
+ conflictText = text
782
+ for (const listener of conflictListeners) {
783
+ try { listener() } catch (error) { /* ignore */ }
784
+ }
785
+ }
786
+ function useConflictText() {
787
+ const [, bump] = React.useReducer((x) => x + 1, 0)
788
+ React.useEffect(() => {
789
+ conflictListeners.add(bump)
790
+ return () => conflictListeners.delete(bump)
791
+ }, [])
792
+ return conflictText
793
+ }
794
+
795
+ /**
796
+ * 语音插件到底是「没装」还是「装了没开」。
797
+ * 靠客户端的 pluginManager 远程接口读组合包清单;没有权限、接口缺方法或
798
+ * 调用失败时一律回 'unknown',界面只会说「不可用」,不会瞎猜。
799
+ */
800
+ /**
801
+ * The plugin-manager namespace, read optionally: the gateway publishes each
802
+ * namespace as the child service `remote.<namespace>`, so read that name and
803
+ * fall back to the property the gateway object exposes. Undefined means the
804
+ * surface is not mounted for this page at all.
805
+ */
806
+ function pluginManager() {
807
+ try {
808
+ const direct = appCtx && appCtx.get('remote.pluginManager')
809
+ if (direct) return direct
810
+ } catch (error) {
811
+ /* fall through */
812
+ }
813
+ try {
814
+ const remote = appCtx && appCtx.get('remote')
815
+ return remote && remote.pluginManager
816
+ } catch (error) {
817
+ return undefined
818
+ }
819
+ }
820
+ /** Unary gateway calls resolve to `{ ok: true, value }` / `{ ok: false, error }`. */
821
+ function unwrap(result) {
822
+ if (result && result.ok === true) return { ok: true, value: result.value }
823
+ const error = result && result.error
824
+ const message = error && (error.message || error.code) ? (error.message || error.code) : '没有响应'
825
+ return { ok: false, error: message }
826
+ }
827
+ async function readBundleState() {
828
+ const manager = pluginManager()
829
+ if (!manager || typeof manager.listBundles !== 'function') return { kind: 'unknown', reason: 'no-manager' }
830
+ let answered
831
+ try {
832
+ answered = unwrap(await manager.listBundles())
833
+ } catch (error) {
834
+ return { kind: 'unknown', reason: String((error && error.message) || error) }
835
+ }
836
+ if (!answered.ok) return { kind: 'unknown', reason: answered.error }
837
+ const bundles = Array.isArray(answered.value) ? answered.value : []
838
+ const bundle = bundles.find((item) => item && item.name === DEPENDENCY_LABEL)
839
+ if (bundle === undefined) return { kind: 'unknown', reason: 'not-listed' }
840
+ // `installed` only says whether the *profile* declares the dependency; a bundle
841
+ // shipped with the installation reports installed:false and is still right there.
842
+ // Real absence is `availability === 'missing'`.
843
+ if (bundle.availability === 'missing') return { kind: 'missing', reason: '' }
844
+ if (bundle.enabled === false) return { kind: 'off', reason: '' }
845
+ return { kind: 'unknown', reason: 'listed-but-unclear' }
846
+ }
847
+ async function setBundleEnabled(enabled) {
848
+ const manager = pluginManager()
849
+ if (!manager || typeof manager.setBundleEnabled !== 'function') return { ok: false, error: '没有可用的插件管理接口' }
850
+ try {
851
+ const answered = unwrap(await manager.setBundleEnabled(DEPENDENCY_LABEL, enabled))
852
+ return answered.ok ? { ok: true } : { ok: false, error: answered.error }
853
+ } catch (error) {
854
+ return { ok: false, error: String((error && error.message) || error) }
855
+ }
856
+ }
857
+
858
+ /**
859
+ * 语音插件到底是「没装」还是「装了没开」。查不到就回 'unknown',界面只说
860
+ * 「不可用」,不瞎猜。`tick` 变化会让它重查一次。
861
+ */
862
+ function useVoicePluginState(active, tick) {
863
+ const [state, setState] = React.useState({ kind: 'checking', reason: '' })
864
+ React.useEffect(() => {
865
+ if (active !== true) return undefined
866
+ let live = true
867
+ readBundleState().then((next) => {
868
+ if (live) setState(next)
869
+ })
870
+ return () => { live = false }
871
+ }, [active, tick])
872
+ return state
873
+ }
874
+ // 可选读取,不形成硬注入等待;未挂载时返回 false 而不是抛错。
875
+ function hasVoiceDependency(ctx) {
876
+ try {
877
+ return ctx.get(DEPENDENCY_SERVICE) !== undefined
878
+ } catch (error) {
879
+ return false
880
+ }
881
+ }
882
+ const DANGER = 'var(--dsw-alias-state-error-primary, #e5484d)'
883
+ const DEPENDENCY_LABEL = '@deepseek-ai/dsh-experimental-voice-input-bundle'
884
+ const MISSING_TEXT = '语音插件未启用,本插件已停用。请在插件列表中启用「语音输入」。'
885
+ // 按快捷键时输入框下面那行提示;只说事实,不出现包名。
886
+ const HINT_TEXT = '语音插件未启用,快捷键暂不可用。'
887
+ const HINT_OFF_TEXT = '语音插件未启用。是否启用「语音输入」插件?'
888
+ const HINT_MISSING_TEXT = '未安装语音插件。请复制包名,在「插件 → 添加插件」中安装。'
889
+ const HINT_UNKNOWN_TEXT = '无法确认语音插件状态。请确认它已安装并启用。'
890
+ // 弹窗正文按「没装 / 没开 / 说不准」三档,措辞都不出现包名。
891
+ const ACTIVATION_TITLE = '语音输入不可用'
892
+ const ACTIVATION_TEXT = {
893
+ missing: '未安装语音插件。请复制下方包名,在「插件 → 添加插件」中安装。',
894
+ off: '语音插件未启用。是否启用「语音输入」插件?',
895
+ unknown: '无法确认语音插件状态。请确认它已安装并启用。',
896
+ checking: '正在读取语音插件状态…',
897
+ }
898
+
899
+ // The bundle-level config slot passes no form, so share the configForms one
900
+ // that apply() binds; the page reads and writes through this store.
901
+ let sharedForm
902
+ const formListeners = new Set()
903
+ function setSharedForm(form) {
904
+ sharedForm = form
905
+ for (const listener of formListeners) listener()
906
+ }
907
+ function useSharedForm() {
908
+ const [form, setForm] = React.useState(sharedForm)
909
+ const [, bump] = React.useReducer((x) => x + 1, 0)
910
+ React.useEffect(() => {
911
+ const listener = () => { setForm(sharedForm); bump() }
912
+ formListeners.add(listener)
913
+ listener()
914
+ return () => { formListeners.delete(listener) }
915
+ }, [])
916
+ React.useEffect(() => {
917
+ if (!form || typeof form.subscribe !== 'function') return undefined
918
+ return form.subscribe(bump)
919
+ }, [form])
920
+ return form
921
+ }
922
+
923
+ // Show the stored default in this platform's own words; custom values pass through.
924
+ function friendlyText(text) {
925
+ if (typeof text !== 'string' || text.trim() === '') return ''
926
+ return text === DEFAULT_HOTKEY ? DEFAULT_INPUT : text
927
+ }
928
+
929
+ /** Rendered directly on the plugin's detail page via `plugins.bundle.config`. */
930
+ function ConfigView() {
931
+ return React.createElement(ConfigPage)
932
+ }
933
+
934
+ function ConfigPage() {
935
+ const form = useSharedForm()
936
+ const dep = useDependency()
937
+ const conflict = useConflictText()
938
+ let snap
939
+ try { snap = form ? form.getSnapshot() : undefined } catch (error) { snap = undefined }
940
+ const raw = resolveRaw(snap && snap.value ? snap.value.hotkey : undefined)
941
+ // 「设为默认」把当前键位记进配置里的 defaultHotkey;「恢复默认」读它。
942
+ // 新安装没有这个值,所以初始仍然是未绑定。
943
+ const savedDefault = snap && snap.value && typeof snap.value.defaultHotkey === 'string'
944
+ ? snap.value.defaultHotkey
945
+ : ''
946
+ // 默认键位按同一套写法显示(mouse4 → Mouse4),存的是原始字符串。
947
+ const savedDefaultBinding = friendlyText(savedDefault) === DEFAULT_INPUT ? parseHotkey(DEFAULT_HOTKEY) : parseHotkey(savedDefault)
948
+ const defaultLabel = savedDefault === '' ? '' : (savedDefaultBinding ? displayHotkey(savedDefaultBinding) : savedDefault)
949
+ const current = friendlyText(raw)
950
+ const effective = parseHotkey(raw)
951
+ const [text, setText] = React.useState(current)
952
+ const [state, setStateRaw] = React.useState('')
953
+ // 提示行的红字:显式传第二参优先,否则按已知的错误话术判断。
954
+ // 成功/中性提示保持默认色,红字只留给出错和被拒的输入。
955
+ const [stateBad, setStateBad] = React.useState(false)
956
+ const setState = (next, bad) => {
957
+ setStateRaw(next)
958
+ setStateBad(bad === true || (bad === undefined
959
+ && (next.startsWith('无法使用') || next.startsWith('这个') || next.startsWith('请先') || next.includes('失败'))))
960
+ }
961
+ const [recording, setRecording] = React.useState(false)
962
+ // 手动输入模式:默认关。录制框默认只收真实按键;有的键不好按出来
963
+ // (小键盘、组合太长),允许切到手动直接写键位文本。
964
+ const [manual, setManual] = React.useState(false)
965
+ const [delayText, setDelayText] = React.useState(String(clampDelay(snap && snap.value ? snap.value.autoSendDelay : 0)))
966
+ const savedDelay = clampDelay(snap && snap.value ? snap.value.autoSendDelay : 0)
967
+ React.useEffect(() => { setDelayText(String(savedDelay)) }, [savedDelay])
968
+ // 延时框每次按键都写配置会产生一串写入请求(0 → 06 → 060):攒 400ms 再落盘,
969
+ // 失焦时立即补写一次,看到的结果一样但请求少得多。
970
+ const delayCommit = React.useState(() => ({ timer: undefined }))[0]
971
+ React.useEffect(() => () => {
972
+ if (delayCommit.timer !== undefined) clearTimeout(delayCommit.timer)
973
+ }, [delayCommit])
974
+ const commitDelaySoon = (seconds) => {
975
+ if (delayCommit.timer !== undefined) clearTimeout(delayCommit.timer)
976
+ delayCommit.timer = setTimeout(() => {
977
+ delayCommit.timer = undefined
978
+ void setAutoSendOptions('autoSendDelay', seconds)
979
+ }, 400)
980
+ if (delayCommit.timer && typeof delayCommit.timer.unref === 'function') delayCommit.timer.unref()
981
+ }
982
+ React.useEffect(() => { setText(current) }, [current])
983
+ // 光标放进输入框就等于在录制:直接按想要的组合即可,不用背写法,也不用点按钮。
984
+ // 左右键单击放行,免得点保存/取消时被自己吞掉;Esc 取消本次录制。
985
+ React.useEffect(() => {
986
+ if (!recording) return undefined
987
+ const accept = (raw, isMouse) => {
988
+ const parsed = parseHotkeyDetailed(raw)
989
+ if (parsed.error !== undefined) {
990
+ setState('无法使用:' + parsed.error)
991
+ return
992
+ }
993
+ setText(raw)
994
+ setState('已记下 ' + displayHotkey(parsed.binding) + ',点「保存」生效。')
995
+ // 记下一个合法组合就停止录制,否则 Tab/Enter 也会被当成按键吞掉,
996
+ // 用户没法用键盘走到「保存」。
997
+ setRecording(false)
998
+ }
999
+ const onKey = (event) => {
1000
+ event.preventDefault()
1001
+ event.stopPropagation()
1002
+ if (event.key === 'Escape') {
1003
+ setText(current)
1004
+ setState('已取消')
1005
+ setRecording(false)
1006
+ recordingHotkey = false
1007
+ if (event.target && typeof event.target.blur === 'function') event.target.blur()
1008
+ return
1009
+ }
1010
+ const raw = eventToHotkey(event, false)
1011
+ if (raw === undefined) {
1012
+ setState('这个键不能用作快捷键')
1013
+ return
1014
+ }
1015
+ accept(raw, false)
1016
+ }
1017
+ const onMouse = (event) => {
1018
+ // 裸左键留给界面自己用(取消、切页),但要说清楚为什么不录,
1019
+ // 否则按了左键界面毫无反应,像是坏了。
1020
+ if (event.button === 0 && !event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey) {
1021
+ setState('左键留给界面点击,不能单独作为快捷键;要配修饰键使用(如 ctrl+mouse1)。', true)
1022
+ return
1023
+ }
1024
+ event.preventDefault()
1025
+ event.stopPropagation()
1026
+ const raw = eventToHotkey(event, true)
1027
+ if (raw === undefined) {
1028
+ setState('这个鼠标键不能用作快捷键')
1029
+ return
1030
+ }
1031
+ accept(raw, true)
1032
+ }
1033
+ recordingHotkey = true
1034
+ window.addEventListener('keydown', onKey, true)
1035
+ window.addEventListener('mousedown', onMouse, true)
1036
+ return () => {
1037
+ recordingHotkey = false
1038
+ window.removeEventListener('keydown', onKey, true)
1039
+ window.removeEventListener('mousedown', onMouse, true)
1040
+ }
1041
+ }, [recording])
1042
+ if (!form) return React.createElement('p', null, '配置尚未就绪,请稍后刷新。')
1043
+ const mutate = async (ops) => {
1044
+ let latest
1045
+ try { latest = form.getSnapshot() } catch (error) { latest = snap }
1046
+ return form.mutate(ops, latest && latest.revision)
1047
+ }
1048
+ const save = async () => {
1049
+ const parsed = parseHotkeyDetailed(text)
1050
+ if (parsed.error !== undefined) {
1051
+ setState('无法使用:' + parsed.error)
1052
+ return
1053
+ }
1054
+ setState('保存中…')
1055
+ try {
1056
+ const ok = await mutate([{ op: 'set', path: ['hotkey'], value: text }])
1057
+ setState(ok ? '已保存,立即生效。' : '保存失败,请重试。')
1058
+ } catch (error) {
1059
+ setState('保存失败,请重试。')
1060
+ }
1061
+ }
1062
+ const reset = async () => {
1063
+ setState('保存中…')
1064
+ const parsed = parseHotkeyDetailed(savedDefault)
1065
+ const value = parsed.error !== undefined || parsed.binding === null ? '' : savedDefault
1066
+ try {
1067
+ const ok = await mutate([{ op: 'set', path: ['hotkey'], value }])
1068
+ if (ok) setText(value === '' ? '' : friendlyText(value))
1069
+ setState(ok
1070
+ ? (value === '' ? '已清空:无默认键位,当前未绑定。' : '已恢复默认键位,立即生效。')
1071
+ : '保存失败,请重试。')
1072
+ } catch (error) {
1073
+ setState('保存失败,请重试。')
1074
+ }
1075
+ }
1076
+ const setAutoSendOptions = async (key, value) => {
1077
+ setState('保存中…')
1078
+ try {
1079
+ const ok = await mutate([{ op: 'set', path: [key], value }])
1080
+ setState(ok ? '已保存,立即生效。' : '保存失败,请重试。')
1081
+ } catch (error) {
1082
+ setState('保存失败,请重试。')
1083
+ }
1084
+ }
1085
+ const setAsDefault = async () => {
1086
+ const parsed = parseHotkeyDetailed(text)
1087
+ if (parsed.error !== undefined || parsed.binding === null) {
1088
+ setState('请先录制一个可用的键位,再设为默认。')
1089
+ return
1090
+ }
1091
+ setState('保存中…')
1092
+ try {
1093
+ const ok = await mutate([{ op: 'set', path: ['defaultHotkey'], value: text }])
1094
+ setState(ok ? '已设为默认键位;「恢复默认」会回到它。' : '保存失败,请重试。')
1095
+ } catch (error) {
1096
+ setState('保存失败,请重试。')
1097
+ }
1098
+ }
1099
+ // 一键回到未绑定:等于保存空值,与「恢复默认」在没设过默认时的行为一致。
1100
+ const clear = async () => {
1101
+ setState('保存中…')
1102
+ try {
1103
+ const ok = await mutate([{ op: 'set', path: ['hotkey'], value: '' }])
1104
+ if (ok) setText('')
1105
+ setState(ok ? '已清空:当前未绑定。' : '保存失败,请重试。')
1106
+ } catch (error) {
1107
+ setState('保存失败,请重试。')
1108
+ }
1109
+ }
1110
+ const inputProps = {
1111
+ value: text,
1112
+ readOnly: !manual,
1113
+ 'aria-label': '快捷键录制框',
1114
+ // 手动输入:每次键入都过一遍解析,格式错了立刻说,不等到保存。
1115
+ onChange: manual
1116
+ ? (event) => {
1117
+ const next = event && event.target && typeof event.target.value === 'string' ? event.target.value : ''
1118
+ setText(next)
1119
+ if (next.trim() === '') { setState(''); return }
1120
+ const parsed = parseHotkeyDetailed(next)
1121
+ setState(parsed.error !== undefined ? '无法使用:' + parsed.error : '写法可用,点「保存」生效。')
1122
+ }
1123
+ : () => {},
1124
+ onFocus: manual
1125
+ ? undefined
1126
+ : () => {
1127
+ setRecording(true)
1128
+ setState('按下所需组合(Esc 取消)')
1129
+ },
1130
+ onBlur: manual ? undefined : () => setRecording(false),
1131
+ spellCheck: false,
1132
+ title: manual ? '直接输入键位,例如 ctrl+alt+P' : '点击后按下所需组合',
1133
+ style: {
1134
+ width: '240px', fontFamily: 'monospace', marginRight: '8px',
1135
+ cursor: manual ? 'text' : 'pointer',
1136
+ },
1137
+ }
1138
+ const input = Primitives.Input
1139
+ ? React.createElement(Primitives.Input, inputProps)
1140
+ : React.createElement('input', {
1141
+ ...inputProps,
1142
+ style: {
1143
+ ...inputProps.style, padding: '6px 10px', borderRadius: '6px',
1144
+ border: '1px solid var(--dsh-border, #555)', background: 'transparent', color: 'inherit',
1145
+ },
1146
+ })
1147
+ const button = (label, onClick, variant) => {
1148
+ if (Primitives.Button) {
1149
+ return React.createElement(Primitives.Button, {
1150
+ variant: variant || 'outline', size: 'md', onClick,
1151
+ style: { marginRight: '8px' },
1152
+ }, label)
1153
+ }
1154
+ return React.createElement('button', {
1155
+ type: 'button', onClick,
1156
+ style: {
1157
+ padding: '6px 14px', borderRadius: '6px', cursor: 'pointer',
1158
+ border: '1px solid var(--dsh-border, #555)', background: 'transparent', color: 'inherit',
1159
+ marginRight: '8px',
1160
+ },
1161
+ }, label)
1162
+ }
1163
+ // 自动发送:默认关闭。延时发送期间按 Esc 能取消,文案里写明。
1164
+ const autoSendOn = Boolean(snap && snap.value && snap.value.autoSend === true)
1165
+ const autoSendDelay = clampDelay(snap && snap.value ? snap.value.autoSendDelay : 0)
1166
+ const autoSendBusy = snap && snap.value && snap.value.autoSendBusy === 'enter' ? 'enter' : 'queue'
1167
+ const autoSendBlock = React.createElement('div', {
1168
+ style: {
1169
+ marginTop: '14px', padding: '10px 12px', borderRadius: '8px',
1170
+ border: '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.25))',
1171
+ fontSize: '13px',
1172
+ },
1173
+ },
1174
+ // 一行三等分(顺序 1/2/3):发送方式 | 延时 | 复选框+文字。
1175
+ React.createElement('div', {
1176
+ style: { marginTop: '8px', display: 'flex', alignItems: 'center', gap: '12px' },
1177
+ },
1178
+ React.createElement('label', {
1179
+ style: { flex: '1 1 0', display: 'flex', alignItems: 'center', gap: '6px', lineHeight: 1, minWidth: 0 },
1180
+ },
1181
+ '发送方式:',
1182
+ React.createElement('select', {
1183
+ value: autoSendBusy,
1184
+ 'aria-label': '自动发送方式',
1185
+ disabled: !autoSendOn,
1186
+ onChange: (event) => {
1187
+ void setAutoSendOptions('autoSendBusy', event.target.value === 'enter' ? 'enter' : 'queue')
1188
+ },
1189
+ style: { flex: '1 1 auto', height: '30px', padding: '4px 8px', borderRadius: '6px', boxSizing: 'border-box', minWidth: 0 },
1190
+ },
1191
+ React.createElement('option', { value: 'queue' }, '排队发送'),
1192
+ React.createElement('option', { value: 'enter' }, '插队发送'))),
1193
+ React.createElement('label', {
1194
+ style: { flex: '1 1 0', display: 'flex', alignItems: 'center', gap: '6px', lineHeight: 1, minWidth: 0 },
1195
+ },
1196
+ '发送延时:',
1197
+ React.createElement('input', {
1198
+ type: 'number',
1199
+ min: 0,
1200
+ max: MAX_AUTO_SEND_DELAY,
1201
+ step: 1,
1202
+ value: delayText,
1203
+ 'aria-label': '自动发送延时秒数',
1204
+ disabled: !autoSendOn,
1205
+ onChange: (event) => {
1206
+ const next = event.target.value
1207
+ setDelayText(next)
1208
+ const parsed = Number(next)
1209
+ // 能解析就先排队落盘;清空或非法时只改输入框,保留上一次有效的秒数。
1210
+ if (next.trim() !== '' && Number.isFinite(parsed)) {
1211
+ commitDelaySoon(Math.min(MAX_AUTO_SEND_DELAY, Math.max(0, Math.round(parsed))))
1212
+ }
1213
+ },
1214
+ onBlur: () => {
1215
+ if (delayCommit.timer !== undefined) { clearTimeout(delayCommit.timer); delayCommit.timer = undefined }
1216
+ const parsed = Number(delayText)
1217
+ if (delayText.trim() === '' || !Number.isFinite(parsed)) {
1218
+ setDelayText(String(autoSendDelay))
1219
+ return
1220
+ }
1221
+ const clamped = clampDelay(parsed)
1222
+ setDelayText(String(clamped))
1223
+ if (clamped !== autoSendDelay) void setAutoSendOptions('autoSendDelay', clamped)
1224
+ },
1225
+ style: { flex: '1 1 auto', width: '60px', height: '30px', padding: '4px 8px', borderRadius: '6px', boxSizing: 'border-box', minWidth: 0 },
1226
+ }),
1227
+ '秒'),
1228
+ React.createElement('label', {
1229
+ style: { flex: '1 1 0', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '8px', cursor: 'pointer', fontSize: '13px', lineHeight: 1, minWidth: 0 },
1230
+ },
1231
+ React.createElement('input', {
1232
+ type: 'checkbox',
1233
+ checked: autoSendOn,
1234
+ 'aria-label': '识别完成后自动发送',
1235
+ onChange: (event) => { void setAutoSendOptions('autoSend', event.target.checked) },
1236
+ }),
1237
+ '启用')),
1238
+ React.createElement('p', {
1239
+ style: { margin: '8px 0 0', fontSize: '12px', lineHeight: 1.6, opacity: 0.75 },
1240
+ }, autoSendOn
1241
+ ? ((autoSendDelay > 0
1242
+ ? '识别完成 ' + autoSendDelay + ' 秒后自动发送(0 = 立即,最长 ' + MAX_AUTO_SEND_DELAY + ' 秒);延时期间按 Esc 可取消本次发送。'
1243
+ : '识别完成后立即发送(最长延时 ' + MAX_AUTO_SEND_DELAY + ' 秒)。')
1244
+ + '录音被取消、未识别出文本、或因草稿变动导致插入失败时不发送。'
1245
+ + (autoSendBusy === 'enter'
1246
+ ? '插队发送在繁忙时模拟按一次回车;要真正插队,需把 DSH 设置「繁忙时的发送行为」设为「插话发送」,否则等同排队。'
1247
+ : '排队发送在繁忙时进入消息队列。'))
1248
+ : '未勾选时,识别结果仅插入输入框,发送由用户按下回车决定。'),
1249
+ )
1250
+ return React.createElement('div', null,
1251
+ dep.settled && dep.ready === false
1252
+ ? React.createElement('p', {
1253
+ role: 'alert',
1254
+ style: { margin: '0 0 8px', color: DANGER },
1255
+ }, MISSING_TEXT)
1256
+ : null,
1257
+ React.createElement('p', { style: { margin: '0 0 8px' } },
1258
+ '按一次开始录音,再次按下停止并识别。保存后立即生效,无需重启。'),
1259
+ React.createElement('p', { style: { margin: '0 0 8px' } },
1260
+ '当前生效:', React.createElement('code', null,
1261
+ effective !== null && effective !== undefined
1262
+ ? displayHotkey(effective)
1263
+ : (raw === '' ? '未绑定(已停用)' : '(无效)'))),
1264
+ conflict === ''
1265
+ ? null
1266
+ : React.createElement('p', {
1267
+ role: 'alert',
1268
+ style: { margin: '0 0 8px', color: DANGER, fontSize: '13px', lineHeight: 1.6 },
1269
+ }, '⚠ ' + conflict),
1270
+ React.createElement('p', { style: { margin: '0 0 8px', opacity: 0.85 } },
1271
+ '默认键位:', React.createElement('code', null, defaultLabel === '' ? '未设置' : defaultLabel)),
1272
+ React.createElement('div', null, input,
1273
+ hintButton(manual ? '回到录制' : '手动输入', () => {
1274
+ const next = !manual
1275
+ setManual(next)
1276
+ setRecording(false)
1277
+ setState(next
1278
+ ? '已切换为手动输入:直接输入键位写法,点「保存」生效。'
1279
+ : '已切回录制:点击输入框后按下所需组合。')
1280
+ }, 'brand'),
1281
+ button('保存', save),
1282
+ button('设为默认', setAsDefault), button('恢复默认', reset), button('清空', clear)),
1283
+ React.createElement('p', { style: { margin: '0 0 8px', opacity: 0.85, fontSize: '13px' } },
1284
+ '鼠标键规则:mouse4、mouse5(后退/前进)可单按;'
1285
+ + (IS_WEB ? '网页版里左/中/右键都需配修饰键。' : '桌面版里右键(mouse3)也可单按;左/中键需配修饰键。')),
1286
+ autoSendBlock,
1287
+ raw === ''
1288
+ ? React.createElement('p', {
1289
+ role: 'note',
1290
+ style: { margin: '12px 0 0', padding: '10px 12px', borderRadius: '8px', fontSize: '13px', lineHeight: 1.6, background: 'var(--dsw-alias-bg-layer-1, rgba(127,127,127,0.12))', color: 'var(--dsw-alias-label-secondary, #9aa0a6)' },
1291
+ }, PLATFORM_NOTICE)
1292
+ : null,
1293
+ state === ''
1294
+ ? null
1295
+ : React.createElement('p', {
1296
+ role: stateBad ? 'alert' : 'status',
1297
+ style: { margin: '8px 0 0', color: stateBad ? DANGER : undefined },
1298
+ }, state),
1299
+ )
1300
+ }
1301
+
1302
+ // Minimal focus management for the two plugin-owned modal dialogs. Recording
1303
+ // a hotkey consumes Escape first; a second Escape closes the dialog.
1304
+ function useModalDialog(active, onClose, containerRef) {
1305
+ const closeRef = React.useRef(onClose)
1306
+ closeRef.current = onClose
1307
+ React.useEffect(() => {
1308
+ if (!active) return undefined
1309
+ const previous = document.activeElement
1310
+ const node = containerRef.current
1311
+ const focusable = node && typeof node.querySelectorAll === 'function'
1312
+ ? Array.from(node.querySelectorAll('button:not([disabled]), input:not([disabled]), [tabindex="0"]'))
1313
+ : []
1314
+ const first = focusable[0] || node
1315
+ if (first && typeof first.focus === 'function') first.focus()
1316
+ const onKey = (event) => {
1317
+ if (event.key === 'Escape') {
1318
+ if (recordingHotkey) return
1319
+ event.preventDefault()
1320
+ event.stopPropagation()
1321
+ closeRef.current()
1322
+ return
1323
+ }
1324
+ if (event.key !== 'Tab' || focusable.length === 0) return
1325
+ const current = document.activeElement
1326
+ const at = focusable.indexOf(current)
1327
+ if (event.shiftKey && (at <= 0)) {
1328
+ event.preventDefault()
1329
+ focusable[focusable.length - 1].focus()
1330
+ } else if (!event.shiftKey && (at === focusable.length - 1 || at < 0)) {
1331
+ event.preventDefault()
1332
+ focusable[0].focus()
1333
+ }
1334
+ }
1335
+ window.addEventListener('keydown', onKey, true)
1336
+ return () => {
1337
+ window.removeEventListener('keydown', onKey, true)
1338
+ if (previous && previous.isConnected !== false && typeof previous.focus === 'function') previous.focus()
1339
+ }
1340
+ }, [active, containerRef])
1341
+ }
1342
+
1343
+ /**
1344
+ * Rendered by the plugin list right after the user enables this bundle.
1345
+ * It shows a dialog only when the probe has settled on "missing": while the
1346
+ * probe is pending or the dictation plugin is fine, nothing appears.
1347
+ */
1348
+ function ActivationNotice(props) {
1349
+ const dep = useDependency()
1350
+ const missing = dep.settled && dep.ready === false
1351
+ const [tick, setTick] = React.useState(0)
1352
+ const [busy, setBusy] = React.useState(false)
1353
+ const [failure, setFailure] = React.useState('')
1354
+ const state = useVoicePluginState(missing, tick)
1355
+ const kind = state.kind
1356
+ const [closed, setClosed] = React.useState(false)
1357
+ const [copied, setCopied] = React.useState(false)
1358
+ // 键位还没设时,同一个插槽换成「先设一个键」的引导框(软引导:可以稍后再说)。
1359
+ const label = useHotkeyLabel()
1360
+ const unbound = label === '未绑定' && dep.settled && dep.ready !== false
1361
+ const [setupClosed, setSetupClosed] = React.useState(false)
1362
+ const [pending, setPending] = React.useState('')
1363
+ const [setupNote, setSetupNote] = React.useState('')
1364
+ const [setupBusy, setSetupBusy] = React.useState(false)
1365
+ const [listening, setListening] = React.useState(false)
1366
+ React.useEffect(() => {
1367
+ if (!listening) return undefined
1368
+ const accept = (raw) => {
1369
+ const parsed = parseHotkeyDetailed(raw)
1370
+ if (parsed.error !== undefined || parsed.binding === null) {
1371
+ setSetupNote('无法使用:' + (parsed.error || '请按一个可用按键'))
1372
+ return
1373
+ }
1374
+ setPending(raw)
1375
+ setSetupNote('已记下 ' + displayHotkey(parsed.binding) + ',点「保存」生效。')
1376
+ setListening(false)
1377
+ }
1378
+ const onKey = (event) => {
1379
+ event.preventDefault()
1380
+ event.stopPropagation()
1381
+ if (event.key === 'Escape') {
1382
+ setPending('')
1383
+ setSetupNote('已取消')
1384
+ setListening(false)
1385
+ recordingHotkey = false
1386
+ if (event.target && typeof event.target.blur === 'function') event.target.blur()
1387
+ return
1388
+ }
1389
+ const raw = eventToHotkey(event, false)
1390
+ if (raw === undefined) {
1391
+ setSetupNote('这个键不能用作快捷键')
1392
+ return
1393
+ }
1394
+ accept(raw)
1395
+ }
1396
+ const onMouse = (event) => {
1397
+ if (event.button === 0 && !event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey) return
1398
+ event.preventDefault()
1399
+ event.stopPropagation()
1400
+ const raw = eventToHotkey(event, true)
1401
+ if (raw === undefined) {
1402
+ setSetupNote('这个鼠标键不能用作快捷键')
1403
+ return
1404
+ }
1405
+ accept(raw)
1406
+ }
1407
+ recordingHotkey = true
1408
+ window.addEventListener('keydown', onKey, true)
1409
+ window.addEventListener('mousedown', onMouse, true)
1410
+ return () => {
1411
+ recordingHotkey = false
1412
+ window.removeEventListener('keydown', onKey, true)
1413
+ window.removeEventListener('mousedown', onMouse, true)
1414
+ }
1415
+ }, [listening])
1416
+ const dialogRef = React.useRef(null)
1417
+ const dialogOpen = missing ? !closed : unbound && !setupClosed
1418
+ const dismissDialog = () => {
1419
+ if (missing) setClosed(true)
1420
+ else setSetupClosed(true)
1421
+ if (typeof props.onDismiss === 'function') props.onDismiss()
1422
+ }
1423
+ useModalDialog(dialogOpen, dismissDialog, dialogRef)
1424
+ const closeSetup = dismissDialog
1425
+ const saveSetup = async () => {
1426
+ const form = sharedForm
1427
+ if (!form) {
1428
+ setSetupNote('配置尚未就绪,请刷新后重试。')
1429
+ return
1430
+ }
1431
+ const parsed = parseHotkeyDetailed(pending)
1432
+ if (parsed.error !== undefined || parsed.binding === null) {
1433
+ setSetupNote('无法使用:' + (parsed.error || '请先按一个组合键'))
1434
+ return
1435
+ }
1436
+ setSetupBusy(true)
1437
+ try {
1438
+ let snap
1439
+ try { snap = form.getSnapshot() } catch (error) { snap = undefined }
1440
+ const ok = await form.mutate([{ op: 'set', path: ['hotkey'], value: pending }], snap && snap.revision)
1441
+ if (ok) {
1442
+ setSetupClosed(true)
1443
+ if (typeof props.onDismiss === 'function') props.onDismiss()
1444
+ return
1445
+ }
1446
+ setSetupNote('保存失败,请重试。')
1447
+ } catch (error) {
1448
+ setSetupNote('保存失败,请重试。')
1449
+ } finally {
1450
+ setSetupBusy(false)
1451
+ }
1452
+ }
1453
+ if (!missing) {
1454
+ if (!unbound || setupClosed) return null
1455
+ return React.createElement('div', {
1456
+ role: 'dialog',
1457
+ 'aria-modal': 'true',
1458
+ 'aria-labelledby': 'voice-hotkey-setup-title',
1459
+ style: {
1460
+ position: 'fixed', inset: 0, zIndex: 2147483000,
1461
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
1462
+ background: 'rgba(0, 0, 0, 0.45)',
1463
+ },
1464
+ },
1465
+ React.createElement('div', {
1466
+ ref: dialogRef,
1467
+ tabIndex: -1,
1468
+ style: {
1469
+ position: 'relative',
1470
+ width: '420px', maxWidth: 'calc(100vw - 32px)', padding: '20px 22px',
1471
+ borderRadius: '12px', fontSize: '13px', lineHeight: 1.7,
1472
+ background: 'var(--dsw-alias-bg-overlay, #1c1c1e)',
1473
+ color: 'var(--dsw-alias-label-primary, #f5f5f5)',
1474
+ border: '1px solid ' + DANGER,
1475
+ boxShadow: '0 12px 40px rgba(0, 0, 0, 0.35)',
1476
+ },
1477
+ },
1478
+ React.createElement('h3', {
1479
+ id: 'voice-hotkey-setup-title',
1480
+ style: { margin: '0 0 8px', fontSize: '15px', color: DANGER },
1481
+ }, '先设一个快捷键'),
1482
+ React.createElement('p', { style: { margin: '0 0 14px' } }, SETUP_TEXT),
1483
+ React.createElement('input', {
1484
+ readOnly: true,
1485
+ value: pending,
1486
+ 'aria-label': '快捷键录制框',
1487
+ placeholder: '点这里,然后按下组合键',
1488
+ onFocus: () => {
1489
+ setListening(true)
1490
+ setSetupNote('按下所需组合(Esc 取消)')
1491
+ },
1492
+ onBlur: () => setListening(false),
1493
+ title: '点击后按下所需组合',
1494
+ style: {
1495
+ width: '100%', boxSizing: 'border-box', padding: '8px 10px', marginBottom: '10px',
1496
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: '13px',
1497
+ borderRadius: '8px', cursor: 'pointer', color: 'inherit', background: 'transparent',
1498
+ border: '1px solid var(--dsw-alias-border-l2, #4a4a4a)',
1499
+ },
1500
+ }),
1501
+ setupNote === '' ? null : React.createElement('p', {
1502
+ style: { margin: '0 0 12px', fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #a3a3a3)' },
1503
+ }, setupNote),
1504
+ React.createElement('div', null,
1505
+ actionButton(setupBusy ? '保存中…' : '保存', saveSetup, true, setupBusy || pending === ''),
1506
+ actionButton('稍后', closeSetup, false, setupBusy)),
1507
+ ),
1508
+ )
1509
+ }
1510
+ if (closed) return null
1511
+ const onDismiss = props && props.onDismiss
1512
+ const onOpenDetails = props && props.onOpenDetails
1513
+ const close = () => {
1514
+ // React state first so the dialog goes away even if the slot owner keeps it mounted.
1515
+ setClosed(true)
1516
+ if (typeof onDismiss === 'function') onDismiss()
1517
+ }
1518
+ const goToList = () => {
1519
+ // `onOpenDetails` opens THIS plugin's detail page, which is the wrong
1520
+ // place to install from. `pluginNavigation.openList()` is the cross
1521
+ // plugin hook that selects the Plugins list.
1522
+ let opened = false
1523
+ try {
1524
+ const nav = appCtx && appCtx.get('pluginNavigation')
1525
+ if (nav && typeof nav.openList === 'function') {
1526
+ nav.openList()
1527
+ opened = true
1528
+ }
1529
+ } catch (error) {
1530
+ opened = false
1531
+ }
1532
+ if (!opened && typeof onOpenDetails === 'function') onOpenDetails()
1533
+ }
1534
+ const button = actionButton
1535
+ const enable = async () => {
1536
+ setBusy(true)
1537
+ setFailure('')
1538
+ const done = await setBundleEnabled(true)
1539
+ setBusy(false)
1540
+ if (done.ok) {
1541
+ // Enabling the voice plugin reloads the page; re-check anyway so a
1542
+ // live-only apply still flips this dialog to "ready".
1543
+ setTick((value) => value + 1)
1544
+ return
1545
+ }
1546
+ setFailure('启用失败:' + done.error + '。可在插件列表中手动启用。')
1547
+ if (typeof onOpenDetails === 'function') onOpenDetails()
1548
+ }
1549
+ const copySpec = async () => {
1550
+ let done = false
1551
+ try {
1552
+ const nav = (typeof window !== 'undefined' && window && window.navigator)
1553
+ || (typeof navigator !== 'undefined' ? navigator : undefined)
1554
+ const clipboard = nav ? nav.clipboard : undefined
1555
+ if (clipboard && typeof clipboard.writeText === 'function') {
1556
+ await clipboard.writeText(DEPENDENCY_LABEL)
1557
+ done = true
1558
+ }
1559
+ } catch (error) {
1560
+ done = false
1561
+ }
1562
+ setCopied(done)
1563
+ }
1564
+ const actions = []
1565
+ if (kind === 'off') {
1566
+ actions.push(button(busy ? '正在启用…' : '启用', enable, true, busy))
1567
+ actions.push(button('稍后', close, false, busy))
1568
+ } else if (kind === 'missing') {
1569
+ actions.push(button('稍后', close, true))
1570
+ } else {
1571
+ actions.push(button('打开插件列表', goToList, true))
1572
+ actions.push(button('稍后', close))
1573
+ }
1574
+ return React.createElement('div', {
1575
+ role: 'dialog',
1576
+ 'aria-modal': 'true',
1577
+ 'aria-labelledby': 'voice-hotkey-activation-title',
1578
+ style: {
1579
+ position: 'fixed', inset: 0, zIndex: 2147483000,
1580
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
1581
+ background: 'rgba(0, 0, 0, 0.45)',
1582
+ },
1583
+ },
1584
+ React.createElement('div', {
1585
+ ref: dialogRef,
1586
+ tabIndex: -1,
1587
+ style: {
1588
+ position: 'relative',
1589
+ width: '420px', maxWidth: 'calc(100vw - 32px)', padding: '20px 22px',
1590
+ borderRadius: '12px', fontSize: '13px', lineHeight: 1.7,
1591
+ background: 'var(--dsw-alias-bg-overlay, #1c1c1e)',
1592
+ color: 'var(--dsw-alias-label-primary, #f5f5f5)',
1593
+ border: '1px solid ' + DANGER,
1594
+ boxShadow: '0 12px 40px rgba(0, 0, 0, 0.35)',
1595
+ },
1596
+ },
1597
+ React.createElement('button', {
1598
+ type: 'button',
1599
+ 'aria-label': '关闭',
1600
+ title: '关闭',
1601
+ onClick: close,
1602
+ style: {
1603
+ position: 'absolute', top: '8px', right: '8px',
1604
+ width: '26px', height: '26px', padding: 0,
1605
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
1606
+ borderRadius: '6px', cursor: 'pointer', fontSize: '16px', lineHeight: 1,
1607
+ border: 'none', background: 'transparent',
1608
+ color: 'var(--dsw-alias-label-secondary, #a3a3a3)',
1609
+ },
1610
+ }, '×'),
1611
+ React.createElement('h3', {
1612
+ id: 'voice-hotkey-activation-title',
1613
+ style: { margin: '0 0 8px', fontSize: '15px', color: DANGER },
1614
+ }, ACTIVATION_TITLE),
1615
+ React.createElement('p', { style: { margin: '0 0 16px' } }, ACTIVATION_TEXT[kind] || ACTIVATION_TEXT.unknown),
1616
+ kind !== 'missing' ? null : React.createElement('p', {
1617
+ style: { margin: '0 0 16px' },
1618
+ },
1619
+ // A link-styled button: the spec stays a fixed string, and the click
1620
+ // copies it. `user-select: all` keeps the manual fallback working.
1621
+ React.createElement('button', {
1622
+ type: 'button',
1623
+ onClick: copySpec,
1624
+ title: '点击复制包名',
1625
+ 'aria-label': '复制包名 ' + DEPENDENCY_LABEL,
1626
+ style: {
1627
+ padding: 0, border: 'none', background: 'none', textAlign: 'left', cursor: 'pointer',
1628
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: '12px',
1629
+ color: 'var(--dsw-alias-brand-primary, #6ea8ff)',
1630
+ textDecoration: 'underline', textUnderlineOffset: '2px',
1631
+ userSelect: 'all', wordBreak: 'break-all',
1632
+ },
1633
+ }, DEPENDENCY_LABEL),
1634
+ copied ? React.createElement('span', {
1635
+ style: {
1636
+ marginLeft: '8px', fontSize: '12px',
1637
+ color: 'var(--dsw-alias-state-success-primary, #30a46c)',
1638
+ },
1639
+ }, '已复制') : null,
1640
+ ),
1641
+ failure === '' ? null : React.createElement('p', { style: { margin: '0 0 16px', color: DANGER } }, failure),
1642
+ React.createElement('div', {
1643
+ style: { display: 'flex', gap: '8px', justifyContent: 'flex-end' },
1644
+ }, actions),
1645
+ ),
1646
+ )
1647
+ }
1648
+
1649
+ /**
1650
+ * A red tag beside the bundle page's title, through `plugins.detail.badge`.
1651
+ * The list row's one-liner is static package text with no slot of its own,
1652
+ * so this is where a live state can sit next to the bundle's name.
1653
+ */
1654
+ function DependencyBadge(props) {
1655
+ const dep = useDependency()
1656
+ const subject = props && props.subject
1657
+ if (!subject || subject.kind !== 'bundle') return null
1658
+ if (!subject.pkg || subject.pkg.name !== BUNDLE_CONFIG_KEY) return null
1659
+ if (!dep.settled || dep.ready !== false) return null
1660
+ return React.createElement('span', {
1661
+ role: 'status',
1662
+ style: {
1663
+ padding: '1px 8px', borderRadius: '6px', border: '1px solid ' + DANGER,
1664
+ color: DANGER, fontSize: '12px', lineHeight: 1.6, whiteSpace: 'nowrap',
1665
+ },
1666
+ }, '语音插件未启用')
1667
+ }
1668
+
1669
+ /**
1670
+ * The same button in both places: primitives when the shell exposes them,
1671
+ * a plain button with the theme's error colour otherwise.
1672
+ */
1673
+ function actionButton(label, onClick, primary, disabled) {
1674
+ if (Primitives.Button) {
1675
+ return React.createElement(Primitives.Button, {
1676
+ variant: primary ? 'primary' : 'ghost',
1677
+ size: 'sm',
1678
+ onClick,
1679
+ disabled: disabled === true,
1680
+ }, label)
1681
+ }
1682
+ return React.createElement('button', {
1683
+ type: 'button',
1684
+ onClick,
1685
+ disabled: disabled === true,
1686
+ style: {
1687
+ padding: '4px 14px', borderRadius: '6px', cursor: disabled === true ? 'default' : 'pointer',
1688
+ fontSize: '12px', opacity: disabled === true ? 0.6 : 1,
1689
+ border: primary ? 'none' : '1px solid ' + DANGER,
1690
+ background: primary ? DANGER : 'transparent',
1691
+ color: primary ? '#fff' : 'inherit',
1692
+ },
1693
+ }, label)
1694
+ }
1695
+
1696
+ /**
1697
+ * Text-only button for the composer line. The dialog can afford a filled
1698
+ * button; here it would out-shout the one sentence it belongs to.
1699
+ */
1700
+ function hintButton(label, onClick, tone, disabled) {
1701
+ return React.createElement('button', {
1702
+ type: 'button',
1703
+ onClick,
1704
+ disabled: disabled === true,
1705
+ style: {
1706
+ padding: '0 2px', border: 'none', background: 'none',
1707
+ cursor: disabled === true ? 'default' : 'pointer',
1708
+ fontSize: '12px', lineHeight: 1.6, font: 'inherit',
1709
+ opacity: disabled === true ? 0.6 : 1,
1710
+ color: tone === 'brand'
1711
+ ? 'var(--dsw-alias-brand-primary, #4ea1ff)'
1712
+ : 'var(--dsw-alias-label-secondary, #a3a3a3)',
1713
+ textDecoration: 'underline', textUnderlineOffset: '2px',
1714
+ },
1715
+ }, label)
1716
+ }
1717
+
1718
+ /** The voice plugin's own page, where its on/off switch lives. */
1719
+ function openVoicePlugin() {
1720
+ try {
1721
+ const nav = appCtx && appCtx.get('pluginNavigation')
1722
+ if (nav && typeof nav.openBundle === 'function') {
1723
+ // An absent bundle lands on the plugin list instead, which is where
1724
+ // the install entry is.
1725
+ nav.openBundle(DEPENDENCY_LABEL)
1726
+ return
1727
+ }
1728
+ } catch (error) {
1729
+ /* fall through to the list */
1730
+ }
1731
+ openPluginList()
1732
+ }
1733
+
1734
+ /** This plugin's own detail page, where its config form lives. */
1735
+ function openPluginDetails() {
1736
+ try {
1737
+ const nav = appCtx && appCtx.get('pluginNavigation')
1738
+ if (nav && typeof nav.openBundle === 'function') {
1739
+ nav.openBundle(BUNDLE_CONFIG_KEY)
1740
+ return
1741
+ }
1742
+ } catch (error) {
1743
+ /* fall through to the list */
1744
+ }
1745
+ openPluginList()
1746
+ }
1747
+
1748
+ /** The plugin list, through the manager's own navigation service. */
1749
+ function openPluginList() {
1750
+ try {
1751
+ const nav = appCtx && appCtx.get('pluginNavigation')
1752
+ if (nav && typeof nav.openList === 'function') nav.openList()
1753
+ } catch (error) {
1754
+ /* ignore */
1755
+ }
1756
+ }
1757
+
1758
+ /**
1759
+ * A small pill in the composer toolbar: the configured key, so the hotkey is
1760
+ * visible while the plugin is running. Red once dictation is known missing.
1761
+ */
1762
+ function ShortcutBadge(props) {
1763
+ const dep = useDependency()
1764
+ const label = useHotkeyLabel()
1765
+ const conflict = useConflictText()
1766
+ const [hover, setHover] = React.useState(false)
1767
+ const anchorRef = React.useRef(null)
1768
+ const latest = React.useRef({})
1769
+ const hasSession = Boolean(props && props.sessionId !== undefined && typeof props.useInput === 'function')
1770
+ // Slot standardProps are stable for a mounted slot. The dummy keeps older
1771
+ // shells and isolated tests renderable without the conversation facade.
1772
+ const useInput = hasSession ? props.useInput : () => undefined
1773
+ const input = useInput((value) => value)
1774
+ latest.current = { input, inputActions: props && props.inputActions }
1775
+ React.useEffect(() => {
1776
+ if (!hasSession) return undefined
1777
+ return registerComposer(props, anchorRef, latest)
1778
+ }, [hasSession, props && props.sessionId, anchorRef, latest])
1779
+ const missing = dep.settled && dep.ready === false
1780
+ const unbound = label === '未绑定'
1781
+ const invalid = label === '配置无效'
1782
+ const unavailable = missing || unbound || invalid
1783
+ const colour = unavailable ? DANGER : 'var(--dsw-alias-label-tertiary, #9aa0a6)'
1784
+ return React.createElement('button', {
1785
+ ref: anchorRef,
1786
+ type: 'button',
1787
+ onClick: missing ? openVoicePlugin : openPluginDetails,
1788
+ onFocus: () => noteComposer(props && props.sessionId),
1789
+ onMouseDown: () => noteComposer(props && props.sessionId),
1790
+ 'data-unbound': unbound || invalid ? 'true' : undefined,
1791
+ onMouseEnter: () => setHover(true),
1792
+ onMouseLeave: () => setHover(false),
1793
+ title: missing
1794
+ ? '语音插件未启用,快捷键暂不可用(点击查看「语音输入」)'
1795
+ : unbound
1796
+ ? '尚未设置快捷键,语音输入快捷键暂不可用(点击设置)'
1797
+ : invalid
1798
+ ? '键位配置无效,快捷键暂不可用(点击重新设置)'
1799
+ : '语音快捷键:' + label + (conflict === '' ? '' : ';' + conflict) + '(点击修改)',
1800
+ 'aria-label': unbound || invalid ? '语音快捷键 ' + label + '(点击设置)' : '语音快捷键 ' + label,
1801
+ style: {
1802
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
1803
+ width: '24px', height: '22px', padding: 0,
1804
+ border: 'none', borderRadius: '6px', cursor: 'pointer',
1805
+ background: hover ? 'var(--dsw-alias-bg-layer-2, rgba(255, 255, 255, 0.08))' : 'transparent',
1806
+ color: colour, opacity: unavailable ? 1 : 0.85,
1807
+ },
1808
+ }, React.createElement('svg', {
1809
+ width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none',
1810
+ stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round',
1811
+ 'aria-hidden': 'true',
1812
+ },
1813
+ React.createElement('rect', { x: 1.5, y: 3.5, width: 13, height: 9, rx: 1.6 }),
1814
+ React.createElement('path', { d: 'M4.2 6.6h0M6.6 6.6h0M9 6.6h0M11.4 6.6h0M4.2 9.4h0M11.4 9.4h0' }),
1815
+ React.createElement('path', { d: 'M6.2 9.4h3.6' }),
1816
+ ))
1817
+ }
1818
+
1819
+ /**
1820
+ * A single line under the composer card. It is empty unless the user just
1821
+ * pressed the hotkey while the dictation plugin was unavailable, and it goes
1822
+ * away as soon as that plugin shows up.
1823
+ */
1824
+ function ComposerHint() {
1825
+ const dep = useDependency()
1826
+ const hint = useHint()
1827
+ const kindOfHint = useHintKind()
1828
+ const [tick, setTick] = React.useState(0)
1829
+ const [busy, setBusy] = React.useState(false)
1830
+ const [failure, setFailure] = React.useState('')
1831
+ const state = useVoicePluginState(hint !== null && kindOfHint === 'dependency', tick)
1832
+ if (hint === null) return null
1833
+ // 倒计时和「已取消」借同一个通道显示,但它们不是「语音插件缺失」:
1834
+ // 只出文字,不挂启用/打开插件这类动作。
1835
+ if (kindOfHint === 'autosend' || kindOfHint === 'status') {
1836
+ return React.createElement('div', {
1837
+ role: 'status',
1838
+ style: {
1839
+ padding: '6px 12px', margin: '0 auto', maxWidth: '760px',
1840
+ color: 'var(--dsw-alias-label-secondary, #a3a3a3)',
1841
+ fontSize: '12px', lineHeight: 1.6, textAlign: 'center',
1842
+ },
1843
+ }, hint)
1844
+ }
1845
+ if (dep.settled && dep.ready === true) return null
1846
+ const kind = state.kind
1847
+ // Same wording as the dialog, one line shorter: the actions follow the
1848
+ // same three cases so this needs no separate vocabulary.
1849
+ const detail = kind === 'off'
1850
+ ? HINT_OFF_TEXT
1851
+ : kind === 'missing'
1852
+ ? HINT_MISSING_TEXT
1853
+ : kind === 'checking'
1854
+ ? hint
1855
+ : HINT_UNKNOWN_TEXT
1856
+ const enable = async () => {
1857
+ setBusy(true)
1858
+ setFailure('')
1859
+ const done = await setBundleEnabled(true)
1860
+ setBusy(false)
1861
+ if (done.ok) {
1862
+ setTick((value) => value + 1)
1863
+ return
1864
+ }
1865
+ setFailure('启用失败:' + done.error)
1866
+ }
1867
+ // Quiet text buttons: this sits in the composer footer next to the status
1868
+ // line, so a filled button would shout louder than the message itself.
1869
+ const actions = kind === 'off'
1870
+ ? [hintButton(busy ? '正在启用…' : '启用', enable, 'brand', busy), hintButton('稍后', clearHint, 'muted', busy)]
1871
+ : [hintButton('打开插件', openPluginList, 'brand'), hintButton('稍后', clearHint, 'muted')]
1872
+ return React.createElement('div', {
1873
+ role: 'status',
1874
+ style: {
1875
+ padding: '6px 12px', margin: '0 auto', maxWidth: '760px',
1876
+ color: DANGER, fontSize: '12px', lineHeight: 1.6,
1877
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
1878
+ flexWrap: 'wrap', gap: '10px',
1879
+ },
1880
+ },
1881
+ React.createElement('span', null, failure === '' ? detail : failure),
1882
+ React.createElement('span', {
1883
+ style: { display: 'inline-flex', alignItems: 'center', gap: '6px' },
1884
+ }, actions),
1885
+ )
1886
+ }
1887
+
1888
+ let disposePreviousApply
1889
+ let diagnosticOwner
1890
+ function disposeHandle(handle) {
1891
+ try {
1892
+ if (typeof handle === 'function') handle()
1893
+ else if (handle && typeof handle.dispose === 'function') handle.dispose()
1894
+ } catch (error) {
1895
+ /* already disposed */
1896
+ }
1897
+ }
1898
+
1899
+ return {
1900
+ apply(ctx) {
1901
+ // A repeated apply must not leave two global listeners or let an old
1902
+ // cleanup tear down the new runtime.
1903
+ if (disposePreviousApply) disposePreviousApply()
1904
+ clearHint()
1905
+ cancelAutoSend(false)
1906
+ appCtx = ctx
1907
+ const owner = {}
1908
+ const ownMonitor = createDependencyMonitor(ctx)
1909
+ monitor = ownMonitor
1910
+ let binding = null
1911
+ // 键位变化后重算冲突提示;官方服务不可用时保持为空操作。
1912
+ let refreshConflicts = () => {}
1913
+ setHotkeyLabel('未绑定')
1914
+ let mode = 'default'
1915
+ let currentMode = 'default'
1916
+ let cleaned = false
1917
+ const cleanups = []
1918
+ const addCleanup = (dispose) => { if (typeof dispose === 'function') cleanups.push(dispose) }
1919
+
1920
+ const publish = (nextMode) => {
1921
+ if (typeof nextMode === 'string') currentMode = nextMode
1922
+ const state = ownMonitor.state
1923
+ diagnosticOwner = owner
1924
+ window.__voiceHotkey = {
1925
+ mode: currentMode,
1926
+ hotkey: binding === null ? hotkeyLabel : displayHotkey(binding),
1927
+ dependency: state.ready === true,
1928
+ dependencyState: { ready: state.ready === true, settled: state.settled, changes: state.changes },
1929
+ toggle: () => toggle(currentComposer()),
1930
+ }
1931
+ }
1932
+ const mark = (nextMode) => {
1933
+ if (typeof nextMode === 'string') mode = nextMode
1934
+ try {
1935
+ const state = ownMonitor.state
1936
+ const flag = state.settled && state.ready === false ? '-nodep' : ''
1937
+ document.title = document.title.replace(/\s*·voice:[a-z-]+/u, '') + ' ·voice:' + mode + flag
1938
+ } catch (error) {
1939
+ /* ignore */
1940
+ }
1941
+ }
1942
+ const cleanup = () => {
1943
+ if (cleaned) return
1944
+ cleaned = true
1945
+ for (let at = cleanups.length - 1; at >= 0; at -= 1) {
1946
+ try { cleanups[at]() } catch (error) { /* continue cleanup */ }
1947
+ }
1948
+ cancelAutoSend(false)
1949
+ composerSessions.clear()
1950
+ activeComposerId = undefined
1951
+ recordingHotkey = false
1952
+ clearHint()
1953
+ if (monitor === ownMonitor) monitor = undefined
1954
+ if (appCtx === ctx) appCtx = undefined
1955
+ try { document.title = document.title.replace(/\s*·voice:[a-z-]+/u, '') } catch (error) { /* ignore */ }
1956
+ if (diagnosticOwner === owner) {
1957
+ try { delete window.__voiceHotkey } catch (error) { window.__voiceHotkey = undefined }
1958
+ diagnosticOwner = undefined
1959
+ }
1960
+ if (disposePreviousApply === cleanup) disposePreviousApply = undefined
1961
+ }
1962
+ disposePreviousApply = cleanup
1963
+
1964
+ ctx.effect(() => {
1965
+ const offMonitor = ownMonitor.subscribe(() => {
1966
+ if (ownMonitor.state.ready === true && hintKind === 'dependency') clearHint()
1967
+ if (ownMonitor.state.ready === false) cancelAutoSend(false)
1968
+ mark()
1969
+ publish()
1970
+ })
1971
+ const stopMonitor = ownMonitor.start()
1972
+ addCleanup(offMonitor)
1973
+ addCleanup(stopMonitor)
1974
+
1975
+ const runHotkey = (event) => {
1976
+ if (!hasVoiceDependency(ctx)) {
1977
+ // Keep the documented non-invasive behaviour: explain, but let the
1978
+ // original key combination continue to the app/browser.
1979
+ showHint(HINT_TEXT)
1980
+ return false
1981
+ }
1982
+ event.preventDefault()
1983
+ event.stopPropagation()
1984
+ const session = currentComposer()
1985
+ const starting = Boolean(session && !voiceRow(session.root))
1986
+ if (starting) cancelAutoSend(false)
1987
+ try {
1988
+ const problem = toggle(session)
1989
+ if (problem !== undefined) {
1990
+ showHint(problem, 'status')
1991
+ return true
1992
+ }
1993
+ if (starting && autoSend) {
1994
+ if (!autoSendSupported(session)) {
1995
+ showHint('当前版本无法确认会话草稿,已停用本次自动发送;热键仍可使用。', 'status')
1996
+ return true
1997
+ }
1998
+ watchDictation(session)
1999
+ }
2000
+ } catch (error) {
2001
+ console.warn('[voice-hotkey] 切换失败:', error)
2002
+ showHint('语音输入切换失败,请使用麦克风按钮重试。', 'status')
2003
+ }
2004
+ // 本次按键已被我们消费(preventDefault 已执行),调用方可据此
2005
+ // 决定要不要继续吞掉后续事件(右键的 contextmenu)。
2006
+ return true
2007
+ }
2008
+
2009
+ const onKeyDown = (event) => {
2010
+ noteComposerActivity(event.target)
2011
+ if (recordingHotkey || event.repeat) return
2012
+ if (binding === null || binding.mouse !== undefined || !matches(event, binding)) return
2013
+ runHotkey(event)
2014
+ }
2015
+ // 右键作为热键触发后,浏览器/壳还会在同一串点击上派发 contextmenu;
2016
+ // 只有真的消费了这次右键才吞掉它,缺依赖或没命中时照常弹菜单。
2017
+ let suppressContextMenu = false
2018
+ const onMouseDown = (event) => {
2019
+ noteComposerActivity(event.target)
2020
+ if (recordingHotkey) return
2021
+ suppressContextMenu = false
2022
+ if (binding === null || !matchesMouse(event, binding)) return
2023
+ suppressContextMenu = runHotkey(event) === true && event.button === 2
2024
+ }
2025
+ const onContextMenu = (event) => {
2026
+ if (recordingHotkey) {
2027
+ // 录制中的右键会被输入框捕获为键位,菜单本身只会碍事。
2028
+ event.preventDefault()
2029
+ return
2030
+ }
2031
+ if (!suppressContextMenu) return
2032
+ suppressContextMenu = false
2033
+ event.preventDefault()
2034
+ }
2035
+ const onFocusIn = (event) => noteComposerActivity(event.target)
2036
+ const onEscape = (event) => {
2037
+ if (event.key !== 'Escape' || recordingHotkey) return
2038
+ if (autoSession === undefined && autoSendTimer === undefined) return
2039
+ cancelAutoSend(true)
2040
+ }
2041
+ // Stop-and-transcribe is the only voice-toolbar action that keeps an
2042
+ // auto-send session alive. Cancel, retry and conflict insertion all
2043
+ // require a fresh user decision and must never inherit this session.
2044
+ const onVoiceActivityClick = (event) => {
2045
+ if (!autoSession || !event.target || typeof event.target.closest !== 'function') return
2046
+ const button = event.target.closest('button')
2047
+ const row = button && typeof button.closest === 'function' ? button.closest('[data-voice-activity]') : undefined
2048
+ if (!row || row !== voiceRow(autoSession.root)) return
2049
+ const phase = row.getAttribute('data-voice-activity')
2050
+ const label = (button.getAttribute('aria-label') || '').trim()
2051
+ if (phase === 'recording' && STOP.test(label)) return
2052
+ cancelAutoSend(true)
2053
+ }
2054
+ window.addEventListener('keydown', onKeyDown, true)
2055
+ window.addEventListener('keydown', onEscape, true)
2056
+ window.addEventListener('mousedown', onMouseDown, true)
2057
+ window.addEventListener('contextmenu', onContextMenu, true)
2058
+ window.addEventListener('focusin', onFocusIn, true)
2059
+ window.addEventListener('click', onVoiceActivityClick, true)
2060
+ addCleanup(() => {
2061
+ window.removeEventListener('keydown', onKeyDown, true)
2062
+ window.removeEventListener('keydown', onEscape, true)
2063
+ window.removeEventListener('mousedown', onMouseDown, true)
2064
+ window.removeEventListener('contextmenu', onContextMenu, true)
2065
+ window.removeEventListener('focusin', onFocusIn, true)
2066
+ window.removeEventListener('click', onVoiceActivityClick, true)
2067
+ })
2068
+
2069
+ const disposeSlots = ctx.inject(['slots'], (slotsCtx) => {
2070
+ const slots = slotsCtx.slots
2071
+ if (!slots || typeof slots.inject !== 'function') return undefined
2072
+ const register = (key, component, id) => {
2073
+ try {
2074
+ const options = id === undefined
2075
+ ? { name: key, key: BUNDLE_CONFIG_KEY }
2076
+ : { name: key, id }
2077
+ return slots.inject(key, () => slots.register(options, component))
2078
+ } catch (error) {
2079
+ return undefined
2080
+ }
2081
+ }
2082
+ const disposers = [
2083
+ register('plugins.bundle.config', ConfigView),
2084
+ register('plugins.bundle.activation', ActivationNotice),
2085
+ register('plugins.detail.badge', DependencyBadge, 'voice-hotkey-dependency'),
2086
+ register('conversation.input.right', ShortcutBadge, 'voice-hotkey-badge'),
2087
+ register('conversation.composer.dock', ComposerHint, 'voice-hotkey-hint'),
2088
+ ]
2089
+ return () => {
2090
+ for (const dispose of disposers) disposeHandle(dispose)
2091
+ }
2092
+ })
2093
+ addCleanup(() => disposeHandle(disposeSlots))
2094
+
2095
+ const disposeConfig = ctx.inject(['configForms'], (configCtx) => {
2096
+ const forms = configCtx.configForms
2097
+ if (!forms || typeof forms.get !== 'function' || typeof forms.describe !== 'function') return undefined
2098
+ const describe = forms.describe()
2099
+ let activeForm
2100
+ let unbindForm
2101
+ let boundNs
2102
+
2103
+ const resolveNamespace = () => {
2104
+ let view
2105
+ try { view = describe.getSnapshot().view } catch (error) { return undefined }
2106
+ const namespaces = (view && view.namespaces) || []
2107
+ for (const id of ENTRY_IDS) {
2108
+ for (const row of namespaces) if (row.ns === id) return row.ns
2109
+ }
2110
+ const candidates = namespaces.filter((row) => row.value && typeof row.value === 'object'
2111
+ && 'hotkey' in row.value && 'defaultHotkey' in row.value
2112
+ && 'autoSend' in row.value && 'autoSendDelay' in row.value)
2113
+ return candidates.length === 1 ? candidates[0].ns : undefined
2114
+ }
2115
+ const unbindActive = () => {
2116
+ if (unbindForm) unbindForm()
2117
+ unbindForm = undefined
2118
+ activeForm = undefined
2119
+ boundNs = undefined
2120
+ setSharedForm(undefined)
2121
+ }
2122
+ const pull = () => {
2123
+ if (!activeForm) return
2124
+ let snap
2125
+ try { snap = activeForm.getSnapshot() } catch (error) { return }
2126
+ const nextAutoSend = Boolean(snap && snap.value && snap.value.autoSend === true)
2127
+ if (autoSend && !nextAutoSend) cancelAutoSend(false)
2128
+ autoSend = nextAutoSend
2129
+ autoSendDelaySeconds = clampDelay(snap && snap.value ? snap.value.autoSendDelay : 0)
2130
+ autoSendBusy = snap && snap.value && snap.value.autoSendBusy === 'enter' ? 'enter' : 'queue'
2131
+ const text = resolveRaw(snap && snap.value ? snap.value.hotkey : undefined)
2132
+ if (text === '') {
2133
+ binding = null
2134
+ setHotkeyLabel('未绑定')
2135
+ publish('config')
2136
+ mark('config')
2137
+ refreshConflicts()
2138
+ return
2139
+ }
2140
+ const parsed = parseHotkeyDetailed(text)
2141
+ if (parsed.error !== undefined || parsed.binding === null) {
2142
+ binding = null
2143
+ setHotkeyLabel('配置无效')
2144
+ console.warn('[voice-hotkey] 无法解析键位:', text)
2145
+ publish('config')
2146
+ mark('config')
2147
+ refreshConflicts()
2148
+ return
2149
+ }
2150
+ binding = parsed.binding
2151
+ setHotkeyLabel(displayHotkey(binding))
2152
+ publish('config')
2153
+ mark('config')
2154
+ refreshConflicts()
2155
+ }
2156
+ const sync = () => {
2157
+ const ns = resolveNamespace()
2158
+ if (ns === boundNs) return
2159
+ unbindActive()
2160
+ if (!ns) {
2161
+ autoSend = false
2162
+ autoSendBusy = 'queue'
2163
+ autoSendDelaySeconds = 0
2164
+ cancelAutoSend(false)
2165
+ binding = null
2166
+ setHotkeyLabel('未绑定')
2167
+ publish('config')
2168
+ mark('config')
2169
+ return
2170
+ }
2171
+ const nextForm = forms.get(ns)
2172
+ if (!nextForm) return
2173
+ boundNs = ns
2174
+ activeForm = nextForm
2175
+ setSharedForm(activeForm)
2176
+ pull()
2177
+ if (typeof activeForm.subscribe === 'function') unbindForm = activeForm.subscribe(pull)
2178
+ }
2179
+
2180
+ let unbindDescribe
2181
+ try { unbindDescribe = describe.subscribe(sync) } catch (error) { unbindDescribe = undefined }
2182
+ if (typeof describe.ensure === 'function') {
2183
+ try { describe.ensure().catch(() => {}) } catch (error) { /* ignore */ }
2184
+ }
2185
+ sync()
2186
+ return () => {
2187
+ unbindActive()
2188
+ if (unbindDescribe) unbindDescribe()
2189
+ }
2190
+ })
2191
+ addCleanup(() => disposeHandle(disposeConfig))
2192
+
2193
+ // 冲突检测:键位和官方快捷键目录撞车时提前说一声。只读官方服务,
2194
+ // 不注册、不拦截;服务不在(旧壳、未随装的页面)就整段沉默。
2195
+ // 鼠标键和小键盘官方目录管不到,映射不出物理键的也跳过,不编造结论。
2196
+ const disposeShortcuts = ctx.inject(['shortcuts'], (scope) => {
2197
+ const shortcuts = scope.shortcuts
2198
+ if (!shortcuts || typeof shortcuts.describeBinding !== 'function') return undefined
2199
+ const unsubs = []
2200
+ const recompute = () => {
2201
+ if (binding === null) { setConflictText(''); return }
2202
+ const official = toOfficialBinding(binding)
2203
+ if (official === null) { setConflictText(''); return }
2204
+ let described
2205
+ try {
2206
+ described = shortcuts.describeBinding(official)
2207
+ } catch (error) {
2208
+ setConflictText('')
2209
+ return
2210
+ }
2211
+ const issue = described && described.issue
2212
+ const conflicts = described && Array.isArray(described.conflicts) ? described.conflicts : []
2213
+ if (conflicts.length === 0) {
2214
+ setConflictText(issue
2215
+ ? '当前环境为这个组合保留了专门用途,快捷键可能无法生效。'
2216
+ : '')
2217
+ return
2218
+ }
2219
+ let labels = conflicts
2220
+ try {
2221
+ const rows = shortcuts.catalog && typeof shortcuts.catalog.getSnapshot === 'function'
2222
+ ? shortcuts.catalog.getSnapshot()
2223
+ : []
2224
+ if (Array.isArray(rows)) {
2225
+ labels = conflicts.map((id) => {
2226
+ const row = rows.find((item) => item && item.id === id)
2227
+ return (row && row.label) || id
2228
+ })
2229
+ }
2230
+ } catch (error) { /* labels 退回 id */ }
2231
+ const shown = labels.slice(0, 3).join('、') + (labels.length > 3 ? ' 等' : '')
2232
+ setConflictText('这个组合已被「' + shown + '」占用,两边会同时响应;建议换一个键。')
2233
+ }
2234
+ refreshConflicts = recompute
2235
+ try { unsubs.push(shortcuts.catalog.subscribe(recompute)) } catch (error) { /* 目录不可订阅就算了 */ }
2236
+ recompute()
2237
+ return () => {
2238
+ refreshConflicts = () => {}
2239
+ for (const off of unsubs) { try { off() } catch (error) { /* already gone */ } }
2240
+ setConflictText('')
2241
+ }
2242
+ })
2243
+ addCleanup(() => disposeHandle(disposeShortcuts))
2244
+
2245
+ publish('default')
2246
+ mark('default')
2247
+ return cleanup
2248
+ }, 'voice-hotkey: configurable dictation toggle')
2249
+ },
2250
+ }
2251
+ },
2252
+ })