okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1631a9fde
main
1/** 2* Screens that are not needed to show the start screen load the first time they are used. 3* 4* `lazyScreen(load, pick)` is React.lazy over a dynamic import, for the routed screens. 5* `useLoadedModule(load, wanted)` is for surfaces that stay mounted and animate open (the Settings and set-up 6* dialogs): it returns the module once its code is here (null until then), and the caller opens the surface at 7* that point, so it appears exactly as before (same first frame, same focus target) instead of opening empty and 8* filling in. If a chunk cannot be fetched the error is thrown into render, and reaches the app's boundary as for 9* any other screen that fails to show. 10*/ 11import { lazy , useEffect , useState , type ComponentType } from 'react' ; 12 13export function lazyScreen < M , P extends object > ( load :() => Promise < M >, pick :( module :M ) => ComponentType < P >) { 14return lazy (() => load (). then (( module ) => ({ default :pick ( module ) }))); 15} 16 17const loaded = new WeakMap < object , unknown >(); 18 19export function useLoadedModule < M > ( load :() => Promise < M >, wanted :boolean ) :M | null { 20const [ module , setModule ] = useState < M | null >(() => ( loaded . get ( load ) as M | undefined ) ?? null ); 21const [ failure , setFailure ] = useState < unknown >( null ); 22useEffect (() => { 23if ( ! wanted || module ) return ; 24let live = true ; 25load (). then (( value ) => { loaded . set ( load , value ); if ( live ) setModule ( value ); }, ( error ) => { if ( live ) setFailure ( error ?? new Error ( 'chunk failed' )); }); 26return () => { live = false ; }; 27}, [ wanted , module , load ]); 28if ( failure ) throw failure ; 29return module ; 30}