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: