import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { gradeContrast, contrastRatio } from "./lib/contrast"; import { allowsInInput, findBinding, findConflicts, formatCombo, isEditable, normalizeCombo, type Binding, type Context, } from "./lib/shortcuts"; const baseBindings: Binding[] = [ { id: "search.focus", title: "聚焦搜索框", combo: "meta+k", scope: "global", enabled: true, }, { id: "search.slash", title: "聚焦搜索框(斜杠)", combo: "/", scope: "global", enabled: true, }, { id: "help.open", title: "打开快捷键帮助", combo: "?", scope: "global", enabled: true, }, { id: "help.close", title: "关闭帮助对话框", combo: "escape", scope: "dialog", enabled: true, }, { id: "help.confirm", title: "确认并关闭帮助", combo: "meta+enter", scope: "dialog", enabled: true, }, { id: "contrast.muted", title: "切换到低对比示例", combo: "shift+c", scope: "global", enabled: true, }, ]; const experimentalBinding: Binding = { id: "search.experiment", title: "快速搜索(实验)", combo: "meta+k", scope: "global", enabled: true, }; export function buildBindings(conflictMode: boolean): Binding[] { return conflictMode ? [...baseBindings, experimentalBinding] : [...baseBindings]; } export default function App() { const [conflictMode, setConflictMode] = useState(false); const [helpOpen, setHelpOpen] = useState(false); const [lastCombo, setLastCombo] = useState(""); const [lastCommandId, setLastCommandId] = useState(""); const [announcement, setAnnouncement] = useState("等待快捷键输入"); const [composing, setComposing] = useState(false); const [imeValue, setImeValue] = useState(""); const [imeEvents, setImeEvents] = useState([]); const [foreground, setForeground] = useState("#2563eb"); const [background, setBackground] = useState("#ffffff"); const [dialogLog, setDialogLog] = useState([]); const [focusId, setFocusId] = useState("help-close"); const searchRef = useRef(null); const imeRef = useRef(null); const triggerRef = useRef(null); const closeRef = useRef(null); const docsRef = useRef(null); const resetRef = useRef(null); const composingRef = useRef(false); const bindings = useMemo(() => buildBindings(conflictMode), [conflictMode]); const conflicts = useMemo(() => findConflicts(bindings), [bindings]); const contrast = useMemo( () => gradeContrast(contrastRatio(foreground, background)), [foreground, background], ); const closeHelp = useCallback((message: string) => { setHelpOpen(false); setAnnouncement(message); requestAnimationFrame(() => triggerRef.current?.focus()); }, []); const runCommand = useCallback( (id: string) => { setLastCommandId(id); if (id === "search.focus" || id === "search.slash") { setAnnouncement("已聚焦搜索框"); searchRef.current?.focus(); return; } if (id === "help.open") { setHelpOpen(true); setAnnouncement("已打开快捷键帮助"); return; } if (id === "help.close") { closeHelp("已关闭快捷键帮助"); return; } if (id === "help.confirm") { closeHelp("已确认帮助内容"); return; } if (id === "contrast.muted") { setForeground("#94a3b8"); setAnnouncement("已切换到低对比示例"); } }, [closeHelp], ); useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { const combo = normalizeCombo(event); setLastCombo(combo); if (composingRef.current || event.isComposing) return; if (isEditable(event.target) && !allowsInInput(combo)) { setImeEvents((events) => [`忽略(输入框):${combo}`, ...events].slice(0, 5), ); return; } const context: Context = helpOpen ? "dialog" : "app"; const binding = findBinding(bindings, combo, context); if (!binding) return; event.preventDefault(); runCommand(binding.id); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [bindings, helpOpen, runCommand]); useEffect(() => { if (!helpOpen) return; const frame = requestAnimationFrame(() => closeRef.current?.focus()); return () => cancelAnimationFrame(frame); }, [helpOpen]); useEffect(() => { const snapshot = () => ({ conflictMode, helpOpen, lastCombo, lastCommandId, announcement, composing, foreground, background, conflictIds: conflicts.flatMap((conflict) => conflict.ids), }); window.__snapshot = snapshot; window.__getConflictIds = () => findConflicts(buildBindings(true)).flatMap((conflict) => conflict.ids); window.__setConflictMode = (value) => setConflictMode(value); window.__openHelp = () => setHelpOpen(true); window.__closeHelp = () => closeHelp("已关闭快捷键帮助"); window.__setContrast = (fg, bg) => { setForeground(fg); setBackground(bg); }; window.__setIme = (value) => setImeValue(value); window.__setAnnouncement = (value) => setAnnouncement(value); window.__setComposing = (value) => { composingRef.current = value; setComposing(value); }; window.__reset = () => { composingRef.current = false; setComposing(false); setHelpOpen(false); setConflictMode(false); setLastCombo(""); setLastCommandId(""); setAnnouncement("等待快捷键输入"); setForeground("#2563eb"); setBackground("#ffffff"); setImeValue(""); setImeEvents([]); }; window.__prepareShots = async () => { setHelpOpen(false); setConflictMode(true); setForeground("#2563eb"); setBackground("#ffffff"); setImeValue("正在输入:工具调用"); setLastCombo("meta+k"); setLastCommandId("search.focus"); setAnnouncement("已聚焦搜索框"); }; window.__smoke = async () => { const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const text = (testId: string): string => document.querySelector(`[data-testid="${testId}"]`) ?.textContent ?? ""; window.__reset?.(); await wait(120); const normalized = normalizeCombo({ key: "K", metaKey: true, shiftKey: true, }); window.dispatchEvent( new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, }), ); await wait(100); const shortcutAnnouncement = text("announcement"); window.__setConflictMode?.(true); await wait(100); const conflictIds = window.__getConflictIds?.() ?? []; window.__setConflictMode?.(false); await wait(100); triggerRef.current?.focus(); window.dispatchEvent( new KeyboardEvent("keydown", { key: "?", bubbles: true }), ); await wait(140); const focusFirst = document.activeElement?.getAttribute("data-testid") ?? ""; const lastButton = document.querySelector( '[data-testid="help-reset"]', ); lastButton?.focus(); lastButton?.dispatchEvent( new KeyboardEvent("keydown", { key: "Tab", bubbles: true }), ); await wait(60); const tabWrapped = document.activeElement?.getAttribute("data-testid") === "help-close"; const firstButton = document.querySelector( '[data-testid="help-close"]', ); firstButton?.focus(); firstButton?.dispatchEvent( new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, }), ); await wait(60); const shiftTabWrapped = document.activeElement?.getAttribute("data-testid") === "help-reset"; window.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true }), ); await wait(140); const focusRestored = document.activeElement?.getAttribute("data-testid") === "help-trigger"; window.__reset?.(); await wait(100); imeRef.current?.focus(); imeRef.current?.dispatchEvent( new CompositionEvent("compositionstart", { bubbles: true }), ); await wait(40); imeRef.current?.dispatchEvent( new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, }), ); await wait(80); const imeBlocked = text("last-command") === "—"; imeRef.current?.dispatchEvent( new CompositionEvent("compositionend", { bubbles: true }), ); await wait(40); imeRef.current?.dispatchEvent( new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, }), ); await wait(100); const imeAfterEnd = text("last-command") === "search.focus"; const imeAnnouncement = text("announcement"); return { normalized, conflictIds, shortcutAnnouncement, focusFirst, tabWrapped, shiftTabWrapped, focusRestored, imeBlocked, imeAfterEnd, imeAnnouncement, contrastPrimary: contrastRatio("#2563eb", "#ffffff"), contrastMuted: contrastRatio("#94a3b8", "#ffffff"), dialogLog, }; }; }, [ announcement, background, closeHelp, composing, conflictMode, conflicts, dialogLog, foreground, helpOpen, lastCombo, lastCommandId, ]); const announceDialog = (label: string): void => { setDialogLog((log) => [`${label} · ${new Date().toISOString()}`, ...log].slice(0, 3), ); }; const focusItem = (direction: 1 | -1): void => { const order = [closeRef, docsRef, resetRef]; const active = order.findIndex( (ref) => ref.current === document.activeElement, ); const next = (active + direction + order.length) % order.length; order[next]?.current?.focus(); }; return (
快捷键与可访问性 WCAG 2.2 AA
{announcement}

快捷键注册表

{conflicts.length > 0 && (
检测到 {conflicts.length} 组冲突: {conflicts.map((conflict) => ( {conflict.combo}({conflict.ids.join(" / ")}) ))}
)} {bindings.map((binding) => { const duplicated = conflicts.some((conflict) => conflict.ids.includes(binding.id), ); return ( ); })}
命令 作用域 组合键 状态
{binding.title} {binding.scope} {formatCombo(binding.combo)} {duplicated ? ( 冲突 ) : ( 可用 )}
最近按键
{lastCombo || "—"}
最近命令
{lastCommandId || "—"}

对比度检查

{contrast.aaNormal ? "AA 通过" : "AA 未通过"}
对比度
{contrast.ratio.toFixed(2)}:1
正文示例:工具调用需要你的确认。
大字号示例
正文 AA ≥ 4.5:{contrast.aaNormal ? "通过" : "未通过"} 大字 AA ≥ 3:{contrast.aaLarge ? "通过" : "未通过"} AAA ≥ 7:{contrast.aaaNormal ? "通过" : "未通过"}

输入法与组合键

{composing ? "组合中" : "空闲"}
setImeValue(event.target.value)} onCompositionStart={() => { composingRef.current = true; setComposing(true); setImeEvents((events) => ["组合开始:忽略快捷键", ...events].slice(0, 5), ); }} onCompositionEnd={() => { composingRef.current = false; setComposing(false); setImeEvents((events) => ["组合结束:恢复快捷键", ...events].slice(0, 5), ); }} />

组合期间不执行任何单键或组合键命令;结束后恢复正常。

    {imeEvents.map((event) => (
  • {event}
  • ))}
{helpOpen && (
{ if (event.target === event.currentTarget) closeHelp("已关闭快捷键帮助"); }} >
{ if (event.key !== "Tab") return; event.preventDefault(); focusItem(event.shiftKey ? -1 : 1); }} >

快捷键帮助

焦点被困在对话框内;Tab 与 Shift+Tab 循环,Esc 关闭并把焦点还给触发按钮。

  • ?{" "} 打开帮助
  • Esc{" "} 关闭
  • ⌘ Enter{" "} 确认

当前焦点: {focusId === "help-close" ? "关闭" : focusId === "help-docs" ? "查看文档" : "重置"}

    {dialogLog.map((line) => (
  • {line}
  • ))}
)}
); } declare global { interface Window { __snapshot?: () => unknown; __getConflictIds?: () => string[]; __setConflictMode?: (value: boolean) => void; __openHelp?: () => void; __closeHelp?: () => void; __setContrast?: (fg: string, bg: string) => void; __setIme?: (value: string) => void; __setAnnouncement?: (value: string) => void; __setComposing?: (value: boolean) => void; __reset?: () => void; __prepareShots?: () => Promise; __smoke?: () => Promise; } }