示例工程 21-keyboard-focus-a11y

21-keyboard-focus-a11y/app/.tsc/src/App.js

javascript · 25 KB

import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { gradeContrast, contrastRatio } from "./lib/contrast";
import { allowsInInput, findBinding, findConflicts, formatCombo, isEditable, normalizeCombo, } from "./lib/shortcuts";
const baseBindings = [
    {
        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 = {
    id: "search.experiment",
    title: "快速搜索(实验)",
    combo: "meta+k",
    scope: "global",
    enabled: true,
};
export function buildBindings(conflictMode) {
    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) => {
        setHelpOpen(false);
        setAnnouncement(message);
        requestAnimationFrame(() => triggerRef.current?.focus());
    }, []);
    const runCommand = useCallback((id) => {
        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) => {
            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 = 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) => new Promise((resolve) => setTimeout(resolve, ms));
            const text = (testId) => 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) => {
        setDialogLog((log) => [`${label} · ${new Date().toISOString()}`, ...log].slice(0, 3));
    };
    const focusItem = (direction) => {
        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 (_jsxs("div", { className: "min-h-screen bg-surface text-text", children: [_jsxs("header", { className: "flex h-14 items-center justify-between border-b border-border px-5", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("span", { className: "font-semibold", children: "\u5FEB\u6377\u952E\u4E0E\u53EF\u8BBF\u95EE\u6027" }), _jsx("span", { className: "rounded-full border border-border px-2 py-0.5 text-[11px] text-muted", children: "WCAG 2.2 AA" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "rounded-full bg-primary-soft px-2 py-1 text-[11px] text-primary", role: "status", "aria-live": "polite", "data-testid": "announcement", children: announcement }), _jsx("button", { ref: triggerRef, className: "h-8 rounded border border-border px-3 text-xs", "data-testid": "help-trigger", onClick: () => setHelpOpen(true), children: "\u6253\u5F00\u5E2E\u52A9\uFF08?\uFF09" })] })] }), _jsx("div", { className: "border-b border-border px-5 py-2", children: _jsxs("label", { className: "flex items-center gap-2 text-xs", children: [_jsx("span", { className: "shrink-0 text-muted", children: "\u641C\u7D22" }), _jsx("input", { ref: searchRef, "data-testid": "search-input", className: "w-full max-w-md rounded border border-border bg-panel px-3 py-1.5 outline-none focus:ring-2 focus:ring-ring", placeholder: "\u2318K \u6216 / \u805A\u7126\u8FD9\u91CC" })] }) }), _jsxs("div", { className: "grid gap-4 p-5 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]", children: [_jsxs("section", { className: "rounded-card border border-border", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-border px-4 py-3", children: [_jsx("h1", { className: "text-sm font-semibold", children: "\u5FEB\u6377\u952E\u6CE8\u518C\u8868" }), _jsxs("label", { className: "flex items-center gap-2 text-xs text-muted", children: [_jsx("input", { type: "checkbox", checked: conflictMode, "data-testid": "conflict-toggle", onChange: (event) => setConflictMode(event.target.checked) }), "\u6CE8\u5165\u91CD\u590D\u7ED1\u5B9A"] })] }), conflicts.length > 0 && (_jsxs("div", { className: "border-b border-[#fecaca] bg-[#fef2f2] px-4 py-2 text-xs text-[#b91c1c]", "data-testid": "conflict-banner", children: ["\u68C0\u6D4B\u5230 ", conflicts.length, " \u7EC4\u51B2\u7A81\uFF1A", conflicts.map((conflict) => (_jsxs("code", { className: "ml-1", children: [conflict.combo, "\uFF08", conflict.ids.join(" / "), "\uFF09"] }, conflict.combo)))] })), _jsxs("table", { className: "w-full text-left text-xs", children: [_jsx("thead", { className: "text-muted", children: _jsxs("tr", { children: [_jsx("th", { className: "px-4 py-2 font-normal", children: "\u547D\u4EE4" }), _jsx("th", { className: "px-4 py-2 font-normal", children: "\u4F5C\u7528\u57DF" }), _jsx("th", { className: "px-4 py-2 font-normal", children: "\u7EC4\u5408\u952E" }), _jsx("th", { className: "px-4 py-2 font-normal", children: "\u72B6\u6001" })] }) }), _jsx("tbody", { children: bindings.map((binding) => {
                                            const duplicated = conflicts.some((conflict) => conflict.ids.includes(binding.id));
                                            return (_jsxs("tr", { className: "border-t border-border", "data-testid": `binding-${binding.id}`, children: [_jsx("td", { className: "px-4 py-2", children: binding.title }), _jsx("td", { className: "px-4 py-2 text-muted", children: binding.scope }), _jsx("td", { className: "px-4 py-2", children: _jsx("kbd", { className: "rounded border border-border bg-panel px-1.5 py-0.5 font-mono text-[11px]", children: formatCombo(binding.combo) }) }), _jsx("td", { className: "px-4 py-2", children: duplicated ? (_jsx("span", { className: "text-destructive", children: "\u51B2\u7A81" })) : (_jsx("span", { className: "text-muted", children: "\u53EF\u7528" })) })] }, binding.id));
                                        }) })] }), _jsxs("div", { className: "grid grid-cols-2 gap-3 border-t border-border p-4 text-xs", children: [_jsxs("div", { children: [_jsx("div", { className: "text-muted", children: "\u6700\u8FD1\u6309\u952E" }), _jsx("code", { "data-testid": "last-combo", className: "text-sm", children: lastCombo || "—" })] }), _jsxs("div", { children: [_jsx("div", { className: "text-muted", children: "\u6700\u8FD1\u547D\u4EE4" }), _jsx("code", { "data-testid": "last-command", className: "text-sm", children: lastCommandId || "—" })] })] })] }), _jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("section", { className: "rounded-card border border-border", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-border px-4 py-3", children: [_jsx("h2", { className: "text-sm font-semibold", children: "\u5BF9\u6BD4\u5EA6\u68C0\u67E5" }), _jsx("span", { className: `rounded-full px-2 py-0.5 text-[11px] ${contrast.aaNormal
                                                    ? "bg-[#dcfce7] text-[#166534]"
                                                    : "bg-[#fee2e2] text-[#991b1b]"}`, "data-testid": "contrast-badge", children: contrast.aaNormal ? "AA 通过" : "AA 未通过" })] }), _jsxs("div", { className: "p-4", children: [_jsxs("div", { className: "flex items-center gap-3 text-xs", children: [_jsxs("label", { className: "flex items-center gap-2", children: ["\u524D\u666F", _jsx("input", { type: "color", value: foreground, "data-testid": "fg-color", onChange: (event) => setForeground(event.target.value), className: "h-8 w-10 rounded border border-border" })] }), _jsxs("label", { className: "flex items-center gap-2", children: ["\u80CC\u666F", _jsx("input", { type: "color", value: background, "data-testid": "bg-color", onChange: (event) => setBackground(event.target.value), className: "h-8 w-10 rounded border border-border" })] }), _jsxs("div", { className: "ml-auto text-right", children: [_jsx("div", { className: "text-[11px] text-muted", children: "\u5BF9\u6BD4\u5EA6" }), _jsxs("div", { className: "text-lg font-semibold", "data-testid": "contrast-ratio", children: [contrast.ratio.toFixed(2), ":1"] })] })] }), _jsxs("div", { className: "mt-3 rounded border border-border p-3", style: { color: foreground, backgroundColor: background }, "data-testid": "contrast-sample", children: [_jsx("div", { className: "text-base", children: "\u6B63\u6587\u793A\u4F8B\uFF1A\u5DE5\u5177\u8C03\u7528\u9700\u8981\u4F60\u7684\u786E\u8BA4\u3002" }), _jsx("div", { className: "text-2xl font-semibold", children: "\u5927\u5B57\u53F7\u793A\u4F8B" })] }), _jsxs("div", { className: "mt-3 flex flex-wrap gap-2 text-[11px]", children: [_jsxs("span", { className: `rounded border border-border px-2 py-1 ${contrast.aaNormal ? "text-[#166534]" : "text-[#991b1b]"}`, "data-testid": "aa-normal", children: ["\u6B63\u6587 AA \u2265 4.5\uFF1A", contrast.aaNormal ? "通过" : "未通过"] }), _jsxs("span", { className: `rounded border border-border px-2 py-1 ${contrast.aaLarge ? "text-[#166534]" : "text-[#991b1b]"}`, "data-testid": "aa-large", children: ["\u5927\u5B57 AA \u2265 3\uFF1A", contrast.aaLarge ? "通过" : "未通过"] }), _jsxs("span", { className: `rounded border border-border px-2 py-1 ${contrast.aaaNormal ? "text-[#166534]" : "text-[#991b1b]"}`, children: ["AAA \u2265 7\uFF1A", contrast.aaaNormal ? "通过" : "未通过"] })] }), _jsxs("div", { className: "mt-3 flex gap-2 text-[11px]", children: [_jsx("button", { className: "rounded border border-border px-2 py-1", onClick: () => {
                                                            setForeground("#2563eb");
                                                            setBackground("#ffffff");
                                                        }, children: "\u4E3B\u8272 / \u767D\u5E95" }), _jsx("button", { className: "rounded border border-border px-2 py-1", "data-testid": "contrast-low", onClick: () => {
                                                            setForeground("#94a3b8");
                                                            setBackground("#ffffff");
                                                        }, children: "\u5F31\u5316 / \u767D\u5E95" })] })] })] }), _jsxs("section", { className: "rounded-card border border-border", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-border px-4 py-3", children: [_jsx("h2", { className: "text-sm font-semibold", children: "\u8F93\u5165\u6CD5\u4E0E\u7EC4\u5408\u952E" }), _jsx("span", { className: `rounded-full px-2 py-0.5 text-[11px] ${composing
                                                    ? "bg-[#fef3c7] text-[#92400e]"
                                                    : "bg-panel text-muted"}`, "data-testid": "composing-badge", children: composing ? "组合中" : "空闲" })] }), _jsxs("div", { className: "p-4", children: [_jsx("input", { ref: imeRef, className: "w-full rounded border border-border bg-surface px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring", placeholder: "\u7528\u4E2D\u6587\u8F93\u5165\u6CD5\u8BD5\u8BD5\uFF1A\u8F93\u5165\u300C\u5DE5\u5177\u300D\u518D\u6309 \u2318K", value: imeValue, "data-testid": "ime-input", onChange: (event) => 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));
                                                } }), _jsx("p", { className: "mt-2 text-xs text-muted", children: "\u7EC4\u5408\u671F\u95F4\u4E0D\u6267\u884C\u4EFB\u4F55\u5355\u952E\u6216\u7EC4\u5408\u952E\u547D\u4EE4\uFF1B\u7ED3\u675F\u540E\u6062\u590D\u6B63\u5E38\u3002" }), _jsx("ul", { className: "mt-2 flex flex-col gap-1 text-[11px] text-muted", "data-testid": "ime-log", children: imeEvents.map((event) => (_jsx("li", { children: event }, event))) })] })] })] })] }), helpOpen && (_jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-6", role: "presentation", onMouseDown: (event) => {
                    if (event.target === event.currentTarget)
                        closeHelp("已关闭快捷键帮助");
                }, children: _jsxs("div", { className: "w-[460px] rounded-card border border-border bg-surface p-5 shadow-xl", role: "dialog", "aria-modal": "true", "aria-labelledby": "help-title", "data-testid": "help-dialog", onKeyDown: (event) => {
                        if (event.key !== "Tab")
                            return;
                        event.preventDefault();
                        focusItem(event.shiftKey ? -1 : 1);
                    }, children: [_jsx("h2", { id: "help-title", className: "text-base font-semibold", children: "\u5FEB\u6377\u952E\u5E2E\u52A9" }), _jsx("p", { className: "mt-2 text-sm text-muted", children: "\u7126\u70B9\u88AB\u56F0\u5728\u5BF9\u8BDD\u6846\u5185\uFF1BTab \u4E0E Shift+Tab \u5FAA\u73AF\uFF0CEsc \u5173\u95ED\u5E76\u628A\u7126\u70B9\u8FD8\u7ED9\u89E6\u53D1\u6309\u94AE\u3002" }), _jsxs("ul", { className: "mt-3 flex flex-col gap-1 text-xs text-muted", children: [_jsxs("li", { children: [_jsx("kbd", { className: "rounded border border-border px-1", children: "?" }), " ", "\u6253\u5F00\u5E2E\u52A9"] }), _jsxs("li", { children: [_jsx("kbd", { className: "rounded border border-border px-1", children: "Esc" }), " ", "\u5173\u95ED"] }), _jsxs("li", { children: [_jsx("kbd", { className: "rounded border border-border px-1", children: "\u2318 Enter" }), " ", "\u786E\u8BA4"] })] }), _jsxs("div", { className: "mt-4 flex justify-end gap-2", children: [_jsx("button", { ref: closeRef, className: `rounded border border-border px-3 py-1.5 text-sm ${focusId === "help-close"
                                        ? "ring-2 ring-ring ring-offset-2 ring-offset-surface"
                                        : ""}`, "data-testid": "help-close", onFocus: () => setFocusId("help-close"), onClick: () => closeHelp("已关闭快捷键帮助"), children: "\u5173\u95ED" }), _jsx("button", { ref: docsRef, className: `rounded border border-border px-3 py-1.5 text-sm ${focusId === "help-docs"
                                        ? "ring-2 ring-ring ring-offset-2 ring-offset-surface"
                                        : ""}`, "data-testid": "help-docs", onFocus: () => setFocusId("help-docs"), onClick: () => announceDialog("查看文档"), children: "\u67E5\u770B\u6587\u6863" }), _jsx("button", { ref: resetRef, className: `rounded bg-primary px-3 py-1.5 text-sm text-primary-foreground ${focusId === "help-reset"
                                        ? "ring-2 ring-ring ring-offset-2 ring-offset-surface"
                                        : ""}`, "data-testid": "help-reset", onFocus: () => setFocusId("help-reset"), onClick: () => {
                                        announceDialog("重置快捷键");
                                        closeHelp("已重置快捷键");
                                    }, children: "\u91CD\u7F6E" })] }), _jsxs("p", { className: "mt-2 text-right text-[11px] text-muted", children: ["\u5F53\u524D\u7126\u70B9\uFF1A", focusId === "help-close"
                                    ? "关闭"
                                    : focusId === "help-docs"
                                        ? "查看文档"
                                        : "重置"] }), _jsx("ul", { className: "mt-3 text-[11px] text-muted", "data-testid": "dialog-log", children: dialogLog.map((line) => (_jsx("li", { children: line }, line))) })] }) }))] }));
}
//# sourceMappingURL=App.js.map