File size: 29,714 Bytes
f5696cb
e13472e
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
f5696cb
 
a93637f
 
aa1490a
 
e88a3a3
 
 
 
 
 
a93637f
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
 
e88a3a3
9a6cb9a
e88a3a3
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
f5696cb
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
 
 
 
 
 
e88a3a3
 
 
9a6cb9a
e88a3a3
 
a93637f
 
e88a3a3
f5696cb
e88a3a3
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
e88a3a3
 
9a6cb9a
e88a3a3
 
 
 
 
 
 
 
 
 
 
bdac669
 
 
 
 
 
 
 
e88a3a3
 
bdac669
e88a3a3
 
bdac669
e88a3a3
 
 
 
 
 
 
 
 
 
 
a83fcff
e88a3a3
 
 
a83fcff
e88a3a3
 
 
 
 
 
9a6cb9a
e88a3a3
 
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
f5696cb
 
e88a3a3
f5696cb
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
e88a3a3
f5696cb
 
e88a3a3
9a6cb9a
e88a3a3
cfd4ac1
9a6cb9a
 
 
 
 
 
 
 
 
 
 
f5696cb
e88a3a3
 
f5696cb
 
 
 
 
e88a3a3
 
 
 
 
aa1490a
 
 
 
 
 
 
e88a3a3
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
f5696cb
e88a3a3
 
 
 
 
 
bdac669
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfd4ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
a83fcff
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a93637f
 
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdac669
e88a3a3
 
bdac669
e88a3a3
 
 
bdac669
e88a3a3
 
 
bdac669
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1490a
 
 
 
 
e88a3a3
aa1490a
e88a3a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// sheet/KeyTips.tsx - Excel-style Alt key tips over the sheet ribbon (wave 52, W52-T17, owner
// instruction 20, ruling R7; AutoWiki/waves/wave52/proto/excel-behaviour-spec.md Part B,
// rules KT-1 through KT-21 and D-1/D-2/D-3/D-6/D-7).
//
// ⭐⭐ WHAT THIS COMPONENT IS. A SEPARATE keyboard-capture layer, entirely independent of
// `Ribbon.tsx`'s own roving-focus handler (`onKeyDown`, gated on `open === ""`). This layer takes
// over the keyboard the moment a bare `Alt` press-and-release toggles it on, and hands the
// keyboard back the moment it closes. It never reads or writes `Ribbon.tsx`'s React state; it
// walks the DOM under `containerRef` for `[data-kt]` targets (W52-T16's registry) and calls
// `.click()` / `.focus()` on the real buttons, which is what keeps 30+ `control()` call sites in
// `Ribbon.tsx` untouched by this ticket.
//
// ⛔ CONTRACT C5 — `document`-LEVEL, `{capture: true}`, `stopPropagation()` ON EVERY KEY CONSUMED
// WHILE ACTIVE. `SheetGrid.tsx` is never imported here and never edited by this ticket; capturing
// at `document` ahead of the grid's own listener is what keeps the grid from ever seeing a
// keystroke this layer is currently interpreting (KT-19). When the layer is IDLE (no Alt pending,
// not active), this file swallows NOTHING — a bare keystroke reaches the grid exactly as before.
//
// ⛔ D-2/D-3 — BARE ALT, KEYDOWN-THEN-KEYUP, NOTHING ELSE PRESSED, UNDER 800ms, WINDOW FOCUSED.
// A bare press toggles the layer; held Alt plus a live first-level letter also enters its path
// (W54-T24). Other Alt chords belong to the browser/OS; Alt+F/Alt+D/Alt+Tab are never intercepted
// while idle. Once active, letters resolve the key-tip sequence in order. The pending-Alt state
// is cleared on `blur` and `visibilitychange` so an Alt-tab away and back never leaves a stray
// toggle armed.
//
// ⭐ KT-10/11/12 — TWO CASES, TOLD APART BY `data-kt-opens`, NEVER GUESSED FROM STRING LENGTH. A
// badge with no `data-kt-opens` is PREFIX-MATCHED (`FS` fires only once both `F` and `S` land;
// typing `F` alone hides every non-`F` badge and fires nothing, per KT-10). A control carrying
// `data-kt-opens="gallery"` OPENS its popover on its OWN badge, and this layer then re-derives a
// fresh badge set from whatever `.sheet-ribbon-pop` is now open (KT-11).
//
// ⚠ SCOPE, STATED HONESTLY (the ticket's own "best effort" clause for the third level). The first
// two levels show the tab strip's badges, then ONLY the chosen tab's group controls, with prefix
// match, Left/Right and Enter nav, and Escape/Alt exit. Strip actions use their own gallery/leaf
// path. Wave 55 gives Up/Down back to the grid immediately, except inside a colour gallery,
// where S67-T17 lets all four arrows walk the swatch grid (`swatchWalk`). The gallery level is
// exercised for Borders and Paste: every item carrying `data-kt` supplies its own letter.
// Every OTHER gallery (Insert, Delete, Format,
// Clear, Fill/Text colour, Font size, Number format) still gets Escape-to-close and generic
// arrow/Enter navigation among its menu items (`navFallback` below), because every one of them
// already carries `[data-kt-opens="gallery"][aria-expanded="true"]` — but their INSIDE items paint
// no letter badges yet. That gap is booked in the ticket's HANDOFF, not hidden here.
import { useCallback, useEffect, useReducer, useRef } from "react";
import type { RefObject } from "react";
import { KEY_TIP_GRID_ARROW_EVENT, isArrowKey, keyTipGridArrow, swatchGridStep } from "./shortcuts";

type Depth = "tabs" | "home" | "gallery";

interface KtState {
  active: boolean;
  depth: Depth;
  prefix: string;
  focusedIdx: number;
}

const INITIAL: KtState = { active: false, depth: "tabs", prefix: "", focusedIdx: 0 };

/** D-3's own number: a bare Alt keydown/keyup pair further apart than this is not "a press". */
const ALT_PRESS_MS = 800;

export interface KeyTipsProps {
  /** The ribbon's own root node (`Ribbon.tsx`'s `rootRef`) — never a fresh ref. Threading a new
   *  prop through 30+ `control()` call sites is the wrong-shaped fix for a badge layer that only
   *  needs to READ the DOM those calls already stamp with `data-kt`. */
  containerRef: RefObject<HTMLDivElement | null>;
}

type KeyTipElement = HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement;

interface Target {
  el: KeyTipElement;
  code: string;
}

function isTextChar(key: string): boolean {
  return /^[a-zA-Z0-9]$/.test(key);
}

/** ⭐⭐ W54-T24 (instruction 11) — THE MEASURED CAUSE OF "shortcuts do not work when done fast".
 *  Typed slowly, a person presses Alt, RELEASES it, then types H: the keyup toggles the layer on
 *  and every later letter lands. Typed fast, the same person is still HOLDING Alt when H arrives,
 *  which is how the owner writes the sequence and how Excel itself accepts it. On that path the
 *  old code marked the press a chord, refused to activate, and the whole sequence died: measured
 *  0 of 5 held runs against 5 of 5 sequential runs, headless Chromium, 2026-09-06.
 *  This predicate is what keeps the fix narrow. A held Alt plus a letter only becomes a key-tip
 *  activation when that letter names a live FIRST-LEVEL badge in the tab strip (tabs and actions),
 *  so every other Alt chord the browser owns (Alt+D, Alt+F, Alt+Left) is never touched. */
function isFirstLevelCode(container: HTMLElement | null, ch: string): boolean {
  return getTargets(container, "tabs").some((t) => t.code.startsWith(ch));
}

/** How long the pressed look stays on a control the key-tip layer fired. DESIGN's interaction
 *  layer: 100 to 200 ms, ease-out, transform and opacity ONLY. */
const PRESS_MS = 120;

/** ⭐ W54-T24, the second half of instruction 11. A key-tip activation calls `.click()` on a real
 *  button, so NO pointer event is ever dispatched and a `:active` or `pointerdown` rule on the
 *  ribbon can never fire for it. The key-tip path therefore needs its own brief press state, and
 *  this is it: a transform, which cannot move anything around it, degrading to a short opacity
 *  change when the reader asks for reduced motion. */
function pressFeedback(el: HTMLElement): void {
  const reduced = typeof window.matchMedia === "function"
    && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const priorTransform = el.style.transform;
  const priorOpacity = el.style.opacity;
  const priorTransition = el.style.transition;
  el.style.transition = reduced ? `opacity ${PRESS_MS}ms ease-out` : `transform ${PRESS_MS}ms ease-out`;
  if (reduced) el.style.opacity = "0.72";
  else el.style.transform = "scale(0.97)";
  window.setTimeout(() => {
    el.style.transform = priorTransform;
    el.style.opacity = priorOpacity;
    el.style.transition = priorTransition;
  }, PRESS_MS);
}

/** Every `[data-kt]` element visible AT THIS DEPTH, with its badge code. Each depth is
 *  scoped to the DOM region that owns it: the tab strip, the active tab's group row, or
 *  the open gallery.
 *  ⚠ `verify_grid_ux.py::w54_t24_speed_shape` slices this file from `pressFeedback` up to
 *  the words "Every `[data-kt]` element", so this comment is a GATE ANCHOR: reword the rest
 *  of the sentence freely, never that phrase. Measured W57-T08: rewriting the whole line
 *  raised `ValueError: substring not found` and the gate died mid-run. */
function getTargets(container: HTMLElement | null, depth: Depth): Target[] {
  if (!container) return [];
  if (depth === "tabs") {
    return collect(container.querySelectorAll<KeyTipElement>(".sheet-ribbon-tabs [data-kt]"));
  }
  if (depth === "gallery") {
    const panel = openPanel(container);
    return panel ? collect(panel.querySelectorAll<HTMLButtonElement>("[data-kt]")) : [];
  }
  return collect(container.querySelectorAll<HTMLButtonElement>(".sheet-ribbon-scroll [data-kt]"));
}

/** The open gallery panel the keyboard is inside: the ribbon popover, or, while one of its own
 *  flyouts is open (S67-T15's Line Color and Line Style, DOM children of the Borders panel that
 *  carry `sheet-ribbon-pop-portal` themselves), that innermost flyout. */
function openPanel(container: HTMLElement): HTMLElement | null {
  const openPop = (container.querySelector<HTMLElement>(".sheet-ribbon-pop")
    // ⭐⭐ W53-T07 (instruction 25) — THE OPEN POPOVER IS A CHILD OF `<body>` NOW. Every
    // ribbon menu renders through `AnchoredOverlay`, which portals, so it is no longer a
    // descendant of `Ribbon.tsx`'s `rootRef` and this container query returns null. Without
    // this fallback the THIRD key-tip depth (Alt, then the group letter, then the letters
    // inside the open gallery) dies silently: no error, no gate, just badges that stop
    // appearing. ⚠ `document` is safe as the wider scope because exactly one popover is ever
    // open - `Ribbon.tsx::open` is a single `Popover` value, not a set.
    ?? document.querySelector<HTMLElement>(".sheet-ribbon-pop"));
  if (!openPop) return null;
  // S67-T17: while a flyout is open, its items are the gallery the keys walk, not the panel's.
  const nested = openPop.querySelectorAll<HTMLElement>(".sheet-ribbon-pop-portal");
  return nested.length ? nested[nested.length - 1] : openPop;
}

/** ⭐⭐ S67-T17 (instruction 18, O28) — THE COLOUR GALLERY'S WALK LIST, OR NULL FOR EVERY OTHER
 *  GALLERY. A panel is a colour gallery when it holds a `.sheet-ribbon-swatches` grid: Fill Color,
 *  Font Color, and the Borders gallery's Line Color flyout. Asked by CLASS, never by role, because
 *  Line Color's swatches are `menuitemradio` where Fill's are `menuitem`. The walk list is every
 *  enabled button in the panel in reading order, so the arrows reach "No fill", "Reset the text
 *  colour" and "Automatic" around the palette as well as the swatches in it. A gallery WITHOUT a
 *  swatch grid answers null and keeps W55-T05's behaviour exactly. */
function swatchWalk(container: HTMLElement | null): HTMLButtonElement[] | null {
  const panel = container ? openPanel(container) : null;
  if (!panel?.querySelector(".sheet-ribbon-swatches .sheet-ribbon-swatch")) return null;
  return Array.from(panel.querySelectorAll<HTMLButtonElement>("button:not(:disabled)"));
}

function collect(list: NodeListOf<KeyTipElement>): Target[] {
  const out: Target[] = [];
  list.forEach((el) => {
    const code = (el.dataset.kt || "").toUpperCase();
    if (code) out.push({ el, code });
  });
  return out;
}

/** Every entry whose code starts with `prefix` (KT-10 -- typing the first character of a
 *  two-character badge hides every OTHER badge and keeps the survivors showing both chars). */
function pickTargets(container: HTMLElement | null, depth: Depth, prefix: string): Target[] {
  const all = getTargets(container, depth);
  return prefix ? all.filter((t) => t.code.startsWith(prefix)) : all;
}

/** A gallery that paints no `data-kt` badges yet (best-effort scope, see file header) still gets
 *  generic arrow/Enter navigation among its own menu items. */
function navFallback(container: HTMLElement | null, depth: Depth): HTMLButtonElement[] {
  if (!container || depth !== "gallery") return [];
  const panel = openPanel(container);
  return panel ? Array.from(panel.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")) : [];
}

function navElements(container: HTMLElement | null, depth: Depth, prefix: string): KeyTipElement[] {
  const picked = pickTargets(container, depth, prefix).map((t) => t.el);
  return picked.length ? picked : navFallback(container, depth);
}

export default function KeyTips({ containerRef }: KeyTipsProps) {
  const stateRef = useRef<KtState>(INITIAL);
  const [, bump] = useReducer((n: number) => n + 1, 0);
  const overlayRef = useRef<HTMLDivElement | null>(null);
  const previousFocusRef = useRef<HTMLElement | null>(null);
  const altDownAtRef = useRef<number | null>(null);
  const altChordRef = useRef(false);
  const pendingExactRef = useRef<number | null>(null);

  const clearPendingExact = useCallback(() => {
    if (pendingExactRef.current !== null) window.clearTimeout(pendingExactRef.current);
    pendingExactRef.current = null;
  }, []);

  useEffect(() => clearPendingExact, [clearPendingExact]);

  const setKt = useCallback((patch: Partial<KtState>) => {
    clearPendingExact();
    stateRef.current = { ...stateRef.current, ...patch };
    bump();
  }, [bump, clearPendingExact]);

  /** KT-17's soft signal for an unmatched keystroke: a brief pulse, never a state change, so it
   *  never disturbs a still-open two-character prefix. */
  const flash = useCallback(() => {
    const el = overlayRef.current;
    if (!el) return;
    el.classList.remove("sheet-kt-flash");
    void el.offsetWidth; // force a reflow so a REPEATED miss still replays the animation
    el.classList.add("sheet-kt-flash");
  }, []);

  const deactivateAll = useCallback((restoreFocus = true) => {
    const el = previousFocusRef.current;
    previousFocusRef.current = null;
    setKt(INITIAL);
    if (restoreFocus) requestAnimationFrame(() => el?.focus?.());
  }, [setKt]);

  const activateFirstLevel = useCallback(() => {
    previousFocusRef.current = (document.activeElement as HTMLElement) ?? null;
    setKt({ active: true, depth: "tabs", prefix: "", focusedIdx: 0 });
    requestAnimationFrame(() => {
      if (!stateRef.current.active || stateRef.current.depth !== "tabs") return;
      containerRef.current?.querySelector<HTMLButtonElement>('[data-ribbon="tab-home"]')?.focus();
    });
  }, [setKt, containerRef]);

  /** S67-T17: close a flyout open inside the gallery (Line Color, Line Style) through the opener
   *  that toggles it, and hand focus back to that opener. False when no flyout is open. */
  const flyoutOpener = useCallback((): HTMLButtonElement | null => {
    const panel = containerRef.current ? openPanel(containerRef.current) : null;
    if (!panel || panel.classList.contains("sheet-ribbon-pop")) return null;
    return panel.parentElement?.closest(".sheet-ribbon-pop")
      ?.querySelector<HTMLButtonElement>('[aria-haspopup="menu"][aria-expanded="true"]') ?? null;
  }, [containerRef]);

  const closeFlyout = useCallback((): boolean => {
    const opener = flyoutOpener();
    if (!opener) return false;
    opener.click();
    setKt({ prefix: "", focusedIdx: 0 });
    requestAnimationFrame(() => opener.focus());
    return true;
  }, [flyoutOpener, setKt]);

  /** KT-14/15/16's ladder: one step back per Escape, never a full exit until the first level. */
  const stepBack = useCallback(() => {
    const st = stateRef.current;
    // S67-T17: a flyout inside the gallery is its own rung, and on ESCAPE the shared overlay
    // arbiter (`ui/useEscapeClose`) is the one that closes it: the flyout is the topmost layer and
    // the arbiter hears this same keydown. Closing it here as well (clicking its opener) unmounts it
    // synchronously, which promotes the gallery to topmost before the arbiter runs, so the arbiter
    // then closed the GALLERY too and left its 19 badges over the grid (measured on the snapshot:
    // both panels gone inside the same keydown). So key tips only re-anchor on the gallery.
    const opener = st.depth === "gallery" ? flyoutOpener() : null;
    if (opener) {
      setKt({ prefix: "", focusedIdx: 0 });
      requestAnimationFrame(() => opener.focus());
      return;
    }
    if (st.depth === "gallery") {
      const opener = containerRef.current?.querySelector<HTMLButtonElement>(
        '[data-kt-opens="gallery"][aria-expanded="true"]',
      );
      // Galleries can open from either level, so the opener's DOM location determines where Escape returns.
      const depth = opener?.closest(".sheet-ribbon-tabs") ? "tabs" : "home";
      opener?.click();
      setKt({ depth, prefix: "", focusedIdx: 0 });
      requestAnimationFrame(() => opener?.focus());
      return;
    }
    if (st.depth === "home") {
      if (st.prefix !== "") {
        setKt({ prefix: "", focusedIdx: 0 });
        return;
      }
      setKt({ depth: "tabs", focusedIdx: 0 });
      requestAnimationFrame(() => {
        containerRef.current?.querySelector<HTMLButtonElement>('[data-ribbon="tab-home"]')?.focus();
      });
      return;
    }
    deactivateAll();
  }, [containerRef, deactivateAll, flyoutOpener, setKt]);

  /** A first-level tab reveals its own group controls (KT-8/KT-9); strip actions follow the
   *  same gallery/leaf handling as group controls.
   */
  const activate = useCallback((el: KeyTipElement) => {
    const st = stateRef.current;
    pressFeedback(el); // W54-T24: the pressed look lands on the same tick as the command
    // S66-T09 (R24): a text field badge (the ribbon search, `data-kt="Q"`) ends the key-tip session
    // and takes the caret. `.click()` alone never focuses an input, so it is focused first; the
    // click still runs because it is the search's own open door after Escape closed its list.
    if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
      deactivateAll(false);
      el.focus();
      el.select();
      // A search already focused still needs its click door after Escape dismissed the list.
      el.click();
      return;
    }
    if (st.depth === "tabs" && el.dataset.ribbon?.startsWith("tab-")) {
      el.click();
      setKt({ depth: "home", prefix: "", focusedIdx: 0 });
      requestAnimationFrame(() => {
        navElements(containerRef.current, "home", "")[0]?.focus();
        // Re-read badge targets after React replaces the active tab's group row.
        bump();
      });
      return;
    }
    if (el.dataset.ktOpens === "gallery") {
      el.click();
      setKt({ depth: "gallery", prefix: "", focusedIdx: 0 });
      requestAnimationFrame(() => {
        if (!stateRef.current.active || stateRef.current.depth !== "gallery") return;
        navElements(containerRef.current, "gallery", "")[0]?.focus();
        // S68-T28: re-read the portalled gallery after its items mount. The existing fixed
        // badge layer paints Paste and Borders identically without changing menu layout.
        bump();
      });
      return;
    }
    // ⭐ S67-T17 (O28): an item inside the gallery that opens a flyout of its own (S67-T15's Line
    // Color and Line Style). Line Color is a colour gallery, so the key tips stay on and the
    // arrows walk its swatches. Two frames: the flyout mounts in the first and its own overlay
    // layer focuses its first item there, so the swatch focus has to land after that. A flyout
    // with no swatch grid (Line Style) ends the key tips exactly as a leaf always did, leaving
    // focus where the flyout put it.
    if (st.depth === "gallery" && el.getAttribute("aria-haspopup") === "menu") {
      el.click();
      setKt({ prefix: "", focusedIdx: 0 });
      requestAnimationFrame(() => requestAnimationFrame(() => {
        if (!stateRef.current.active || stateRef.current.depth !== "gallery") return;
        const walk = swatchWalk(containerRef.current);
        if (!walk) {
          deactivateAll(false);
          return;
        }
        const start = walk.findIndex((b) => b.matches(".sheet-ribbon-swatch.is-on"));
        const idx = start >= 0 ? start : walk.findIndex((b) => b.matches(".sheet-ribbon-swatch"));
        walk[idx]?.focus();
        setKt({ focusedIdx: Math.max(idx, 0) });
      }));
      return;
    }
    // A leaf action or a gallery item: it fires, and per real Excel the whole KeyTip layer closes
    // and the keyboard returns to wherever it was before Alt was first pressed.
    el.click();
    deactivateAll();
  }, [bump, containerRef, deactivateAll, setKt]);

  const handleCharacter = useCallback((ch: string) => {
    const st = stateRef.current;
    const targets = getTargets(containerRef.current, st.depth);
    const candidate = st.prefix + ch;
    const exact = targets.find((t) => t.code === candidate);
    // Keep both existing codes: Home's C (Copy) used to swallow CU (Currency). Only an
    // ambiguous exact match waits; the next character or any ladder transition cancels it.
    if (exact && targets.some((t) => t.code !== candidate && t.code.startsWith(candidate))) {
      setKt({ prefix: candidate, focusedIdx: 0 });
      pendingExactRef.current = window.setTimeout(() => {
        pendingExactRef.current = null;
        setKt({ prefix: "" });
        if (exact.el.disabled) flash();
        else activate(exact.el);
      }, 250);
      return;
    }
    if (exact) {
      setKt({ prefix: "" });
      if (exact.el.disabled) {
        flash(); // KT-18: a disabled control's key is a no-op, not a fire
        return;
      }
      activate(exact.el);
      return;
    }
    if (!targets.some((t) => t.code.startsWith(candidate))) {
      flash(); // KT-17: unmatched, no-op, prefix (if any) stays exactly as it was
      return;
    }
    setKt({ prefix: candidate, focusedIdx: 0 }); // KT-10: partial two-character prefix
  }, [activate, containerRef, flash, setKt]);

  const onDocKeyDown = useCallback((e: KeyboardEvent) => {
    if (e.key === "Alt") {
      altDownAtRef.current = Date.now();
      altChordRef.current = false;
      // ⭐⭐ W54-T24 — TAKE THE BARE ALT AWAY FROM THE BROWSER, ON THE KEYDOWN. On Windows and
      // Linux desktop Chrome an unconsumed Alt press-and-release moves focus into the browser's
      // own menu bar, and everything typed next goes there instead of to this layer. The old code
      // only prevented the default on the KEYUP, and only on the branch that toggled, so a press
      // the layer rejected still armed the menu. Consuming it here costs nothing: a bare Alt has
      // no other meaning on this page, and AltGr (which Windows delivers as Control plus Alt) is
      // excluded so composed characters still work.
      if (!e.ctrlKey && !e.metaKey && !e.shiftKey) e.preventDefault();
      return;
    }
    // ⭐⭐ W54-T24 — ALT HELD PLUS A FIRST LEVEL LETTER IS THE SAME COMMAND AS ALT THEN THE
    // LETTER. This is the fast typist's path and the one that used to die: see
    // `isFirstLevelCode` above for the measurement and for why the match is required, which is
    // what keeps every browser owned Alt chord untouched.
    if ((altDownAtRef.current !== null || e.altKey) && !e.ctrlKey && !e.metaKey
        && !stateRef.current.active && isTextChar(e.key)
        && isFirstLevelCode(containerRef.current, e.key.toUpperCase())) {
      e.preventDefault(); e.stopPropagation();
      altChordRef.current = true; // the trailing Alt keyup must not toggle the layer a second time
      activateFirstLevel();
      handleCharacter(e.key.toUpperCase());
      return;
    }
    if (altDownAtRef.current !== null) altChordRef.current = true; // a real chord, not a bare press
    if (!stateRef.current.active) return; // IDLE: swallow nothing (contract C5)

    const st = stateRef.current;
    const targets = navElements(containerRef.current, st.depth, st.prefix);

    if (e.key === "Escape") {
      e.preventDefault(); e.stopPropagation();
      stepBack();
      return;
    }
    // ⭐⭐ S67-T17 (instruction 18, ruling R29 / O28) — INSIDE A COLOUR GALLERY THE ARROWS WALK
    // THE PALETTE. Fill Color, Font Color and the Line Color flyout are grids, so all four arrows
    // move the focus ring through them in two dimensions (`swatchGridStep`) and none of them
    // reaches the grid: the selection stays where it is. This NARROWS W55-T05 / R4 for swatch
    // grids only; every other gallery falls through to it unchanged. Enter applies the focused
    // colour through `activate`, which closes the key tips and returns focus to the grid.
    const walk = st.depth === "gallery" ? swatchWalk(containerRef.current) : null;
    if (walk && isArrowKey(e.key)) {
      e.preventDefault(); e.stopPropagation();
      const from = walk.indexOf(document.activeElement as HTMLButtonElement);
      const next = swatchGridStep(walk.map((b) => b.getBoundingClientRect()), from, e.key);
      // Left at the flyout's first item closes it, as the flyout's own ArrowLeft does.
      if (e.key === "ArrowLeft" && from >= 0 && next === from && closeFlyout()) return;
      if (next >= 0) {
        setKt({ focusedIdx: next });
        walk[next].focus();
      }
      return;
    }
    if (walk && (e.key === "Enter" || e.key === " ")) {
      e.preventDefault(); e.stopPropagation();
      const el = walk.find((b) => b === document.activeElement) ?? walk[st.focusedIdx];
      if (el) activate(el);
      return;
    }
    // W55-T05 / R4: Up and Down leave the Alt path instead of walking its badges. The original
    // document-capture key cannot reach Glide because focus currently belongs to the ribbon, so
    // consume it once, close synchronously, and hand one semantic arrow to this ribbon's own
    // SheetGrid wrapper. That wrapper owns selection and focus; no global key listener competes
    // with the shared overlay/Escape stack.
    const gridArrow = keyTipGridArrow(e.key);
    if (gridArrow) {
      e.preventDefault(); e.stopPropagation();
      deactivateAll(false);
      containerRef.current?.closest<HTMLElement>(".sheet-grid-wrap")?.dispatchEvent(
        new CustomEvent(KEY_TIP_GRID_ARROW_EVENT, { detail: { key: gridArrow } }),
      );
      return;
    }
    if (e.key === "ArrowRight") {
      e.preventDefault(); e.stopPropagation();
      if (targets.length) {
        const next = (st.focusedIdx + 1) % targets.length;
        setKt({ focusedIdx: next });
        targets[next]?.focus();
      }
      return;
    }
    if (e.key === "ArrowLeft") {
      e.preventDefault(); e.stopPropagation();
      if (targets.length) {
        const next = (st.focusedIdx - 1 + targets.length) % targets.length;
        setKt({ focusedIdx: next });
        targets[next]?.focus();
      }
      return;
    }
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault(); e.stopPropagation();
      const el = targets[st.focusedIdx];
      if (el) {
        if (el.disabled) flash();
        else activate(el);
      }
      return;
    }
    if (isTextChar(e.key)) {
      e.preventDefault(); e.stopPropagation();
      handleCharacter(e.key.toUpperCase());
      return;
    }
    if (e.key === "Shift" || e.key === "Control" || e.key === "Meta" || e.key === "AltGraph") {
      return; // a bare modifier changes nothing and cannot reach the grid as input on its own
    }
    // Any other key (Tab, Backspace, function keys, punctuation, ...): KT-19 says the grid must
    // not receive it as cell input while the layer is active, so it is consumed here -- but with
    // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every
    // non-actionable key a person might happen to touch.
    e.preventDefault(); e.stopPropagation();
  }, [activate, activateFirstLevel, closeFlyout, containerRef, deactivateAll, flash,
      handleCharacter, stepBack, setKt]);

  const onDocKeyUp = useCallback((e: KeyboardEvent) => {
    if (e.key !== "Alt") return;
    const downAt = altDownAtRef.current;
    const chordUsed = altChordRef.current;
    altDownAtRef.current = null;
    altChordRef.current = false;
    if (downAt === null || chordUsed) return; // D-2: a real chord was in play, not a bare press
    if (Date.now() - downAt > ALT_PRESS_MS) return; // D-3: too slow to count as one press
    if (!document.hasFocus()) return; // D-3: the window lost focus mid-press
    e.preventDefault();
    e.stopPropagation();
    if (stateRef.current.active) deactivateAll(); // KT-16: Alt at ANY depth is a full reset
    else activateFirstLevel(); // KT-1/KT-2/KT-3
  }, [activateFirstLevel, deactivateAll]);

  const onBlur = useCallback(() => {
    clearPendingExact();
    altDownAtRef.current = null;
    altChordRef.current = false;
  }, [clearPendingExact]);

  const onVisibility = useCallback(() => {
    if (document.hidden) {
      clearPendingExact();
      altDownAtRef.current = null;
      altChordRef.current = false;
    }
  }, [clearPendingExact]);

  useEffect(() => {
    document.addEventListener("keydown", onDocKeyDown, true);
    document.addEventListener("keyup", onDocKeyUp, true);
    window.addEventListener("blur", onBlur);
    document.addEventListener("visibilitychange", onVisibility);
    return () => {
      document.removeEventListener("keydown", onDocKeyDown, true);
      document.removeEventListener("keyup", onDocKeyUp, true);
      window.removeEventListener("blur", onBlur);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, [onDocKeyDown, onDocKeyUp, onBlur, onVisibility]);

  const st = stateRef.current;
  if (!st.active) return null;

  const visible = pickTargets(containerRef.current, st.depth, st.prefix);

  // S68-T28: an open gallery is a PORTALLED `.cg-overlay` (`--cg-z-overlay`, 110) since wave 53,
  // while the layer's own rule still sits at `--cg-z-mapchrome` (65, written for the in-place
  // `.sheet-ribbon-pop`), so every gallery badge painted UNDER its menu item and no Paste or Borders
  // letter was visible. Only at gallery depth does the layer rise one step above that overlay.
  const galleryLift = st.depth === "gallery" ? { zIndex: "calc(var(--cg-z-overlay) + 1)" } : undefined;
  return (
    <div ref={overlayRef} className="sheet-kt-layer" aria-hidden="true" style={galleryLift}>
      {visible.map((t) => {
        const rect = t.el.getBoundingClientRect();
        return (
          <span
            key={`${t.code}-${Math.round(rect.left)}-${Math.round(rect.top)}`}
            className={"sheet-kt-badge" + (t.el.disabled ? " is-dim" : "")}
            style={{ left: rect.left - 2, top: rect.bottom - 10 }}
          >
            {t.code}
          </span>
        );
      })}
    </div>
  );
}