scene: the viewer's place choice (placeState) is the first input of the one place resolution; a pick rebuilds the scene; loadIndex and listPlaces

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-26 17:52:14 +01:00
commit c877f6d0b3
8 changed files with 350 additions and 21 deletions

View file

@ -9,11 +9,12 @@ import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
import { forgetPlaceChoice, setPlaceChoice } from './placeState';
import { hold, poseAt, resetHeading } from './ridge/heading';
import { resetCamera, setCamera } from './cameraState';
import { sunAt } from './ridge/sunAt';
import { ridgeWeather } from './ridge/weather';
import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed';
import { creditLine, parseWeatherFile, WEATHER_FEEDS, weatherFromFile } from './ridge/weatherFeed';
const { createRidgeScene, createScene, createBackdrop } = vi.hoisted(() => ({
createRidgeScene: vi.fn(),
@ -126,6 +127,7 @@ beforeEach(() => {
createRidgeScene.mockReset();
createScene.mockReset();
createBackdrop.mockReset();
forgetPlaceChoice();
});
afterEach(() => {
setSkyClock();
@ -407,6 +409,28 @@ describe('the ridge planes', () => {
scene?.dispose();
});
it("draws the place the viewer picks: one rebuild over that place's manifest; an id the index does not list decides nothing", async () => {
served();
loader();
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
const placeOf = (n: number) => createRidgeScene.mock.calls[n][0].backdrop.manifest.view.place.id;
expect(placeOf(0)).toBe('vienna');
setPlaceChoice('graz');
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(placeOf(1)).toBe('graz');
expect(getSkyPlace()?.id).toBe('graz');
setPlaceChoice('atlantis'); // not in the index: the choice is ignored, so the default is drawn
await flush();
expect(placeOf(2)).toBe('vienna');
expect(createRidgeScene).toHaveBeenCalledTimes(3);
scene?.dispose();
setPlaceChoice('graz');
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(3); // disposed: the door no longer listens to the choice
});
it('awaits the first arc of tiles round the heading before the scene is made, and anchors a new place at its rest azimuth', async () => {
served();
resetHeading();
@ -849,7 +873,7 @@ describe('the ridge cards and the live scene', () => {
it("reads the weather against the manifest place's sun, not the fallback place's", async () => {
const w = wireManifest() as any;
const place = { ...w.place, id: 'weather-place', lat: -33, lon: -163.65, tz_h: -11 };
const place = { ...w.place, id: 'vienna', lat: -33, lon: -163.65, tz_h: -11 };
const now = new Date('2026-11-11T10:50:00Z');
const wx = {
fetched_at: '2026-11-11T10:45:00Z',
@ -859,7 +883,7 @@ describe('the ridge cards and the live scene', () => {
humidity_pct: 60,
sunshine_s_10min: null,
glow_wm2: 100,
attribution: WEATHER_ATTRIBUTION,
attribution: creditLine(WEATHER_FEEDS.vienna),
};
vi.stubGlobal(
'fetch',
@ -878,7 +902,7 @@ describe('the ridge cards and the live scene', () => {
setSkyClock(() => now);
createRidgeScene.mockReturnValue(fakeScene());
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
const file = parseWeatherFile(wx)!;
const file = parseWeatherFile(wx, WEATHER_FEEDS.vienna)!;
const at = (p: { lat: number; lon: number }) =>
weatherFromFile(
file,

View file

@ -4,6 +4,7 @@ import { debugOverlaysAllowed } from './debugOverlays';
import { getConstellationLines, getResolvedSkyState, getSkyChoice, subscribe } from './skyState';
import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import { subscribePlaceChoice } from './placeState';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
@ -271,7 +272,13 @@ export async function startBackgroundScene(
if (loggedIn) scene.login();
}
};
const off = subscribe(rebuild);
// A place picked in the Place submenu is a rebuild: `skyKey` re-resolves the place (skyPlace.ts), which is the sky's place, and so the key's.
const offSky = subscribe(rebuild);
const offPlace = subscribePlaceChoice(rebuild);
const off = () => {
offSky();
offPlace();
};
// A change that landed while the first build was awaited was missed by the subscription.
rebuild();
return {

View file

@ -0,0 +1,73 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const KEY = 'ratatoskr.skyPlace';
const store = (initial: Record<string, string> = {}) => {
const data = new Map(Object.entries(initial));
const set = vi.fn((k: string, v: string) => void data.set(k, v));
vi.stubGlobal('localStorage', { getItem: (k: string) => data.get(k) ?? null, setItem: set });
return { data, set };
};
const fresh = async () => {
vi.resetModules();
return import('./placeState');
};
beforeEach(() => store());
afterEach(() => vi.unstubAllGlobals());
describe('the viewer place choice', () => {
it('is none until picked, then persists per viewer under ratatoskr.skyPlace', async () => {
const { data } = store();
const a = await fresh();
expect(a.getPlaceChoice()).toBeUndefined();
a.setPlaceChoice('fuji');
expect(a.getPlaceChoice()).toBe('fuji');
expect(data.get(KEY)).toBe('fuji');
store({ [KEY]: 'fuji' });
expect((await fresh()).getPlaceChoice()).toBe('fuji');
});
it('reads garbage as no choice', async () => {
for (const bad of ['', ' ', '{"id":"fuji"}', 'Fuji!', '../x', 'a'.repeat(65)]) {
store({ [KEY]: bad });
expect((await fresh()).getPlaceChoice()).toBeUndefined();
}
});
it('holds for the page load when storage refuses, reading and writing', async () => {
vi.stubGlobal('localStorage', {
getItem: () => {
throw new Error('blocked');
},
setItem: () => {
throw new Error('blocked');
},
});
const s = await fresh();
expect(s.getPlaceChoice()).toBeUndefined();
s.setPlaceChoice('matterhorn');
expect(s.getPlaceChoice()).toBe('matterhorn');
});
it('tells listeners once per change, and not for the same id or a malformed one', async () => {
const s = await fresh();
const heard = vi.fn();
const off = s.subscribePlaceChoice(heard);
s.setPlaceChoice('fuji');
s.setPlaceChoice('fuji');
s.setPlaceChoice('NOT AN ID');
expect(heard).toHaveBeenCalledTimes(1);
s.setPlaceChoice('amadablam');
expect(heard).toHaveBeenCalledTimes(2);
off();
s.setPlaceChoice('fuji');
expect(heard).toHaveBeenCalledTimes(2);
});
it('does not write storage for a choice it already holds', async () => {
const { set } = store({ [KEY]: 'fuji' });
const s = await fresh();
s.setPlaceChoice('fuji');
expect(set).not.toHaveBeenCalled();
});
});

View file

@ -0,0 +1,49 @@
// The place the viewer picked in the scene view's Place submenu (ruling ridge-places-dropdown-first-four): an id, per viewer, kept in this browser only and never
// shared. It is a wish, not a place: whether it names a baked place is decided by `skyPlace.ts`, the one resolution, which ignores an id the index does not list.
// Main-chunk safe: no sky, no ridge code.
const KEY = 'ratatoskr.skyPlace';
/** A place id as the baker writes it; anything else in storage is no choice. */
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
let choice: string | undefined;
let read = false;
const listeners = new Set<() => void>();
/** The viewer's picked place id, or undefined for none (never picked, refused storage, or garbage in storage). */
export function getPlaceChoice(): string | undefined {
if (!read) {
read = true;
try {
const v = localStorage.getItem(KEY);
choice = v !== null && ID.test(v) ? v : undefined;
} catch {
choice = undefined;
}
}
return choice;
}
/** Pick a place. Stored when storage allows (else it holds for this page load); listeners hear it only when the id changed. */
export function setPlaceChoice(id: string): void {
if (!ID.test(id) || getPlaceChoice() === id) return;
choice = id;
try {
localStorage.setItem(KEY, id);
} catch {
// Storage is refused (private mode, quota): the choice holds for this page load only.
}
[...listeners].forEach((cb) => cb());
}
export function subscribePlaceChoice(cb: () => void): () => void {
listeners.add(cb);
return () => {
listeners.delete(cb);
};
}
/** For tests: forget the choice held in memory and read storage afresh at the next ask. */
export const forgetPlaceChoice = (): void => {
choice = undefined;
read = false;
};

View file

@ -199,9 +199,23 @@ async function getJson(url: string, init?: RequestInit): Promise<unknown> {
}
const memo = new Map<string, Promise<RidgeManifest>>();
const indexMemo = new Map<string, Promise<RidgeIndex>>();
const listMemo = new Map<string, Promise<PlaceListing[]>>();
/** The baked places' index (`${baseUrl}public/ridge/index.json`), memoised per URL; a failure is not remembered. */
export function loadIndex(baseUrl: string): Promise<RidgeIndex> {
const root = `${baseUrl}public/ridge/`;
const hit = indexMemo.get(root);
if (hit) return hit;
// The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and tiles are content-addressed.
const p = getJson(`${root}index.json`, { cache: 'no-cache' }).then(parseIndex);
indexMemo.set(root, p);
p.catch(() => indexMemo.delete(root));
return p;
}
/**
* The manifest of a baked place: `${baseUrl}public/ridge/index.json` names each place's directory, then `<dir>/manifest.json` is read.
* The manifest of a baked place: the index names each place's directory, then `<dir>/manifest.json` is read.
* `placeId` picks the entry (unknown or absent: the index's default). Memoised per index URL and place; a failure is not remembered.
* Rejects on any failure: the caller degrades to the sky-only scene.
*/
@ -211,10 +225,7 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise<RidgeMa
const hit = memo.get(key);
if (hit) return hit;
const p = (async () => {
const index = parseIndex(
// The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and tiles are content-addressed.
await getJson(`${root}index.json`, { cache: 'no-cache' })
);
const index = await loadIndex(baseUrl);
const id = placeId !== undefined && placeId in index.places ? placeId : index.default;
const name = index.places[id];
if (name === undefined) throw new Error(`ridge: index has no place ${id}`);
@ -226,5 +237,36 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise<RidgeMa
return p;
}
/** A baked place as the Place submenu lists it: the manifest's own name and zone (local time on its card). */
export interface PlaceListing {
id: string;
name: string;
tz: string;
}
/** The baked places in the index's order, named by their manifests; a place whose manifest fails to load is left out. Memoised per index URL; a failure is not remembered. */
export function listPlaces(baseUrl: string): Promise<PlaceListing[]> {
const root = `${baseUrl}public/ridge/`;
const hit = listMemo.get(root);
if (hit) return hit;
const p = (async () => {
const index = await loadIndex(baseUrl);
const found = await Promise.allSettled(
Object.keys(index.places).map(async (id): Promise<PlaceListing> => {
const m = await loadManifest(baseUrl, id);
return { id, name: m.name, tz: m.view.place.tz };
})
);
return found.flatMap((f) => (f.status === 'fulfilled' ? [f.value] : []));
})();
listMemo.set(root, p);
p.catch(() => listMemo.delete(root));
return p;
}
/** For tests: forget every memoised manifest. */
export const forgetManifests = (): void => memo.clear();
export const forgetManifests = (): void => {
memo.clear();
indexMemo.clear();
listMemo.clear();
};

View file

@ -0,0 +1,91 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
import { momentFor } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { sunAt } from './ridge/sunAt';
import { ensureSkyPlace, loadPlaceManifest, resolvePlaceId } from './skyPlace';
import { forgetPlaceChoice, setPlaceChoice } from './placeState';
import { getSkyPlace, setSkyPlace, subscribe } from './skyState';
const index = {
default: 'vienna',
places: { vienna: 'v', fuji: 'f', matterhorn: 'm', amadablam: 'a', grandcanyon: 'g' },
};
describe('which place is drawn', () => {
it('is the listed viewer choice before the config place, the config place before the default', () => {
expect(resolvePlaceId(index, 'matterhorn', 'fuji')).toBe('fuji');
expect(resolvePlaceId(index, 'matterhorn', undefined)).toBe('matterhorn');
expect(resolvePlaceId(index, undefined, undefined)).toBe('vienna');
});
it('ignores an unlisted viewer choice, and falls to the default for an unlisted config place', () => {
expect(resolvePlaceId(index, 'matterhorn', 'atlantis')).toBe('matterhorn');
expect(resolvePlaceId(index, 'atlantis', 'atlantis')).toBe('vienna');
expect(resolvePlaceId(index, undefined, 'constructor')).toBe('vienna');
});
});
describe('the place drawn follows the choice through the one resolution', () => {
const noon: SkyChoice = { kind: 'named', id: 'noon' };
const at = new Date('2030-06-21T09:00:00Z');
const names: Record<string, string> = {
'v/manifest.json': 'vienna',
'f/manifest.json': 'fuji',
};
beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
forgetPlaceChoice();
forgetManifests();
vi.stubGlobal(
'fetch',
vi.fn(async (url: string) => {
const id = Object.entries(names).find(([k]) => url.endsWith(`/${k}`))?.[1];
const w = wireManifest() as { place: Record<string, unknown> };
const body = url.endsWith('index.json')
? { ...wireIndex, places: { vienna: 'v', fuji: 'f' } }
: {
...w,
place: {
...w.place,
id,
name: id,
...(id === 'fuji' ? { lat: 35.2, lon: 138.6, tz: 'Asia/Tokyo' } : {}),
},
};
return { ok: true, status: 200, json: async () => body };
})
);
});
afterEach(() => {
vi.unstubAllGlobals();
forgetPlaceChoice();
});
it("a pick draws that place's own sun (Fuji at Noon is another instant than Vienna at Noon), and the sky's place changes once", async () => {
setSkyPlace(undefined);
const heard = vi.fn();
const off = subscribe(heard);
const a = await ensureSkyPlace(undefined);
expect(a.view.place.id).toBe('vienna');
expect(heard).toHaveBeenCalledTimes(1);
setPlaceChoice('fuji');
const b = await ensureSkyPlace(undefined);
await ensureSkyPlace(undefined); // asked again: the same place, no further change
expect(b.view.place.id).toBe('fuji');
expect(getSkyPlace()?.id).toBe('fuji');
expect(heard).toHaveBeenCalledTimes(2);
const noonAt = (p: typeof a.view.place) => momentFor(noon, p, at).getTime();
expect(noonAt(b.view.place)).not.toBe(noonAt(a.view.place));
expect(sunAt(b.view.place, momentFor(noon, b.view.place, at)).elevation).toBeGreaterThan(60);
off();
});
it('loads the manifest of the resolved place for any reader', async () => {
setPlaceChoice('fuji');
expect((await loadPlaceManifest({ place: 'vienna' })).name).toBe('fuji');
setPlaceChoice('atlantis');
expect((await loadPlaceManifest({ place: 'fuji' })).name).toBe('fuji');
expect((await loadPlaceManifest(undefined)).name).toBe('vienna');
});
});

View file

@ -1,11 +1,13 @@
// The place the sky is over, and the one decision of which place is drawn. The store (skyState.ts) holds the place; this file is the only writer
// The place the sky is over, and the one decision of which place is drawn: the viewer's choice (placeState.ts) if the index lists it, else the config's place if
// listed, else the index's default. The store (skyState.ts) holds the place; this file is the only writer
// of it: the baked place's manifest, loaded once and shared, when the ridge planes are drawn, and the fallback view (view.ts FALLBACK_VIEW) when
// they are not (the manifest or its cards did not load), because the scene is then the sky alone over that view. So the sky, the weather, the
// rebuild key, the ink and the Auto timer all read the place the scene draws. Main-chunk safe: no sky, no ridge code, only the manifest parser,
// the fallback view and the store.
import type { BackgroundSceneConfig } from './tier';
import { loadManifest } from './ridge/manifest';
import type { RidgeManifest } from './ridge/manifest';
import { loadIndex, loadManifest } from './ridge/manifest';
import type { RidgeIndex, RidgeManifest } from './ridge/manifest';
import { getPlaceChoice } from './placeState';
import { FALLBACK_VIEW } from './ridge/view';
import type { View } from './ridge/view';
import { setSkyPlace } from './skyState';
@ -13,13 +15,31 @@ import { setSkyPlace } from './skyState';
// Set when a build drew the sky alone, so a rebuild key made before the next build is for the view that is drawn.
let skyOnly = false;
/** The id of the place to draw: the viewer's choice if the index lists it, else the config's if listed, else the index's default. An id the index does not list decides nothing. */
export const resolvePlaceId = (
index: Pick<RidgeIndex, 'default' | 'places'>,
configPlace: string | undefined,
choice: string | undefined = getPlaceChoice()
): string =>
[choice, configPlace].find(
(id): id is string => id !== undefined && Object.prototype.hasOwnProperty.call(index.places, id)
) ?? index.default;
/** The manifest of the place to draw (`resolvePlaceId`); memoised, rejects on any failure. */
export async function loadPlaceManifest(
config: Pick<BackgroundSceneConfig, 'place'> | undefined
): Promise<RidgeManifest> {
const base = import.meta.env.BASE_URL;
return loadManifest(base, resolvePlaceId(await loadIndex(base), config?.place));
}
/** A scene start is a fresh attempt at the planes. */
export function resetSkyPlanes(): void {
skyOnly = false;
}
/**
* Load the manifest of the place `config` names (unknown or absent: the index's default, as `loadManifest` decides) and make the view being
* Load the manifest of the place to draw (`resolvePlaceId`) and make the view being
* drawn the sky's place. Safe to call whenever a reader wants the view: the load is memoised and setting the same place is not a change. A
* failed load is the fallback view, returned with its error so the scene can be the sky alone.
*/
@ -29,7 +49,7 @@ export async function ensureSkyPlace(
let manifest: RidgeManifest | null = null;
let fail: Error | null = null;
try {
manifest = await loadManifest(import.meta.env.BASE_URL, config?.place);
manifest = await loadPlaceManifest(config);
} catch (e) {
fail = e instanceof Error ? e : new Error(String(e));
}

View file

@ -4,8 +4,10 @@ import type { CameraChoice } from '../features/scene/cameraState';
import { getSceneView, subscribeSceneView } from '../features/scene/sceneView';
import type { SceneViewState } from '../features/scene/sceneView';
import { getConstellationLines, subscribe as subscribeSky } from '../features/scene/skyState';
import { loadManifest } from '../features/scene/ridge/manifest';
import type { RidgeManifest } from '../features/scene/ridge/manifest';
import { listPlaces } from '../features/scene/ridge/manifest';
import type { PlaceListing, RidgeManifest } from '../features/scene/ridge/manifest';
import { getPlaceChoice, subscribePlaceChoice } from '../features/scene/placeState';
import { loadPlaceManifest } from '../features/scene/skyPlace';
import { readCapabilities, resolveTier } from '../features/scene/tier';
import { useClientConfig } from './useClientConfig';
@ -30,22 +32,43 @@ export const useCameraHeld = (): boolean => useSyncExternalStore(onCamera, isHel
export const useConstellationLines = (): boolean =>
useSyncExternalStore(subscribeSky, getConstellationLines);
/** The manifest of the configured place when the ridge scene is on and it has loaded (memoised by `loadManifest`, so this fetches nothing the scene did not). */
/** The viewer's picked place id (placeState.ts), undefined for none. */
export const usePlaceChoice = (): string | undefined =>
useSyncExternalStore(subscribePlaceChoice, getPlaceChoice);
/** The baked places the carousel offers (`listPlaces`: memoised, so the session reads them once); undefined until they have loaded, and */
export function usePlaceList(): PlaceListing[] | undefined {
const [list, setList] = useState<PlaceListing[]>();
useEffect(() => {
let live = true;
listPlaces(import.meta.env.BASE_URL).then(
(l) => live && setList(l),
() => live && setList(undefined)
);
return () => {
live = false;
};
}, []);
return list;
}
/** The manifest of the place being drawn (the viewer's choice, else the config's, else the index's default: skyPlace.ts) when the ridge scene is on and it has loaded (memoised by `loadManifest`, so this fetches nothing the scene did not). */
export function useRidgeManifest(): RidgeManifest | undefined {
const config = useClientConfig().backgroundScene;
const ridgeOn = !!config && config.style !== 'raymarch';
const choice = usePlaceChoice();
const [manifest, setManifest] = useState<RidgeManifest>();
useEffect(() => {
if (!ridgeOn) return undefined;
let live = true;
loadManifest(import.meta.env.BASE_URL, config?.place).then(
loadPlaceManifest(config).then(
(m) => live && setManifest(m),
() => live && setManifest(undefined)
);
return () => {
live = false;
};
}, [ridgeOn, config?.place]);
}, [ridgeOn, config, choice]);
return ridgeOn ? manifest : undefined;
}