okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-split-int (c157ea373) into f-split-qa1: my new strings renumbered after s3236 (s3237-s3255)e5476b0e1

main
5.7 KiB150 linesraw
1/**
2 * Focus management for surfaces that reveal themselves.
3 *
4 * Overlays in this app stay mounted and animate open, which means their
5 * `visibility` flips through a discrete transition. A `focus()` call in the same
6 * commit as the open is therefore dropped — the element is still
7 * `visibility: hidden` when the effect runs — which left the command palette
8 * open with focus on a sidebar button *behind* it.
9 *
10 * So focus is applied once the surface actually reports visible, Tab is kept
11 * inside while it is open, and focus returns to whatever opened it on close.
12 */
13import { useEffect, useRef, type RefObject } from 'react';
14
15const FOCUSABLE = [
16  'a[href]',
17  'button:not([disabled])',
18  'input:not([disabled])',
19  'select:not([disabled])',
20  'textarea:not([disabled])',
21  'summary',
22  '[tabindex]:not([tabindex="-1"])',
23].join(',');
24const activeSurfaces: { identity: symbol; root: HTMLElement }[] = [];
25export function isTopSurface(root: HTMLElement | null) { return activeSurfaces.at(-1)?.root === root; }
26const managedInert = new Map<HTMLElement, boolean>();
27
28/** Recompute from the top surface instead of restoring stale sibling snapshots.
29 * React may open one mounted dialog in the same commit that closes another.
30 * Its current data-open value takes precedence over the previous inert value.
31 */
32function syncBackgroundInert() {
33  for (const [node, previous] of managedInert) {
34    node.inert = node.matches('[role="dialog"][data-open]')
35      ? node.dataset.open !== 'true'
36      : previous;
37  }
38  managedInert.clear();
39  const top = activeSurfaces.at(-1)?.root;
40  if (!top) return;
41  let branch = top;
42  while (branch.parentElement) {
43    // A lower surface may previously have made this branch inert.
44    branch.inert = false;
45    for (const node of Array.from(branch.parentElement.children)) {
46      if (node instanceof HTMLElement && node !== branch && !node.matches('.scrim,.dialog-scrim,.nav-scrim')) {
47        managedInert.set(node, node.inert);
48        node.inert = true;
49      }
50    }
51    branch = branch.parentElement;
52    if (branch === document.body) break;
53  }
54}
55
56function focusables(root: HTMLElement): HTMLElement[] {
57  return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
58    (el) => !el.closest('[inert]') && getComputedStyle(el).visibility === 'visible' && (el.offsetParent !== null || el === document.activeElement),
59  );
60}
61
62/**
63 * @param open    whether the surface is showing
64 * @param ref     the surface element
65 * @param initial optional element to focus instead of the first focusable one
66 */
67export function useSurfaceFocus(
68  open: boolean,
69  ref: RefObject<HTMLElement | null>,
70  initial?: RefObject<HTMLElement | null>,
71) {
72  const token = useRef(Symbol('surface'));
73  const returnTo = useRef<HTMLElement | null>(null);
74  const wasOpen = useRef(false);
75
76  useEffect(() => {
77    if (!open || !ref.current) return;
78    const identity = token.current;
79    returnTo.current = document.activeElement as HTMLElement | null;
80    wasOpen.current = true;
81    activeSurfaces.push({ identity, root: ref.current });
82    syncBackgroundInert();
83    return () => {
84      const at = activeSurfaces.findIndex(surface => surface.identity === identity);
85      if (at >= 0) activeSurfaces.splice(at, 1);
86      syncBackgroundInert();
87    };
88  }, [open, ref]);
89
90  // Focus once the surface is genuinely visible, not merely mounted.
91  useEffect(() => {
92    if (!open) return undefined;
93    let frame = 0;
94    let tries = 0;
95    const attempt = () => {
96      const el = ref.current;
97      if (!el) return;
98      if (getComputedStyle(el).visibility !== 'visible' && tries < 30) {
99        tries += 1;
100        frame = requestAnimationFrame(attempt);
101        return;
102      }
103      const target = initial?.current ?? el.querySelector<HTMLElement>('[data-initial-focus]') ?? focusables(el)[0] ?? el;
104      target?.focus();
105    };
106    frame = requestAnimationFrame(attempt);
107    // A page that is not being painted (a window that is covered or in the background) holds animation frames back, and then focus would stay
108    // on whatever opened the surface, behind it (QA F03). A timer is not held back, so it moves focus in if the frame did not.
109    const fallback = setTimeout(() => { const el = ref.current; if (el && !el.contains(document.activeElement) && isTopSurface(el)) attempt(); }, 80);
110    return () => { cancelAnimationFrame(frame); clearTimeout(fallback); };
111  }, [open, ref, initial]);
112
113  // Keep Tab inside while open.
114  useEffect(() => {
115    if (!open) return undefined;
116    const onKey = (e: KeyboardEvent) => {
117      if (activeSurfaces.at(-1)?.identity !== token.current) return;
118      if (e.key !== 'Tab') return;
119      const el = ref.current;
120      if (!el) return;
121      const items = focusables(el);
122      if (!items.length) {
123        e.preventDefault();
124        return;
125      }
126      const first = items[0];
127      const last = items[items.length - 1];
128      const active = document.activeElement as HTMLElement | null;
129      const outside = !active || !el.contains(active);
130      if (e.shiftKey && (active === first || outside)) {
131        e.preventDefault();
132        last.focus();
133      } else if (!e.shiftKey && (active === last || outside)) {
134        e.preventDefault();
135        first.focus();
136      }
137    };
138    document.addEventListener('keydown', onKey, true);
139    return () => document.removeEventListener('keydown', onKey, true);
140  }, [open, ref]);
141
142  // Hand focus back on close — but not on first mount, when nothing was taken.
143  useEffect(() => {
144    if (open || !wasOpen.current) return;
145    wasOpen.current = false;
146    const target = returnTo.current;
147    const top = activeSurfaces.at(-1)?.root;
148    if (target && document.contains(target) && !target.closest('[inert]') && (!top || top.contains(target))) target.focus();
149  }, [open]);
150}