From 1a752bcb86c3de64e8944d578d205be8e9eed8c4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 26 Nov 2026 11:34:05 +0100 Subject: [PATCH 01/10] ridge sky: the constellation lines have one setter; picking Night again no longer toggles them pickSkyChoice's Night-while-Night branch is deleted (ruling ridge-scene-view-submenus supersedes ridge-constellation-lines-hidden-extra), which left it a copy of setSkyChoice, so it goes too. setConstellationLines(on) persists and emits once per change. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/scene/SkyStateControl.tsx | 6 +-- src/app/features/scene/index.test.ts | 10 ++--- src/app/features/scene/skyForState.test.ts | 3 +- src/app/features/scene/skyState.test.ts | 47 ++++++++++++---------- src/app/features/scene/skyState.ts | 26 +++++------- 5 files changed, 45 insertions(+), 47 deletions(-) diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx index c8c5a374..8fa219be 100644 --- a/src/app/features/scene/SkyStateControl.tsx +++ b/src/app/features/scene/SkyStateControl.tsx @@ -14,7 +14,7 @@ import { import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '../../utils/keyboard'; import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState'; -import { pickSkyChoice, skyNow } from './skyState'; +import { setSkyChoice, skyNow } from './skyState'; import { FREE_DATE_MAX, FREE_DATE_MIN, @@ -200,7 +200,7 @@ export function SkyStateControl() { role="menuitemradio" aria-checked={checked} onClick={() => { - pickSkyChoice(c); + setSkyChoice(c); setCords(undefined); }} after={checked ? : undefined} @@ -229,7 +229,7 @@ export function SkyStateControl() { )} {ridgeOn && ( 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/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..5aa824f4 100644 --- a/src/app/features/scene/skyState.ts +++ b/src/app/features/scene/skyState.ts @@ -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. */ From 3ea23704247e064507f571122c6829fc8fbd3bda Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 26 Nov 2026 11:34:43 +0100 Subject: [PATCH 02/10] scene view: sceneView.ts owns whether the view is open and which submenu One history entry per open, Back and Return the same close, #root inert and hidden while open, the held rotation resumed through cameraState on close. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/scene/sceneView.test.ts | 132 +++++++++++++++++++++++ src/app/features/scene/sceneView.ts | 93 ++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 src/app/features/scene/sceneView.test.ts create mode 100644 src/app/features/scene/sceneView.ts diff --git a/src/app/features/scene/sceneView.test.ts b/src/app/features/scene/sceneView.test.ts new file mode 100644 index 00000000..41bfec69 --- /dev/null +++ b/src/app/features/scene/sceneView.test.ts @@ -0,0 +1,132 @@ +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, + 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, + }); + vi.stubGlobal('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', { + 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 gives the focus back 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); + expect(entryEl.focused).toBe(1); + closeSceneView(); + expect(back).toBe(1); + }); + + it("the browser's Back button closes it (the entry is already gone), once, and the focus returns", () => { + openSceneView(); + const seen = vi.fn(); + subscribeSceneView(seen); + 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); + expect(entryEl.focused).toBe(1); + }); + + 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); + }); +}); diff --git a/src/app/features/scene/sceneView.ts b/src/app/features/scene/sceneView.ts new file mode 100644 index 00000000..7c215418 --- /dev/null +++ b/src/app/features/scene/sceneView.ts @@ -0,0 +1,93 @@ +// 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, which takes the focus back when it closes. */ +let entry: 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; + try { + history.pushState({ ...(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 back where it was. */ +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 }); + const back = entry; + entry = null; + set({ open: false, submenu: undefined }); + back?.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 && history.state?.[SCENE_VIEW_HISTORY_MARK]) 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 }); +} From ad13bb2c24c79a2dc163dc0bd3fc587091e86f54 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 26 Nov 2026 11:50:53 +0100 Subject: [PATCH 03/10] scene view: the fullscreen view replaces the sky menu The entry button opens the view; its rail (Return, View, Time, Sky, Place) holds the moved time choices and picker, the rotation mode, speed and signed offset sliders (bounded by maxSpeed and offsetRange, committed on release through cameraState), the constellation lines switch and the credits. Dragging, arrows and a horizontal wheel turn the heading by hand through heading.hold; Return resumes the rotation via setCamera. The credit lives in the Place submenu per ruling ridge-view-credits-home. Co-Authored-By: Claude Sonnet 5.5 --- src/app/features/estate/EstateNavigator.tsx | 4 +- src/app/features/scene/BackgroundScene.tsx | 40 ++- src/app/features/scene/SkyStateControl.tsx | 291 ++---------------- src/app/features/scene/sceneShell.css.ts | 3 + src/app/features/scene/sceneView.test.ts | 18 +- src/app/features/scene/sceneView.ts | 10 +- src/app/features/scene/view/PlaceSubmenu.tsx | 38 +++ src/app/features/scene/view/SceneView.css.ts | 77 +++++ .../features/scene/view/SceneView.test.tsx | 162 ++++++++++ src/app/features/scene/view/SceneView.tsx | 236 ++++++++++++++ src/app/features/scene/view/SkySubmenu.tsx | 41 +++ .../TimeSubmenu.test.tsx} | 28 +- src/app/features/scene/view/TimeSubmenu.tsx | 164 ++++++++++ .../features/scene/view/ViewSubmenu.test.tsx | 126 ++++++++ src/app/features/scene/view/ViewSubmenu.tsx | 153 +++++++++ src/app/features/scene/view/turning.test.ts | 80 +++++ src/app/features/scene/view/turning.ts | 61 ++++ src/app/hooks/useSceneView.ts | 49 +++ src/app/pages/auth/AuthLayout.tsx | 4 +- src/app/phoneTapTargets.test.ts | 3 +- 20 files changed, 1275 insertions(+), 313 deletions(-) create mode 100644 src/app/features/scene/view/PlaceSubmenu.tsx create mode 100644 src/app/features/scene/view/SceneView.css.ts create mode 100644 src/app/features/scene/view/SceneView.test.tsx create mode 100644 src/app/features/scene/view/SceneView.tsx create mode 100644 src/app/features/scene/view/SkySubmenu.tsx rename src/app/features/scene/{SkyStateControl.test.tsx => view/TimeSubmenu.test.tsx} (85%) create mode 100644 src/app/features/scene/view/TimeSubmenu.tsx create mode 100644 src/app/features/scene/view/ViewSubmenu.test.tsx create mode 100644 src/app/features/scene/view/ViewSubmenu.tsx create mode 100644 src/app/features/scene/view/turning.test.ts create mode 100644 src/app/features/scene/view/turning.ts create mode 100644 src/app/hooks/useSceneView.ts diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index 746b45b9..4bd43e35 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/SkyStateControl'; type IconSrc = ComponentProps['src']; @@ -389,7 +389,7 @@ export function EstateNavigator() { {title} - + + + , + portal + ); +} + /** * The one host for the background scene, mounted once at the app root. Fixed behind everything * (z-index -1 sits above the body's background and below all normal content; the signed-out * screens and the signed-in shell, see sceneShell.css.ts, are clear so the scene shows through). The ridge scene * draws its layers into this wrapper beside the canvas, so the wrapper is the positioned box. - * Tier 'off' renders nothing and loads nothing. + * Tier 'off' renders no scene and loads none; the scene view's host is here too, since the view is an overlay over this scene. */ export function BackgroundScene() { const config = useClientConfig().backgroundScene; @@ -35,13 +53,17 @@ export function BackgroundScene() { }; }, [config, enabled]); - if (!enabled) return null; return ( -
- -
+ <> + {enabled && ( +
+ +
+ )} + + ); } diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SkyStateControl.tsx index 8fa219be..86be7713 100644 --- a/src/app/features/scene/SkyStateControl.tsx +++ b/src/app/features/scene/SkyStateControl.tsx @@ -1,282 +1,27 @@ -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 { setSkyChoice, 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 React from 'react'; +import { Icon, IconButton, Icons } from 'folds'; 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); +import { loadSceneView, openSceneView } from './sceneView'; /** - * 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. + * 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. */ -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()); +export function SceneViewEntry() { + const preload = () => { + loadSceneView().catch(() => undefined); // a failed chunk is asked for again when the view opens }; - 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 ( - { - setSkyChoice(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/sceneShell.css.ts b/src/app/features/scene/sceneShell.css.ts index 18911a1b..033f4703 100644 --- a/src/app/features/scene/sceneShell.css.ts +++ b/src/app/features/scene/sceneShell.css.ts @@ -28,3 +28,6 @@ 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' }); diff --git a/src/app/features/scene/sceneView.test.ts b/src/app/features/scene/sceneView.test.ts index 41bfec69..0b221041 100644 --- a/src/app/features/scene/sceneView.test.ts +++ b/src/app/features/scene/sceneView.test.ts @@ -40,10 +40,13 @@ beforeEach(() => { }, getElementById: (id: string) => id === 'root' - ? { setAttribute: (k: string) => rootAttrs.add(k), removeAttribute: (k: string) => rootAttrs.delete(k) } + ? { + setAttribute: (k: string) => rootAttrs.add(k), + removeAttribute: (k: string) => rootAttrs.delete(k), + } : null, }); - vi.stubGlobal('history', { + const history = { get state() { return stack[stack.length - 1]; }, @@ -53,12 +56,17 @@ beforeEach(() => { 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 }); + vi.stubGlobal('localStorage', { + getItem: () => null, + setItem: () => undefined, + removeItem: () => undefined, + }); resetCamera(); }); @@ -95,7 +103,7 @@ describe('the scene view', () => { openSceneView(); const seen = vi.fn(); subscribeSceneView(seen); - history.back(); + 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 diff --git a/src/app/features/scene/sceneView.ts b/src/app/features/scene/sceneView.ts index 7c215418..90181198 100644 --- a/src/app/features/scene/sceneView.ts +++ b/src/app/features/scene/sceneView.ts @@ -52,7 +52,10 @@ export function openSceneView(): void { if (state.open) return; entry = document.activeElement instanceof HTMLElement ? document.activeElement : null; try { - history.pushState({ ...(history.state ?? {}), [SCENE_VIEW_HISTORY_MARK]: true }, ''); + 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 @@ -82,7 +85,7 @@ 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 && history.state?.[SCENE_VIEW_HISTORY_MARK]) history.back(); + if (wasPushed && window.history.state?.[SCENE_VIEW_HISTORY_MARK]) window.history.back(); pushed = false; } @@ -91,3 +94,6 @@ 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'); diff --git a/src/app/features/scene/view/PlaceSubmenu.tsx b/src/app/features/scene/view/PlaceSubmenu.tsx new file mode 100644 index 00000000..585d63ca --- /dev/null +++ b/src/app/features/scene/view/PlaceSubmenu.tsx @@ -0,0 +1,38 @@ +import React from 'react'; +import { Box, Text } from 'folds'; +import { useDrawnPlace } from '../../../hooks/useSkyState'; +import { terrainCredit, WEATHER_CREDIT_URL, WEATHER_DATASET } 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 its credits. The carousel of baked places is cut ridge-places; until it lands this names the place shown. + * The elevation credit lives here, under the place it credits (ruling ridge-view-credits-home), with the weather's, which GeoSphere asks for with any view of + * its data. + */ +export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined }) { + const place = useDrawnPlace() ?? FALLBACK_VIEW.place; + const credit = terrainCredit(manifest); + return ( + + {place.id} + + + Data + + {credit && ( + + {credit} + + )} + + 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..e9be61af --- /dev/null +++ b/src/app/features/scene/view/SceneView.css.ts @@ -0,0 +1,77 @@ +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' } }, +}); + +/** 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: 0.12 } }, +}); + +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..2828e3e4 --- /dev/null +++ b/src/app/features/scene/view/SceneView.test.tsx @@ -0,0 +1,162 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { PhoneHit } from '../../../styles/PhoneHit.css'; +import SceneView, { Rail, SUBMENUS } from './SceneView'; + +// 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[], +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => [ + typeof init === 'function' ? (init as () => unknown)() : init, + () => undefined, + ]; + 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('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; + 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); + }); +}); 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..fc64db74 --- /dev/null +++ b/src/app/features/scene/view/SkySubmenu.tsx @@ -0,0 +1,41 @@ +import React from 'react'; +import { Box, Switch, Text } from 'folds'; +import { useConstellationLines } from '../../../hooks/useSceneView'; +import { setConstellationLines } from '../skyState'; +import { LINES_CREDIT, STARS_CREDIT } from '../ridge/credits'; + +/** + * The Sky submenu of the scene view: the constellation lines (an explicit option, per viewer; it replaces the hidden re-pick of Night) and the credits of the + * stars and the lines drawn over them. + */ +export function SkySubmenu() { + const lines = useConstellationLines(); + return ( + + + + Constellation lines + + setConstellationLines(on)} + /> + + + Drawn over the stars of a night sky. + + + + Data + + + {STARS_CREDIT}. + + + {LINES_CREDIT}. + + + + ); +} 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: