diff --git a/docs/gamecult/ridge-backdrop-target.md b/docs/gamecult/ridge-backdrop-target.md index 83e6b1ad..238dd71c 100644 --- a/docs/gamecult/ridge-backdrop-target.md +++ b/docs/gamecult/ridge-backdrop-target.md @@ -9,11 +9,11 @@ The live noise ridge is nearly invisible on a phone (about 1.35:1 against the da - One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser. - The ground under the authored 500 m near clip is the place's own DEM from 1 m, drawn by card 0 inside the silhouette of the terrain at the clip and riding card 0's slide; everything that bounds the view reads terrain at or beyond the clip: `r_max` is where the linear slide holds for the nearest solid terrain each card draws in each tile (a tile of near ground only binds at the clip, 500 m, where it is slid), and every bake keeps 150 rows under the horizon so the plane reaches the bottom of every viewport. - Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it. -- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI. +- Phone cost is bounded: no per-frame script for the ridge (one exception: while a finger or the mouse is down in the scene view, pointer events turn the heading and the heading owner re-issues the rig; the twinkle is the other), decoded size and fetched size gated in CI. - The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360. - Motion is derived, not authored: a card's scale and shift come each second from the heading, the camera's angle on its circle and the viewer's offset (one pose, one owner: `ridge/heading.ts`, whose every change starts a segment from the pose the view has, and whose eases keep each pose inside the baked bound) and the card's distance (`ridge/view.ts` `cardPose`), and ride the compositor as one animation per card. - The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause. -- A baked asset names its baker version, DEM source and licence in a validated manifest; the credits shown in the Sky menu come from the manifest. +- A baked asset names its baker version, DEM source and licence in a validated manifest; the terrain credit shown in the scene view's Place submenu comes from the manifest. ## Not in scope Button size (Void's). Patching the old noise-ridge path. Cone sampling. Live DEM access from the browser. diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index 746b45b9..ba4246cb 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -55,7 +55,7 @@ import { activateEstateRoom, awaitMyJoin } from './joinEstateRoom'; import { useEstate, useEstateRootId } from './useEstate'; import * as css from './EstateNavigator.css'; import { DeskEntry } from '../desk'; -import { SkyStateControl } from '../scene/SkyStateControl'; +import { SceneViewEntry } from '../scene/SceneViewEntry'; type IconSrc = ComponentProps['src']; @@ -389,7 +389,7 @@ export function EstateNavigator() { {title} - + - - + <> + {enabled && ( + + )} + + ); } diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 9679079f..f1e0d3ea 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -11,7 +11,7 @@ means "keep the CSS ground". Everything below this section describes the opt-in same keyframes as the cards; a residency tick or a reissue paints a new plate about the heading once it is within that margin of the plate's edge (or the speed asks for more slack) and swaps it in the same tick, keyed from the clock after the paint (the same sky at the same screen place, so nothing moves; the twinkle schedule runs over the catalogue, so a swap keeps which stars swing; the plate's backing store is capped at 3 Mpx, the pixel ratio lowering before the plate shrinks). Then come the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). A sky with no physical model is a gradient in the host canvas. - With no cards (the load failed) the scene shows the sky, stars and weather only, the plate facing the place's rest azimuth and staying. No script runs per frame except the twinkle, at most every 50 ms. + With no cards (the load failed) the scene shows the sky, stars and weather only, the plate facing the place's rest azimuth and staying. No script runs per frame except the twinkle, at most every 50 ms, and, only inside the scene view while a pointer is down, the pointer events that turn the heading (below). The host canvas and its parent must be positioned and the parent must clip (the plate is wider than the viewport); the canvas should fill the parent. A resize rebuilds it; so does a sky change (`index.ts`). - Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. @@ -86,6 +86,14 @@ sky. Rain is the gauge; cloud is an estimate from the global radiation against H 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). +## The scene view + +`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. + +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. + ## Entry points - `index.ts` `startBackgroundScene(config.backgroundScene, capabilities, options)` is the host's diff --git a/src/app/features/scene/SceneViewEntry.test.tsx b/src/app/features/scene/SceneViewEntry.test.tsx new file mode 100644 index 00000000..a7a4a9d6 --- /dev/null +++ b/src/app/features/scene/SceneViewEntry.test.tsx @@ -0,0 +1,18 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SceneViewEntry } from './SceneViewEntry'; + +const offered = vi.hoisted(() => ({ value: true })); +vi.mock('../../hooks/useSceneView', () => ({ useSceneViewOffered: () => offered.value })); + +describe('the scene view entry', () => { + it('is offered with the scene on', () => { + offered.value = true; + expect((SceneViewEntry() as { props: Record }).props['aria-label']).toBe( + 'Scene view' + ); + }); + it('is not offered when the scene tier is off', () => { + offered.value = false; + expect(SceneViewEntry()).toBeNull(); + }); +}); diff --git a/src/app/features/scene/SceneViewEntry.tsx b/src/app/features/scene/SceneViewEntry.tsx new file mode 100644 index 00000000..941b01b3 --- /dev/null +++ b/src/app/features/scene/SceneViewEntry.tsx @@ -0,0 +1,31 @@ +import React from 'react'; +import { Icon, IconButton, Icons } from 'folds'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { useSceneViewOffered } from '../../hooks/useSceneView'; +import { loadSceneView, openSceneView } from './sceneView'; + +/** + * The title-bar button that opens the scene view, the fullscreen view of the background scene with its own controls (sceneView.ts). A single button, not a + * row, so the bar still fits a 320 px phone beside the search button. The view's code loads when the button is hovered or focused. Not offered when the + * scene tier is off: there is no scene to look at. + */ +export function SceneViewEntry() { + const offered = useSceneViewOffered(); + if (!offered) return null; + const preload = () => { + loadSceneView().catch(() => undefined); // a failed chunk is asked for again when the view opens (SceneViewHost) + }; + return ( + + + + ); +} diff --git a/src/app/features/scene/SceneViewHost.test.tsx b/src/app/features/scene/SceneViewHost.test.tsx new file mode 100644 index 00000000..a322b01e --- /dev/null +++ b/src/app/features/scene/SceneViewHost.test.tsx @@ -0,0 +1,156 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { SceneViewHost, SceneViewLoading } from './SceneViewHost'; + +// The hooks are held still (view/SceneView.test.tsx): the element tree is read, effects are kept and run by the test. +const held = vi.hoisted(() => ({ + effects: [] as Array<() => unknown>, + open: true, + offered: true, + view: undefined as unknown, + closed: 0, + restored: 0, + sets: [] as unknown[], + loads: [] as Array<(m: unknown) => void>, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = () => [held.view, (v: unknown) => held.sets.push(v)]; + const useEffect = (fn: () => unknown) => { + held.effects.push(fn); + }; + return { ...actual, default: { ...actual, useState, useEffect }, useState, useEffect }; +}); +vi.mock('react-dom', () => ({ createPortal: (node: unknown) => node })); +vi.mock('../../hooks/useSceneView', () => ({ + useSceneViewState: () => ({ open: held.open, submenu: undefined }), + useSceneViewOffered: () => held.offered, +})); +vi.mock('./sceneView', () => ({ + closeSceneView: () => { + held.closed += 1; + }, + restoreEntryFocus: () => { + held.restored += 1; + }, + loadSceneViewOrClose: () => new Promise((res) => held.loads.push(res)), +})); + +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 []; +}; + +beforeEach(() => { + held.effects.length = 0; + held.open = true; + held.offered = true; + held.view = undefined; + held.closed = 0; + held.restored = 0; + held.sets.length = 0; + held.loads.length = 0; + vi.stubGlobal('document', { getElementById: () => ({}) }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the view while its code loads', () => { + it('shows a Return that closes the view, with the phone tap target', () => { + const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return'); + expect(String(ret?.props?.className)).toContain(PhoneHit); + (ret?.props?.onClick as () => void)(); + expect(held.closed).toBe(1); + }); + + it('closes on Escape, and takes its listener off', () => { + const on: Record void> = {}; + let off = 0; + vi.stubGlobal('window', { + addEventListener: (t: string, cb: (e: unknown) => void) => { + on[t] = cb; + }, + removeEventListener: () => { + off += 1; + }, + }); + SceneViewLoading(); + const cleanup = held.effects[0]() as () => void; + on.keydown({ key: 'a', stopPropagation: () => undefined }); + expect(held.closed).toBe(0); + on.keydown({ key: 'Escape', stopPropagation: () => undefined }); + expect(held.closed).toBe(1); + cleanup(); + expect(off).toBe(1); + }); + + it('the open host stands Return in the portal until the view is loaded', () => { + expect((SceneViewHost() as unknown as El).type).toBe(SceneViewLoading); + }); + + it('asks for the code when the view opens, and the failed load (which closes the view) is the loader, not the host', () => { + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(1); + }); +}); + +describe('the host and the focus', () => { + it('gives the entry its focus once the view is closed, and never while it is open', () => { + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.restored).toBe(0); + held.effects.length = 0; + held.open = false; + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.restored).toBe(1); + }); +}); + +describe('the view code arriving', () => { + const run = () => { + SceneViewHost(); + return held.effects.map((e) => e()).filter((c): c is () => void => typeof c === 'function'); + }; + it('is mounted when it arrives while the view is open', async () => { + const View = () => null; + run(); + held.loads[0]({ default: View }); + await Promise.resolve(); + await Promise.resolve(); + expect(held.sets).toEqual([{ View }]); + }); + it('is dropped when it arrives after the view closed again', async () => { + const cleanups = run(); + cleanups.forEach((c) => c()); + held.loads[0]({ default: () => null }); + await Promise.resolve(); + await Promise.resolve(); + expect(held.sets).toEqual([]); + }); +}); + +describe('the host', () => { + it('renders nothing and loads nothing while the view is closed', () => { + held.open = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(0); + expect(held.closed).toBe(0); + }); + + it('with the scene tier off an open view closes, shows nothing and loads nothing', () => { + held.offered = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.closed).toBe(1); + expect(held.loads).toHaveLength(0); + }); +}); diff --git a/src/app/features/scene/SceneViewHost.tsx b/src/app/features/scene/SceneViewHost.tsx new file mode 100644 index 00000000..ba299a25 --- /dev/null +++ b/src/app/features/scene/SceneViewHost.tsx @@ -0,0 +1,72 @@ +import React, { ComponentType, useEffect, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { Icon, IconButton, Icons } from 'folds'; +import { PhoneHit } from '../../styles/PhoneHit.css'; +import { useSceneViewOffered, useSceneViewState } from '../../hooks/useSceneView'; +import { closeSceneView, loadSceneViewOrClose, restoreEntryFocus } from './sceneView'; +import * as css from './sceneShell.css'; + +/** + * What stands in the portal while the view's code loads: Return and Escape, so the view can be left before the rest of it is there. The app behind is hidden + * and inert already, so without this the screen is blank. + */ +export function SceneViewLoading() { + useEffect(() => { + const onKey = (evt: KeyboardEvent) => { + if (evt.key === 'Escape') { + evt.stopPropagation(); + closeSceneView(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, []); + return ( + + + + ); +} + +/** + * The scene view (sceneView.ts) in the portal layer while it is open: over the scene, outside the app it hides. Its code is a chunk of its own: until it has + * loaded, `SceneViewLoading` is what is shown, and a failed load closes the view (`loadSceneViewOrClose`). The view is not offered with the scene tier off, so an + * open view that finds the tier off closes. + */ +export function SceneViewHost() { + const { open } = useSceneViewState(); + const offered = useSceneViewOffered(); + const [view, setView] = useState<{ View: ComponentType } | undefined>(); + const shown = open && offered; + + // The view is gone from the page (its focus trap with it) once `open` is false: only now can the entry take the focus and keep it. + useEffect(() => { + if (!open) restoreEntryFocus(); + }, [open]); + + useEffect(() => { + if (open && !offered) closeSceneView(); + }, [open, offered]); + + useEffect(() => { + if (!shown) return undefined; + let live = true; + loadSceneViewOrClose().then((m) => { + if (live && m) setView({ View: m.default }); + }); + return () => { + live = false; + }; + }, [shown]); + + const portal = document.getElementById('portalContainer'); + if (!shown || !portal) return null; + return createPortal(view ? : , portal); +} diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx deleted file mode 100644 index c8c5a374..00000000 --- a/src/app/features/scene/SkyStateControl.tsx +++ /dev/null @@ -1,282 +0,0 @@ -import React, { MouseEventHandler, useEffect, useRef, useState } from 'react'; -import { - Box, - config, - Icon, - IconButton, - Icons, - Menu, - MenuItem, - PopOut, - RectCords, - Text, -} from 'folds'; -import FocusTrap from 'focus-trap-react'; -import { stopPropagation } from '../../utils/keyboard'; -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, - STARS_CREDIT, - terrainCredit, - WEATHER_CREDIT, - WEATHER_CREDIT_URL, - WEATHER_DATASET, -} from './ridge/credits'; -import { useClientConfig } from '../../hooks/useClientConfig'; -import { PhoneHit } from '../../styles/PhoneHit.css'; - -export const MOMENT_LABEL: Record = { - 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); - -/** - * 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(onChange: (el: T) => void) { - const ref = useRef(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; - -/** 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((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((el) => { - at.current.minutes = Number(el.value); - onCommit({ kind: 'free', ...at.current }); - }); - const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz); - return ( - - - setMinutes(Number(evt.currentTarget.value))} - /> - - {hhmm(minutes)} {zone} - - - ); -} - -/** - * 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 choice = useSkyChoice(); - const drawn = useDrawnPlace(); - const [picking, setPicking] = useState(false); - const [cords, setCords] = useState(); - const backgroundScene = useClientConfig().backgroundScene; - - const placeId = backgroundScene?.place; - const place = drawn ?? FALLBACK_VIEW.place; - const [credit, setCredit] = useState(); - const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch'; - useEffect(() => { - if (!ridgeOn) return undefined; - let live = true; - loadManifest(import.meta.env.BASE_URL, placeId).then( - (m) => live && setCredit(terrainCredit(m)), - () => live && setCredit(undefined) - ); - return () => { - live = false; - }; - }, [ridgeOn, placeId]); - const open: MouseEventHandler = (evt) => { - setCords(evt.currentTarget.getBoundingClientRect()); - }; - - return ( - { - setCords(undefined); - setPicking(false); - }, - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => - evt.key === 'ArrowDown' && !(evt.target instanceof HTMLInputElement), - isKeyBackward: (evt: KeyboardEvent) => - evt.key === 'ArrowUp' && !(evt.target instanceof HTMLInputElement), - escapeDeactivates: stopPropagation, - }} - > - - - {MENU_CHOICES.map((c) => { - const checked = sameChoice(c, choice); - return ( - { - pickSkyChoice(c); - setCords(undefined); - }} - after={checked ? : undefined} - > - - {choiceLabel(c)} - - - ); - })} - setPicking(!picking)} - after={choice.kind === 'free' ? : undefined} - > - - Pick a moment - - - {picking && ( - - )} - {ridgeOn && ( - - - Data - - {credit && ( - - {credit} - - )} - - Datenquelle: GeoSphere Austria -{' '} - - {WEATHER_CREDIT_URL} - - . {WEATHER_DATASET}. - - - {STARS_CREDIT}. - - - {LINES_CREDIT}. - - - )} - - - - } - > - - - - - ); -} diff --git a/src/app/features/scene/cameraState.test.ts b/src/app/features/scene/cameraState.test.ts index c2f20d3d..6bbb9f02 100644 --- a/src/app/features/scene/cameraState.test.ts +++ b/src/app/features/scene/cameraState.test.ts @@ -45,6 +45,15 @@ describe('the viewer camera', () => { expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 1, offsetM: -30 }); }); + it('a reduced-motion visit starts still with the default speed and offset kept, which apply once a moving mode is chosen (ruling ridge-reduced-motion-starts-still)', () => { + reduced.matches = true; + expect(getCamera()).toEqual({ mode: 'still', speedDegPerS: 0.6, offsetM: 200 }); + expect(effectiveMode()).toBe('still'); + setCamera({ mode: 'both' }); + expect(getCamera()).toEqual({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + expect(effectiveMode()).toBe('both'); + }); + it('keeps each change per viewer, and tells listeners only of a change', () => { const cb = vi.fn(); subscribe(cb); diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index 7a0db7d9..cec2be88 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { atSolarTime } from './ridge/skyTestkit'; import type { Scene } from './Scene'; import { PREPARE_DEADLINE_MS, startBackgroundScene } from './index'; -import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState'; +import { getResolvedSkyState, getSkyPlace, setConstellationLines, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState'; import { skyBand } from './ridge/skyMoment'; import type { SkyChoice } from './ridge/skyMoment'; import { ridgeSkyFor } from './skyForState'; @@ -789,21 +789,21 @@ describe('the ridge cards and the live scene', () => { scene?.dispose(); }); - it('rebuilds the scene with the constellation lines when Night is re-picked while Night is the choice, and again to take them off', async () => { + it('rebuilds the scene with the constellation lines when they are switched on, and again to take them off', async () => { serve(); loader(); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); expect(createRidgeScene.mock.calls[0][0].lines).toBe(false); - pickSkyChoice(NIGHT); // from Auto: a choice, a frozen sky + setSkyChoice(NIGHT); // from Auto: a choice, a frozen sky await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); expect(createRidgeScene.mock.calls[1][0].lines).toBe(false); - pickSkyChoice(NIGHT); // re-picked: the lines + setConstellationLines(true); await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(3); expect(createRidgeScene.mock.calls[2][0].lines).toBe(true); - pickSkyChoice(NIGHT); + setConstellationLines(false); await flush(); expect(createRidgeScene.mock.calls[3][0].lines).toBe(false); scene?.dispose(); diff --git a/src/app/features/scene/ridge/credits.test.ts b/src/app/features/scene/ridge/credits.test.ts index bea5f04f..062939eb 100644 --- a/src/app/features/scene/ridge/credits.test.ts +++ b/src/app/features/scene/ridge/credits.test.ts @@ -1,6 +1,7 @@ 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, @@ -10,12 +11,13 @@ import { 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 Sky menu shows', () => { +describe('the credits the scene view shows', () => { it("are the sources' own", () => { expect(WEATHER_CREDIT).toBe(WEATHER_ATTRIBUTION); }); @@ -59,3 +61,10 @@ 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 49f2c5ba..8c94f27f 100644 --- a/src/app/features/scene/ridge/credits.ts +++ b/src/app/features/scene/ridge/credits.ts @@ -1,4 +1,4 @@ -// What the Ridge background owes its data sources, shown in the Sky menu (SkyStateControl). Plain strings in their own module so the +// 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 // manifest's own `attribution` (terrainCredit): the baker writes it, so no constant here can drift from the bake. import type { RidgeManifest } from './manifest'; @@ -24,3 +24,7 @@ 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/sceneShell.css.ts b/src/app/features/scene/sceneShell.css.ts index 18911a1b..2d2ef01d 100644 --- a/src/app/features/scene/sceneShell.css.ts +++ b/src/app/features/scene/sceneShell.css.ts @@ -1,4 +1,4 @@ -import { createVar, fallbackVar, globalStyle } from '@vanilla-extract/css'; +import { createVar, fallbackVar, globalStyle, style } from '@vanilla-extract/css'; import { color } from 'folds'; // While the background scene runs (html[data-scene], set by BackgroundScene) the signed-in shell @@ -28,3 +28,13 @@ globalStyle(':root[data-scene] #root', { const surfaceInkVar = createVar(); globalStyle(':root[data-scene] body', { vars: { [surfaceInkVar]: color.Surface.Container } }); export const surfaceInk = fallbackVar(surfaceInkVar, color.Surface.Container); + +// While the scene view is open (sceneView.ts) the app stays mounted, so the chat keeps its scroll and its composer, but it is hidden (and inert, set by sceneView.ts). +globalStyle(':root[data-scene-view] #root', { visibility: 'hidden' }); + +// Return while the scene view's code is still loading (SceneViewHost.tsx): the view's own rail is not there yet, so this one button stands where its Return will be. +export const LoadingReturn = style({ + position: 'fixed', + top: 'max(0.5rem, env(safe-area-inset-top))', + left: 'max(0.5rem, env(safe-area-inset-left))', +}); diff --git a/src/app/features/scene/sceneView.test.ts b/src/app/features/scene/sceneView.test.ts new file mode 100644 index 00000000..798c9aa5 --- /dev/null +++ b/src/app/features/scene/sceneView.test.ts @@ -0,0 +1,193 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getCamera, holdCamera, isHeld, resetCamera } from './cameraState'; +import { + SCENE_VIEW_ATTRIBUTE, + SCENE_VIEW_HISTORY_MARK, + closeSceneView, + getSceneView, + loadSceneView, + loadSceneViewOrClose, + restoreEntryFocus, + openSceneView, + setSubmenu, + subscribeSceneView, +} from './sceneView'; + +// No DOM here: the few things the module touches (, #root, the focused element, the history stack and the window's popstate) are stand-ins. +class Entry { + focused = 0; + focus() { + this.focused += 1; + } +} +const entryEl = new Entry(); +let attrs: Set; +let rootAttrs: Set; +let stack: Array | null>; +let pops: Set<() => void>; +let back: number; + +beforeEach(() => { + attrs = new Set(); + rootAttrs = new Set(); + stack = [{ idx: 0 }]; + pops = new Set(); + back = 0; + entryEl.focused = 0; + vi.stubGlobal('HTMLElement', Entry); + vi.stubGlobal('document', { + activeElement: entryEl, + documentElement: { + setAttribute: (k: string) => attrs.add(k), + removeAttribute: (k: string) => attrs.delete(k), + }, + getElementById: (id: string) => + id === 'root' + ? { + setAttribute: (k: string) => rootAttrs.add(k), + removeAttribute: (k: string) => rootAttrs.delete(k), + } + : null, + }); + const history = { + get state() { + return stack[stack.length - 1]; + }, + pushState: (s: Record) => stack.push(s), + back: () => { + back += 1; + stack.pop(); + [...pops].forEach((cb) => cb()); + }, + }; + vi.stubGlobal('window', { + history, + addEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.add(cb), + removeEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.delete(cb), + }); + vi.stubGlobal('localStorage', { + getItem: () => null, + setItem: () => undefined, + removeItem: () => undefined, + }); + resetCamera(); +}); + +afterEach(() => { + closeSceneView(); + vi.unstubAllGlobals(); +}); + +describe('the scene view', () => { + it('opens with one history entry that keeps what the router keeps, the app inert and the page marked', () => { + openSceneView(); + openSceneView(); + expect(getSceneView()).toEqual({ open: true, submenu: undefined }); + expect(stack).toHaveLength(2); + expect(stack[1]).toEqual({ idx: 0, [SCENE_VIEW_HISTORY_MARK]: true }); + expect(rootAttrs.has('inert')).toBe(true); + expect(attrs.has(SCENE_VIEW_ATTRIBUTE)).toBe(true); + }); + + it('the Return icon closes it, takes its entry off the stack, frees the app and owes the focus to the entry', () => { + openSceneView(); + closeSceneView(); + expect(getSceneView().open).toBe(false); + expect(stack).toHaveLength(1); + expect(back).toBe(1); + expect(rootAttrs.size).toBe(0); + expect(attrs.size).toBe(0); + closeSceneView(); + expect(back).toBe(1); + }); + + it("the browser's Back button closes it (the entry is already gone), once", () => { + openSceneView(); + const seen = vi.fn(); + subscribeSceneView(seen); + window.history.back(); + expect(getSceneView().open).toBe(false); + expect(stack).toHaveLength(1); + expect(back).toBe(1); // that one was the browser's; the close did not go back again + expect(seen).toHaveBeenCalledTimes(1); + expect(rootAttrs.size).toBe(0); + }); + + it('shows one submenu at a time, and choosing the one shown closes its panel', () => { + setSubmenu('view'); + expect(getSceneView().submenu).toBeUndefined(); // closed: nothing to show + openSceneView(); + setSubmenu('view'); + expect(getSceneView().submenu).toBe('view'); + setSubmenu('time'); + expect(getSceneView().submenu).toBe('time'); + setSubmenu('time'); + expect(getSceneView().submenu).toBeUndefined(); + setSubmenu('sky'); + closeSceneView(); + openSceneView(); + expect(getSceneView().submenu).toBeUndefined(); + }); + + it('Return resumes a rotation a manual turn held, through the camera store', () => { + openSceneView(); + holdCamera(0); + expect(isHeld()).toBe(true); + const mode = getCamera().mode; + closeSceneView(); + expect(isHeld()).toBe(false); + expect(getCamera().mode).toBe(mode); + }); +}); + +describe('the view code failing to load', () => { + it('closes an open view: the app is live again, nothing stays hidden, and the next open can ask again', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + openSceneView(); + const got = await loadSceneViewOrClose(() => Promise.reject(new Error('chunk'))); + expect(got).toBeUndefined(); + expect(getSceneView().open).toBe(false); + expect(rootAttrs.size).toBe(0); + expect(attrs.size).toBe(0); + openSceneView(); + expect(getSceneView().open).toBe(true); + }); + + it('a load that succeeds leaves the view open and hands back the module', async () => { + openSceneView(); + const mod = { default: () => null } as unknown as Awaited>; + expect(await loadSceneViewOrClose(() => Promise.resolve(mod))).toBe(mod); + expect(getSceneView().open).toBe(true); + }); +}); + +describe('the focus after a close', () => { + const closes: Array<[string, () => void]> = [ + ['Return', () => closeSceneView()], + ['Escape (the view calls closeSceneView)', () => closeSceneView()], + ['Back', () => window.history.back()], + ]; + it.each(closes)( + '%s: the close does not touch the focus (the trap is still mounted); restoreEntryFocus gives it to the entry, once', + (_name, close) => { + openSceneView(); + close(); + expect(getSceneView().open).toBe(false); + expect(entryEl.focused).toBe(0); + restoreEntryFocus(); + expect(entryEl.focused).toBe(1); + restoreEntryFocus(); + expect(entryEl.focused).toBe(1); + } + ); + + it('nothing is owed while the view is open, and a reopen forgets an unclaimed focus', () => { + openSceneView(); + restoreEntryFocus(); + expect(entryEl.focused).toBe(0); + closeSceneView(); + openSceneView(); + restoreEntryFocus(); + expect(entryEl.focused).toBe(0); + }); +}); diff --git a/src/app/features/scene/sceneView.ts b/src/app/features/scene/sceneView.ts new file mode 100644 index 00000000..00027d7e --- /dev/null +++ b/src/app/features/scene/sceneView.ts @@ -0,0 +1,129 @@ +// The scene view: whether the fullscreen view of the scene is open, and which submenu it shows. The one owner of both (ruling ridge-scene-view-fullscreen). Opening +// pushes one history entry, so the browser's Back button, Escape and the Return icon are all the same act, closing; while it is open the app (#root) is inert and +// hidden but stays mounted, so the chat keeps its scroll and its composer. Closing is Return: the rotation a manual turn held resumes through `cameraState` +// (ruling ridge-view-turn-handback). The view's controls write the stores that own what they set (cameraState.ts, skyState.ts) and hold no copy of them. +// Main-chunk safe (no React, no ridge code), as skyState.ts and cameraState.ts are. +import { getCamera, setCamera } from './cameraState'; + +export type Submenu = 'view' | 'time' | 'sky' | 'place'; + +export interface SceneViewState { + open: boolean; + /** The submenu whose panel is up, if any: one at a time. */ + submenu: Submenu | undefined; +} + +/** Set on while the view is open: the shell is hidden and the view is the only thing over the scene. */ +export const SCENE_VIEW_ATTRIBUTE = 'data-scene-view'; +/** The mark the view's history entry carries beside whatever the router keeps in `history.state`. */ +export const SCENE_VIEW_HISTORY_MARK = 'ratatoskrSceneView'; + +let state: SceneViewState = { open: false, submenu: undefined }; +const listeners = new Set<() => void>(); +/** The control that opened the view. */ +let entry: HTMLElement | null = null; +/** The control that is owed the focus: set by a close, taken by `restoreEntryFocus` once the view's focus trap is gone. */ +let owed: HTMLElement | null = null; +/** Whether this view pushed a history entry that is still on top of the stack. */ +let pushed = false; + +export const getSceneView = (): SceneViewState => state; + +export const subscribeSceneView = (cb: () => void): (() => void) => { + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +}; + +const set = (next: SceneViewState): void => { + state = next; + [...listeners].forEach((cb) => cb()); +}; + +const root = (): HTMLElement | null => document.getElementById('root'); + +/** Browser Back (or Forward over the entry) while the view is open: it is Return, and the entry is already gone. */ +const onPopState = (): void => { + pushed = false; + finish(); +}; + +/** Open the view: one history entry, the app inert and hidden behind it. A second call while open changes nothing. */ +export function openSceneView(): void { + if (state.open) return; + entry = document.activeElement instanceof HTMLElement ? document.activeElement : null; + owed = null; + try { + window.history.pushState( + { ...(window.history.state ?? {}), [SCENE_VIEW_HISTORY_MARK]: true }, + '' + ); + pushed = true; + } catch { + pushed = false; // no history to push to: Return and Escape still close it + } + window.addEventListener('popstate', onPopState); + document.documentElement.setAttribute(SCENE_VIEW_ATTRIBUTE, ''); + root()?.setAttribute('inert', ''); + set({ open: true, submenu: undefined }); +} + +/** Everything closing does, whichever way it came: the app live again, the rotation a manual turn held resumed, the focus owed back to the entry (`restoreEntryFocus`). */ +function finish(): void { + if (!state.open) return; + window.removeEventListener('popstate', onPopState); + document.documentElement.removeAttribute(SCENE_VIEW_ATTRIBUTE); + root()?.removeAttribute('inert'); + // Picking the mode already chosen ends a hold (cameraState.ts): the scene behind the chat turns again from where the viewer left it. + setCamera({ mode: getCamera().mode }); + owed = entry; + entry = null; + set({ open: false, submenu: undefined }); +} + +/** + * Give the focus back to the control that opened the view. The one owner of that focus, called by the host once the view has unmounted: while the view's focus + * trap is still mounted it pulls focus back to Return, and its unmount then drops it to the body. Nothing is owed while the view is open or once it has been + * restored, so a call at any other time changes nothing. + */ +export function restoreEntryFocus(): void { + const to = owed; + owed = null; + to?.focus?.(); +} + +/** Return: close the view, and take its history entry off the stack when it is still the top one. */ +export function closeSceneView(): void { + if (!state.open) return; + const wasPushed = pushed; + finish(); // takes the popstate listener off first, so the back below does not close twice + if (wasPushed && window.history.state?.[SCENE_VIEW_HISTORY_MARK]) window.history.back(); + pushed = false; +} + +/** Show a submenu's panel, or none; choosing the one already shown closes its panel. */ +export function setSubmenu(submenu: Submenu | undefined): void { + if (!state.open) return; + set({ open: true, submenu: submenu === state.submenu ? undefined : submenu }); +} + +/** The view's code, a chunk of its own: asked for when the entry is hovered or focused, and by the host when the view opens. */ +export const loadSceneView = () => import('./view/SceneView'); + +/** + * The view's code for the host: a failed load closes the view (the app live again, the focus back on the entry), so nothing stays hidden behind a view that + * will not come. The next open asks for the chunk again. Resolves to the module, or undefined when the load failed. + */ +export async function loadSceneViewOrClose( + load: typeof loadSceneView = loadSceneView +): Promise> | undefined> { + try { + return await load(); + } catch (e) { + // eslint-disable-next-line no-console + console.warn('Scene view unavailable:', e); + closeSceneView(); + return undefined; + } +} diff --git a/src/app/features/scene/skyForState.test.ts b/src/app/features/scene/skyForState.test.ts index 8523443a..3ebe988d 100644 --- a/src/app/features/scene/skyForState.test.ts +++ b/src/app/features/scene/skyForState.test.ts @@ -150,8 +150,7 @@ describe('the rebuild key and the constellation lines', () => { const now = atSolarTime(12, 0); const off = f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now); const dayOff = f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now); - st.pickSkyChoice(named('night')); - st.pickSkyChoice(named('night')); + st.setConstellationLines(true); expect(f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now)).toBe(`${off}:lines`); expect(f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now)).toBe(dayOff); }); diff --git a/src/app/features/scene/skyState.test.ts b/src/app/features/scene/skyState.test.ts index 73576ed8..ffd25717 100644 --- a/src/app/features/scene/skyState.test.ts +++ b/src/app/features/scene/skyState.test.ts @@ -335,54 +335,58 @@ describe('Auto follows the clock', () => { }); }); -describe('the constellation lines toggle', () => { +describe('the constellation lines', () => { let storage: ReturnType; beforeEach(() => { storage = fakeStorage(); vi.stubGlobal('localStorage', storage); }); - it('are off by default, and a first pick of Night is a plain choice that leaves them off', async () => { + it('are off by default, and picking Night is a plain choice that leaves them off', async () => { const m = await fresh(); expect(m.getConstellationLines()).toBe(false); - m.pickSkyChoice(night); + m.setSkyChoice(night); expect(m.getSkyChoice()).toEqual(night); expect(m.getConstellationLines()).toBe(false); }); - it('re-picking Night while the choice is Night toggles them, tells the listeners, and keeps the choice', async () => { + it('picking Night while the choice is Night does nothing: no toggle, no notice', async () => { const m = await fresh(); m.setSkyPlace(VIENNA); - m.pickSkyChoice(night); + m.setSkyChoice(night); const cb = vi.fn(); m.subscribe(cb); - m.pickSkyChoice(night); + m.setSkyChoice(night); + m.setSkyChoice(night); + expect(m.getConstellationLines()).toBe(false); + expect(cb).not.toHaveBeenCalled(); + expect(m.getSkyChoice()).toEqual(night); + }); + + it('setConstellationLines sets them, tells the listeners once per change, and keeps the choice', async () => { + const m = await fresh(); + m.setSkyPlace(VIENNA); + m.setSkyChoice(night); + const cb = vi.fn(); + m.subscribe(cb); + m.setConstellationLines(true); + m.setConstellationLines(true); expect(m.getConstellationLines()).toBe(true); expect(cb.mock.calls).toEqual([['night']]); expect(m.getSkyChoice()).toEqual(night); - m.pickSkyChoice(night); + m.setConstellationLines(false); expect(m.getConstellationLines()).toBe(false); expect(cb).toHaveBeenCalledTimes(2); }); - it('are not toggled by re-picking any other choice, nor by picking Night from Auto that is drawing night', async () => { - const m = await fresh(); - m.pickSkyChoice(noon); - m.pickSkyChoice(noon); - expect(m.getConstellationLines()).toBe(false); - m.setSkyClock(() => new Date('2026-12-04T00:00:00Z')); - m.pickSkyChoice(auto); - m.pickSkyChoice(night); - expect(m.getConstellationLines()).toBe(false); - }); - it('persist per viewer, and come back from storage', async () => { const m = await fresh(); - m.pickSkyChoice(night); - m.pickSkyChoice(night); + m.setConstellationLines(true); expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on'); const again = await fresh(); expect(again.getConstellationLines()).toBe(true); + again.setConstellationLines(false); + expect(storage.data.get(again.SKY_LINES_KEY)).toBe('off'); }); it('survive a refused storage: they hold for the page and read as off from a broken store', async () => { @@ -399,8 +403,7 @@ describe('the constellation lines toggle', () => { }); const m = await fresh(); expect(m.getConstellationLines()).toBe(false); - m.pickSkyChoice(night); - m.pickSkyChoice(night); + m.setConstellationLines(true); expect(m.getConstellationLines()).toBe(true); }); }); diff --git a/src/app/features/scene/skyState.ts b/src/app/features/scene/skyState.ts index 0551b021..5042f175 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -34,7 +34,7 @@ export function parseSkyChoice(raw: unknown): SkyChoice | undefined { const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b); -// The sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon. +// The old sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon. const OLD_KEY = 'ratatoskr.skyState'; const FROM_OLD = new Map([ ['auto', AUTO], @@ -69,7 +69,7 @@ function load(): SkyChoice { let clock: () => Date = () => new Date(); -/** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */ +/** The constellation lines: on or off, per viewer, off by default; set by `setConstellationLines`. */ export const SKY_LINES_KEY = 'ratatoskr.skyLines'; let lines: boolean | undefined; @@ -165,22 +165,18 @@ export function setSkyPlace(p: Place | undefined): void { } /** - * A pick in the sky menu. Picking a choice sets it; picking Night while the choice already is Night toggles the constellation lines, which - * listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag). + * The constellation lines on or off (the Sky submenu of the scene view, ruling ridge-scene-view-submenus): per viewer, stored. Listeners hear it as a sky change + * (the scene is rebuilt for it: `ridgeSkyKey` carries the flag), once, and only when the flag moved. This is the one setter; picking Night again sets nothing. */ -export function pickSkyChoice(c: SkyChoice): void { - const now = getSkyChoice(); - if (c.kind === 'named' && c.id === 'night' && now.kind === 'named' && now.id === 'night') { - lines = !getConstellationLines(); - try { - localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off'); - } catch { - // Storage is refused: the lines hold for this page load only. - } - emit(); - return; +export function setConstellationLines(on: boolean): void { + if (getConstellationLines() === on) return; + lines = on; + try { + localStorage.setItem(SKY_LINES_KEY, on ? 'on' : 'off'); + } catch { + // Storage is refused: the lines hold for this page load only. } - setSkyChoice(c); + emit(); } /** 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. */ diff --git a/src/app/features/scene/view/PlaceSubmenu.test.tsx b/src/app/features/scene/view/PlaceSubmenu.test.tsx new file mode 100644 index 00000000..30be0a52 --- /dev/null +++ b/src/app/features/scene/view/PlaceSubmenu.test.tsx @@ -0,0 +1,52 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { parseManifest } from '../ridge/manifest'; +import { wireManifest } from '../ridge/manifest.fixture'; +import { FALLBACK_VIEW } from '../ridge/view'; +import { LINES_CREDIT, STARS_CREDIT, WEATHER_CREDIT_URL } from '../ridge/credits'; +import { PlaceSubmenu } 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 })); + +/** Every string reachable through any prop of the element tree. */ +const strings = (node: unknown): string[] => { + if (typeof node === 'string') return [node]; + if (Array.isArray(node)) return node.flatMap(strings); + if (node && typeof node === 'object' && 'props' in node) + return Object.values((node as { props: object }).props).flatMap(strings); + return []; +}; +const text = (node: unknown) => strings(node).join(' '); +const manifest = parseManifest(wireManifest(), 'http://x/ridge/vienna/'); + +beforeEach(() => { + held.place = FALLBACK_VIEW.place; +}); + +describe('the credits (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); + expect(t).toContain(STARS_CREDIT); + expect(t).toContain(LINES_CREDIT); + }); + + it('Sky carries only the lines switch and its note: no credit of any wording', () => { + expect(strings(SkySubmenu()).filter((x) => /\s/.test(x))).toEqual([ + 'Constellation lines', + 'Drawn over the stars of a night sky.', + ]); + }); + + 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' }; + 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 + }); +}); diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx new file mode 100644 index 00000000..dfeaba66 --- /dev/null +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -0,0 +1,53 @@ +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 { FALLBACK_VIEW } from '../ridge/view'; + +/** + * 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. + */ +export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined }) { + const place = useDrawnPlace() ?? FALLBACK_VIEW.place; + const credit = terrainCredit(manifest); + return ( + + {place.id} + + + Data + + {credit && ( + + {credit} + + )} + + {STARS_CREDIT}. + + + {LINES_CREDIT}. + + {weatherServes(place) && ( + + Datenquelle: GeoSphere Austria -{' '} + + {WEATHER_CREDIT_URL} + + . {WEATHER_DATASET}. + + )} + + + ); +} diff --git a/src/app/features/scene/view/SceneView.css.ts b/src/app/features/scene/view/SceneView.css.ts new file mode 100644 index 00000000..26699f00 --- /dev/null +++ b/src/app/features/scene/view/SceneView.css.ts @@ -0,0 +1,80 @@ +import { style } from '@vanilla-extract/css'; +import { color, config } from 'folds'; +import { PLATE_TINT, SKY_PLATE_FALLBACK } from '../skyPlate'; +import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize'; + +// The fullscreen scene view (sceneView.ts): the app is hidden behind it, so what is left over the scene is a turning surface and, top left, an icon rail and one +// panel. The rail and the panel are plates, blurred and tinted toward the sky like the chat bubbles (skyPlate.css.ts, PLATE_TINT), so their text reads over any sky. +const fill = `var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`; +const text = `var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`; +const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`; +const GUTTER = 'max(0.5rem, env(safe-area-inset-top))'; + +export const Root = style({ + position: 'fixed', + inset: 0, +}); + +/** The whole viewport: a drag, a wheel or a swipe on it turns the view. A touch is never the page's (there is none to scroll). */ +export const Surface = style({ + position: 'absolute', + inset: 0, + touchAction: 'none', + overscrollBehavior: 'none', + userSelect: 'none', + cursor: 'grab', + selectors: { '&:active': { cursor: 'grabbing' } }, +}); + +/** How much of the rail and the panel is left while a finger is down: they step out of the way of the turn (ruling ridge-view-phone-one-finger). */ +export const TURNING_CHROME_OPACITY = 0.12; + +/** The rail and the panel, top left. It takes no pointer itself, so a drag over its gaps turns the view; its plates do. It fades while a finger is down. */ +export const Chrome = style({ + position: 'absolute', + top: GUTTER, + left: `max(0.5rem, env(safe-area-inset-left))`, + display: 'flex', + alignItems: 'flex-start', + gap: config.space.S200, + pointerEvents: 'none', + transition: 'opacity 150ms', + selectors: { [`${Root}[data-turning="true"] &`]: { opacity: TURNING_CHROME_OPACITY } }, +}); + +const Plate = style({ + pointerEvents: 'auto', + backgroundColor: [fill, `color-mix(in srgb, ${fill} ${PLATE_TINT * 100}%, transparent)`], + backdropFilter: 'blur(12px)', + WebkitBackdropFilter: 'blur(12px)', + color: text, + borderRadius: config.radii.R400, + vars: { + [color.Background.OnContainer]: text, + [color.Surface.OnContainer]: text, + [color.SurfaceVariant.OnContainer]: text, + }, +}); + +export const Rail = style([ + Plate, + { + display: 'flex', + flexDirection: 'column', + gap: config.space.S100, + padding: config.space.S100, + }, +]); + +export const Panel = style([ + Plate, + { + boxSizing: 'border-box', + width: '22rem', + maxWidth: 'calc(100vw - 5.5rem)', + maxHeight: `calc(100dvh - 2 * ${GUTTER})`, + overflowY: 'auto', + padding: config.space.S300, + '@media': { [PHONE]: { width: 'calc(100vw - 5.5rem)' } }, + }, +]); diff --git a/src/app/features/scene/view/SceneView.test.tsx b/src/app/features/scene/view/SceneView.test.tsx new file mode 100644 index 00000000..9d6a24f9 --- /dev/null +++ b/src/app/features/scene/view/SceneView.test.tsx @@ -0,0 +1,241 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import SceneView, { Rail, SUBMENUS } from './SceneView'; +import { TURNING_CHROME_OPACITY } from './SceneView.css'; + +// 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(() => ({ + effects: [] as Array<() => unknown>, + submenu: undefined as unknown, + closed: 0, + picked: [] as unknown[], + turning: [] as boolean[], + turner: [] as Array<[string, ...unknown[]]>, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => [ + typeof init === 'function' ? (init as () => unknown)() : init, + (v: unknown) => typeof v === 'boolean' && held.turning.push(v), + ]; + const useRef = (init: unknown) => ({ current: init }); + const useMemo = (fn: () => unknown) => fn(); + const useEffect = (fn: () => unknown) => { + held.effects.push(fn); + }; + return { + ...actual, + default: { ...actual, useState, useRef, useEffect, useMemo }, + useState, + useRef, + useEffect, + useMemo, + }; +}); +vi.mock('../../../hooks/useSceneView', () => ({ + useSceneViewState: () => ({ open: true, submenu: held.submenu }), + useRidgeManifest: () => undefined, +})); +vi.mock('../sceneView', () => ({ + closeSceneView: () => { + held.closed += 1; + }, + setSubmenu: (s: unknown) => held.picked.push(s), +})); +vi.mock('./turning', () => ({ + pxPerDegreeOf: () => 20, + createTurner: () => ({ + down: (x: number) => held.turner.push(['down', x]), + move: (x: number) => held.turner.push(['move', x]), + up: () => held.turner.push(['up']), + wheel: (dx: number) => held.turner.push(['wheel', dx]), + key: () => false, + }), +})); +vi.mock('focus-trap-react', () => ({ default: ({ children }: { children: unknown }) => children })); + +type El = { type?: unknown; ref?: unknown; key?: 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 labels = (els: El[]) => els.map((e) => e.props?.['aria-label']).filter(Boolean); + +beforeEach(() => { + held.effects.length = 0; + held.submenu = undefined; + held.closed = 0; + held.picked.length = 0; + held.turning.length = 0; + held.turner.length = 0; + vi.stubGlobal('window', { + innerWidth: 1280, + innerHeight: 720, + addEventListener: () => undefined, + removeEventListener: () => undefined, + }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('the rail', () => { + const rail = () => + walk( + Rail({ + items: SUBMENUS, + active: undefined, + onReturn: () => undefined, + onPick: () => undefined, + }) + ); + + it('lists Return first, then View, Time, Sky and Place, as a vertical toolbar', () => { + const els = rail(); + expect(els[0].props).toMatchObject({ role: 'toolbar', 'aria-orientation': 'vertical' }); + expect( + els.filter((e) => typeof e.props?.label === 'string').map((e) => e.props?.label) + ).toEqual(['Return', 'View', 'Time', 'Sky', 'Place']); + }); + + it('every rail icon is an IconButton carrying PhoneHit, with a label and a roving tab stop on Return', () => { + const buttons = rail() + .filter((e) => typeof e.props?.label === 'string') + .map((e) => + walk((e.type as (p: unknown) => unknown)(e.props)).find( + (x) => x.props?.className === PhoneHit + ) + ); + expect(buttons).toHaveLength(5); + buttons.forEach((b) => expect(b?.props?.['aria-label']).toBeTruthy()); + expect(buttons.map((b) => b?.props?.tabIndex)).toEqual([0, -1, -1, -1, -1]); + }); + + it('marks the submenu whose panel is up, and Return and a pick go to their handlers', () => { + const onPick = vi.fn(); + const onReturn = vi.fn(); + const els = walk(Rail({ items: SUBMENUS, active: 'time', onReturn, onPick })); + const item = (label: string) => + els.find((e) => e.props?.label === label)?.props as Record; + expect(['View', 'Time', 'Sky', 'Place'].map((l) => item(l).pressed)).toEqual([ + false, + true, + false, + false, + ]); + (item('Return').onClick as () => void)(); + (item('Sky').onClick as () => void)(); + expect(onReturn).toHaveBeenCalledOnce(); + expect(onPick).toHaveBeenCalledWith('sky'); + }); +}); + +describe('the view', () => { + const tree = () => walk(SceneView()); + const panels = () => tree().filter((e) => e.type === 'section'); + + it('shows no panel until a submenu is picked, then exactly one', () => { + expect(panels()).toHaveLength(0); + for (const s of ['view', 'time', 'sky', 'place']) { + held.submenu = s; + expect(panels()).toHaveLength(1); + } + }); + + it('a drag over the rail or its panel does not turn the view: the turning surface holds neither', () => { + held.submenu = 'view'; + const els = walk(SceneView()); + const surface = els.find((e) => typeof e.props?.onPointerDown === 'function') as El; + expect(walk(surface.props?.children)).toEqual([]); + expect(labels(walk(surface))).toEqual([]); + // the chrome is a sibling of the surface, so a pointer on a plate never reaches the surface's handlers + const root = els.find((e) => e.props?.['data-turning'] !== undefined) as El; + const kids = (root.props?.children as El[]).filter(Boolean); + expect(kids).toHaveLength(2); + expect(kids[0]).toBe(surface); + }); + + it('Escape is Return: the key listener closes the view', () => { + const listeners: Record void> = {}; + vi.stubGlobal('window', { + innerWidth: 1280, + innerHeight: 720, + addEventListener: (t: string, cb: (e: unknown) => void) => { + listeners[t] = cb; + }, + removeEventListener: () => undefined, + }); + SceneView(); + held.effects.forEach((run) => run()); + listeners.keydown({ key: 'Escape', stopPropagation: () => undefined }); + expect(held.closed).toBe(1); + }); +}); + +describe('one finger on the phone (ruling ridge-view-phone-one-finger)', () => { + const surface = () => + walk(SceneView()).find((e) => typeof e.props?.onPointerDown === 'function') as El; + const on = (name: string, evt: Record) => + (surface().props?.[name] as (e: unknown) => void)({ + currentTarget: { setPointerCapture: () => undefined }, + pointerId: 1, + pointerType: 'touch', + isPrimary: true, + button: 0, + clientX: 0, + clientY: 0, + ...evt, + }); + + it('the rail and the panel fade while a finger is down and come back when it lifts', () => { + expect(TURNING_CHROME_OPACITY).toBeGreaterThan(0); + expect(TURNING_CHROME_OPACITY).toBeLessThan(0.5); + on('onPointerDown', { clientX: 100 }); + on('onPointerUp', {}); + on('onPointerDown', { clientX: 100 }); + on('onPointerCancel', {}); + expect(held.turning).toEqual([true, false, true, false]); + }); + + it('only horizontal movement turns: the vertical is never given to the turner', () => { + on('onPointerDown', { clientX: 100, clientY: 50 }); + on('onPointerMove', { clientX: 140, clientY: 900 }); + on('onPointerMove', { clientX: 140, clientY: -900 }); + expect(held.turner).toEqual([['down', 100], ['move', 140], ['move', 140]]); + held.turner.length = 0; + on('onWheel', { deltaX: 2, deltaY: 90 }); + expect(held.turner).toEqual([]); // a mostly vertical wheel is not a turn either + }); + + it('a second finger (not the primary pointer) starts nothing', () => { + on('onPointerDown', { isPrimary: false, clientX: 100 }); + expect(held.turner).toEqual([]); + expect(held.turning).toEqual([]); + }); + + it('a mouse turns only with its main button', () => { + on('onPointerDown', { pointerType: 'mouse', button: 2, clientX: 100 }); + expect(held.turner).toEqual([]); + on('onPointerDown', { pointerType: 'mouse', button: 0, clientX: 100 }); + expect(held.turner).toEqual([['down', 100]]); + }); +}); + +describe('the chrome styles (a vanilla-extract rule cannot be read back, so the source is)', () => { + const css = readFileSync(join(__dirname, 'SceneView.css.ts'), 'utf8'); + it('the fade rule uses the constant the test above bounds', () => { + expect(css).toMatch(/data-turning="true"] &`]: { opacity: TURNING_CHROME_OPACITY }/); + }); + it('the chrome takes no pointer itself, so a drag over its gaps turns the view; its plates do', () => { + const chrome = css.slice(css.indexOf('export const Chrome'), css.indexOf('const Plate')); + expect(chrome).toContain("pointerEvents: 'none'"); + const plate = css.slice(css.indexOf('const Plate'), css.indexOf('export const Rail')); + expect(plate).toContain("pointerEvents: 'auto'"); + }); +}); diff --git a/src/app/features/scene/view/SceneView.tsx b/src/app/features/scene/view/SceneView.tsx new file mode 100644 index 00000000..854320b5 --- /dev/null +++ b/src/app/features/scene/view/SceneView.tsx @@ -0,0 +1,236 @@ +import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from 'react'; +import { Icon, IconButton, Icons } from 'folds'; +import FocusTrap from 'focus-trap-react'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import { useRidgeManifest, useSceneViewState } from '../../../hooks/useSceneView'; +import { closeSceneView, setSubmenu } from '../sceneView'; +import type { Submenu } from '../sceneView'; +import { FALLBACK_VIEW } from '../ridge/view'; +import * as css from './SceneView.css'; +import { createTurner, pxPerDegreeOf } from './turning'; +import { PlaceSubmenu } from './PlaceSubmenu'; +import { SkySubmenu } from './SkySubmenu'; +import { TimeSubmenu } from './TimeSubmenu'; +import { ViewSubmenu } from './ViewSubmenu'; + +type IconSrc = React.ComponentProps['src']; + +/** The rail after Return, in order. */ +export const SUBMENUS: ReadonlyArray<{ id: Submenu; label: string; icon: IconSrc }> = [ + { id: 'view', label: 'View', icon: Icons.Eye }, + { id: 'time', label: 'Time', icon: Icons.Clock }, + { id: 'sky', label: 'Sky', icon: Icons.Star }, + { id: 'place', label: 'Place', icon: Icons.Pin }, +]; + +/** One icon of the rail: 44 px to tap on a phone (PhoneHit). */ +function RailButton({ + label, + icon, + pressed, + tabIndex, + buttonRef, + onClick, +}: { + label: string; + icon: IconSrc; + pressed?: boolean; + tabIndex: number; + buttonRef: (el: HTMLButtonElement | null) => void; + onClick: () => void; +}) { + return ( + + + + ); +} + +/** + * The icon rail, a vertical toolbar: Return first, then a submenu each. Roving focus: one stop in the Tab order, the arrow keys (Home, End) move along it. + * `active` is the submenu whose panel is up. + */ +export function Rail({ + items, + active, + onReturn, + onPick, +}: { + items: typeof SUBMENUS; + active: Submenu | undefined; + onReturn: () => void; + onPick: (id: Submenu) => void; +}) { + const [stop, setStop] = useState(0); + const buttons = useRef>([]); + const count = items.length + 1; + const goTo = (to: number) => { + const next = (to + count) % count; + setStop(next); + buttons.current[next]?.focus(); + }; + const onKeyDown = (evt: KeyboardEvent) => { + const moves: Record = { + ArrowDown: stop + 1, + ArrowUp: stop - 1, + Home: 0, + End: count - 1, + }; + const to = moves[evt.key]; + if (typeof to !== 'number') return; + evt.preventDefault(); + goTo(to); + }; + return ( +
+ { + buttons.current[0] = el; + }} + onClick={onReturn} + /> + {items.map((item, i) => ( + { + buttons.current[i + 1] = el; + }} + onClick={() => { + setStop(i + 1); + onPick(item.id); + }} + /> + ))} +
+ ); +} + +const typing = (t: EventTarget | null): boolean => + t instanceof HTMLInputElement || + t instanceof HTMLSelectElement || + t instanceof HTMLTextAreaElement; + +/** + * The scene view (sceneView.ts opens it): the whole viewport is a surface that turns the view by hand, and over it, top left, the rail of submenus and the + * one panel that is up. Return, Escape and the browser's Back all close it. The chat behind it stays mounted; nothing here navigates. + */ +export default function SceneView() { + const { submenu } = useSceneViewState(); + const manifest = useRidgeManifest(); + const surface = useRef(null); + const [turning, setTurning] = useState(false); + const [size, setSize] = useState(() => ({ w: window.innerWidth, h: window.innerHeight })); + + useEffect(() => { + const read = () => { + const el = surface.current; + setSize({ + w: el?.clientWidth || window.innerWidth, + h: el?.clientHeight || window.innerHeight, + }); + }; + read(); + window.addEventListener('resize', read); + return () => window.removeEventListener('resize', read); + }, []); + + // The turner reads the viewport and the place at each event, so a resize or a late manifest changes nothing it holds. + const latest = useRef({ manifest, size }); + latest.current = { manifest, size }; + const turner = useMemo( + () => + createTurner(() => + pxPerDegreeOf( + latest.current.manifest?.view ?? FALLBACK_VIEW, + latest.current.size.w, + latest.current.size.h + ) + ), + [] + ); + + useEffect(() => { + const onKey = (evt: globalThis.KeyboardEvent) => { + if (evt.key === 'Escape') { + evt.stopPropagation(); + closeSceneView(); + } else if (!typing(evt.target) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) { + if (turner.key(evt.key, evt.shiftKey)) evt.preventDefault(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, [turner]); + + const release = () => { + turner.up(); + setTurning(false); + }; + + return ( + +
+
{ + if (!evt.isPrimary || (evt.pointerType === 'mouse' && evt.button !== 0)) return; + evt.currentTarget.setPointerCapture?.(evt.pointerId); + turner.down(evt.clientX); + setTurning(true); + }} + onPointerMove={(evt) => turner.move(evt.clientX)} + onPointerUp={release} + onPointerCancel={release} + onWheel={(evt) => { + if (Math.abs(evt.deltaX) > Math.abs(evt.deltaY)) turner.wheel(evt.deltaX); + }} + /> +
+ + {submenu && ( +
s.id === submenu)?.label} + > + {submenu === 'view' && } + {submenu === 'time' && } + {submenu === 'sky' && } + {submenu === 'place' && } +
+ )} +
+
+ + ); +} diff --git a/src/app/features/scene/view/SkySubmenu.tsx b/src/app/features/scene/view/SkySubmenu.tsx new file mode 100644 index 00000000..22d223e1 --- /dev/null +++ b/src/app/features/scene/view/SkySubmenu.tsx @@ -0,0 +1,26 @@ +import React from 'react'; +import { Box, Switch, Text } from 'folds'; +import { useConstellationLines } from '../../../hooks/useSceneView'; +import { setConstellationLines } from '../skyState'; + +/** The Sky submenu of the scene view: the constellation lines, an explicit option per viewer (it replaces the hidden re-pick of Night). Its data credits are in Place. */ +export function SkySubmenu() { + const lines = useConstellationLines(); + return ( + + + + Constellation lines + + setConstellationLines(on)} + /> + + + Drawn over the stars of a night sky. + + + ); +} diff --git a/src/app/features/scene/SkyStateControl.test.tsx b/src/app/features/scene/view/TimeSubmenu.test.tsx similarity index 85% rename from src/app/features/scene/SkyStateControl.test.tsx rename to src/app/features/scene/view/TimeSubmenu.test.tsx index df06280b..5b6b70e9 100644 --- a/src/app/features/scene/SkyStateControl.test.tsx +++ b/src/app/features/scene/view/TimeSubmenu.test.tsx @@ -1,13 +1,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import type { SkyChoice } from './ridge/skyMoment'; -import { FALLBACK_VIEW } from './ridge/view'; +import type { SkyChoice } from '../ridge/skyMoment'; +import { FALLBACK_VIEW } from '../ridge/view'; import { MENU_CHOICES, SkyMomentPicker, - SkyStateControl, + TimeSubmenu, choiceLabel, useNativeChange, -} from './SkyStateControl'; +} from './TimeSubmenu'; // 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 @@ -34,11 +34,10 @@ vi.mock('react', async (importOriginal) => { useEffect, }; }); -vi.mock('../../hooks/useSkyState', () => ({ +vi.mock('../../../hooks/useSkyState', () => ({ useSkyChoice: () => held.choice, useDrawnPlace: () => FALLBACK_VIEW.place, })); -vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) })); type El = { type?: unknown; ref?: unknown; props?: Record }; /** Every element reachable through any prop (children, `content`, `after`). */ @@ -67,9 +66,9 @@ beforeEach(() => { held.choice = { kind: 'auto' }; }); -describe('the sky menu choices', () => { - const tree = () => walk(SkyStateControl()); - const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio'); +describe('the Time submenu choices', () => { + const tree = () => walk(TimeSubmenu()); + const radios = () => tree().filter((e) => e.props?.role === 'radio'); it('lists Auto and the six named moments, then Pick a moment', () => { expect(MENU_CHOICES.map(choiceLabel)).toEqual([ @@ -81,6 +80,7 @@ describe('the sky menu choices', () => { 'Dusk', 'Night', ]); + expect(tree().find((e) => e.props?.role === 'radiogroup')?.props?.['aria-label']).toBe('Time'); expect(radios().map((e) => textOf(e))).toEqual([ 'Auto', 'Dawn', @@ -102,16 +102,6 @@ describe('the sky menu choices', () => { 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: