dsh-better-chat/src/client/chat/key-hint.ts

182 lines
5.7 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.

/**
* 审批卡键盘提示:在操作行左侧显示「Enter 允许(单次) · Ctrl+Enter
* 始终允许 · Esc 拒绝」的键帽提示,文案直接取卡片按钮的实际文字。
*
* 提示只是说明,不参与点击:pointer-events: none、aria-hidden,且只挂在
* 卡片操作行里(详情滚动区之外)。React 重渲染把提示冲掉时,MutationObserver
* 会按按钮文案的签名重新挂回去;卡片作答后(aria-busy)立即移除。
*/
import { actionButtons } from './approval-keys.js'
export const HINT_ATTR = 'data-better-chat-keyhint'
const CARD_SELECTOR = '[data-approval-key]'
const SEPARATOR = '·'
export interface HintPart {
key: string
label: string
}
export interface HintLabels {
allow?: string
always?: string
reject?: string
}
/** 纯判定:当前平台是否用 Cmd 代替 Ctrl(只影响提示文案)。 */
export function isMacPlatform(platform: string | undefined | null): boolean {
return typeof platform === 'string' && /Mac|iPhone|iPad|iPod/.test(platform)
}
/**
* 纯函数:根据卡片上实际存在的按钮文案,生成提示的分段。
* 没有「始终允许」按钮时就不显示 Ctrl+Enter。
*/
export function hintParts(labels: HintLabels, mac: boolean): HintPart[] {
const parts: HintPart[] = []
if (labels.allow) parts.push({ key: 'Enter', label: labels.allow })
// Use the word "Cmd" instead of the ⌘ glyph: the glyph falls back to a CJK
// character under some font stacks, while "Cmd" is always legible.
if (labels.always) parts.push({ key: mac ? 'Cmd+Enter' : 'Ctrl+Enter', label: labels.always })
if (labels.reject) parts.push({ key: 'Esc', label: labels.reject })
return parts
}
/** 纯函数:提示内容的签名,用于判断是否需要重建。 */
export function hintSignature(parts: readonly HintPart[]): string {
return parts.map((part) => `${part.key}=${part.label}`).join('|')
}
const HINT_CSS = [
'margin-right:auto',
'display:inline-flex',
'flex-wrap:wrap',
'align-items:center',
'gap:6px',
'font-size:12px',
'line-height:18px',
'color:var(--dsw-alias-label-tertiary,#8b919b)',
'user-select:none',
'pointer-events:none',
].join(';')
const KEYCAP_CSS = [
'display:inline-flex',
'align-items:center',
'justify-content:center',
'height:18px',
'padding:0 5px',
'border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35))',
'border-bottom-width:2px',
'border-radius:5px',
'background:var(--dsw-alias-bg-module-platform,rgba(127,127,127,.08))',
'font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace)',
'font-size:11px',
'line-height:1',
'letter-spacing:.2px',
].join(';')
const PAIR_CSS = 'display:inline-flex;align-items:center;gap:5px'
const SEPARATOR_CSS = 'opacity:.45;margin:0 2px'
function labelOf(button: HTMLButtonElement | undefined): string | undefined {
if (!button) return undefined
const text = button.textContent?.trim()
return text ? text : undefined
}
function buildHint(doc: Document, parts: readonly HintPart[]): HTMLElement {
const hint = doc.createElement('div')
hint.setAttribute(HINT_ATTR, '')
hint.setAttribute('role', 'note')
hint.setAttribute('aria-hidden', 'true')
hint.style.cssText = HINT_CSS
parts.forEach((part, index) => {
if (index > 0) {
const separator = doc.createElement('span')
separator.textContent = SEPARATOR
separator.style.cssText = SEPARATOR_CSS
hint.append(separator)
}
const pair = doc.createElement('span')
pair.style.cssText = PAIR_CSS
const keycap = doc.createElement('span')
keycap.textContent = part.key
keycap.style.cssText = KEYCAP_CSS
const label = doc.createElement('span')
label.textContent = part.label
pair.append(keycap, label)
hint.append(pair)
})
return hint
}
function removeHints(doc: Document): void {
for (const hint of doc.querySelectorAll(`[${HINT_ATTR}]`)) hint.remove()
}
/**
* 安装审批卡键盘提示,返回卸载函数。
* @param platform 用于区分 Cmd/Ctrl;默认读 navigator.platform。
*/
export function installKeyHints(
doc: Document,
platform: string | undefined | null = doc.defaultView?.navigator?.platform,
): () => void {
const mac = isMacPlatform(platform)
let disposed = false
const syncCard = (card: Element): void => {
const buttons = actionButtons(card)
const existing = card.querySelector(`[${HINT_ATTR}]`)
const answered = card.getAttribute('aria-busy') === 'true'
if (answered || buttons.length < 2 || buttons[0].disabled || buttons[1].disabled) {
existing?.remove()
return
}
const always = buttons.length >= 3 && !buttons[2].disabled ? buttons[2] : undefined
const parts = hintParts({
allow: labelOf(buttons[1]),
always: labelOf(always),
reject: labelOf(buttons[0]),
}, mac)
if (parts.length === 0) {
existing?.remove()
return
}
const signature = hintSignature(parts)
if (existing && existing.getAttribute('data-signature') === signature) return
existing?.remove()
const row = buttons[0].parentElement
if (!row) return
const hint = buildHint(doc, parts)
hint.setAttribute('data-signature', signature)
row.insertBefore(hint, row.firstChild)
}
const sync = (): void => {
if (disposed) return
const cards = doc.querySelectorAll(CARD_SELECTOR)
if (cards.length === 0) {
removeHints(doc)
return
}
for (const card of cards) syncCard(card)
}
const observer = new MutationObserver(sync)
observer.observe(doc.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['aria-busy', 'disabled'],
})
sync()
return () => {
disposed = true
observer.disconnect()
removeHints(doc)
}
}