diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index e3510d31..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,11 +198,11 @@ 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 zone (local time on its card). */ +/** 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; - tz: string; + place: Place; } const memo = new Map>(); @@ -254,7 +254,7 @@ export function listPlaces(baseUrl: string): Promise { const found = await Promise.allSettled( Object.keys(index.places).map(async (id): Promise => { const m = await loadManifest(baseUrl, id); - return { id, name: m.name, tz: m.view.place.tz }; + return { id, name: m.name, place: m.view.place }; }) ); return found.flatMap((f) => (f.status === 'fulfilled' ? [f.value] : [])); diff --git a/src/app/features/scene/view/PlaceSubmenu.test.tsx b/src/app/features/scene/view/PlaceSubmenu.test.tsx index 264b5849..9dfc670a 100644 --- a/src/app/features/scene/view/PlaceSubmenu.test.tsx +++ b/src/app/features/scene/view/PlaceSubmenu.test.tsx @@ -2,6 +2,7 @@ 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 } from '../ridge/credits'; import { WEATHER_FEEDS, creditLine } from '../ridge/weatherFeed'; @@ -10,6 +11,9 @@ import { SkySubmenu } from './SkySubmenu'; // 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[], @@ -20,7 +24,14 @@ vi.mock('react', async (importOriginal) => { const useEffect = () => undefined; return { ...actual, default: { ...actual, useRef, useEffect }, useRef, useEffect }; }); -vi.mock('../../../hooks/useSkyState', () => ({ useDrawnPlace: () => held.place })); +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, @@ -28,7 +39,6 @@ vi.mock('../../../hooks/useSceneView', () => ({ vi.mock('../placeState', () => ({ setPlaceChoice: (id: string) => held.picked.push(id) })); vi.mock('../skyState', () => ({ setConstellationLines: () => undefined, - skyNow: () => new Date('2030-06-21T10:00:00Z'), })); type El = { type?: unknown; props?: Record }; @@ -58,25 +68,33 @@ const strings = (node: unknown): string[] => { 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[] = [ - { id: 'vienna', name: 'Vienna', tz: 'Europe/Vienna' }, - { id: 'fuji', name: 'Fuji', tz: 'Asia/Tokyo' }, - { id: 'matterhorn', name: 'Matterhorn', tz: 'Europe/Zurich' }, - { id: 'amadablam', name: 'Ama Dablam', tz: 'Asia/Kathmandu' }, - { id: 'grandcanyon', name: 'Grand Canyon', tz: 'America/Phoenix' }, + 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 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', now: NOW, onPick: () => undefined })); + 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', @@ -87,6 +105,38 @@ describe('the Place carousel', () => { 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); @@ -94,7 +144,7 @@ describe('the Place carousel', () => { onPick('grandcanyon'); expect(held.picked).toEqual(['grandcanyon']); held.picked.length = 0; - const own = walk(PlaceCarousel({ places: FIVE, current: 'vienna', now: NOW, onPick })); + 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 @@ -120,7 +170,7 @@ describe('the Place carousel', () => { children: FIVE.map((_, i) => ({ offsetLeft: i * 100, offsetWidth: 100 })), }; const own = walk( - PlaceCarousel({ places: FIVE, current: 'vienna', now: NOW, onPick: (id) => held.picked.push(id) }) + 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) => { diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx index deaefb1a..9eb51a55 100644 --- a/src/app/features/scene/view/PlaceSubmenu.tsx +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -1,15 +1,15 @@ import React, { useEffect, useRef } from 'react'; import { Box, Icon, IconButton, Icons, Text } from 'folds'; -import { useDrawnPlace } from '../../../hooks/useSkyState'; +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 } from '../ridge/skyMoment'; +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 { skyNow } from '../skyState'; import { hhmm } from './TimeSubmenu'; import * as css from './SceneView.css'; @@ -33,17 +33,20 @@ const centredIndex = (strip: HTMLElement): number => { }; /** - * The baked places, one card each (its name and its local time now), swiped or stepped with the arrows; the card in the middle is the place drawn + * 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; }) { @@ -101,7 +104,7 @@ export function PlaceCarousel({ > {p.name} - {hhmm(localMinutes(now, p.tz))} local + {hhmm(localMinutes(momentFor(choice, p.place, now), p.place.tz))} local ))} @@ -127,12 +130,14 @@ export function PlaceCarousel({ 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 ( {places && places.length > 1 ? ( - + ) : ( {manifest?.name ?? place.id} )} diff --git a/src/app/hooks/useSceneView.ts b/src/app/hooks/useSceneView.ts index fde744ec..a1f33317 100644 --- a/src/app/hooks/useSceneView.ts +++ b/src/app/hooks/useSceneView.ts @@ -36,7 +36,7 @@ export const useConstellationLines = (): boolean => 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 */ +/** 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(() => { diff --git a/src/app/hooks/useSkyState.test.ts b/src/app/hooks/useSkyState.test.ts new file mode 100644 index 00000000..8632164b --- /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'; + +// 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 { useSkyMinute } = await import('./useSkyState'); + +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(); +}