okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e5476b0e1
main
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 () { 33for ( const [ node , previous ] of managedInert ) { 34node . inert = node . matches ( '[role="dialog"][data-open]' ) 35 ?node . dataset . open !== 'true' 36 :previous ; 37} 38managedInert . clear (); 39const top = activeSurfaces . at ( - 1 )?. root ; 40if ( ! top ) return ; 41let branch = top ; 42while ( branch . parentElement ) { 43// A lower surface may previously have made this branch inert. 44branch . inert = false ; 45for ( const node of Array . from ( branch . parentElement . children )) { 46if ( node instanceof HTMLElement && node !== branch && ! node . matches ( '.scrim,.dialog-scrim,.nav-scrim' )) { 47managedInert . set ( node , node . inert ); 48node . inert = true ; 49} 50} 51branch = branch . parentElement ; 52if ( branch === document . body ) break ; 53} 54} 55 56function focusables ( root :HTMLElement ) :HTMLElement [] { 57return [ ...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 ( 68open :boolean , 69ref :RefObject < HTMLElement | null >, 70initial ?:RefObject < HTMLElement | null >, 71) { 72const token = useRef ( Symbol ( 'surface' )); 73const returnTo = useRef < HTMLElement | null >( null ); 74const wasOpen = useRef ( false ); 75 76useEffect (() => { 77if ( ! open || ! ref . current ) return ; 78const identity = token . current ; 79returnTo . current = document . activeElement as HTMLElement | null ; 80wasOpen . current = true ; 81activeSurfaces . push ({ identity, root :ref . current }); 82syncBackgroundInert (); 83return () => { 84const at = activeSurfaces . findIndex ( surface => surface . identity === identity ); 85if ( at >= 0 ) activeSurfaces . splice ( at , 1 ); 86syncBackgroundInert (); 87}; 88}, [ open , ref ]); 89 90// Focus once the surface is genuinely visible, not merely mounted. 91useEffect (() => { 92if ( ! open ) return undefined ; 93let frame = 0 ; 94let tries = 0 ; 95const attempt = () => { 96const el = ref . current ; 97if ( ! el ) return ; 98if ( getComputedStyle ( el ). visibility !== 'visible' && tries < 30 ) { 99tries += 1 ; 100frame = requestAnimationFrame ( attempt ); 101return ; 102} 103const target = initial ?. current ?? el . querySelector < HTMLElement >( '[data-initial-focus]' ) ?? focusables ( el )[ 0 ] ?? el ; 104target ?. focus (); 105}; 106frame = 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. 109const fallback = setTimeout (() => { const el = ref . current ; if ( el && ! el . contains ( document . activeElement ) && isTopSurface ( el )) attempt (); }, 80 ); 110return () => { cancelAnimationFrame ( frame ); clearTimeout ( fallback ); }; 111}, [ open , ref , initial ]); 112 113// Keep Tab inside while open. 114useEffect (() => { 115if ( ! open ) return undefined ; 116const onKey = ( e :KeyboardEvent ) => { 117if ( activeSurfaces . at ( - 1 )?. identity !== token . current ) return ; 118if ( e . key !== 'Tab' ) return ; 119const el = ref . current ; 120if ( ! el ) return ; 121const items = focusables ( el ); 122if ( ! items . length ) { 123e . preventDefault (); 124return ; 125} 126const first = items [ 0 ]; 127const last = items [ items . length - 1 ]; 128const active = document . activeElement as HTMLElement | null ; 129const outside = ! active || ! el . contains ( active ); 130if ( e . shiftKey && ( active === first || outside )) { 131e . preventDefault (); 132last . focus (); 133} else if ( ! e . shiftKey && ( active === last || outside )) { 134e . preventDefault (); 135first . focus (); 136} 137}; 138document . addEventListener ( 'keydown' , onKey , true ); 139return () => document . removeEventListener ( 'keydown' , onKey , true ); 140}, [ open , ref ]); 141 142// Hand focus back on close — but not on first mount, when nothing was taken. 143useEffect (() => { 144if ( open || ! wasOpen . current ) return ; 145wasOpen . current = false ; 146const target = returnTo . current ; 147const top = activeSurfaces . at ( - 1 )?. root ; 148if ( target && document . contains ( target ) && ! target . closest ( '[inert]' ) && ( ! top || top . contains ( target ))) target . focus (); 149}, [ open ]); 150}