From cd81f85d058d7db554b3cbf798c3cdd82215eac6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 21 Nov 2026 00:07:01 +0100 Subject: [PATCH] Sky menu fixes: one owner of the drawn place, Night is tonight's, named moments roll - skyPlace.ts is the only writer of the sky's place: the manifest's when the cards load, FALLBACK_VIEW's when the manifest or cards fail; the scene draws the view it told the store, so sky, weather, ink and Auto agree on every drawn state (Auto ticks on the fallback). - useSkyPlace removed: only a scene start fetches the manifest. - Old-key migration writes the new key first; a refused write keeps the pick for the page load. - A named moment re-resolves when the place-local day rolls over (the one timer); Night is the nearest solar midnight (before the day's noon the one just passed or coming), keyed by the instant drawn. - Baker validate/schema check place.tz as load_preset does; Vienna manifest baker_version 3 (it carries tz). Co-Authored-By: Claude Sonnet 5.5 --- .../ridge/vienna-6815bb9dca99/manifest.json | 2 +- scripts/ridge-bake/export.py | 7 +- scripts/ridge-bake/ridge-bake.schema.json | 3 +- scripts/ridge-bake/tests/test_ridge.py | 3 + src/app/features/scene/README.md | 8 ++- src/app/features/scene/index.test.ts | 72 ++++++++++++++++++- src/app/features/scene/index.ts | 17 +++-- .../features/scene/ridge/skyMoment.test.ts | 27 ++++++- src/app/features/scene/ridge/skyMoment.ts | 42 +++++++---- src/app/features/scene/skyPlace.ts | 45 +++++++++--- src/app/features/scene/skyState.test.ts | 54 +++++++++++++- src/app/features/scene/skyState.ts | 35 ++++++--- src/app/hooks/useSkyState.ts | 14 +--- src/app/pages/ThemeManager.tsx | 3 - 14 files changed, 263 insertions(+), 69 deletions(-) diff --git a/public/ridge/vienna-6815bb9dca99/manifest.json b/public/ridge/vienna-6815bb9dca99/manifest.json index 2cafc1ef..b7772445 100644 --- a/public/ridge/vienna-6815bb9dca99/manifest.json +++ b/public/ridge/vienna-6815bb9dca99/manifest.json @@ -1,6 +1,6 @@ { "schema": 2, - "baker_version": 2, + "baker_version": 3, "bake_id": "6815bb9dca99", "place": { "id": "vienna", diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 7c475a3d..03982d5d 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -7,6 +7,7 @@ The runtime reads manifest.json (SCHEMA is its contract) and nothing else about import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work).""" import os, sys, json, math, shutil, hashlib, argparse, tempfile from pathlib import Path +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import numpy as np, imagecodecs @@ -35,11 +36,12 @@ ATTRIBUTION = dict( # ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) _num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} _numnull = {'type': ['number', 'null']} +_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props} _file = _obj(file=_str, bytes=_int) SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': { 'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str, - place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_str), + place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz), view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num), curvature=_obj(r_earth_m=_num, k_ref=_num), encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}), @@ -55,6 +57,9 @@ def validate(x, s, path='$'): if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}') + if s.get('format') == 'iana-tz': + try: ZoneInfo(x) + except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows') if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}") if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}') if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}') diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json index bf1d3f48..e32238f0 100644 --- a/scripts/ridge-bake/ridge-bake.schema.json +++ b/scripts/ridge-bake/ridge-bake.schema.json @@ -62,7 +62,8 @@ "type": "number" }, "tz": { - "type": "string" + "type": "string", + "format": "iana-tz" } } }, diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index 29d877c7..4780ae1b 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -189,6 +189,9 @@ def test_manifest_v2_writer(): assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m'] for c in m['cards']: for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c + bad = json.loads(json.dumps(m)); bad['place']['tz'] = 'Mars/Olympus' + try: export.validate(bad, export.SCHEMA['$defs']['manifest']); raise AssertionError('a zone the system does not know validated') + except ValueError as e: assert 'time zone' in str(e), e assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF) idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name}) pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id' diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 4c2ea152..0f9f9e14 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -58,14 +58,16 @@ The viewer's choice is Auto, one of six named moments (Dawn, Morning, Noon, Gold minute of the day). `ridge/skyMoment.ts` is the one owner of what it draws: `momentFor(choice, place, now)` returns the instant and `skyBand(elevation)` turns the sun at that instant into day, dusk or night (day from 6 degrees up, night from 6 down), which the ink theme (`skyTheme.ts`, `skyInk.ts`), the display budget (`ridge/toneMap.ts`) and the rebuild key (`skyForState.ts`) all read. Auto is the real sun over the loaded place now. A named moment is -today's at the place, from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at +today's at the place (Night tonight's: the solar midnight nearest, before the day's noon the one just passed or coming, after it the one coming), from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at +4, morning at the lesser of 15 degrees and half the noon elevation, noon the day's maximum, night solar midnight). Place-local time comes only from `place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the 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` loads the manifest of the configured place and makes its place the -sky's, so the ink and the scene read one place; until it is known no sky is drawn for ink and the theme's own ink stands. +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 +settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, a card that will not 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 diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index e6ecc0e1..d03b023b 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { atSolarTime } from './ridge/skyTestkit'; import type { Scene } from './Scene'; import { startBackgroundScene } from './index'; -import { getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace } from './skyState'; +import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState'; +import { skyBand } from './ridge/skyMoment'; import type { SkyChoice } from './ridge/skyMoment'; import { ridgeSkyFor } from './skyForState'; import { forgetManifests } from './ridge/manifest'; @@ -394,7 +395,7 @@ describe('the ridge planes', () => { expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); }); - it("makes the manifest's place the sky's place, so the ink and the scene read one place; a failed load leaves none", async () => { + it("makes the manifest's place the sky's place, so the ink and the scene read one place; a failed load makes it the drawn fallback's", async () => { served(); loader(); createRidgeScene.mockReturnValue(fakeScene()); @@ -409,7 +410,72 @@ describe('the ridge planes', () => { ); setSkyPlace(undefined); (await startBackgroundScene(config, caps, { canvas }))?.dispose(); - expect(getSkyPlace()).toBeUndefined(); + expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place); + }); + + it('a manifest that fails to load: the ink follows the drawn fallback sky, and Auto still ticks', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })) + ); + createRidgeScene.mockReturnValue(fakeScene()); + setSkyPlace(undefined); + setSkyChoice(NOON); + const scene = await startBackgroundScene(config, caps, { canvas }); + try { + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place); + expect(getResolvedSkyState()).toBe('day'); + expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation)); + } finally { + scene?.dispose(); + } + // Auto crosses dusk with the place the fallback scene drew. + setSkyChoice(AUTO); + vi.useFakeTimers(); + try { + let now = atSolarTime(17, 0); + setSkyClock(() => now); + const heard = vi.fn(); + const off = subscribe(heard); + now = atSolarTime(18, 10); + vi.advanceTimersByTime(60_000); + expect(heard).toHaveBeenCalledWith('dusk'); + off(); + } finally { + vi.useRealTimers(); + } + }); + + it('cards that fail on a place that is not the fallback: the sky and the ink are at the one place, the fallback', async () => { + const fuji = { + ...(wireManifest() as any).place, + id: 'fuji', + lat: 35.36, + lon: 138.73, + tz: 'Asia/Tokyo', + }; + served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ place: fuji }) }); + const { ctl } = loader(); + ctl.fail = true; + createRidgeScene.mockReturnValue(fakeScene()); + setSkyPlace(undefined); + setSkyChoice(NOON); + const scene = await startBackgroundScene(config, caps, { canvas }); + try { + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.backdrop).toBeUndefined(); + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place); + expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation)); + // The next key, made before the next build, is for the view that is drawn: the place does not flip back to the manifest's. + setSkyChoice(DUSK); + await flush(); + expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place); + } finally { + scene?.dispose(); + } }); const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => { diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 3a53cb02..71cb88d4 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -3,7 +3,7 @@ import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './t import { debugOverlaysAllowed } from './debugOverlays'; import { getConstellationLines, getSkyChoice, subscribe } from './skyState'; import type { SkyChoice } from './ridge/skyMoment'; -import { ensureSkyPlace } from './skyPlace'; +import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace'; import type { SkyColours } from './ridge/skyColour'; import type { Backdrop } from './ridge/Backdrop'; import { FALLBACK_VIEW } from './ridge/view'; @@ -62,30 +62,32 @@ async function prepare( const { manifest, fail } = await ensureSkyPlace(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per - // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone. + // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone, over the view the store is told of. let backdrop: Backdrop | null = null; - let sky: SkyColours | undefined; + let lit: SkyColours | undefined; let planesFail: Error | null = fail; if (manifest) { try { const manifestSky = ridgeSkyFor(choice, manifest.view); - sky = manifestSky; const { loadBackdrop } = await import('./ridge/Backdrop'); backdrop = await loadBackdrop( manifest, manifestSky.physical as NonNullable ); if (!backdrop) throw new Error('ridge cards did not load'); + lit = manifestSky; } catch (e) { backdrop = null; - sky = undefined; planesFail = e instanceof Error ? e : new Error(String(e)); } } + const view = drawnView(backdrop ? manifest : null); + if (!lit) await loadWeather(weatherUrl(), view.place); + const sky = lit ?? ridgeSkyFor(choice, view); const made = guarded(() => createRidgeScene({ ...options, - sky: sky ?? ridgeSkyFor(choice, FALLBACK_VIEW), + sky, backdrop: backdrop ?? undefined, lines: getConstellationLines(), }) @@ -107,7 +109,7 @@ async function skyKey( ): Promise { try { const { loadWeather, ridgeSkyKey } = await import('./skyForState'); - const view = (await ensureSkyPlace(config)).manifest?.view ?? FALLBACK_VIEW; + const { view } = await ensureSkyPlace(config); await loadWeather(weatherUrl(), view.place); return ridgeSkyKey(choice, view); } catch { @@ -144,6 +146,7 @@ export async function startBackgroundScene( planesFailed = planesFail !== null; }; const prepared = (choice: SkyChoice) => prepare(config, { ...options, tier, debug }, choice); + resetSkyPlanes(); const choice = getSkyChoice(); const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice); const firstReady = await prepared(choice); diff --git a/src/app/features/scene/ridge/skyMoment.test.ts b/src/app/features/scene/ridge/skyMoment.test.ts index 6f58e058..019c58ba 100644 --- a/src/app/features/scene/ridge/skyMoment.test.ts +++ b/src/app/features/scene/ridge/skyMoment.test.ts @@ -30,8 +30,8 @@ const PLACES: Record = { const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20']; const MIN = 60_000; -/** The place-local noon of `date`: any instant of that local day names it. */ -const during = (date: string, p: Place): Date => zonedInstant(date, 720, p.tz); +/** 18:00 place-local on `date`: any instant of that local day names it, and one after the sun's noon, so Night is the coming midnight. */ +const during = (date: string, p: Place): Date => zonedInstant(date, 1080, p.tz); const at = (id: MomentId, p: Place, date: string): Date => momentFor({ kind: 'named', id }, p, during(date, p)); const el = (p: Place, t: Date): number => sunAt(p, t).elevation; @@ -184,6 +184,29 @@ describe('Fuji dawn is Japanese dawn', () => { }); }); +describe("Night is tonight's, the nearest one", () => { + const night = { kind: 'named', id: 'night' } as const; + const p = PLACES.vienna; + it('at 00:30 it is the midnight coming within the hour, not the one a day ahead; after noon the one coming', () => { + const at = Date.parse('2026-06-21T22:30:00Z'); // 00:30 on June 22, Vienna + const early = momentFor(night, p, new Date(at)); + expect(localDate(early, p.tz)).toBe('2026-06-22'); + expect(early.getTime() - at).toBeGreaterThan(0); + expect(early.getTime() - at).toBeLessThan(2 * 3_600_000); + const evening = momentFor(night, p, new Date('2026-06-22T12:00:00Z')); // 14:00 June 22 + expect(localDate(evening, p.tz)).toBe('2026-06-23'); + expect(evening.getTime() - early.getTime()).toBeGreaterThan(23.9 * 3_600_000); + expect(evening.getTime() - early.getTime()).toBeLessThan(24.1 * 3_600_000); + expect(momentFor(night, p, new Date('2026-06-22T18:00:00Z')).getTime()).toBe(evening.getTime()); + }); + it('the key follows the instant drawn: it is the same across the midnight roll and changes at the noon side', () => { + const k = (iso: string) => momentKey(night, p, new Date(iso)); + expect(k('2026-06-21T22:30:00Z')).toBe(k('2026-06-21T21:30:00Z')); // 00:30 and 23:30 + expect(k('2026-06-21T22:30:00Z')).not.toBe(k('2026-06-22T12:00:00Z')); + expect(k('2026-06-22T12:00:00Z')).toBe(k('2026-06-22T20:00:00Z')); + }); +}); + describe('purity and bands', () => { it('auto is the time it is given', () => { const now = new Date('2026-05-05T05:05:05Z'); diff --git a/src/app/features/scene/ridge/skyMoment.ts b/src/app/features/scene/ridge/skyMoment.ts index adc832f1..684fcc2c 100644 --- a/src/app/features/scene/ridge/skyMoment.ts +++ b/src/app/features/scene/ridge/skyMoment.ts @@ -191,7 +191,8 @@ interface Rule { /** * The named moments, one row each (tuned by eye, ruling ridge-look-tuned-by-eye-no-contrast-gates). A crossing the day does not have - * (polar) falls to the day's noon (rising) or midnight (setting). Night is solar midnight: the sun's lowest in the 24 h after noon. + * (polar) falls to the day's noon (rising) or midnight (setting). Night is solar midnight, tonight's: before the day's noon the one that + * just passed or is coming this morning, after it the one that is coming (`momentOf`'s `before`), never one a whole day away. */ export const SKY_MOMENTS: Record = { dawn: { at: 'rising', deg: () => -3 }, @@ -202,27 +203,42 @@ export const SKY_MOMENTS: Record = { night: { at: 'midnight' }, }; -function momentOf(id: MomentId, d: Day): number { +function momentOf(id: MomentId, d: Day, before: boolean): number { const rule = SKY_MOMENTS[id]; const f = (t: number) => elevationAt(d.place, t); const midnight = () => peak(f, d.noon, d.noon + DAY, -1); if (rule.at === 'noon') return d.noon; - if (rule.at === 'midnight') return midnight(); + if (rule.at === 'midnight') return before ? peak(f, d.noon - DAY, d.noon, -1) : midnight(); const deg = rule.deg ? rule.deg(d.noonElevation) : 0; if (rule.at === 'rising') return crossing(f, deg, d.from, d.noon, true) ?? d.noon; return crossing(f, deg, d.noon, d.to, false) ?? midnight(); } +const days = new Map(); const named = new Map(); -/** The instant of a named moment on a place-local date at the place (memoised: the answer is a pure function of these). */ -function namedInstant(id: MomentId, place: Place, date: string): Date { - const key = `${id}|${date}|${place.tz}|${place.lat}|${place.lon}`; - let t = named.get(key); - if (t === undefined) { +/** The place-local day `date` at the place (memoised: a pure function of these). */ +function dayOf(place: Place, date: string): Day { + const key = `${date}|${place.tz}|${place.lat}|${place.lon}`; + let d = days.get(key); + if (!d) { const from = zonedInstant(date, 0, place.tz).getTime(); const to = zonedInstant(dateOf(utcOfDate(date) + DAY), 0, place.tz).getTime(); const noon = peak((x) => elevationAt(place, x), from, to, 1); - t = momentOf(id, { place, from, to, noon, noonElevation: elevationAt(place, noon) }); + d = { place, from, to, noon, noonElevation: elevationAt(place, noon) }; + if (days.size > 256) days.clear(); + days.set(key, d); + } + return d; +} + +/** The instant of a named moment on a place-local date at the place (memoised). Only Night looks at `now`: which side of the day's noon it is. */ +function namedInstant(id: MomentId, place: Place, date: string, now: Date): Date { + const d = dayOf(place, date); + const before = now.getTime() < d.noon; + const key = `${id}|${date}|${before}|${place.tz}|${place.lat}|${place.lon}`; + let t = named.get(key); + if (t === undefined) { + t = momentOf(id, d, before); if (named.size > 256) named.clear(); named.set(key, t); } @@ -240,10 +256,10 @@ const clampDate = (date: string): string => : date; const clampMinutes = (m: number): number => Math.min(1439, Math.max(0, Math.floor(m) || 0)); -/** The instant the sky is drawn at for a choice at a place: auto is `now`; a named moment is today's at the place; a free moment is its own. */ +/** The instant the sky is drawn at for a choice at a place: auto is `now`; a named moment is today's at the place (Night: tonight's, the nearest one); a free moment is its own. */ export function momentFor(choice: SkyChoice, place: Place, now: Date): Date { if (choice.kind === 'auto') return now; - if (choice.kind === 'named') return namedInstant(choice.id, place, localDate(now, place.tz)); + if (choice.kind === 'named') return namedInstant(choice.id, place, localDate(now, place.tz), now); return zonedInstant(clampDate(choice.date), clampMinutes(choice.minutes), place.tz); } @@ -262,9 +278,9 @@ export function seedFree( }; } -/** What a rebuild is for, of the moment: live for auto, the id and place-local date for a named one, the date and minutes for a free one. */ +/** What a rebuild is for, of the moment: live for auto, the id and place-local date of the instant for a named one, the date and minutes for a free one. */ export function momentKey(choice: SkyChoice, place: Place, now: Date): string { if (choice.kind === 'auto') return 'live'; - if (choice.kind === 'named') return `${choice.id}@${localDate(now, place.tz)}`; + if (choice.kind === 'named') return `${choice.id}@${localDate(momentFor(choice, place, now), place.tz)}`; return `${clampDate(choice.date)}@${clampMinutes(choice.minutes)}`; } diff --git a/src/app/features/scene/skyPlace.ts b/src/app/features/scene/skyPlace.ts index 227b5d09..bf91d708 100644 --- a/src/app/features/scene/skyPlace.ts +++ b/src/app/features/scene/skyPlace.ts @@ -1,24 +1,47 @@ -// The place the sky is over: the baked place's manifest, loaded once and shared. Its View is the one owner of the sun's place and the camera -// for the weather, the sky, the rebuild key and the planes; its Place is what the sky store (skyState.ts) resolves the drawn sky for, so the -// ink and the scene read one place. Main-chunk safe: no sky, no ridge code, only the manifest parser and the store. +// 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 fallback view and the store. import type { BackgroundSceneConfig } from './tier'; import { loadManifest } from './ridge/manifest'; import type { RidgeManifest } from './ridge/manifest'; +import { FALLBACK_VIEW } from './ridge/view'; +import type { View } from './ridge/view'; 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; + +/** 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 its place the - * sky's. Safe to call whenever a reader wants the manifest: the load is memoised and setting the same place is not a change. A failed load - * leaves the place as it was (none, at first: no sky is drawn for ink) and is returned, so the scene can be the sky alone. + * 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. */ export async function ensureSkyPlace( config: Pick | undefined -): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> { +): Promise<{ manifest: RidgeManifest | null; view: View; fail: Error | null }> { + let manifest: RidgeManifest | null = null; + let fail: Error | null = null; try { - const manifest = await loadManifest(import.meta.env.BASE_URL, config?.place); - setSkyPlace(manifest.view.place); - return { manifest, fail: null }; + manifest = await loadManifest(import.meta.env.BASE_URL, config?.place); } catch (e) { - return { manifest: null, fail: e instanceof Error ? e : new Error(String(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 { + skyOnly = manifest === null; + const view = manifest?.view ?? FALLBACK_VIEW; + setSkyPlace(view.place); + return view; } diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts index cfec28ba..73576ed8 100644 --- a/src/app/features/scene/skyState.test.ts +++ b/src/app/features/scene/skyState.test.ts @@ -120,6 +120,36 @@ describe('persistence', () => { expect(m.getSkyChoice()).toEqual(night); }); + it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => { + storage.data.set(OLD_KEY, 'day'); + vi.stubGlobal('localStorage', { + ...storage, + setItem: () => { + throw new Error('denied'); + }, + }); + expect((await fresh()).getSkyChoice()).toEqual(noon); + expect(storage.data.has(OLD_KEY)).toBe(true); + }); + + it('writes the new key before it removes the old one', async () => { + storage.data.set(OLD_KEY, 'dusk'); + const order: string[] = []; + vi.stubGlobal('localStorage', { + ...storage, + setItem: (k: string, v: string) => { + order.push(`set ${k}`); + storage.data.set(k, v); + }, + removeItem: (k: string) => { + order.push(`remove ${k}`); + storage.data.delete(k); + }, + }); + expect((await fresh()).getSkyChoice()).toEqual(dusk); + expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]); + }); + it('persists a set choice under one key and reads it back after a reload', async () => { (await fresh()).setSkyChoice(dusk); expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]); @@ -261,18 +291,38 @@ describe('Auto follows the clock', () => { offLate(); }); - it('keeps no timer without listeners or when a moment is chosen', async () => { + it('keeps no timer without listeners or when a free moment is chosen; one timer serves Auto and a named moment', async () => { const m = await fresh(); const off = m.subscribe(() => undefined); expect(vi.getTimerCount()).toBe(1); - m.setSkyChoice(night); + m.setSkyChoice({ kind: 'free', date: '2026-07-01', minutes: 600 }); expect(vi.getTimerCount()).toBe(0); + m.setSkyChoice(night); + expect(vi.getTimerCount()).toBe(1); m.setSkyChoice(auto); expect(vi.getTimerCount()).toBe(1); off(); expect(vi.getTimerCount()).toBe(0); }); + it('a named moment is told again when the place-local day rolls over, once, and not before', async () => { + const m = await fresh(); + m.setSkyPlace(VIENNA); + m.setSkyChoice(noon); + let now = new Date('2026-06-21T21:30:00Z'); // 23:30 in Vienna + m.setSkyClock(() => now); + const cb = vi.fn(); + const off = m.subscribe(cb); + vi.advanceTimersByTime(10 * 60_000); + expect(cb).not.toHaveBeenCalled(); + now = new Date('2026-06-21T22:05:00Z'); // 00:05 on the 22nd + vi.advanceTimersByTime(60_000); + expect(cb).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(60 * 60_000); + expect(cb).toHaveBeenCalledTimes(1); + off(); + }); + it('notifies a change of choice with the resolved sky', async () => { const m = await fresh(); m.setSkyPlace(VIENNA); diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index b4b34361..0551b021 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -1,7 +1,7 @@ // Which sky the signed-out page is drawn against: three small stores and the notice that one of them moved. The viewer's choice (Auto, a // named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is // `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores. -import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, skyBand } from './ridge/skyMoment'; +import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, momentKey, skyBand } from './ridge/skyMoment'; import type { FixedSkyState, MomentId, SkyChoice } from './ridge/skyMoment'; import { sunAt } from './ridge/sunAt'; import type { Place } from './ridge/view'; @@ -47,12 +47,18 @@ function load(): SkyChoice { try { const old = localStorage.getItem(OLD_KEY); if (old !== null) { - localStorage.removeItem(OLD_KEY); const migrated = FROM_OLD.get(old); if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) { - localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated)); + try { + // The new key first: a refusal leaves the old one in place, and the pick holds for this page load. + localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated)); + } catch { + return migrated; + } + localStorage.removeItem(OLD_KEY); return migrated; } + localStorage.removeItem(OLD_KEY); } const stored = localStorage.getItem(SKY_CHOICE_KEY); return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO; @@ -84,6 +90,7 @@ let place: Place | undefined; const listeners = new Set<(s: FixedSkyState | undefined) => void>(); let timer: ReturnType | undefined; let shown: FixedSkyState | undefined; +let shownKey: string | undefined; const TICK_MS = 60_000; /** The choice (what the control shows). */ @@ -102,20 +109,25 @@ export const skyNow = (): Date => clock(); export const getResolvedSkyState = (): FixedSkyState | undefined => place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).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()); + const emit = () => { shown = getResolvedSkyState(); + shownKey = drawnKey(); [...listeners].forEach((cb) => cb(shown)); }; -// While anyone listens and the choice is Auto, one timer checks the clock each minute and tells -// listeners when the resolved band changes from the one last told (`shown`, set when telling and when the -// first listener arrives, never by a later arrival or departure). Otherwise there is no timer. +// While anyone listens and the choice is Auto or a named moment, one timer checks the clock each minute and tells +// listeners when the resolved band, or the moment drawn (an Auto band, a named moment's place-local day), changes from the one +// last told (`shown` and `shownKey`, set when telling and when the first listener arrives, never by a later arrival or departure). +// A free moment does not move with the clock, so it has no timer. function sync(): void { clearTimeout(timer); timer = undefined; - if (listeners.size === 0 || getSkyChoice().kind !== 'auto') return; + if (listeners.size === 0 || getSkyChoice().kind === 'free') return; const tick = () => { - if (getResolvedSkyState() !== shown) emit(); + if (getResolvedSkyState() !== shown || drawnKey() !== shownKey) emit(); timer = setTimeout(tick, TICK_MS); }; timer = setTimeout(tick, TICK_MS); @@ -171,9 +183,12 @@ export function pickSkyChoice(c: SkyChoice): void { setSkyChoice(c); } -/** Listeners hear the resolved band: on a change of choice or place, and while Auto, when the clock crosses a boundary. */ +/** Listeners hear the resolved band: on a change of choice or place, while Auto, when the clock crosses a band, and while a named moment, when the place-local day rolls over. */ export function subscribe(cb: (s: FixedSkyState | undefined) => void): () => void { - if (listeners.size === 0) shown = getResolvedSkyState(); + if (listeners.size === 0) { + shown = getResolvedSkyState(); + shownKey = drawnKey(); + } listeners.add(cb); sync(); return () => { diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index f2dbcb2b..f8d56674 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -1,4 +1,4 @@ -import { useEffect, useSyncExternalStore } from 'react'; +import { useSyncExternalStore } from 'react'; import { getResolvedSkyState, getSkyChoice, @@ -7,9 +7,7 @@ import { } from '../features/scene/skyState'; import type { Place } from '../features/scene/ridge/view'; import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment'; -import { ensureSkyPlace } from '../features/scene/skyPlace'; import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; -import { useClientConfig } from './useClientConfig'; /** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useResolvedSkyState`. */ export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice); @@ -18,16 +16,8 @@ export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, get export const useResolvedSkyState = (): FixedSkyState | undefined => useSyncExternalStore(subscribe, getResolvedSkyState); -/** The place the sky is over, or undefined until the manifest is loaded. */ +/** The place the sky is over, or undefined until a scene has settled what it draws (skyPlace.ts). */ export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subscribe, getSkyPlace); -/** Make the configured place the sky's (skyPlace.ts). Mounted once by each theme manager; the load is shared and idempotent. */ -export const useSkyPlace = (): void => { - const place = useClientConfig().backgroundScene?.place; - useEffect(() => { - ensureSkyPlace({ place }); - }, [place]); -}; - /** 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); diff --git a/src/app/pages/ThemeManager.tsx b/src/app/pages/ThemeManager.tsx index 3ed4c8dd..092ace6c 100644 --- a/src/app/pages/ThemeManager.tsx +++ b/src/app/pages/ThemeManager.tsx @@ -8,7 +8,6 @@ import { useSceneInk, useSkyTheme, } from '../hooks/useTheme'; -import { useSkyPlace } from '../hooks/useSkyState'; import { useSetting } from '../state/hooks/settings'; import { settingsAtom } from '../state/settings'; import { labelInk } from '../features/scene/skyInk'; @@ -17,7 +16,6 @@ import { SKY_LABEL_INK } from '../features/scene/skyLabelInk'; export function UnAuthRouteThemeManager() { // Signed-out pages are Midnight Sky unless the sky state picks otherwise; they ignore the // system scheme. - useSkyPlace(); const theme = useSkyTheme() ?? MidnightSkyTheme; useEffect(() => { @@ -30,7 +28,6 @@ export function UnAuthRouteThemeManager() { } export function AuthRouteThemeManager({ children }: { children: ReactNode }) { - useSkyPlace(); const activeTheme = useActiveTheme(); const [monochromeMode] = useSetting(settingsAtom, 'monochromeMode'); const skyInk = useSceneInk();