// --------------------------------------------------------------------------- // ui/useEscapeClose.ts — W51-T01, the wave-51 base kit. // // ONE Escape arbiter for the whole app. Before this, every overlay installed its // own capture-phase `keydown` listener and each one decided for itself whether it // was allowed to act; a menu opened INSIDE a dialog therefore raced the dialog, // and which one closed depended on listener registration order rather than on // which surface the user was actually looking at. // // The rule is topmost-wins, and it is arbitrated by ONE module-level stack: // * `useEscapeClose(active, onClose, …)` pushes while active, pops on unmount. // * ONE lazily-installed capture-phase listener serves every entry. // * Escape reaches the LAST entry pushed and nothing else, then stops. // // ⚠ WHY THE DECISION IS A PURE FUNCTION, NOT AN `if` INSIDE THE HANDLER. // The handler needs `document`, so it cannot run under the node harness that // `verify_overlay.py` uses, and a rule that no gate can execute is a rule that // silently rots. `escapeTargets` and `escapeDecision` therefore take plain // arguments and return plain values: the handler is a thin shell over them, the // gate runs them directly, and the gate's negative control mutates the COMPILED // artifact of this file (the idiom verify_overlay.py already uses for the // placement maths) rather than ever writing a broken rule to disk. // // ⛔ `cancelEditFirst` DEFAULTS TO FALSE, ON PURPOSE. Every overlay that existed // before this file blurred the focused element and closed on ONE Escape, and // `useOverlayLayer` is shared by anchored menus AND fixed drawers — flipping the // default would turn every rename input, cohort picker and date editor in the // grid into a two-Escape close, app-wide, from a base-kit ticket that adopted // nothing. ConfirmDialog opts IN; nothing else does. // --------------------------------------------------------------------------- import { useEffect, useRef } from "react"; /** One live overlay's claim on Escape. */ export interface EscapeEntry { /** Called when Escape resolves to this entry. */ close: () => void; /** * When true, an Escape pressed while a text edit inside this overlay has focus * cancels THAT EDIT and stops; a second Escape closes the overlay. */ cancelEditFirst: boolean; /** The overlay's own DOM node, used only to ask whether focus is inside it. */ container?: () => HTMLElement | null; } /** The shape `escapeDecision` needs from the focused element. Deliberately not a * DOM type, so the rule is executable without a DOM. */ export interface FocusedShape { tagName: string; isContentEditable: boolean; type?: string; /** Is this element inside the topmost overlay's own container? */ insideTop: boolean; } export type EscapeDecision = "ignore" | "cancel-edit" | "close"; const stack: EscapeEntry[] = []; /** How many overlays currently claim Escape. Exported for tests. */ export function escapeStackDepth(): number { return stack.length; } /** * THE ARBITER. Everything Escape does, it does to exactly these entries. * * ⚠ This returns an ARRAY of length 0 or 1 rather than `Entry | null` so that the * "only the topmost" claim is a MEASURABLE property of the returned value. A gate * asserting `escapeTargets([a, b, c]).length === 1` goes red the moment somebody * broadcasts to the whole stack; a nullable single return cannot express that * failure at all, so its negative control could never fire. */ export function escapeTargets(entries: readonly EscapeEntry[]): EscapeEntry[] { return entries.length ? [entries[entries.length - 1]] : []; } /** Is the focused element a live text edit? */ export function isEditingElement( focused: { tagName: string; isContentEditable: boolean; type?: string } | null ): boolean { if (!focused) return false; if (focused.isContentEditable) return true; const tag = focused.tagName.toUpperCase(); if (tag === "INPUT" && ["checkbox", "radio", "button", "submit", "reset", "file", "range", "color", "hidden", "image"].includes((focused.type ?? "text").toLowerCase())) return false; return tag === "INPUT" || tag === "TEXTAREA"; } /** What one Escape press means, given the topmost entry and what has focus. */ export function escapeDecision( top: EscapeEntry | null, focused: FocusedShape | null ): EscapeDecision { if (!top) return "ignore"; if (top.cancelEditFirst && focused && focused.insideTop && isEditingElement(focused)) return "cancel-edit"; return "close"; } /** * The entries Escape would reach RIGHT NOW, from the LIVE module stack. * * ⛔⛔ W-683. `escapeTargets` was only ever run over HAND-BUILT arrays and `escapeStackDepth()` * was only ever asserted to be 0, so the push/splice that actually orders this stack was exercised * by NOTHING -- swapping `stack.push` for `stack.unshift` inverted topmost-wins while every leg * stayed green. This is the same call the document handler makes (`escapeTargets(stack)`), so a * gate asserting on it is asserting the real path rather than a copy of it. */ export function liveEscapeTargets(): EscapeEntry[] { return escapeTargets(stack); } /** * Claim Escape for `entry`; the returned function releases it. * * ⛔ THE EFFECT BODY LIVES HERE, EXPORTED, for the reason this file already gives about * `escapeTargets`: "a rule that no gate can execute is a rule that silently rots". `useEscapeClose` * calls exactly this, so driving it IS driving the hook's own mount and unmount. */ export function claimEscape(entry: EscapeEntry): () => void { install(); stack.push(entry); return () => { const at = stack.lastIndexOf(entry); if (at >= 0) stack.splice(at, 1); }; } let installed = false; function onDocumentKeyDown(event: KeyboardEvent): void { if (event.key !== "Escape") return; const targets = escapeTargets(stack); if (!targets.length) return; event.preventDefault(); event.stopPropagation(); const active = document.activeElement instanceof HTMLElement ? document.activeElement : null; for (const top of targets) { const node = top.container?.() ?? null; const focused: FocusedShape | null = active ? { tagName: active.tagName, type: active instanceof HTMLInputElement ? active.type : undefined, isContentEditable: active.isContentEditable, insideTop: node ? node.contains(active) : true, } : null; const decision = escapeDecision(top, focused); // Blur first, then close: an overlay that unmounts while one of its inputs holds // focus leaves the browser to guess where focus goes next, and the guess is . if (active && focused?.insideTop) active.blur(); if (decision === "cancel-edit") continue; top.close(); } } function install(): void { if (installed || typeof document === "undefined") return; document.addEventListener("keydown", onDocumentKeyDown, true); installed = true; } export interface EscapeCloseOptions { /** See the note at the top of this file: FALSE is the pre-existing behaviour. */ cancelEditFirst?: boolean; container?: () => HTMLElement | null; } /** * Claim Escape while `active`. The topmost claimant wins and nothing below it hears * the key at all. */ export function useEscapeClose( active: boolean, onClose: () => void, options: EscapeCloseOptions = {} ): void { const { cancelEditFirst = false, container } = options; // ⚠ REFS, so a re-render with a fresh `onClose` or a fresh `container` closure does // NOT pop and re-push the entry. A pop/push reorders the stack, which would silently // promote a background overlay above the one the user is looking at — the exact // failure this module exists to end. const closeRef = useRef(onClose); const containerRef = useRef(container); closeRef.current = onClose; containerRef.current = container; useEffect(() => { if (!active) return; const entry: EscapeEntry = { close: () => closeRef.current(), cancelEditFirst, container: () => containerRef.current?.() ?? null, }; // W-683: the mount and the unmount are `claimEscape`'s, so the gate drives the same code. return claimEscape(entry); }, [active, cancelEditFirst]); }