diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index f1e0d3ea..549510b4 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -21,8 +21,8 @@ means "keep the CSS ground". Everything below this section describes the opt-in and shows `n / median / p95` in a corner readout. - `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host passes `ridgeSkyFor` (skyForState.ts) instead. -- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry, - unknown or absent: the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON +- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (`skyPlace.ts` `resolvePlaceId` picks the entry: the viewer's choice if the index lists it, else config `backgroundScene.place` if listed, else + the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo, straight alpha) and a geometry WebP (the normal as 'rt8', the log-distance, and the wall code R = G = 255 for the extruded face under a ridge), each tile with the card's distance there; `camera.r_max_m` bounds the parallax offset over every angle of the camera on its circle and `camera.r_max_forward_m` with the camera on its heading alone. Schema 2 is refused with a message naming the stale deploy. `index.ts` @@ -73,15 +73,15 @@ today's at the place (Night tonight's: the solar midnight nearest, before the da named moments draw today's weather; a free moment draws a clear sky. `skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key -of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the configured place (nothing else fetches it, so a page with no scene fetches nothing) and the build +of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the place `resolvePlaceId` names, the viewer's pick (`placeState.ts`, localStorage `ratatoskr.skyPlace`, per viewer) before the config's place before the index default (nothing else fetches it, so a page with no scene fetches nothing) and the build settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, no tile that will decode), so the sky, the weather, the ink and the Auto timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band changes or a named moment's place-local day rolls over. The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear. -The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit -"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at". Shape: `{fetched_at, observed_at, station, precip_mm_10min, humidity_pct, -glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station, is a clear +The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station at Vienna (Wien Hohe Warte), credit +"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at". Weather is per place: `ridge/weatherFeed.ts` `WEATHER_FEEDS` is the table of places that have an observation source (station, credit, dataset; today only `vienna`), and `loadWeather` draws a place without a row with a clear sky and does not fetch the file. A new place gets weather by adding its row there and a source in the refresher: no other edit; its credit follows from the row. Shape: `{fetched_at, observed_at, station, precip_mm_10min, humidity_pct, +glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station than the place's feed's, is a clear sky. Rain is the gauge; cloud is an estimate from the global radiation against Haurwitz's clear-sky value, cross-checked by the sunshine duration, with the humidity as the fallback when the sun is low (`ridge/weatherFeed.ts`). The weather draws a cloud deck in the sky (`ridge/clouds.ts`) and lays tiled rain streaks over the sky (`ridge/rain.ts`, compositor-driven, none in a still). @@ -90,7 +90,7 @@ duration, with the humidity as the fallback when the sun is low (`ridge/weatherF `sceneView.ts` owns whether the fullscreen view is open and which submenu is up (main-chunk safe). The entry is `SceneViewEntry` (`SceneViewEntry.tsx`), the icon button in the navigator and sign-in headers; it preloads the view's chunk on hover or focus. Opening pushes one history entry (so the browser Back button, Escape and Return are the same close), sets `html[data-scene-view]` and makes `#root` inert and hidden while it stays mounted, so the chat keeps its scroll and composer. `SceneViewHost.tsx` (mounted by `BackgroundScene.tsx`) loads `view/SceneView.tsx` as a chunk of its own and mounts it in `#portalContainer`; until it has loaded it stands Return and Escape there, a failed load closes the view, and once the view is gone it gives the focus back to the entry (`restoreEntryFocus`). -The view is a full-viewport turning surface and, top left, a toolbar rail (Return, View, Time, Sky, Place; every icon `PhoneHit`) beside one panel at a time. View (`view/ViewSubmenu.tsx`): rotation mode, speed (bounded by `view.ts` `maxSpeed` for the mode) and the signed parallax offset (`offsetRange`), each written to `cameraState.ts` on release. Time (`view/TimeSubmenu.tsx`): the sky menu's moments and free moment, unchanged, to `skyState.ts` `setSkyChoice`. Sky (`view/SkySubmenu.tsx`): the constellation lines (`setConstellationLines`, the one setter). Place (`view/PlaceSubmenu.tsx`): the place shown and every data credit (terrain, stars, lines, and the weather only where the feed serves the place; ruling ridge-view-credits-home); the carousel is cut ridge-places. Return calls `setCamera` with the chosen mode, which ends a hold. +The view is a full-viewport turning surface and, top left, a toolbar rail (Return, View, Time, Sky, Place; every icon `PhoneHit`) beside one panel at a time. View (`view/ViewSubmenu.tsx`): rotation mode, speed (bounded by `view.ts` `maxSpeed` for the mode) and the signed parallax offset (`offsetRange`), each written to `cameraState.ts` on release. Time (`view/TimeSubmenu.tsx`): the sky menu's moments and free moment, unchanged, to `skyState.ts` `setSkyChoice`. Sky (`view/SkySubmenu.tsx`): the constellation lines (`setConstellationLines`, the one setter). Place (`view/PlaceSubmenu.tsx`): a carousel of the baked places (`manifest.ts` `listPlaces`: the index's list, each named by its manifest; a card is the name and the place-local time of the moment the sky draws there, `skyMoment.ts` `momentFor` (the clock under Auto, ticking each minute; the picked moment otherwise); swipe, arrows or a tap pick, through `placeState.ts` `setPlaceChoice`; absent while the index lists one place) and every data credit (terrain, stars, lines, and the weather only for a place with a feed; ruling ridge-view-credits-home). A pick makes `index.ts` rebuild the scene, which re-resolves the place; the sky's place in the store (`skyState.ts` `getSkyPlace`, what the carousel, credits and ink read) is written only when that scene is made (`skyPlace.ts` `drawnView`), so a place whose tiles do not come stays pending while the canvas, the carousel and the store keep the place that is up (the loader's own backoff asks again), and a pick of it again gives the pending build up for a fresh one. Return calls `setCamera` with the chosen mode, which ends a hold. Manual turning (`view/turning.ts`) happens only inside the view: a one-finger or mouse horizontal drag turns the heading one for one with the far sky (`dh = -dx / (pxPerDegH x plane.scale)`), the arrows 5 degrees (Shift 15), a horizontal wheel or swipe one for one; each event calls `heading.hold`, which re-issues the rig, and the rotation stays held until a mode is picked or Return is pressed. Pitch is never turned. While a pointer is down the panel and rail fade. diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index cec2be88..cffadc0d 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -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,61 @@ 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('a picked place whose tiles do not come is not the drawn place: the store stays on the scene that is up, nothing loops, and a later pick of it builds afresh', async () => { + served(); + const d = loader(); + const [vienna, graz] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(vienna).mockReturnValueOnce(graz); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(getSkyPlace()?.id).toBe('vienna'); + d.ctl.fail = true; // graz's tiles answer 503 + setPlaceChoice('graz'); + for (let i = 0; i < 5; i += 1) await flush(); + expect(d.ctl.made).toHaveLength(2); // one backdrop for the pick, asked once: the loader's own backoff retries it, the door builds nothing more + expect(d.ctl.made[1].manifest.view.place.id).toBe('graz'); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(getSkyPlace()?.id).toBe('vienna'); // the canvas draws vienna, and so does the store + expect(vienna.dispose).not.toHaveBeenCalled(); + setPlaceChoice('graz'); // a tap on the same place asks again: the pending build is given up for a fresh one + for (let i = 0; i < 5; i += 1) await flush(); + expect(d.ctl.made).toHaveLength(3); + expect(d.ctl.made[1].dispose).toHaveBeenCalledOnce(); + expect(getSkyPlace()?.id).toBe('vienna'); + setPlaceChoice('vienna'); // back to the place that is up: nothing to build, the pending graz is left to its pick + for (let i = 0; i < 5; i += 1) await flush(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + setPlaceChoice('graz'); + for (let i = 0; i < 5; i += 1) await flush(); + d.ctl.arrive(); // the tiles come + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(getSkyPlace()?.id).toBe('graz'); + expect(vienna.dispose).toHaveBeenCalledOnce(); + scene?.dispose(); + }); + 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(); @@ -840,7 +897,7 @@ describe('the ridge cards and the live scene', () => { expect(createRidgeScene).toHaveBeenCalledOnce(); forgetManifests(); serve({ ...w, place: { ...w.place, id: 'graz' } }); - setSkyPlace(undefined); + setSkyPlace(FALLBACK_VIEW.place); // the store only moves on a made scene, so the test moves it to wake the door once more await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz'); @@ -849,7 +906,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 +916,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 +935,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, diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index de2a0693..0e3509cb 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -1,9 +1,10 @@ import type { Scene, SceneOptions } from './Scene'; import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier'; import { debugOverlaysAllowed } from './debugOverlays'; -import { getConstellationLines, getResolvedSkyState, getSkyChoice, subscribe } from './skyState'; +import { getConstellationLines, getSkyChoice, skyBandAt, 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'; @@ -84,13 +85,16 @@ async function prepare( }; superseded.addEventListener('abort', release, { once: true }); let band: FixedSkyState | undefined; - const guarded = (make: () => Scene | null): Prepared => ({ + /** `commit` runs when the scene is made, never before: only then is its place the drawn one (`drawnView`). */ + const guarded = (make: () => Scene | null, commit?: () => void): Prepared => ({ planesFail: null, sky: band, discard: release, make: () => { try { - return make(); + const scene = make(); + if (scene) commit?.(); + return scene; } catch (e) { release(); options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); @@ -116,7 +120,6 @@ 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); @@ -147,17 +150,20 @@ async function prepare( planesFail = e instanceof Error ? e : new Error(String(e)); } } - const view = drawnView(backdrop ? manifest : null); + // What this build draws. The store's place is told when the scene is made (`commit`), so a build that is still loading, or that is given up, names nothing. + const view = backdrop && manifest ? manifest.view : FALLBACK_VIEW; if (!lit) await loadWeather(weatherUrl(), view.place); const sky = lit ?? ridgeSkyFor(choice, view); - if (!lit) band = getResolvedSkyState(); - const made = guarded(() => - createRidgeScene({ - ...options, - sky, - backdrop: backdrop ?? undefined, - lines: getConstellationLines(), - }) + band = skyBandAt(choice, view.place); + const made = guarded( + () => + createRidgeScene({ + ...options, + sky, + backdrop: backdrop ?? undefined, + lines: getConstellationLines(), + }), + () => drawnView(backdrop ? manifest : null) ); return { ...made, planesFail }; } catch (e) { @@ -271,7 +277,18 @@ 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 pick (skyPlace.ts) into the place to build, and so the key's; the store's place stays the + // drawn one until that scene is made. A pick is also a request to try again: what stands pending (a place whose tiles do not come) is given up for a fresh build, and + // a pick of the place already up is the key of the scene shown, so it builds nothing. + const offSky = subscribe(rebuild); + const offPlace = subscribePlaceChoice(() => { + built = shown; + rebuild(); + }); + const off = () => { + offSky(); + offPlace(); + }; // A change that landed while the first build was awaited was missed by the subscription. rebuild(); return { diff --git a/src/app/features/scene/placeState.test.ts b/src/app/features/scene/placeState.test.ts new file mode 100644 index 00000000..193f4d94 --- /dev/null +++ b/src/app/features/scene/placeState.test.ts @@ -0,0 +1,77 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const KEY = 'ratatoskr.skyPlace'; +const store = (initial: Record = {}) => { + 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 of every valid pick, a repeat of the id included (a tap on a place that has not come up asks again), and not of 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(2); + s.setPlaceChoice('amadablam'); + expect(heard).toHaveBeenCalledTimes(3); + off(); + s.setPlaceChoice('fuji'); + expect(heard).toHaveBeenCalledTimes(3); + }); + + 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(); + }); +}); diff --git a/src/app/features/scene/placeState.ts b/src/app/features/scene/placeState.ts new file mode 100644 index 00000000..a0cc78fb --- /dev/null +++ b/src/app/features/scene/placeState.ts @@ -0,0 +1,54 @@ +// 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 it changed and storage allows (else it holds for this page load). Listeners hear every valid pick, a repeat of the id included: a tap + * on a place that has not come up (its tiles did not load) is a request to try again, and a listener that has nothing to do for it ignores it. + */ +export function setPlaceChoice(id: string): void { + if (!ID.test(id)) return; + if (getPlaceChoice() !== id) { + 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; +}; diff --git a/src/app/features/scene/ridge/credits.test.ts b/src/app/features/scene/ridge/credits.test.ts index 062939eb..4ab1e58e 100644 --- a/src/app/features/scene/ridge/credits.test.ts +++ b/src/app/features/scene/ridge/credits.test.ts @@ -1,32 +1,15 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -import { FALLBACK_VIEW } from './view'; import { LINES_CREDIT, LINES_SOURCE_URL, STARS_CREDIT, STARS_SOURCE_URL, - WEATHER_CREDIT, - WEATHER_CREDIT_URL, - WEATHER_DATASET, terrainCredit, - weatherServes, } from './credits'; import { parseIndex, parseManifest } from './manifest'; import { wireManifest } from './manifest.fixture'; -import { WEATHER_ATTRIBUTION } from './weatherFeed'; - -describe('the credits the scene view shows', () => { - it("are the sources' own", () => { - expect(WEATHER_CREDIT).toBe(WEATHER_ATTRIBUTION); - }); - it('credit GeoSphere with its requested line, and state a licence only with the dataset named', () => { - expect(WEATHER_CREDIT).toBe(`Datenquelle: GeoSphere Austria - ${WEATHER_CREDIT_URL}`); - expect(WEATHER_CREDIT).not.toMatch(/CC BY/); - expect(WEATHER_DATASET).toMatch(/TAWES.*10-minute.*CC BY 4\.0/); - }); -}); describe('the terrain credit', () => { const shipped = (): { attribution: { credit_line: string; licence: string } } | undefined => { @@ -61,10 +44,3 @@ describe('the night sky credits', () => { expect(LINES_CREDIT).toMatch(/Olaf Frohn.*BSD-3-Clause/); }); }); - -describe('the weather credit', () => { - it("is owed where the feed's station stands, and nowhere else", () => { - expect(weatherServes(FALLBACK_VIEW.place)).toBe(true); - expect(weatherServes({ id: 'elsewhere' })).toBe(false); - }); -}); diff --git a/src/app/features/scene/ridge/credits.ts b/src/app/features/scene/ridge/credits.ts index 8c94f27f..2252381f 100644 --- a/src/app/features/scene/ridge/credits.ts +++ b/src/app/features/scene/ridge/credits.ts @@ -1,14 +1,8 @@ -// What the Ridge background owes its data sources, shown in the scene view (the Place submenu, all of them: ruling ridge-view-credits-home). Plain strings in their own module so the -// main chunk carries these and not the weather parser; credits.test.ts holds them equal to the sources'. The terrain credit is the loaded +// What the Ridge background owes its data sources, shown in the scene view (the Place submenu, all of them: ruling ridge-view-credits-home). The terrain, stars and lines +// credits are plain strings in their own module; credits.test.ts holds them equal to the sources'. The weather's credit is owed place by place and is the feed row's (`weatherFeed.ts`). The terrain credit is the loaded // manifest's own `attribution` (terrainCredit): the baker writes it, so no constant here can drift from the bake. import type { RidgeManifest } from './manifest'; -/** GeoSphere's own requested credit line. It names no licence: that is the dataset's (below). */ -export const WEATHER_CREDIT = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'; -export const WEATHER_CREDIT_URL = 'https://data.hub.geosphere.at'; -/** The dataset the weather is read from, and its licence as the dataset page names it (data.hub.geosphere.at, tawes-v1-10min). */ -export const WEATHER_DATASET = 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0'; - /** The terrain's credit line and licence as the loaded bake states them; undefined until a manifest has loaded (no manifest, no line). */ export const terrainCredit = ( manifest: Pick | undefined @@ -24,7 +18,3 @@ export const LINES_CREDIT = 'Constellation lines: d3-celestial by Olaf Frohn (BSD-3-Clause, copyright 2015 Olaf Frohn), https://github.com/ofrohn/d3-celestial'; export const LINES_SOURCE_URL = 'https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json'; - -/** The one place the weather feed serves: the station (`weatherFeed.ts` STATION) stands at Vienna, and its credit is owed only where its data is drawn. */ -export const WEATHER_PLACE_ID = 'vienna'; -export const weatherServes = (place: { id: string }): boolean => place.id === WEATHER_PLACE_ID; diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index beab1241..49fd26db 100644 --- a/src/app/features/scene/ridge/manifest.ts +++ b/src/app/features/scene/ridge/manifest.ts @@ -2,7 +2,7 @@ // contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is // camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 3: the whole 360 degree ring, K G-buffer cards cut into // azimuth tiles, each tile two files. -import { groundRowsNeeded, type View } from './view'; +import { groundRowsNeeded, type Place, type View } from './view'; /** As export.py MAX_CARDS: the decode budget holds this many. */ export const MAX_CARDS = 6; @@ -198,10 +198,31 @@ async function getJson(url: string, init?: RequestInit): Promise { return res.json(); } +/** A baked place as the Place submenu lists it: the manifest's own name and place (its card reads the moment drawn there, in its zone). */ +export interface PlaceListing { + id: string; + name: string; + place: Place; +} + const memo = new Map>(); +const indexMemo = new Map>(); +const listMemo = new Map>(); + +/** The baked places' index (`${baseUrl}public/ridge/index.json`), memoised per URL; a failure is not remembered. */ +export function loadIndex(baseUrl: string): Promise { + 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 `/manifest.json` is read. + * The manifest of a baked place: the index names each place's directory, then `/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 +232,7 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise { - 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 +244,29 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise { + 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 => { + const m = await loadManifest(baseUrl, id); + return { id, name: m.name, place: m.view.place }; + }) + ); + 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(); +}; diff --git a/src/app/features/scene/ridge/weatherFeed.test.ts b/src/app/features/scene/ridge/weatherFeed.test.ts index 0163224d..81eefb44 100644 --- a/src/app/features/scene/ridge/weatherFeed.test.ts +++ b/src/app/features/scene/ridge/weatherFeed.test.ts @@ -9,7 +9,9 @@ import { parseWeatherFile, OBSERVATION_STALE_MS, STALE_MS, - WEATHER_ATTRIBUTION, + WEATHER_FEEDS, + creditLine, + feedFor, weatherFromFile, clearSkyGhi, cloudEstimate, @@ -17,6 +19,8 @@ import { WeatherFile, } from './weatherFeed'; +const VIENNA = WEATHER_FEEDS.vienna; + const file = (over: Partial = {}): WeatherFile => ({ fetched_at: '2026-11-11T10:45:00Z', observed_at: '2026-11-11T10:40:00Z', @@ -25,18 +29,12 @@ const file = (over: Partial = {}): WeatherFile => ({ humidity_pct: 60, glow_wm2: null, sunshine_s_10min: null, - attribution: WEATHER_ATTRIBUTION, + attribution: creditLine(VIENNA), ...over, }); const NOW = new Date('2026-11-11T10:50:00Z'); describe('weather from the file', () => { - it('credits GeoSphere as its legal page asks, and claims no licence', () => { - expect(WEATHER_ATTRIBUTION).toBe( - 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at' - ); - expect(WEATHER_ATTRIBUTION).not.toMatch(/CC/); - }); it('rain is 0.8..1, by rate', () => { expect(weatherFromFile(file({ precip_mm_10min: 0.1 }), 20)).toBeCloseTo(0.813, 2); expect(weatherFromFile(file({ precip_mm_10min: 3 }), -20)).toBe(1); @@ -192,7 +190,7 @@ describe('reading weather.json', () => { const night = JSON.parse( '{"fetched_at":"2026-11-11T22:48:22Z","observed_at":"2026-11-11T22:40:00Z","station":11035,"precip_mm_10min":0.1,"humidity_pct":100.0,"sunshine_s_10min":0.0,"glow_wm2":0.0,"attribution":"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at"}' ); - expect(parseWeatherFile(night)).toMatchObject({ + expect(parseWeatherFile(night, VIENNA)).toMatchObject({ precip_mm_10min: 0.1, humidity_pct: 100, glow_wm2: 0, @@ -204,7 +202,7 @@ describe('reading weather.json', () => { humidity_pct: null, sunshine_s_10min: null, glow_wm2: null, - }); + }, VIENNA); expect(gap).toMatchObject({ precip_mm_10min: null, humidity_pct: null, @@ -213,38 +211,41 @@ describe('reading weather.json', () => { }); expect(currentWeather(gap, FALLBACK_VIEW.place, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY); }); - it("is not another station's file", () => { - expect(parseWeatherFile({ ...file(), station: 11036 })).toBeNull(); + it("is not another station's file: the check is the place's feed's station", () => { + expect(parseWeatherFile({ ...file(), station: 11036 }, VIENNA)).toBeNull(); + const other = { ...VIENNA, station: 11036 }; + expect(parseWeatherFile({ ...file(), station: 11036 }, other)).toMatchObject({ station: 11036 }); + expect(parseWeatherFile(file(), other)).toBeNull(); }); it('parses the agreed shape, keeping nulls and the sunshine it never reads', () => { const raw = { ...file(), precip_mm_10min: null, glow_wm2: 12, sunshine_s_10min: 0 }; - expect(parseWeatherFile(raw)).toEqual(raw); + expect(parseWeatherFile(raw, VIENNA)).toEqual(raw); }); it('rejects a body without usable times, and anything not an object', () => { - expect(parseWeatherFile({ ...file(), observed_at: 'yesterday' })).toBeNull(); - expect(parseWeatherFile({ ...file(), fetched_at: undefined })).toBeNull(); - expect(parseWeatherFile(null)).toBeNull(); - expect(parseWeatherFile('x')).toBeNull(); + expect(parseWeatherFile({ ...file(), observed_at: 'yesterday' }, VIENNA)).toBeNull(); + expect(parseWeatherFile({ ...file(), fetched_at: undefined }, VIENNA)).toBeNull(); + expect(parseWeatherFile(null, VIENNA)).toBeNull(); + expect(parseWeatherFile('x', VIENNA)).toBeNull(); }); it("rejects a time with no zone: it would be read in the client's local time", () => { - expect(parseWeatherFile({ ...file(), observed_at: '2026-11-10T10:40:00' })).toBeNull(); + expect(parseWeatherFile({ ...file(), observed_at: '2026-11-10T10:40:00' }, VIENNA)).toBeNull(); expect( - parseWeatherFile({ ...file(), observed_at: '2026-11-10T11:40:00+01:00' }) + parseWeatherFile({ ...file(), observed_at: '2026-11-10T11:40:00+01:00' }, VIENNA) ).not.toBeNull(); }); it('is no observation when the file is missing, fails, or is not JSON', async () => { expect( - await fetchWeatherFile('/weather.json', (async () => ({ + await fetchWeatherFile('/weather.json', VIENNA, (async () => ({ ok: false, })) as unknown as typeof fetch) ).toBeNull(); expect( - await fetchWeatherFile('/weather.json', (async () => { + await fetchWeatherFile('/weather.json', VIENNA, (async () => { throw new Error('offline'); }) as unknown as typeof fetch) ).toBeNull(); expect( - await fetchWeatherFile('/weather.json', (async () => ({ + await fetchWeatherFile('/weather.json', VIENNA, (async () => ({ ok: true, json: async () => { throw new Error('bad'); @@ -254,6 +255,21 @@ describe('reading weather.json', () => { }); it('reads a good file', async () => { const f = (async () => ({ ok: true, json: async () => file() })) as unknown as typeof fetch; - expect(await fetchWeatherFile('/weather.json', f)).toEqual(file()); + expect(await fetchWeatherFile('/weather.json', VIENNA, f)).toEqual(file()); + }); +}); + +describe('the feed table', () => { + it('serves Vienna and names no other place', () => { + expect(Object.keys(WEATHER_FEEDS)).toEqual(['vienna']); + expect(feedFor('vienna')).toBe(VIENNA); + ['fuji', 'matterhorn', 'amadablam', 'grandcanyon', '', 'constructor', 'toString'].forEach((id) => + expect(feedFor(id)).toBeUndefined() + ); + }); + it("credits GeoSphere with its requested line, and states a licence only with the dataset named", () => { + expect(creditLine(VIENNA)).toBe(`Datenquelle: GeoSphere Austria - ${VIENNA.url}`); + expect(creditLine(VIENNA)).not.toMatch(/CC BY/); + expect(VIENNA.dataset).toMatch(/TAWES.*10-minute.*CC BY 4\.0/); }); }); diff --git a/src/app/features/scene/ridge/weatherFeed.ts b/src/app/features/scene/ridge/weatherFeed.ts index 7a99ff11..b6ba9d0d 100644 --- a/src/app/features/scene/ridge/weatherFeed.ts +++ b/src/app/features/scene/ridge/weatherFeed.ts @@ -1,22 +1,46 @@ // The weather over the viewpoint as one `weather.ts` number, read from a static `weather.json` next to the page (config.json's // neighbour). The browser never calls a weather service: Eureka's refresher (gamecult-ops, docs/weather-feed.md; the only writer) -// writes the file from GeoSphere Austria's TAWES 10-minute observations (station 11035, Wien Hohe -// Warte). Rain is the gauge. CLOUD IS AN ESTIMATE: TAWES has no cloud cover. By day it is the measured global radiation (GLOW) against +// writes the file from GeoSphere Austria's TAWES 10-minute observations (the Wien Hohe Warte station, WEATHER_FEEDS below). Rain is the gauge. CLOUD IS AN ESTIMATE: TAWES has no cloud cover. By day it is the measured global radiation (GLOW) against // what a clear sky gives at the sun's position now (`clearSkyGhi`, Haurwitz), cross-checked by the sunshine duration (`SO`, seconds of // 600 the direct beam was strong enough to burn the card); with the sun low or down it is a ramp of the humidity. A file that is -// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky. -import { WEATHER_CREDIT } from './credits'; +// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky. A place with no row in WEATHER_FEEDS has no +// observation source at all: it is drawn clear and the file is not read for it. import { sunAt } from './sunAt'; import type { Place } from './view'; /** Reader rule of docs/weather-feed.md: the file is stale 30 minutes after it was fetched or 40 after the observation it holds (the station reports every 10). */ export const STALE_MS = 30 * 60_000; export const OBSERVATION_STALE_MS = 40 * 60_000; -export const STATION = 11035; const SKEW_MS = 5 * 60_000; export const CLEAR_SKY = 0; -/** The credit GeoSphere's legal page asks for. */ -export const WEATHER_ATTRIBUTION = WEATHER_CREDIT; + +/** What a place's observation source owes: the station its rows are read from, the credit GeoSphere's legal page asks for (`credit`, then `url`: it names no licence, the dataset's below does) and the dataset with its licence as the dataset page names it. */ +export interface WeatherFeed { + station: number; + credit: string; + url: string; + dataset: string; +} + +/** + * The places that have a weather source, by place id. A new place gets weather by adding its row here and a source in the refresher (gamecult-ops + * `docs/weather-feed.md`); no other edit. Every place without a row is drawn with a clear sky (`skyForState.ts` `loadWeather`). + */ +export const WEATHER_FEEDS: Readonly> = { + vienna: { + station: 11035, + credit: 'Datenquelle: GeoSphere Austria', + url: 'https://data.hub.geosphere.at', + dataset: 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0', + }, +}; + +/** The feed that serves a place, or undefined for a place with none. */ +export const feedFor = (placeId: string): WeatherFeed | undefined => + Object.prototype.hasOwnProperty.call(WEATHER_FEEDS, placeId) ? WEATHER_FEEDS[placeId] : undefined; + +/** The credit as one line: the source and where it is. */ +export const creditLine = (f: WeatherFeed): string => `${f.credit} - ${f.url}`; /** The file's shape; every measurement is null when the station did not report it. Times are ISO 8601. */ export interface WeatherFile { @@ -38,21 +62,21 @@ const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFi const isZonedTime = (v: unknown): v is string => typeof v === 'string' && /(Z|[+-]\d\d:?\d\d)$/.test(v) && !Number.isNaN(Date.parse(v)); -/** A `WeatherFile` from parsed JSON, or null when it does not have the shape (times missing or unparseable). */ -export function parseWeatherFile(json: unknown): WeatherFile | null { +/** A `WeatherFile` from parsed JSON, or null when it does not have the shape (times missing or unparseable) or is not the feed's station's. */ +export function parseWeatherFile(json: unknown, feed: WeatherFeed): WeatherFile | null { const j = json as Record | null; if (!j || typeof j !== 'object') return null; if (!isZonedTime(j.observed_at) || !isZonedTime(j.fetched_at)) return null; - if (j.station !== STATION) return null; + if (j.station !== feed.station) return null; return { fetched_at: j.fetched_at, observed_at: j.observed_at, - station: STATION, + station: feed.station, precip_mm_10min: num(j.precip_mm_10min), humidity_pct: num(j.humidity_pct), glow_wm2: num(j.glow_wm2), sunshine_s_10min: num(j.sunshine_s_10min), - attribution: typeof j.attribution === 'string' ? j.attribution : WEATHER_ATTRIBUTION, + attribution: typeof j.attribution === 'string' ? j.attribution : creditLine(feed), }; } @@ -123,14 +147,15 @@ export function currentWeather(f: WeatherFile | null, place: Place, now: Date = return weatherFromFile(f, sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation); } -/** Fetch and parse `weather.json`; null on any failure. */ +/** Fetch and parse `weather.json` as the feed's station's; null on any failure. */ export async function fetchWeatherFile( url: string, + feed: WeatherFeed, fetcher: typeof fetch = fetch ): Promise { try { const res = await fetcher(url, { cache: 'no-store' }); - return res.ok ? parseWeatherFile(await res.json()) : null; + return res.ok ? parseWeatherFile(await res.json(), feed) : null; } catch { return null; } diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index 3ebe988d..835bb302 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -128,16 +128,70 @@ describe('the weather of a moment', () => { }); describe('loadWeather', () => { - it('reads the file again for another place inside the refresh window: the weather it set belongs to the sun of the place it was read for', async () => { - const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })); + const VIENNA = FALLBACK_VIEW.place; + const FUJI = { ...ELSEWHERE_VIEW.place, id: 'fuji' }; + const wx = (at: Date) => ({ + fetched_at: at.toISOString(), + observed_at: at.toISOString(), + station: 11035, + precip_mm_10min: 2, + humidity_pct: 99, + glow_wm2: null, + sunshine_s_10min: null, + attribution: 'x', + }); + const t = new Date('2030-01-01T10:00:00Z'); + + it('draws a place with no feed clear and does not fetch: the one file is for one station', async () => { + const fetched = vi.fn(async () => ({ ok: true, json: async () => wx(t) })); vi.stubGlobal('fetch', fetched); - const t = new Date('2030-01-01T00:00:00Z'); - await loadWeather('/w.json', FALLBACK_VIEW.place, t); - await loadWeather('/w.json', FALLBACK_VIEW.place, new Date(t.getTime() + 60_000)); + setFedWeather(0.9); + await loadWeather('/w.json', FUJI, t); + expect(fetched).toHaveBeenCalledTimes(0); + expect(ridgeWeather()).toBe(CLEAR_SKY); + }); + + it('draws Vienna with a fresh file, and reads the file again on coming back from a place without one', async () => { + const fetched = vi.fn(async () => ({ ok: true, json: async () => wx(t) })); + vi.stubGlobal('fetch', fetched); + await loadWeather('/w.json', VIENNA, t); expect(fetched).toHaveBeenCalledTimes(1); - await loadWeather('/w.json', ELSEWHERE_VIEW.place, new Date(t.getTime() + 120_000)); + expect(ridgeWeather()).toBeGreaterThan(0.7); + await loadWeather('/w.json', VIENNA, new Date(t.getTime() + 60_000)); + expect(fetched).toHaveBeenCalledTimes(1); // inside the refresh window + await loadWeather('/w.json', FUJI, new Date(t.getTime() + 120_000)); + expect(fetched).toHaveBeenCalledTimes(1); + expect(ridgeWeather()).toBe(CLEAR_SKY); + await loadWeather('/w.json', VIENNA, new Date(t.getTime() + 180_000)); expect(fetched).toHaveBeenCalledTimes(2); - vi.unstubAllGlobals(); + expect(ridgeWeather()).toBeGreaterThan(0.7); + }); + + it("a fetch that resolves after the place has changed writes nothing: the place the viewer is on is drawn clear, not with the old place's rain", async () => { + let release = () => undefined as void; + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + release = () => resolve({ ok: true, json: async () => wx(later) }); + }) + ) + ); + const later = new Date(t.getTime() + 24 * 3_600_000); + setFedWeather(undefined); + const slow = loadWeather('/w.json', VIENNA, later); // Vienna's file is on the wire + await loadWeather('/w.json', FUJI, new Date(later.getTime() + 1_000)); // the viewer is on Fuji, which has no feed: clear + expect(ridgeWeather()).toBe(CLEAR_SKY); + release(); + await slow; + expect(ridgeWeather()).toBe(CLEAR_SKY); // Vienna's rain is not Fuji's + }); + + it("rejects a file whose station is not the place's feed's: a clear sky", async () => { + vi.stubGlobal('fetch', async () => ({ ok: true, json: async () => ({ ...wx(t), station: 99999 }) })); + await loadWeather('/w.json', VIENNA, t); + expect(ridgeWeather()).toBe(CLEAR_SKY); }); }); diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 75dc28c1..79110262 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -8,7 +8,7 @@ import { sunAt } from './ridge/sunAt'; import type { Place, View } from './ridge/view'; import { BUDGET } from './ridge/toneMap'; import { ridgeWeather, setFedWeather } from './ridge/weather'; -import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; +import { currentWeather, feedFor, fetchWeatherFile } from './ridge/weatherFeed'; import { getConstellationLines, skyNow } from './skyState'; /** A clear sky: what a free moment is drawn with (ruling ridge-weather-on-frozen-moments: today's weather says nothing of another date). */ @@ -37,14 +37,23 @@ const WEATHER_REFRESH_MS = 10 * 60_000; let weatherAt = -Infinity; let weatherPlace = ''; /** - * Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes. - * Never throws: a missing, stale or broken file is a clear sky (`currentWeather`). + * Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes. A file that arrives after + * the place moved on is not written. + * Never throws: a missing, stale or broken file is a clear sky (`currentWeather`). A place with no feed (`feedFor`) is a clear sky and the file is not + * fetched; the place is remembered all the same, so going back to a place with a feed reads the file at once. */ export async function loadWeather(url: string, place: Place, now: Date = skyNow()): Promise { if (place.id === weatherPlace && now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; weatherAt = now.getTime(); weatherPlace = place.id; - setFedWeather(currentWeather(await fetchWeatherFile(url), place, now)); + const feed = feedFor(place.id); + if (!feed) { + setFedWeather(CLEAR_SKY); + return; + } + const weather = currentWeather(await fetchWeatherFile(url, feed), place, now); + // The place the weather is for may have changed while the file was on the wire: `weatherPlace` is the one owner of it, and an answer for another place is dropped. + if (weatherPlace === place.id) setFedWeather(weather); } /** diff --git a/src/app/features/scene/skyPlace.test.ts b/src/app/features/scene/skyPlace.test.ts new file mode 100644 index 00000000..94cc3284 --- /dev/null +++ b/src/app/features/scene/skyPlace.test.ts @@ -0,0 +1,98 @@ +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 { drawnView, 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 = { + '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 }; + 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 resolves to that place's own sun (Fuji at Noon is another instant than Vienna at Noon), and only a made scene moves the store's place", async () => { + setSkyPlace(undefined); + const heard = vi.fn(); + const off = subscribe(heard); + const a = await ensureSkyPlace(undefined); + expect(a.view.place.id).toBe('vienna'); + expect(getSkyPlace()).toBeUndefined(); // asked for, not drawn + expect(heard).not.toHaveBeenCalled(); + setPlaceChoice('fuji'); + const b = await ensureSkyPlace(undefined); + expect(b.view.place.id).toBe('fuji'); + expect(getSkyPlace()).toBeUndefined(); // a build that has not been made names nothing + expect(heard).not.toHaveBeenCalled(); + drawnView(a.manifest); + drawnView(a.manifest); // the same place again: no further change + expect(getSkyPlace()?.id).toBe('vienna'); + expect(heard).toHaveBeenCalledTimes(1); + drawnView(b.manifest); + 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'); + }); +}); diff --git a/src/app/features/scene/skyPlace.ts b/src/app/features/scene/skyPlace.ts index bf91d708..7d2096ba 100644 --- a/src/app/features/scene/skyPlace.ts +++ b/src/app/features/scene/skyPlace.ts @@ -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 -// 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 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 DRAWN place, and `drawnView` is the only writer of it, called when a scene is made: the +// baked place's manifest when the ridge planes are drawn, 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. The pick is a wish and `ensureSkyPlace` only resolves it; a place whose build is still loading, or failed, +// is never the store's. So the carousel, the credits, the ink and the Auto timer all read the place the canvas 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,15 +15,33 @@ 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, + 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 | undefined +): Promise { + 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 - * 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. + * Load the manifest of the place to draw (`resolvePlaceId`) and return the view a build for it draws. Safe to call whenever a reader wants the view: the load is memoised. + * Writes nothing: the store's place is the one drawn (`drawnView`), not the one asked for. A failed load is the fallback view, returned with its error so the scene + * can be the sky alone. */ export async function ensureSkyPlace( config: Pick | undefined @@ -29,19 +49,16 @@ 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)); } const view = manifest && !skyOnly ? manifest.view : FALLBACK_VIEW; - setSkyPlace(view.place); return { manifest, view, fail }; } -/** A build has settled what it draws: the manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's and returns the view. */ -export function drawnView(manifest: RidgeManifest | null): View { +/** A scene has been made and is now what is drawn: its manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's. The one writer of the store's place. */ +export function drawnView(manifest: RidgeManifest | null): void { skyOnly = manifest === null; - const view = manifest?.view ?? FALLBACK_VIEW; - setSkyPlace(view.place); - return view; + setSkyPlace((manifest?.view ?? FALLBACK_VIEW).place); } diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 5042f175..3267468c 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -99,15 +99,18 @@ export const getSkyChoice = (): SkyChoice => { return current; }; -/** The place the sky is over: the loaded manifest's, set by skyPlace.ts; undefined until one is known. */ +/** The place the sky is over: the place of the scene that is up, set by skyPlace.ts when a scene is made; undefined until one is. */ export const getSkyPlace = (): Place | undefined => place; /** The moment the sky is drawn for: the real time, or the test clock. */ export const skyNow = (): Date => clock(); /** The band being drawn: the choice at the place, through `momentFor` and `skyBand`; undefined until a place is known (no sky is drawn for ink). */ -export const getResolvedSkyState = (): FixedSkyState | undefined => - place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).elevation); +export const getResolvedSkyState = (): FixedSkyState | undefined => place && skyBandAt(getSkyChoice(), place); + +/** The band of `choice` at `at`, for any place: what a build for a place not yet drawn is told, since the store holds only the drawn one. */ +export const skyBandAt = (choice: SkyChoice, at: Place, now: Date = skyNow()): FixedSkyState => + skyBand(sunAt(at, momentFor(choice, at, now)).elevation); /** What a rebuild would be for, of the moment now drawn (`momentKey`): a named moment's changes when the place-local day rolls over. */ const drawnKey = (): string | undefined => place && momentKey(getSkyChoice(), place, skyNow()); @@ -155,7 +158,7 @@ export function setSkyChoice(c: SkyChoice): void { } } -/** The place the sky is over (skyPlace.ts, once the manifest is loaded). Listeners hear it, since the band depends on it. */ +/** The place the sky is over (skyPlace.ts `drawnView`, when a scene is made). Listeners hear it, since the band depends on it. */ export function setSkyPlace(p: Place | undefined): void { if (p?.id === place?.id && p?.tz === place?.tz && p?.lat === place?.lat && p?.lon === place?.lon) { return; diff --git a/src/app/features/scene/view/PlaceSubmenu.test.tsx b/src/app/features/scene/view/PlaceSubmenu.test.tsx index 30be0a52..9dfc670a 100644 --- a/src/app/features/scene/view/PlaceSubmenu.test.tsx +++ b/src/app/features/scene/view/PlaceSubmenu.test.tsx @@ -1,17 +1,63 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { parseManifest } from '../ridge/manifest'; +import type { PlaceListing } from '../ridge/manifest'; import { wireManifest } from '../ridge/manifest.fixture'; +import type { SkyChoice } from '../ridge/skyMoment'; import { FALLBACK_VIEW } from '../ridge/view'; -import { LINES_CREDIT, STARS_CREDIT, WEATHER_CREDIT_URL } from '../ridge/credits'; -import { PlaceSubmenu } from './PlaceSubmenu'; +import { LINES_CREDIT, STARS_CREDIT } from '../ridge/credits'; +import { WEATHER_FEEDS, creditLine } from '../ridge/weatherFeed'; +import { PlaceCarousel, PlaceSubmenu, SETTLE_MS } from './PlaceSubmenu'; import { SkySubmenu } from './SkySubmenu'; -const held = vi.hoisted(() => ({ place: undefined as unknown })); -vi.mock('../../../hooks/useSkyState', () => ({ useDrawnPlace: () => held.place })); -vi.mock('../../../hooks/useSceneView', () => ({ useConstellationLines: () => false })); -vi.mock('../skyState', () => ({ setConstellationLines: () => undefined })); +// The hooks are held still (TimeSubmenu.test.tsx): the element tree is read, a function component is expanded by calling it. +const held = vi.hoisted(() => ({ + choice: { kind: 'auto' } as unknown, + clock: new Date('2030-06-21T10:00:00Z'), + live: undefined as boolean | undefined, + place: undefined as unknown, + places: undefined as unknown, + picked: [] as string[], +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useRef = (init: unknown) => ({ current: init }); + const useEffect = () => undefined; + return { ...actual, default: { ...actual, useRef, useEffect }, useRef, useEffect }; +}); +vi.mock('../../../hooks/useSkyState', () => ({ + useDrawnPlace: () => held.place, + useSkyChoice: () => held.choice, + useSkyMinute: (live: boolean) => { + held.live = live; + return held.clock; + }, +})); +vi.mock('../../../hooks/useSceneView', () => ({ + usePlaceList: () => held.places, + useConstellationLines: () => false, +})); +vi.mock('../placeState', () => ({ setPlaceChoice: (id: string) => held.picked.push(id) })); +vi.mock('../skyState', () => ({ + setConstellationLines: () => undefined, +})); -/** Every string reachable through any prop of the element tree. */ +type El = { type?: unknown; props?: Record }; +const walk = (node: unknown): El[] => { + if (Array.isArray(node)) return node.flatMap(walk); + if (node && typeof node === 'object' && 'props' in node) { + const el = node as El; + return [el, ...Object.values(el.props ?? {}).flatMap(walk)]; + } + return []; +}; +const textOf = (node: unknown): string => { + if (typeof node === 'string' || typeof node === 'number') return String(node); + if (Array.isArray(node)) return node.map(textOf).join(''); + if (node && typeof node === 'object' && 'props' in node) { + return textOf((node as El).props?.children); + } + return ''; +}; const strings = (node: unknown): string[] => { if (typeof node === 'string') return [node]; if (Array.isArray(node)) return node.flatMap(strings); @@ -20,13 +66,132 @@ const strings = (node: unknown): string[] => { return []; }; const text = (node: unknown) => strings(node).join(' '); + const manifest = parseManifest(wireManifest(), 'http://x/ridge/vienna/'); +const at = (id: string, name: string, lat: number, lon: number, tz: string): PlaceListing => ({ + id, + name, + place: { id, lat, lon, altitudeKm: 0, tz }, +}); +const FIVE: PlaceListing[] = [ + at('vienna', 'Vienna', 48.2, 16.4, 'Europe/Vienna'), + at('fuji', 'Fuji', 35.36, 138.73, 'Asia/Tokyo'), + at('matterhorn', 'Matterhorn', 45.98, 7.66, 'Europe/Zurich'), + at('amadablam', 'Ama Dablam', 27.86, 86.86, 'Asia/Kathmandu'), + at('grandcanyon', 'Grand Canyon', 36.1, -112.1, 'America/Phoenix'), +]; +const AUTO: SkyChoice = { kind: 'auto' }; +const NOW = new Date('2030-06-21T10:00:00Z'); +const cardsOf = (tree: El[]) => tree.filter((e) => e.props?.['aria-current'] !== undefined); beforeEach(() => { held.place = FALLBACK_VIEW.place; + held.places = FIVE; + held.choice = AUTO; + held.live = undefined; + held.picked.length = 0; }); -describe('the credits (ruling ridge-view-credits-home: Place alone)', () => { +describe('the Place carousel', () => { + it('is one card per baked place, named by the index and showing each place local time now', () => { + const tree = walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick: () => undefined })); + expect(cardsOf(tree).map(textOf)).toEqual([ + 'Vienna12:00 local', + 'Fuji19:00 local', + 'Matterhorn12:00 local', + 'Ama Dablam15:45 local', + 'Grand Canyon03:00 local', + ]); + expect(cardsOf(tree).map((e) => e.props?.['aria-current'])).toEqual([true, false, false, false, false]); + }); + + const minutes = (card: string): number => { + const m = /(\d\d):(\d\d) local/.exec(card); + return Number(m?.[1]) * 60 + Number(m?.[2]); + }; + + it("shows the place-local time of the moment the sky draws: a named moment is that moment at each place, not the real clock, and Auto is the clock", () => { + const noon: SkyChoice = { kind: 'named', id: 'noon' }; + const drawn = (choice: SkyChoice) => + cardsOf(walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice, now: NOW, onPick: () => undefined }))).map(textOf); + const live = drawn(AUTO); + const frozen = drawn(noon); + expect(frozen).not.toEqual(live); + frozen.forEach((card) => { + expect(minutes(card)).toBeGreaterThanOrEqual(11 * 60); // each place's own solar noon, in its own zone + expect(minutes(card)).toBeLessThanOrEqual(14 * 60); + }); + const free: SkyChoice = { kind: 'free', date: '2030-01-15', minutes: 3 * 60 }; + expect(drawn(free).map(minutes)).toEqual([180, 180, 180, 180, 180]); // a free moment is the minute asked, in each zone + }); + + it('is given the sky clock and the choice, and the clock ticks while the sky is live (Auto) and only then', () => { + held.clock = new Date('2030-06-21T10:07:00Z'); + const carousel = () => walk(PlaceSubmenu({ manifest })).find((e) => e.type === PlaceCarousel); + expect(carousel()?.props?.now).toBe(held.clock); + expect(carousel()?.props?.choice).toBe(AUTO); + expect(held.live).toBe(true); + held.choice = { kind: 'named', id: 'dusk' }; + expect(carousel()?.props?.choice).toBe(held.choice); + expect(held.live).toBe(false); + held.clock = NOW; + }); + + it('is in the panel over the index list, and a card or an arrow picks through the choice store', () => { + const carousel = walk(PlaceSubmenu({ manifest })).find((e) => e.type === PlaceCarousel); + expect(carousel?.props?.places).toBe(FIVE); + const onPick = carousel?.props?.onPick as (id: string) => void; + onPick('grandcanyon'); + expect(held.picked).toEqual(['grandcanyon']); + held.picked.length = 0; + const own = walk(PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick })); + const click = (label: string) => + (own.find((e) => e.props?.['aria-label'] === label)?.props?.onClick as () => void)(); + click('Previous place'); // the ring: before Vienna is the last + click('Next place'); + (cardsOf(own)[2].props?.onClick as () => void)(); + expect(held.picked).toEqual(['grandcanyon', 'fuji', 'matterhorn']); + }); + + it('is absent while the index lists one place or none has loaded; the credits stay', () => { + for (const places of [undefined, [FIVE[0]], []]) { + held.places = places; + expect(walk(PlaceSubmenu({ manifest })).some((e) => e.type === PlaceCarousel)).toBe(false); + expect(text(PlaceSubmenu({ manifest }))).toContain(STARS_CREDIT); + } + }); + + it('settles a swipe on the card in the middle and picks it once it rests, not the drawn place', () => { + vi.useFakeTimers(); + try { + const strip = { + scrollLeft: 0, + clientWidth: 100, + children: FIVE.map((_, i) => ({ offsetLeft: i * 100, offsetWidth: 100 })), + }; + const own = walk( + PlaceCarousel({ places: FIVE, current: 'vienna', choice: AUTO, now: NOW, onPick: (id) => held.picked.push(id) }) + ); + const onScroll = own.find((e) => typeof e.props?.onScroll === 'function')?.props?.onScroll as (e: unknown) => void; + const scrollTo = (left: number) => { + strip.scrollLeft = left; + onScroll({ currentTarget: strip }); + }; + scrollTo(100); + scrollTo(200); // still moving: nothing is picked until it rests + expect(held.picked).toEqual([]); + vi.advanceTimersByTime(SETTLE_MS); + expect(held.picked).toEqual(['matterhorn']); + scrollTo(0); // at the drawn place: not a pick + vi.advanceTimersByTime(SETTLE_MS); + expect(held.picked).toEqual(['matterhorn']); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('the credits follow the place (ruling ridge-view-credits-home: Place alone)', () => { it('Place carries the terrain, stars and lines credits', () => { const t = text(PlaceSubmenu({ manifest })); expect(t).toContain(manifest.attribution.creditLine); @@ -41,12 +206,19 @@ describe('the credits (ruling ridge-view-credits-home: Place alone)', () => { ]); }); - it("the weather's credit shows where the feed serves the place, and only there", () => { - expect(text(PlaceSubmenu({ manifest }))).toContain(WEATHER_CREDIT_URL); - held.place = { ...FALLBACK_VIEW.place, id: 'elsewhere' }; + it("the weather's credit is the feed row's, shown for a place with a feed and for no other", () => { + const feed = WEATHER_FEEDS.vienna; const t = text(PlaceSubmenu({ manifest })); - expect(t).not.toContain(WEATHER_CREDIT_URL); - expect(t).not.toContain('GeoSphere'); - expect(t).toContain(STARS_CREDIT); // the other credits do not depend on the place + expect(t).toContain(feed.credit); + expect(t).toContain(feed.url); + expect(t).toContain(feed.dataset); + expect(creditLine(feed)).toBe(`${feed.credit} - ${feed.url}`); + for (const id of ['fuji', 'matterhorn', 'amadablam', 'grandcanyon']) { + held.place = { ...FALLBACK_VIEW.place, id }; + const other = text(PlaceSubmenu({ manifest })); + expect(other).not.toContain(feed.url); + expect(other).not.toContain('GeoSphere'); + expect(other).toContain(STARS_CREDIT); // the other credits do not depend on the place + } }); }); diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx index dfeaba66..9eb51a55 100644 --- a/src/app/features/scene/view/PlaceSubmenu.tsx +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -1,28 +1,146 @@ -import React from 'react'; -import { Box, Text } from 'folds'; -import { useDrawnPlace } from '../../../hooks/useSkyState'; -import { - LINES_CREDIT, - STARS_CREDIT, - terrainCredit, - WEATHER_CREDIT_URL, - WEATHER_DATASET, - weatherServes, -} from '../ridge/credits'; -import type { RidgeManifest } from '../ridge/manifest'; +import React, { useEffect, useRef } from 'react'; +import { Box, Icon, IconButton, Icons, Text } from 'folds'; +import { useDrawnPlace, useSkyChoice, useSkyMinute } from '../../../hooks/useSkyState'; +import { usePlaceList } from '../../../hooks/useSceneView'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import { LINES_CREDIT, STARS_CREDIT, terrainCredit } from '../ridge/credits'; +import type { RidgeManifest, PlaceListing } from '../ridge/manifest'; +import { localMinutes, momentFor } from '../ridge/skyMoment'; +import type { SkyChoice } from '../ridge/skyMoment'; import { FALLBACK_VIEW } from '../ridge/view'; +import { feedFor } from '../ridge/weatherFeed'; +import { setPlaceChoice } from '../placeState'; +import { hhmm } from './TimeSubmenu'; +import * as css from './SceneView.css'; + +/** How long a swipe rests before the card it stopped on is picked, ms. */ +export const SETTLE_MS = 120; + +/** Index of the child of `strip` whose centre is nearest the strip's centre. */ +const centredIndex = (strip: HTMLElement): number => { + const mid = strip.scrollLeft + strip.clientWidth / 2; + let best = 0; + let gap = Infinity; + Array.from(strip.children).forEach((c, i) => { + const el = c as HTMLElement; + const d = Math.abs(el.offsetLeft + el.offsetWidth / 2 - mid); + if (d < gap) { + gap = d; + best = i; + } + }); + return best; +}; /** - * The Place submenu of the scene view: the shell and every credit the view owes (ruling ridge-view-credits-home: Place alone, no footer, no credit in Sky). The - * carousel of baked places is cut ridge-places; until it lands this names the place shown. The terrain credit is the bake's, the stars and the lines are drawn - * over any place at night, and GeoSphere's credit appears only where the weather feed serves the place shown. + * The baked places, one card each (its name and the place-local time of the moment the sky draws there: `momentFor`, the one owner, so the real clock under Auto and the + * picked moment under a named or free one), swiped or stepped with the arrows; the card in the middle is the place drawn + * (`current`), and a pick, a tap on a card, an arrow or a swipe that comes to rest on another, goes to `onPick`. The list is the index's: nothing here keeps a copy. + */ +export function PlaceCarousel({ + places, + current, + choice, + now, + onPick, +}: { + places: PlaceListing[]; + current: string; + choice: SkyChoice; + now: Date; + onPick: (id: string) => void; +}) { + const strip = useRef(null); + const settle = useRef>(); + const shown = useRef(current); + shown.current = current; + const at = Math.max( + 0, + places.findIndex((p) => p.id === current) + ); + + // The drawn place's card goes to the middle, at once (a programmed scroll is not a swipe: it must not end on a card the viewer did not pick). + useEffect(() => { + const el = strip.current; + const card = el?.children[at] as HTMLElement | undefined; + if (el && card) el.scrollLeft = card.offsetLeft - (el.clientWidth - card.offsetWidth) / 2; + }, [at, places]); + useEffect(() => () => clearTimeout(settle.current), []); + + const step = (by: number) => { + const next = places[(at + by + places.length) % places.length]; + if (next) onPick(next.id); + }; + return ( + + step(-1)} + > + + +
{ + const el = evt.currentTarget; + clearTimeout(settle.current); + settle.current = setTimeout(() => { + const to = places[centredIndex(el)]; + if (to && to.id !== shown.current) onPick(to.id); + }, SETTLE_MS); + }} + > + {places.map((p) => ( + + ))} +
+ step(1)} + > + + +
+ ); +} + +/** + * The Place submenu of the scene view: the carousel of the baked places (ruling ridge-places-dropdown-first-four; absent while the index lists one) and every credit the + * view owes (ruling ridge-view-credits-home: Place alone, no footer, no credit in Sky). The terrain credit is the bake's, the stars and the lines are drawn + * over any place at night, and the weather's credit is the feed row's, shown only where the place shown has a feed (`weatherFeed.ts`). */ export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined }) { const place = useDrawnPlace() ?? FALLBACK_VIEW.place; + const places = usePlaceList(); + const choice = useSkyChoice(); + const now = useSkyMinute(choice.kind === 'auto'); const credit = terrainCredit(manifest); + const feed = feedFor(place.id); return ( - {place.id} + {places && places.length > 1 ? ( + + ) : ( + {manifest?.name ?? place.id} + )} Data @@ -38,13 +156,13 @@ export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined {LINES_CREDIT}. - {weatherServes(place) && ( + {feed && ( - Datenquelle: GeoSphere Austria -{' '} - - {WEATHER_CREDIT_URL} + {feed.credit} -{' '} + + {feed.url} - . {WEATHER_DATASET}. + . {feed.dataset}. )} diff --git a/src/app/features/scene/view/SceneView.css.ts b/src/app/features/scene/view/SceneView.css.ts index 26699f00..28c876de 100644 --- a/src/app/features/scene/view/SceneView.css.ts +++ b/src/app/features/scene/view/SceneView.css.ts @@ -78,3 +78,45 @@ export const Panel = style([ '@media': { [PHONE]: { width: 'calc(100vw - 5.5rem)' } }, }, ]); + +/** The Place submenu's carousel: the baked places side by side, one card centred, snapping as it is swiped; an arrow each side steps it. */ +export const Carousel = style({ + display: 'flex', + alignItems: 'center', + gap: config.space.S100, +}); + +export const Strip = style({ + position: 'relative', + display: 'flex', + flexGrow: 1, + minWidth: 0, + gap: config.space.S200, + overflowX: 'auto', + scrollSnapType: 'x mandatory', + scrollbarWidth: 'none', + overscrollBehaviorX: 'contain', + selectors: { '&::-webkit-scrollbar': { display: 'none' } }, +}); + +/** A place's card. Each is as wide as the strip, so the one in the strip is the one in view. */ +export const PlaceCard = style({ + flex: '0 0 100%', + scrollSnapAlign: 'center', + boxSizing: 'border-box', + display: 'flex', + flexDirection: 'column', + gap: config.space.S100, + padding: config.space.S300, + borderRadius: config.radii.R300, + border: `${config.borderWidth.B300} solid currentColor`, + background: 'transparent', + color: 'inherit', + font: 'inherit', + textAlign: 'center', + cursor: 'pointer', + opacity: 0.6, + selectors: { + '&[aria-current="true"]': { opacity: 1 }, + }, +}); diff --git a/src/app/features/scene/view/TimeSubmenu.tsx b/src/app/features/scene/view/TimeSubmenu.tsx index 83753c3e..540079d0 100644 --- a/src/app/features/scene/view/TimeSubmenu.tsx +++ b/src/app/features/scene/view/TimeSubmenu.tsx @@ -23,7 +23,7 @@ export const MOMENT_LABEL: Record = { night: 'Night', }; -const hhmm = (minutes: number): string => +export const hhmm = (minutes: number): string => `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`; /** What the panel calls a choice: Auto, the moment's name, or the free moment's place-local date and time. */ diff --git a/src/app/hooks/useSceneView.ts b/src/app/hooks/useSceneView.ts index d63323f8..a1f33317 100644 --- a/src/app/hooks/useSceneView.ts +++ b/src/app/hooks/useSceneView.ts @@ -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 when the index or its manifests do not load. */ +export function usePlaceList(): PlaceListing[] | undefined { + const [list, setList] = useState(); + 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(); 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; } diff --git a/src/app/hooks/useSkyState.test.ts b/src/app/hooks/useSkyState.test.ts new file mode 100644 index 00000000..4e2e7db9 --- /dev/null +++ b/src/app/hooks/useSkyState.test.ts @@ -0,0 +1,64 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { setSkyClock } from '../features/scene/skyState'; +import { useSkyMinute } from './useSkyState'; + +// useSkyMinute is state and one effect: react is held so the effect can be run and cleaned up by hand. +const held = vi.hoisted(() => ({ + value: undefined as unknown, + sets: [] as Date[], + effect: undefined as undefined | (() => (() => void) | undefined), +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => { + held.value ??= typeof init === 'function' ? (init as () => unknown)() : init; + return [held.value, (v: Date) => held.sets.push(v)]; + }; + const useEffect = (fn: () => (() => void) | undefined) => { + held.effect = fn; + }; + return { ...actual, useState, useEffect }; +}); + +const at = (iso: string) => setSkyClock(() => new Date(iso)); +beforeEach(() => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + held.value = undefined; + held.sets.length = 0; +}); +afterEach(() => { + vi.useRealTimers(); + setSkyClock(); +}); + +describe('the sky minute', () => { + it('while live, re-reads the sky clock at each minute boundary and stops when the effect is cleaned up', () => { + at('2030-06-21T10:00:30Z'); + expect(useSkyMinute(true)).toEqual(new Date('2030-06-21T10:00:30Z')); + const stop = held.effect?.(); + held.sets.length = 0; + at('2030-06-21T10:01:00Z'); + vi.advanceTimersByTime(29_999); + expect(held.sets).toHaveLength(0); // not before the minute turns + vi.advanceTimersByTime(1); + expect(held.sets).toEqual([new Date('2030-06-21T10:01:00Z')]); + at('2030-06-21T10:02:00Z'); + vi.advanceTimersByTime(60_000); + expect(held.sets).toHaveLength(2); + stop?.(); + vi.advanceTimersByTime(10 * 60_000); + expect(held.sets).toHaveLength(2); + }); + + it('not live, sets no timer and reads the sky clock at every render', () => { + at('2030-06-21T10:00:30Z'); + useSkyMinute(false); + const stop = held.effect?.(); + expect(stop).toBeUndefined(); + held.sets.length = 0; + vi.advanceTimersByTime(10 * 60_000); + expect(held.sets).toHaveLength(0); + at('2030-06-22T01:00:00Z'); + expect(useSkyMinute(false)).toEqual(new Date('2030-06-22T01:00:00Z')); + }); +}); diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index e95a8725..e25b35c7 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -1,5 +1,5 @@ -import { useSyncExternalStore } from 'react'; -import { getSkyChoice, getSkyPlace, subscribe } from '../features/scene/skyState'; +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { getSkyChoice, getSkyPlace, skyNow, subscribe } from '../features/scene/skyState'; import type { Place } from '../features/scene/ridge/view'; import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment'; import { getDrawnSky, getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; @@ -15,3 +15,27 @@ export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subsc /** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */ export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn); + +const MINUTE_MS = 60_000; + +/** + * The sky's clock (`skyNow`) for a surface that shows the minute: re-read at every minute boundary while `live` (the sky follows the clock: Auto), and at each + * render otherwise, since a frozen moment does not move with it. The clock is the sky's own; this holds no second one. + */ +export function useSkyMinute(live: boolean): Date { + const [now, setNow] = useState(skyNow); + useEffect(() => { + setNow(skyNow()); + if (!live) return undefined; + let timer: ReturnType; + const next = () => { + timer = setTimeout(() => { + setNow(skyNow()); + next(); + }, MINUTE_MS - (skyNow().getTime() % MINUTE_MS)); + }; + next(); + return () => clearTimeout(timer); + }, [live]); + return live ? now : skyNow(); +}