Sky menu: Auto, six named moments and a free moment picker

Seven radio items plus Pick a moment, which opens a date input and a 5-minute time slider that show the
place-local time and zone and commit on the native change event (slider release), never per input tick.
The picker opens from the moment being drawn, in the place zone (seedFree).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 23:42:48 +01:00
commit e948f99f9e
6 changed files with 456 additions and 74 deletions

View file

@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import {
MENU_CHOICES,
SkyMomentPicker,
SkyStateControl,
choiceLabel,
useNativeChange,
} from './SkyStateControl';
// The component's hooks are held still, as in RoomOutbox.actions.test.tsx: state is its initial value, refs are plain boxes, effects are
// kept to be run once the test has put an element in each ref. The element tree it returns is read and its native events are dispatched
// on a fake input, so no DOM is needed.
const held = vi.hoisted(() => ({
effects: [] as Array<() => unknown>,
choice: { kind: 'auto' } as unknown,
}));
vi.mock('react', async (importOriginal) => {
const actual = await importOriginal<typeof import('react')>();
const useState = (init: unknown) => [
typeof init === 'function' ? (init as () => unknown)() : init,
() => undefined,
];
const useRef = (init: unknown) => ({ current: init });
const useEffect = (fn: () => unknown) => {
held.effects.push(fn);
};
return {
...actual,
default: { ...actual, useState, useRef, useEffect },
useState,
useRef,
useEffect,
};
});
vi.mock('../../hooks/useSkyState', () => ({
useSkyChoice: () => held.choice,
useDrawnPlace: () => FALLBACK_VIEW.place,
}));
vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) }));
type El = { type?: unknown; ref?: unknown; props?: Record<string, unknown> };
/** Every element reachable through any prop (children, `content`, `after`). */
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 '';
};
/** A stand-in input: a real EventTarget with a value. */
const fakeInput = (value: string) => Object.assign(new EventTarget(), { value });
const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type));
beforeEach(() => {
held.effects.length = 0;
held.choice = { kind: 'auto' };
});
describe('the sky menu choices', () => {
const tree = () => walk(SkyStateControl());
const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio');
it('lists Auto and the six named moments, then Pick a moment', () => {
expect(MENU_CHOICES.map(choiceLabel)).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
]);
expect(radios().map((e) => textOf(e))).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
'Pick a moment',
]);
});
it.each([
[{ kind: 'auto' }, 0],
[{ kind: 'named', id: 'dawn' }, 1],
[{ kind: 'named', id: 'night' }, 6],
[{ kind: 'free', date: '2026-12-21', minutes: 400 }, 7],
] as Array<[SkyChoice, number]>)('aria-checked follows the choice %j', (choice, checked) => {
held.choice = choice;
radios().forEach((e, i) => expect(e.props?.['aria-checked'], `item ${i}`).toBe(i === checked));
});
it("the button reads 'Sky: Auto', 'Sky: Dawn' or 'Sky: <date> <time>'", () => {
const label = () =>
tree().find((e) => e.props?.['aria-haspopup'] === 'menu')?.props?.['aria-label'];
expect(label()).toBe('Sky: Auto');
held.choice = { kind: 'named', id: 'dawn' };
expect(label()).toBe('Sky: Dawn');
held.choice = { kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 };
expect(label()).toBe('Sky: 2026-12-21 06:40');
});
});
describe('committing on change, not on input', () => {
it('a native input event commits nothing and the change event commits once', () => {
const commits: string[] = [];
const ref = useNativeChange<HTMLInputElement>((el) => commits.push(el.value));
const target = fakeInput('600');
(ref as { current: unknown }).current = target;
held.effects.forEach((run) => run());
for (let i = 0; i < 5; i += 1) fire(target, 'input');
expect(commits).toEqual([]);
fire(target, 'change');
expect(commits).toEqual(['600']);
});
it('the picker commits the slider on release only, with the date it holds, and the date on change when it is a date in range', () => {
const commits: unknown[] = [];
const tree = walk(
SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 600 },
tz: 'Europe/Vienna',
onCommit: (c) => commits.push(c),
})
);
const input = (type: string) => tree.find((e) => e.type === 'input' && e.props?.type === type);
const date = fakeInput('2026-12-21');
const slider = fakeInput('600');
(input('date')?.ref as { current: unknown }).current = date;
(input('range')?.ref as { current: unknown }).current = slider;
held.effects.forEach((run) => run());
slider.value = '735';
fire(slider, 'input');
fire(slider, 'input');
expect(commits).toEqual([]);
fire(slider, 'change');
expect(commits).toEqual([{ kind: 'free', date: '2026-12-21', minutes: 735 }]);
date.value = '2026-07-15';
fire(date, 'change');
expect(commits[1]).toEqual({ kind: 'free', date: '2026-07-15', minutes: 735 });
date.value = '1800-01-01';
fire(date, 'change');
date.value = '';
fire(date, 'change');
expect(commits).toHaveLength(2);
expect(input('range')?.props).toMatchObject({ min: 0, max: 1439, step: 5 });
expect(input('date')?.props).toMatchObject({ min: '1900-01-01', max: '2100-12-31' });
});
it('the picker shows the place-local time and the zone beside the slider', () => {
const tree = SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 400 },
tz: 'Europe/Vienna',
onCommit: () => undefined,
});
expect(textOf(tree)).toMatch(/^06:40 \S+/);
});
});

View file

@ -1,4 +1,4 @@
import React, { MouseEventHandler, useEffect, useState } from 'react';
import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import {
Box,
config,
@ -13,8 +13,19 @@ import {
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '../../utils/keyboard';
import { useSkyState } from '../../hooks/useSkyState';
import { SKY_STATES, pickSkyState, type SkyState } from './skyState';
import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState';
import { pickSkyChoice, skyNow } from './skyState';
import {
FREE_DATE_MAX,
FREE_DATE_MIN,
MOMENT_IDS,
isDate,
seedFree,
zoneName,
zonedInstant,
} from './ridge/skyMoment';
import type { MomentId, SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import { loadManifest } from './ridge/manifest';
import {
LINES_CREDIT,
@ -27,36 +38,129 @@ import {
import { useClientConfig } from '../../hooks/useClientConfig';
import { PhoneHit } from '../../styles/PhoneHit.css';
const LABEL: Record<SkyState, string> = {
auto: 'Auto',
day: 'Day',
export const MOMENT_LABEL: Record<MomentId, string> = {
dawn: 'Dawn',
morning: 'Morning',
noon: 'Noon',
golden: 'Golden hour',
dusk: 'Dusk',
night: 'Night',
};
const hhmm = (minutes: number): string =>
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
/** What the button and the menu call a choice: Auto, the moment's name, or the free moment's place-local date and time. */
export const choiceLabel = (c: SkyChoice): string =>
c.kind === 'auto'
? 'Auto'
: c.kind === 'named'
? MOMENT_LABEL[c.id]
: `${c.date} ${hhmm(c.minutes)}`;
/** The choices the menu lists, in order. */
export const MENU_CHOICES: readonly SkyChoice[] = [
{ kind: 'auto' },
...MOMENT_IDS.map((id): SkyChoice => ({ kind: 'named', id })),
];
const sameChoice = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
/**
* One title-bar button that opens the four sky states. A single button, not a row, so the bar
* still fits a 320 px phone beside the search button; the menu items carry the state names.
* Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
* input event). Each commit rebuilds the scene, so a drag must commit once.
*/
export function useNativeChange<T extends HTMLElement>(onChange: (el: T) => void) {
const ref = useRef<T>(null);
const latest = useRef(onChange);
latest.current = onChange;
useEffect(() => {
const el = ref.current;
if (!el) return undefined;
const handler = () => latest.current(el);
el.addEventListener('change', handler);
return () => el.removeEventListener('change', handler);
}, []);
return ref;
}
type Free = Extract<SkyChoice, { kind: 'free' }>;
/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
export function SkyMomentPicker({
seed,
tz,
onCommit,
}: {
seed: Free;
tz: string;
onCommit: (c: Free) => void;
}) {
const [minutes, setMinutes] = useState(seed.minutes);
const at = useRef({ date: seed.date, minutes: seed.minutes });
const dateRef = useNativeChange<HTMLInputElement>((el) => {
if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
at.current.date = el.value;
onCommit({ kind: 'free', ...at.current });
});
const sliderRef = useNativeChange<HTMLInputElement>((el) => {
at.current.minutes = Number(el.value);
onCommit({ kind: 'free', ...at.current });
});
const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
return (
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
<input
ref={dateRef}
type="date"
aria-label="Date"
min={FREE_DATE_MIN}
max={FREE_DATE_MAX}
defaultValue={seed.date}
/>
<input
ref={sliderRef}
type="range"
aria-label="Time of day"
min={0}
max={1439}
step={5}
defaultValue={seed.minutes}
onInput={(evt) => setMinutes(Number(evt.currentTarget.value))}
/>
<Text size="T200" priority="300">
{hhmm(minutes)} {zone}
</Text>
</Box>
);
}
/**
* One title-bar button that opens the sky choices: Auto, the six named moments of today at the place, and a free date and time. A single
* button, not a row, so the bar still fits a 320 px phone beside the search button; the menu items carry the names.
*/
export function SkyStateControl() {
const state = useSkyState();
const choice = useSkyChoice();
const drawn = useDrawnPlace();
const [picking, setPicking] = useState(false);
const [cords, setCords] = useState<RectCords>();
const backgroundScene = useClientConfig().backgroundScene;
const place = backgroundScene?.place;
const placeId = backgroundScene?.place;
const place = drawn ?? FALLBACK_VIEW.place;
const [credit, setCredit] = useState<string>();
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
useEffect(() => {
if (!ridgeOn) return undefined;
let live = true;
loadManifest(import.meta.env.BASE_URL, place).then(
loadManifest(import.meta.env.BASE_URL, placeId).then(
(m) => live && setCredit(terrainCredit(m)),
() => live && setCredit(undefined)
);
return () => {
live = false;
};
}, [ridgeOn, place]);
}, [ridgeOn, placeId]);
const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
setCords(evt.currentTarget.getBoundingClientRect());
};
@ -71,34 +175,63 @@ export function SkyStateControl() {
focusTrapOptions={{
initialFocus: '[aria-checked="true"]',
returnFocusOnDeactivate: true,
onDeactivate: () => setCords(undefined),
onDeactivate: () => {
setCords(undefined);
setPicking(false);
},
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
isKeyForward: (evt: KeyboardEvent) =>
evt.key === 'ArrowDown' && !(evt.target instanceof HTMLInputElement),
isKeyBackward: (evt: KeyboardEvent) =>
evt.key === 'ArrowUp' && !(evt.target instanceof HTMLInputElement),
escapeDeactivates: stopPropagation,
}}
>
<Menu role="menu" aria-label="Sky">
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
{SKY_STATES.map((s) => (
<MenuItem
key={s}
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={state === s}
onClick={() => {
pickSkyState(s);
setCords(undefined);
}}
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">{LABEL[s]}</Text>
</Box>
</MenuItem>
))}
{MENU_CHOICES.map((c) => {
const checked = sameChoice(c, choice);
return (
<MenuItem
key={choiceLabel(c)}
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={checked}
onClick={() => {
pickSkyChoice(c);
setCords(undefined);
}}
after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">{choiceLabel(c)}</Text>
</Box>
</MenuItem>
);
})}
<MenuItem
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={choice.kind === 'free'}
aria-expanded={picking}
onClick={() => setPicking(!picking)}
after={choice.kind === 'free' ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">Pick a moment</Text>
</Box>
</MenuItem>
{picking && (
<SkyMomentPicker
seed={seedFree(choice, place, skyNow())}
tz={place.tz}
onCommit={pickSkyChoice}
/>
)}
{ridgeOn && (
<Box
direction="Column"
@ -136,8 +269,8 @@ export function SkyStateControl() {
<IconButton
className={PhoneHit}
variant="Background"
aria-label={`Sky: ${LABEL[state]}`}
title={`Sky: ${LABEL[state]}`}
aria-label={`Sky: ${choiceLabel(choice)}`}
title={`Sky: ${choiceLabel(choice)}`}
aria-haspopup="menu"
aria-expanded={!!cords}
onClick={open}

View file

@ -6,6 +6,7 @@ import {
localMinutes,
momentFor,
momentKey,
seedFree,
skyBand,
zonedInstant,
} from './skyMoment';
@ -18,7 +19,13 @@ const PLACES: Record<string, Place> = {
matterhorn: { id: 'matterhorn', lat: 45.98, lon: 7.78, altitudeKm: 3.1, tz: 'Europe/Zurich' },
fuji: { id: 'fuji', lat: 35.31, lon: 138.63, altitudeKm: 0.4, tz: 'Asia/Tokyo' },
amadablam: { id: 'amadablam', lat: 27.9, lon: 86.9, altitudeKm: 4.2, tz: 'Asia/Kathmandu' },
halfdome: { id: 'halfdome', lat: 37.73, lon: -119.55, altitudeKm: 1.2, tz: 'America/Los_Angeles' },
halfdome: {
id: 'halfdome',
lat: 37.73,
lon: -119.55,
altitudeKm: 1.2,
tz: 'America/Los_Angeles',
},
};
const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20'];
const MIN = 60_000;
@ -31,17 +38,20 @@ const el = (p: Place, t: Date): number => sunAt(p, t).elevation;
describe('the named moments', () => {
describe.each(Object.entries(PLACES))('%s', (_name, p) => {
it.each(DAYS)('%s: dawn < morning < noon < golden < dusk inside the local day, night after noon', (date) => {
const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()]));
expect(t.dawn).toBeLessThan(t.morning);
expect(t.morning).toBeLessThan(t.noon);
expect(t.noon).toBeLessThan(t.golden);
expect(t.golden).toBeLessThan(t.dusk);
expect(t.night).toBeGreaterThan(t.noon);
(['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) =>
expect(localDate(new Date(t[id]), p.tz)).toBe(date)
);
});
it.each(DAYS)(
'%s: dawn < morning < noon < golden < dusk inside the local day, night after noon',
(date) => {
const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()]));
expect(t.dawn).toBeLessThan(t.morning);
expect(t.morning).toBeLessThan(t.noon);
expect(t.noon).toBeLessThan(t.golden);
expect(t.golden).toBeLessThan(t.dusk);
expect(t.night).toBeGreaterThan(t.noon);
(['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) =>
expect(localDate(new Date(t[id]), p.tz)).toBe(date)
);
}
);
it.each(DAYS)('%s: each crossing is at its table elevation, within 0.05 degrees', (date) => {
const noonEl = el(p, at('noon', p, date));
@ -51,18 +61,21 @@ describe('the named moments', () => {
expect(el(p, at('dusk', p, date))).toBeCloseTo(-3, 1);
});
it.each(DAYS)('%s: noon is the day maximum and night the lowest of the 24 h after it', (date) => {
const noon = at('noon', p, date);
const night = at('night', p, date);
for (let m = 0; m < 24 * 60; m += 5) {
const t = new Date(noon.getTime() + m * MIN);
expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3);
it.each(DAYS)(
'%s: noon is the day maximum and night the lowest of the 24 h after it',
(date) => {
const noon = at('noon', p, date);
const night = at('night', p, date);
for (let m = 0; m < 24 * 60; m += 5) {
const t = new Date(noon.getTime() + m * MIN);
expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3);
}
const dayStart = zonedInstant(date, 0, p.tz).getTime();
for (let m = 0; m < 24 * 60; m += 5) {
expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3);
}
}
const dayStart = zonedInstant(date, 0, p.tz).getTime();
for (let m = 0; m < 24 * 60; m += 5) {
expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3);
}
});
);
});
it('morning is half the noon elevation at Vienna in December (the 15 degree rule would never be met)', () => {
@ -111,14 +124,22 @@ describe('zones', () => {
);
it('Kathmandu is UTC+5:45 and Phoenix has no daylight saving', () => {
expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe('2026-12-21T06:15:00.000Z');
expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe('2026-07-01T19:00:00.000Z');
expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe(
'2026-12-21T06:15:00.000Z'
);
expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe(
'2026-07-01T19:00:00.000Z'
);
});
it('a wall time in the spring-forward gap lands after it; one that happens twice is the first', () => {
// Vienna, 2026-03-29: 02:00 became 03:00 (01:00Z). 2026-10-25: 03:00 became 02:00 (01:00Z).
expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe('2026-03-29T01:30:00.000Z');
expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe('2026-10-25T00:30:00.000Z');
expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-03-29T01:30:00.000Z'
);
expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-10-25T00:30:00.000Z'
);
});
it('the place decides, not the zone of the client', () => {
@ -175,8 +196,12 @@ describe('purity and bands', () => {
const t = momentFor({ kind: 'free', date: '2026-12-21', minutes: 400 }, p, new Date());
expect(localDate(t, p.tz)).toBe('2026-12-21');
expect(localMinutes(t, p.tz)).toBe(400);
expect(localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)).toBe('1900-01-01');
expect(localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)).toBe('2100-12-31');
expect(
localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)
).toBe('1900-01-01');
expect(
localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)
).toBe('2100-12-31');
});
it('skyBand: day at 6.0, night at -6.0, dusk between', () => {
@ -192,10 +217,32 @@ describe('purity and bands', () => {
it('the key of a moment follows its local date and id, or its date and minutes', () => {
const p = PLACES.vienna;
const n = { kind: 'named', id: 'noon' } as const;
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(momentKey(n, p, new Date('2026-06-21T20:00:00Z')));
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(momentKey(n, p, new Date('2026-06-22T10:00:00Z')));
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(
momentKey(n, p, new Date('2026-06-21T20:00:00Z'))
);
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(
momentKey(n, p, new Date('2026-06-22T10:00:00Z'))
);
expect(momentKey({ kind: 'free', date: '2026-06-21', minutes: 5 }, p, new Date())).not.toBe(
momentKey({ kind: 'free', date: '2026-06-21', minutes: 10 }, p, new Date())
);
});
});
describe('the picker seed', () => {
it('opens from the moment Auto or a named choice is drawing, in the place zone, to the 5 minutes the slider steps', () => {
const p = PLACES.fuji;
const now = new Date('2026-12-21T04:03:00Z'); // 13:03 at Fuji
expect(seedFree({ kind: 'auto' }, p, now)).toEqual({
kind: 'free',
date: '2026-12-21',
minutes: 13 * 60,
});
const noon = seedFree({ kind: 'named', id: 'noon' }, p, now);
expect(noon.date).toBe('2026-12-21');
expect(Math.abs(noon.minutes - 11 * 60 - 45)).toBeLessThanOrEqual(15); // solar noon at 138.6 E is about 11:45 JST
expect(noon.minutes % 5).toBe(0);
const free = { kind: 'free', date: '2026-07-15', minutes: 330 } as const;
expect(seedFree(free, p, now)).toBe(free);
});
});

View file

@ -21,7 +21,7 @@ export const skyBand = (elevationDeg: number): FixedSkyState =>
elevationDeg >= DAY_FROM ? 'day' : elevationDeg <= -DAY_FROM ? 'night' : 'dusk';
export const MOMENT_IDS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const;
export type MomentId = (typeof MOMENT_IDS)[number];
export type MomentId = typeof MOMENT_IDS[number];
/** What the viewer picked: the live sky, a named moment of today at the place, or a place-local date and minute of the day. */
export type SkyChoice =
@ -67,8 +67,7 @@ const wallAsUtc = (t: number, tz: string): number => {
});
return Date.UTC(v.year, v.month - 1, v.day, v.hour, v.minute, v.second);
};
const offsetAt = (t: number, tz: string): number =>
wallAsUtc(t, tz) - Math.floor(t / 1000) * 1000;
const offsetAt = (t: number, tz: string): number => wallAsUtc(t, tz) - Math.floor(t / 1000) * 1000;
const pad = (n: number, w = 2): string => String(n).padStart(w, '0');
const dateOf = (utcMs: number): string => {
@ -110,6 +109,12 @@ export function zonedInstant(date: string, minutes: number, tz: string): Date {
return new Date(valid.length ? valid[0] : guess - before);
}
/** The short name of the zone at that instant ('CET', 'GMT+5:45'): what the picker shows beside a place-local time. */
export const zoneName = (at: Date, tz: string): string =>
new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'short' })
.formatToParts(at)
.find((p) => p.type === 'timeZoneName')?.value ?? tz;
// ---------------------------------------------------------------------------------------------------------------- the named moments
const elevationAt = (place: Place, t: number): number => sunAt(place, new Date(t)).elevation;
@ -231,8 +236,8 @@ const clampDate = (date: string): string =>
!isDate(date) || date < FREE_DATE_MIN
? FREE_DATE_MIN
: date > FREE_DATE_MAX
? FREE_DATE_MAX
: date;
? FREE_DATE_MAX
: 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. */
@ -242,6 +247,21 @@ export function momentFor(choice: SkyChoice, place: Place, now: Date): Date {
return zonedInstant(clampDate(choice.date), clampMinutes(choice.minutes), place.tz);
}
/** The free moment (place-local date, minute to the 5 the slider steps) a choice is drawing now: where the picker opens from. */
export function seedFree(
choice: SkyChoice,
place: Place,
now: Date
): Extract<SkyChoice, { kind: 'free' }> {
if (choice.kind === 'free') return choice;
const at = momentFor(choice, place, now);
return {
kind: 'free',
date: localDate(at, place.tz),
minutes: Math.floor(localMinutes(at, place.tz) / 5) * 5,
};
}
/** 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. */
export function momentKey(choice: SkyChoice, place: Place, now: Date): string {
if (choice.kind === 'auto') return 'live';

View file

@ -62,7 +62,7 @@ describe('sceneThemeId, the theme the page wears', () => {
vi.useFakeTimers();
let hour = 12;
setSkyClock(() => atSolarTime(hour, 10));
const seen: string[] = [];
const seen: Array<string | undefined> = [];
const off = subscribeSky((s) => seen.push(s));
expect(getResolvedSkyState()).toBe('day');
hour = 0;

View file

@ -1,5 +1,11 @@
import { useEffect, useSyncExternalStore } from 'react';
import { getResolvedSkyState, getSkyChoice, subscribe } from '../features/scene/skyState';
import {
getResolvedSkyState,
getSkyChoice,
getSkyPlace,
subscribe,
} from '../features/scene/skyState';
import type { Place } from '../features/scene/ridge/view';
import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment';
import { ensureSkyPlace } from '../features/scene/skyPlace';
import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
@ -12,6 +18,9 @@ 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. */
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;