dsh-better-chat/src/client/chat/approval-keys.ts

166 lines
6.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 功能一:审批卡片的回车批准 / Esc 拒绝(自动送入焦点 + 全局兜底路由)。
*
* 背景(@deepseek-ai/dsh-client-ui-approval):官方审批卡自带键盘处理
* —— Enter 批准(单次)、Esc 拒绝 —— 但 keydown 挂在卡片根节点上,且
* 要求焦点先落在卡片内。审批弹出时焦点往往还在对话区,按回车毫无反应。
*
* 本模块补两件事,不改官方任何逻辑:
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片详情区。
* 2. 焦点不在卡片内时兜底路由:document 捕获阶段拦 keydown,点击卡片
* 操作行里的按钮 —— 回车点「允许(单次)」,Esc 点「拒绝」。
*/
const CARD_SELECTOR = '[data-approval-key]'
const SCROLL_SELECTOR = '[data-approval-scroll]'
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
import {
DEFAULT_BINDINGS,
bindingMatches,
isPlainBinding,
type ApprovalAction,
type ApprovalBinding,
type ApprovalBindings,
} from './bindings.js'
export interface KeyActionInput {
key: string
ctrlKey?: boolean
metaKey?: boolean
altKey?: boolean
shiftKey?: boolean
repeat?: boolean
isComposing?: boolean
keyCode?: number
defaultPrevented?: boolean
target?: Element | null
activeElement?: Element | null
card?: Element | null
/** 卡片是否有可用的「始终允许」按钮(第三个操作按钮)。 */
hasAlways?: boolean
/** 当前快捷键绑定;缺省使用 DEFAULT_BINDINGS。 */
bindings?: ApprovalBindings
}
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
export function actionButtons(card: Element): HTMLButtonElement[] {
return [...card.querySelectorAll('button')].filter(
(button) => !button.closest(SCROLL_SELECTOR),
) as HTMLButtonElement[]
}
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
export function findPendingCard(doc: Document): Element | null {
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
if (card.getAttribute('aria-busy') === 'true') continue
const buttons = actionButtons(card)
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
}
return null
}
/**
* 纯判定:这次 keydown 是否应该路由到审批卡。
*
* 默认绑定:Enter → 允许(单次)、Ctrl/Cmd+Enter → 始终允许、Esc → 拒绝;
* 绑定可由设置页改写(见 bindings.ts),基础键固定 Enter/Escape,只调修饰键。
* 官方卡片本身对带修饰键的按键不作答,所以带修饰键的绑定即使在卡内也由
* 本插件处理;裸 Enter/Esc 在卡内交给官方。
*
* @returns 'allow' | 'reject' | 'always' | null
*/
export function decideKeyAction(input: KeyActionInput): 'allow' | 'reject' | 'always' | null {
const {
repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card, hasAlways,
} = input
if (!card) return null
if (defaultPrevented) return null
if (repeat || isComposing || keyCode === 229) return null
// 正在输入控件里打字时一律不拦截(含卡片内的输入框)。
if (target && typeof target.closest === 'function' && target.closest(EDITABLE_SELECTOR) !== null) {
return null
}
const bindings = input.bindings ?? DEFAULT_BINDINGS
const candidates: Array<[ApprovalAction, ApprovalBinding | null]> = [
['allow', bindings.allow],
['always', hasAlways ? bindings.always : null],
['reject', bindings.reject],
]
for (const [action, binding] of candidates) {
if (!binding || !bindingMatches(binding, input)) continue
if (isPlainBinding(binding)) {
// 裸键在卡内交给官方;Enter 落在别的按钮/链接上时保留它自己的行为。
if (activeElement && card.contains(activeElement)) return null
if (binding.key === 'Enter' && target && typeof target.closest === 'function'
&& target.closest('button, a[href], [role="button"]') !== null) {
return null
}
}
return action
}
return null
}
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
export function shouldAutoFocus(activeElement: Element | null | undefined, card: Element): boolean {
if (!activeElement) return true
if (activeElement === card.ownerDocument?.body) return true
if (card.contains(activeElement)) return false // 已经在卡里
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) {
return false // 正在别处输入
}
return true
}
/** 安装审批键盘增强,返回卸载函数。 */
export function install(doc: Document, getBindings?: () => ApprovalBindings): () => void {
const focusedCards = new WeakSet<Element>()
const tryAutoFocus = (): void => {
const card = findPendingCard(doc)
if (!card || focusedCards.has(card)) return
focusedCards.add(card)
if (!shouldAutoFocus(doc.activeElement, card)) return
const region = card.querySelector(SCROLL_SELECTOR)
if (region && typeof (region as HTMLElement).focus === 'function') (region as HTMLElement).focus()
}
const observer = new MutationObserver(tryAutoFocus)
observer.observe(doc.documentElement, { childList: true, subtree: true })
tryAutoFocus()
const onKeyDown = (event: KeyboardEvent): void => {
const card = findPendingCard(doc)
if (!card) return
const buttons = actionButtons(card)
const hasAlways = buttons.length >= 3 && !buttons[2].disabled
const action = decideKeyAction({
key: event.key,
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
defaultPrevented: event.defaultPrevented,
target: event.target as Element | null, activeElement: doc.activeElement, card, hasAlways,
bindings: getBindings?.() ?? DEFAULT_BINDINGS,
})
if (!action) return
const button = action === 'allow'
? buttons[1]
: action === 'always'
? buttons[2]
: buttons[0]
if (!button || button.disabled) return
event.preventDefault()
event.stopPropagation()
button.click()
}
doc.addEventListener('keydown', onKeyDown, true)
return () => {
observer.disconnect()
doc.removeEventListener('keydown', onKeyDown, true)
}
}