okami.mom/strata

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

Niko1221Merge f-clean-7 (045843071): the app loads screens, languages, Prism and Time-skip on first use; main chunk 3,123,528 -> 755,418 B, start screen 248.5 -> 143.4 ms (p2006 Chrome, median of 10); nothing users see changes (cleanup step 7)1631a9fde

main
1.6 KiB30 linesraw
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>) {
14  return 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 {
20  const [module, setModule] = useState<M | null>(() => (loaded.get(load) as M | undefined) ?? null);
21  const [failure, setFailure] = useState<unknown>(null);
22  useEffect(() => {
23    if (!wanted || module) return;
24    let live = true;
25    load().then((value) => { loaded.set(load, value); if (live) setModule(value); }, (error) => { if (live) setFailure(error ?? new Error('chunk failed')); });
26    return () => { live = false; };
27  }, [wanted, module, load]);
28  if (failure) throw failure;
29  return module;
30}