File size: 8,306 Bytes
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
971c29d
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7e617
 
1d4419b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// ---------------------------------------------------------------------------
// 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 <body>.
    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]);
}