scene: a rebuild has no failure end; ink and theme follow the sky of the scene that is up
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m5s

A rebuild with no tile stays pending (its loader retries) and replaces the shown scene the moment it holds one; a newer rebuild supersedes it. sceneDrawn owns the drawn sky; the door tells it the band of the scene it shows, and the theme and ink hooks read it, not the announced band. A rebuild over a sky-only scene keeps the first-load deadline.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-23 05:46:16 +01:00
commit 013a3783f5
13 changed files with 175 additions and 55 deletions

View file

@ -24,7 +24,7 @@ export function BackgroundScene() {
if (!enabled || !canvas) return undefined;
const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, {
loggedIn: !!getFallbackSession(),
onActive: () => setSceneDrawn(true),
onActive: (sky) => setSceneDrawn(true, sky),
onInactive: () => setSceneDrawn(false),
// eslint-disable-next-line no-console
onFail: (e) => console.warn('Background scene unavailable:', e),

View file

@ -29,7 +29,7 @@ means "keep the CSS ground". Everything below this section describes the opt-in
geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas of the tile's interior and one
overlap column each side. The backdrop holds the arc ahead and two tiles beyond and lets go of the rest; a tile that fails is absent and asked for again by the backdrop itself after a pause that doubles to a minute, for as long as the arc last asked for wants it (a still has no timer of its own), and a file the server answers 404 is not asked for again (the tile is drawn with the cards that came). A sky change is a
rebuild, so it makes a new lighter; nothing is lit per frame, and the host canvas is only ever asked for 2d.
`createRidgeScene({ backdrop })` stays synchronous (`prepare()` awaits the first arc), and a rebuild keeps the old scene up until the new one holds tiles, then swaps (a build a newer one supersedes is given up at once, its requests aborted; a rebuild that ends with no tile leaves the scene that is up, and only a first load that ends with none is the sky alone); the
`createRidgeScene({ backdrop })` stays synchronous (`prepare()` awaits the first arc), and a rebuild keeps the old scene up until the new one holds tiles, then swaps (a build a newer one supersedes is given up at once, its requests aborted; a rebuild has no failure end: with no tile it stays pending beside the scene that is up, its loader asking again, and replaces it the moment it holds one; only a build with no ridge up behind it, a first load or a rebuild over the sky alone, that ends with no tile is the sky alone). The page theme and ink follow the sky of the scene that is up (`sceneDrawn.ts` holds it, set by the door's `onActive`), never the band announced; the
pose survives it. The rig is one div of K boxes, one per card (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's
parent), each holding that card's resident tiles at their unwrapped azimuth. A card's pose (scale and shift) is derived by `view.ts` `cardPose` from its distance at
the heading (`ring.ts`), the viewer's offset and the camera's angle on its circle, as a camera on a circle round the bake centre sees it (ruling ridge-camera-on-circle;

View file

@ -44,6 +44,14 @@ describe('mountBackgroundScene', () => {
expect(scene.login).not.toHaveBeenCalled();
});
it('tells onActive the sky the started scene draws', async () => {
startBackgroundScene.mockResolvedValue({ ...fakeScene(), drawnSky: 'dusk' });
const onActive = vi.fn();
mountBackgroundScene(config, caps, canvas, { loggedIn: false, onActive });
await flush();
expect(onActive).toHaveBeenCalledWith('dusk');
});
it('disposes the scene on unmount, once', async () => {
const scene = fakeScene();
startBackgroundScene.mockResolvedValue(scene);

View file

@ -1,12 +1,13 @@
import { startBackgroundScene } from './index';
import type { Scene } from './index';
import type { StartedScene } from './index';
import type { FixedSkyState } from './ridge/skyMoment';
import type { BackgroundSceneConfig, Capabilities } from './tier';
export type HostOptions = {
/** A Matrix session already exists, so the scene starts past its login moment. */
loggedIn: boolean;
/** The scene is running: the host may now let it show through. Not called when there is none. */
onActive?: () => void;
/** The scene is running: the host may now let it show through, over the sky it draws. Not called when there is none. */
onActive?: (sky?: FixedSkyState) => void;
/** The scene stopped because its GL context was lost: put the CSS ground back until it restores. */
onInactive?: () => void;
/** A shader failed to compile, the chunk failed to load, or starting threw. The CSS ground stays. */
@ -30,7 +31,7 @@ export function mountBackgroundScene(
{ loggedIn, onActive, onInactive, onFail }: HostOptions
): () => void {
let cancelled = false;
let scene: Scene | null = null;
let scene: StartedScene | null = null;
let generation = 0;
const start = () => {
@ -57,7 +58,7 @@ export function mountBackgroundScene(
}
scene = started;
if (!scene) return;
onActive?.();
onActive?.(scene.drawnSky);
if (loggedIn) scene.login();
},
(e) => {

View file

@ -68,14 +68,23 @@ const loader = () => {
fail: false,
calls: [] as any[],
made: [] as any[],
/** The loader's retry succeeds: every backdrop that was asked while `fail` was set now holds a tile, and tells whoever listens. */
arrive: () => undefined as void,
};
const heard = new Set<() => void>();
ctl.arrive = () => {
arrived = true;
[...heard].forEach((cb) => cb());
};
let arrived = false;
createBackdrop.mockImplementation((manifest: unknown, physical: unknown) => {
const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
let made = false;
const bd = {
manifest,
dispose: vi.fn(),
litTiles: () => (made && !fails ? [{ tile: 0, card: 0, canvas: {} }] : []),
litTiles: () => (made && (!fails || arrived) ? [{ tile: 0, card: 0, canvas: {} }] : []),
onTile: vi.fn((cb: () => void) => (heard.add(cb), () => void heard.delete(cb))),
ensure: vi.fn(
() =>
new Promise<void>((resolve) => {
@ -1023,26 +1032,56 @@ describe('the ridge cards and the live scene', () => {
scene?.dispose();
});
it('a rebuild that ends with no tile keeps the scene that is up: nothing is swapped, nothing is told, its backdrop is disposed, and the next change of sky tries again', async () => {
it('a rebuild has no failure end: with no tile it stays pending beside the scene that is up (its loader asking again), replaces it the moment a tile is held, and the ink follows the sky drawn throughout', async () => {
serve();
const d = loader();
const [first, second] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const [onPlanesFail, onInactive, onActive] = [vi.fn(), vi.fn(), vi.fn()];
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive, onActive });
d.ctl.fail = true; // the link blinks for the whole pass of the rebuild
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive, onActive });
expect(scene?.drawnSky).toBe('day');
d.ctl.fail = true; // the link blinks for the whole pass of the rebuild
setSkyChoice(NIGHT);
await flush();
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(first.dispose).not.toHaveBeenCalled(); // the ridge that was fine is still up
expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce();
expect(d.ctl.made[1].dispose).not.toHaveBeenCalled(); // and the build for the new sky is alive, not given up
expect(getResolvedSkyState()).toBe('night'); // the sky is announced as night
expect(scene?.drawnSky).toBe('day'); // the scene up draws day, and that is what the ink follows
expect([onPlanesFail, onInactive, onActive].map((f) => f.mock.calls.length)).toEqual([0, 0, 0]);
d.ctl.fail = false;
setSkyChoice(DUSK); // the next change of sky: the one that failed was never drawn, and this is built now
d.ctl.arrive(); // the loader's retry got a tile through
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(first.dispose).toHaveBeenCalledOnce();
expect(onActive).toHaveBeenCalledOnce();
expect(onActive).toHaveBeenCalledWith('night');
expect(scene?.drawnSky).toBe('night');
expect(onPlanesFail).not.toHaveBeenCalled();
scene?.dispose();
});
it('a pending rebuild is superseded by a newer one, which is given up at once; the newest replaces the scene', async () => {
serve();
const d = loader();
const [first, second] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const onActive = vi.fn();
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.fail = true;
setSkyChoice(NIGHT);
await flush();
setSkyChoice(DUSK);
await flush();
expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce();
expect(d.ctl.made[2].dispose).not.toHaveBeenCalled();
d.ctl.arrive();
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(onActive).toHaveBeenCalledOnce();
expect(onActive).toHaveBeenCalledWith('dusk');
scene?.dispose();
});
@ -1085,11 +1124,15 @@ describe('the ridge cards and the live scene', () => {
await flush();
expect(onPlanesOk).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined();
d.ctl.fail = true; // a rebuild that ends with no tile does not take the planes from the scene that has them
d.ctl.fail = true; // a rebuild with no tile does not take the planes from the scene that has them: it waits
setSkyChoice(NIGHT);
await flush();
expect(onPlanesFail).toHaveBeenCalledOnce();
expect(createRidgeScene).toHaveBeenCalledTimes(3);
d.ctl.arrive();
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(4);
expect(onPlanesFail).toHaveBeenCalledOnce();
scene?.dispose();
});
});

View file

@ -1,14 +1,19 @@
import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { debugOverlaysAllowed } from './debugOverlays';
import { getConstellationLines, getSkyChoice, subscribe } from './skyState';
import type { SkyChoice } from './ridge/skyMoment';
import { getConstellationLines, getResolvedSkyState, getSkyChoice, subscribe } from './skyState';
import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
export type { Scene, SceneStats } from './Scene';
/** The scene the door returns: it also says which sky it draws now (the band of the scene that is up, not of the sky announced). */
export interface StartedScene extends Scene {
readonly drawnSky: FixedSkyState | undefined;
}
export type { SceneStyle, SceneTier } from './tier';
export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompileFail'> & {
@ -16,8 +21,8 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
onCompileFail?: (e: Error) => void;
/** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */
onInactive?: () => void;
/** A rebuild made a scene again: the host lets it show. */
onActive?: () => void;
/** A rebuild made a scene again: the host lets it show, over the sky that scene draws (what the page ink follows). */
onActive?: (sky?: FixedSkyState) => void;
/** The live scene is the sky alone because the baked ridge cards did not load (no manifest, a missing or undecodable card, no WebGL2 to light them). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */
onPlanesFail?: (e: Error) => void;
/** The live scene has its planes after `onPlanesFail` said it had none: the host lets go of the ground it filled. */
@ -34,15 +39,39 @@ interface Prepared {
discard: () => void;
/** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */
planesFail: Error | null;
/** The band of the sky this scene is made with: what it draws once made. */
sky: FixedSkyState | undefined;
}
/** How long the first scene start waits for the first tiles, ms: past it the scene draws with the tiles it has and the rest arrive into it; with none, it is the sky alone. A rebuild has no deadline: the scene it replaces stays up until the new one holds tiles. */
/** How long the first scene start waits for the first tiles, ms: past it the scene draws with the tiles it has and the rest arrive into it; with none, it is the sky alone. A rebuild over a scene with a ridge has no deadline and no failure end: the scene it replaces stays up until the new one holds tiles. */
export const PREPARE_DEADLINE_MS = 6_000;
/** Resolves when `backdrop` holds a tile (its loader retries a failed one on its own backoff) or `stop` aborts. */
const holdsATile = (backdrop: Backdrop, stop: AbortSignal): Promise<void> =>
new Promise<void>((done) => {
if (backdrop.litTiles().length > 0 || stop.aborted) {
done();
return;
}
const off = backdrop.onTile(() => {
off();
done();
});
stop.addEventListener(
'abort',
() => {
off();
done();
},
{ once: true }
);
});
async function prepare(
config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier; debug?: boolean },
choice: SkyChoice,
/** Nothing with a ridge is up to wait behind: the page's first scene, or a rebuild over a scene that is the sky alone. It waits against the deadline and, with no tile, is the sky alone. */
first: boolean,
superseded: AbortSignal
): Promise<Prepared> {
@ -54,8 +83,10 @@ async function prepare(
backdrop = null;
};
superseded.addEventListener('abort', release, { once: true });
let band: FixedSkyState | undefined;
const guarded = (make: () => Scene | null): Prepared => ({
planesFail: null,
sky: band,
discard: release,
make: () => {
try {
@ -85,6 +116,7 @@ async function prepare(
if (manifest) {
try {
const manifestSky = ridgeSkyFor(choice, manifest.view);
band = getResolvedSkyState();
const { createBackdrop } = await import('./ridge/Backdrop');
const heading = await import('./ridge/heading');
backdrop = createBackdrop(manifest, manifestSky.physical as NonNullable<typeof manifestSky.physical>);
@ -94,7 +126,7 @@ async function prepare(
heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now, (mode) => maxSpeed(manifest, mode));
const { h } = heading.poseAt(now);
// The first arc. The first scene of a page has nothing to show meanwhile, so it waits against a deadline (a slow or silent server must not hold it back):
// what is held by then is drawn and the rest fills in. A rebuild has the old scene up and waits for its tiles as long as they take.
// what is held by then is drawn and the rest fills in. A rebuild has the old scene up and has no end: it waits for a tile as long as that takes, its loader asking again.
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
@ -106,6 +138,7 @@ async function prepare(
} finally {
clearTimeout(timer);
}
if (!first) await holdsATile(backdrop, superseded);
if (superseded.aborted) throw new Error('ridge: superseded');
if (backdrop.litTiles().length === 0) throw new Error('ridge cards did not load');
lit = manifestSky;
@ -117,6 +150,7 @@ async function prepare(
const view = drawnView(backdrop ? manifest : null);
if (!lit) await loadWeather(weatherUrl(), view.place);
const sky = lit ?? ridgeSkyFor(choice, view);
if (!lit) band = getResolvedSkyState();
const made = guarded(() =>
createRidgeScene({
...options,
@ -128,7 +162,7 @@ async function prepare(
return { ...made, planesFail };
} catch (e) {
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return { make: () => null, discard: () => undefined, planesFail: null };
return { make: () => null, discard: () => undefined, planesFail: null, sky: undefined };
}
}
@ -167,7 +201,7 @@ export async function startBackgroundScene(
config: BackgroundSceneConfig | undefined,
capabilities: Capabilities,
options: StartOptions
): Promise<Scene | null> {
): Promise<StartedScene | null> {
const tier = resolveTier(config, capabilities);
if (tier === 'off') return null;
const debug = debugOverlaysAllowed(config);
@ -184,19 +218,22 @@ export async function startBackgroundScene(
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice);
const firstReady = await prepared(choice, true, new AbortController().signal);
const first = firstReady.make();
if (!first || config?.style === 'raymarch') return first;
if (!first) return null;
// The ray-march scene has one fixed dusk.
if (config?.style === 'raymarch') return Object.assign(first, { drawnSky: 'dusk' as const });
announce(firstReady.planesFail);
let inner: Scene | null = first;
let built = key0;
let shown = key0; // the sky key of the scene that is up
let drawnSky = firstReady.sky; // the band of the scene that is up
let loggedIn = false;
let disposed = false;
let generation = 0;
let building: AbortController | undefined;
// A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn. What replaces the scene that is up: a new backdrop,
// once it holds tiles; a build a newer one supersedes is given up at once (its requests aborted); a build that ends with no tile never swaps a ridge for the sky alone,
// the next change of sky tries again. Only a first load that ends with no tile is the sky alone.
// the moment it holds tiles (its loader asks again on its own until it does; a rebuild has no failure end); a build a newer one supersedes is given up at once (its
// requests aborted). A rebuild never swaps a ridge for the sky alone; only a build with no ridge up behind it (the first load, or a rebuild over the sky alone) that ends with no tile is the sky alone.
const rebuild = async () => {
// The choice can move while the key is awaited; that change has its own rebuild, so this one stands down.
const next = getSkyChoice();
@ -210,7 +247,7 @@ export async function startBackgroundScene(
const mineAborts = new AbortController();
building = mineAborts;
// The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks.
const ready = await prepared(next, false, mineAborts.signal);
const ready = await prepared(next, planesFailed, mineAborts.signal); // over a sky-only scene there is no ridge to protect: the new sky is drawn at once
if (disposed || mine !== generation) {
ready.discard();
return;
@ -226,10 +263,11 @@ export async function startBackgroundScene(
const scene = ready.make();
inner = scene;
shown = key;
drawnSky = ready.sky;
if (scene) announce(ready.planesFail);
if (!scene) options.onInactive?.();
else {
options.onActive?.();
options.onActive?.(ready.sky);
if (loggedIn) scene.login();
}
};
@ -237,6 +275,9 @@ export async function startBackgroundScene(
// A change that landed while the first build was awaited was missed by the subscription.
rebuild();
return {
get drawnSky() {
return drawnSky;
},
login() {
loggedIn = true;
inner?.login();

View file

@ -413,7 +413,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const { view } = bd.manifest;
const { w, h, scale: dpr } = viewSize();
const win = windowFor(view, w, h);
const at = (stillPose ??= headingPose(clock()));
stillPose ??= headingPose(clock());
const at = stillPose;
const planeTop = h - win.plane.bottom - win.plane.h;
const horizonY = planeTop + view.horizonRow * win.plane.scale;
const poses = bd.manifest.cards.map((_, i) =>
@ -614,7 +615,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
stillPose = undefined;
if (wasStill && opts.backdrop) {
const { h } = headingPose(clock());
void opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined);
opts.backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }).catch(() => undefined);
}
}
freshPose = false;

View file

@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
SCENE_ACTIVE_ATTRIBUTE,
getDrawnSky,
getSceneDrawn,
setSceneDrawn,
subscribeSceneDrawn,
@ -34,4 +35,20 @@ describe('sceneDrawn: one store owns the flag and html[data-scene]', () => {
setSceneDrawn(true);
expect(cb).toHaveBeenCalledTimes(2);
});
it('owns the sky the scene that is up draws: set with the scene, told to subscribers when it changes, gone with the scene', () => {
const cb = vi.fn();
const off = subscribeSceneDrawn(cb);
expect(getDrawnSky()).toBeUndefined();
setSceneDrawn(true, 'day');
expect(getDrawnSky()).toBe('day');
setSceneDrawn(true, 'day');
expect(cb).toHaveBeenCalledTimes(1);
setSceneDrawn(true, 'night'); // a rebuilt scene replaced the one shown
expect(getDrawnSky()).toBe('night');
expect(cb).toHaveBeenCalledTimes(2);
setSceneDrawn(false, 'night'); // no scene draws no sky
expect(getDrawnSky()).toBeUndefined();
off();
});
});

View file

@ -1,16 +1,22 @@
// Whether a background scene is drawing a sky right now. BackgroundScene is the only writer: it sets this when the
// ridge scene starts, and clears it when the scene stops, fails to start, or loses its WebGL context (a restored
// context sets it again). This store also owns html[data-scene], so the attribute the CSS reads and the flag the theme
// hooks read cannot disagree. The configured tier only says a scene may run; this says one does.
// Whether a background scene is drawing a sky right now, and which sky (day, dusk or night) the scene that is up draws. BackgroundScene is the only
// writer: it sets this when a scene is up (told the band of the scene it shows, so a rebuild still loading changes nothing here until it replaces it),
// and clears it when the scene stops, fails to start, or loses its WebGL context (a restored context sets it again). The page theme and ink follow
// this sky, never the band the clock or the choice announces (ruling ink-follows-drawn-sky). This store also owns html[data-scene], so the attribute
// the CSS reads and the flag the theme hooks read cannot disagree. The configured tier only says a scene may run; this says one does.
import type { FixedSkyState } from './ridge/skyMoment';
/** Set on <html> while a scene is drawn, so signed-out screens can let it show through. */
export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene';
let drawn = false;
let drawnSky: FixedSkyState | undefined;
const listeners = new Set<() => void>();
export const getSceneDrawn = (): boolean => drawn;
/** The sky the scene that is up draws; undefined with no scene, or a scene whose sky is not known. */
export const getDrawnSky = (): FixedSkyState | undefined => drawnSky;
export const subscribeSceneDrawn = (cb: () => void): (() => void) => {
listeners.add(cb);
return () => {
@ -18,12 +24,14 @@ export const subscribeSceneDrawn = (cb: () => void): (() => void) => {
};
};
export function setSceneDrawn(on: boolean): void {
export function setSceneDrawn(on: boolean, sky?: FixedSkyState): void {
if (typeof document !== 'undefined') {
if (on) document.documentElement.setAttribute(SCENE_ACTIVE_ATTRIBUTE, '');
else document.documentElement.removeAttribute(SCENE_ACTIVE_ATTRIBUTE);
}
if (on === drawn) return;
const next = on ? sky : undefined;
if (on === drawn && next === drawnSky) return;
drawn = on;
drawnSky = next;
[...listeners].forEach((cb) => cb());
}

View file

@ -1,5 +1,5 @@
// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the
// choice at the place; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
// scene that is up draws; `useDrawnSky`) alone decides the theme and, with it, the ink: Day and Dusk
// wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is
// drawn, that is with the scene off.
import type { FixedSkyState } from './ridge/skyMoment';

View file

@ -1,20 +1,14 @@
import { useSyncExternalStore } from 'react';
import {
getResolvedSkyState,
getSkyChoice,
getSkyPlace,
subscribe,
} from '../features/scene/skyState';
import { getSkyChoice, getSkyPlace, subscribe } from '../features/scene/skyState';
import type { Place } from '../features/scene/ridge/view';
import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment';
import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
import { getDrawnSky, getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useResolvedSkyState`. */
/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useDrawnSky`. */
export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice);
/** The sky being drawn: day, dusk or night, or undefined until the place is known. Unlike the choice it changes as the clock crosses under Auto, so it re-renders. */
export const useResolvedSkyState = (): FixedSkyState | undefined =>
useSyncExternalStore(subscribe, getResolvedSkyState);
/** The sky the scene that is up draws: day, dusk or night, or undefined with no scene. It moves when a scene replaces the one shown, not when the clock or the choice announces a band the scene has not caught up with. */
export const useDrawnSky = (): FixedSkyState | undefined => useSyncExternalStore(subscribeSceneDrawn, getDrawnSky);
/** The place the sky is over, or undefined until a scene has settled what it draws (skyPlace.ts). */
export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subscribe, getSkyPlace);

View file

@ -24,7 +24,7 @@ vi.stubGlobal('window', {
vi.mock('./useSkyState', async () => {
const drawn = await import('../features/scene/sceneDrawn');
return {
useResolvedSkyState: () => 'night',
useDrawnSky: () => drawn.getDrawnSky(),
useSkyChoice: () => ({ kind: 'named', id: 'night' }),
useSceneOn: () => drawn.getSceneDrawn(),
};
@ -70,7 +70,14 @@ describe('the drawn sky decides the theme and ink; the stored theme stands where
});
it('a scene running over a stored theme wears the sky theme and ink', () => {
setSceneDrawn(true);
setSceneDrawn(true, 'night');
expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
});
it('follows the sky of the scene that is up, whatever the clock or the choice announce, and moves when a scene replaces it', () => {
setSceneDrawn(true, 'dusk'); // the choice says night (mocked above); the scene up draws dusk
expect(read()).toBe('noonday-sky|{"state":"dusk","phone":false}');
setSceneDrawn(true, 'night'); // a rebuilt scene replaced it
expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
});
@ -79,10 +86,10 @@ describe('the drawn sky decides the theme and ink; the stored theme stands where
});
it('a restored context wears the sky again', () => {
setSceneDrawn(true);
setSceneDrawn(true, 'night');
setSceneDrawn(false);
expect(read()).toBe('dark-theme|null');
setSceneDrawn(true);
setSceneDrawn(true, 'night');
expect(read()).toBe('midnight-sky|{"state":"night","phone":false}');
});
});

View file

@ -14,7 +14,7 @@ import { settingsAtom } from '../state/settings';
import { useSetting } from '../state/hooks/settings';
import { sceneThemeId } from '../features/scene/skyTheme';
import { sceneInk, type SkyInk } from '../features/scene/skyInk';
import { useResolvedSkyState, useSceneOn } from './useSkyState';
import { useDrawnSky, useSceneOn } from './useSkyState';
import { ScreenSize, useScreenSizeContext } from './useScreenSize';
export enum ThemeKind {
@ -109,16 +109,16 @@ const toTheme = (id: ReturnType<typeof sceneThemeId>): Theme | undefined =>
/** The theme the drawn sky asks for while a scene is on, or undefined for none (signed-out pages then wear Midnight Sky). */
export const useSkyTheme = (): Theme | undefined =>
toTheme(sceneThemeId(useResolvedSkyState(), useSceneOn()));
toTheme(sceneThemeId(useDrawnSky(), useSceneOn()));
/** The sky theme the page wears while a scene is on, or undefined when the person's own theme stands. */
const useSceneSkyThemeId = (): ReturnType<typeof sceneThemeId> =>
sceneThemeId(useResolvedSkyState(), useSceneOn());
sceneThemeId(useDrawnSky(), useSceneOn());
/** The ink the page wears over the scene (`sceneInk`, skyInk.ts), or undefined when the theme's own ink stands. */
export const useSceneInk = (): SkyInk | undefined => {
const themeId = useSceneSkyThemeId();
const state = useResolvedSkyState();
const state = useDrawnSky();
const sceneOn = useSceneOn();
const phone = useScreenSizeContext() === ScreenSize.Mobile;
return useMemo(() => sceneInk(themeId, sceneOn, state, phone), [themeId, sceneOn, state, phone]);