/** * macOS WebKit (`WKWebView` / Safari) can still dispatch a text-insertion `beforeinput` * (`insertText` / `insertCompositionText`) after a ⌘-modified punctuation key such as ⌘/ or ⌘` * — under both ABC (`/` / `` ` ``) and Pinyin (`、` / `·`) — even when the `keydown` handler * called `preventDefault()`. Pressing ⌘ + key on macOS never legitimately types plain text * through `insertText` (paste uses `insertFromPaste`, undo/redo use `historyUndo`/`historyRedo`), * so drop trusted `insertText` / `insertCompositionText` `beforeinput` events that arrive right * after a non-composing ⌘-modified `keydown`. */ const BARE_MODIFIERS = new Set(["Meta", "Shift", "Control", "Alt"]); const TEXT_INSERT_TYPES = new Set(["insertText", "insertCompositionText"]); /** How long after a ⌘-modified `keydown` a stray WebKit text `beforeinput` may still arrive. */ export const CMD_BEFOREINPUT_WINDOW_MS = 150; export interface MacCmdInputGuardOptions { target?: Window; now?: () => number; /** Tests dispatch untrusted events; production only cancels browser-dispatched events. */ isTrusted?: (e: Event) => boolean; } export function installMacCmdInputGuard({ target = window, now = () => performance.now(), isTrusted = (e) => e.isTrusted, }: MacCmdInputGuardOptions = {}): () => void { let pendingAt: number | null = null; const clear = () => { pendingAt = null; }; const onKeyDown = (e: KeyboardEvent) => { if (BARE_MODIFIERS.has(e.key)) return; if (!e.metaKey) { pendingAt = null; return; } pendingAt = e.isComposing ? null : now(); }; const onBeforeInput = (e: Event) => { if (pendingAt === null) return; if (now() - pendingAt > CMD_BEFOREINPUT_WINDOW_MS) { pendingAt = null; return; } if (!isTrusted(e)) return; const inputType = (e as InputEvent).inputType; if (!TEXT_INSERT_TYPES.has(inputType)) return; e.preventDefault(); e.stopImmediatePropagation(); }; target.addEventListener("keydown", onKeyDown, true); target.addEventListener("beforeinput", onBeforeInput, true); target.addEventListener("pointerdown", clear, true); target.addEventListener("blur", clear); return () => { target.removeEventListener("keydown", onKeyDown, true); target.removeEventListener("beforeinput", onBeforeInput, true); target.removeEventListener("pointerdown", clear, true); target.removeEventListener("blur", clear); }; }