Merge pull request 'Ridge scene view: fullscreen view with icon rail (Return, View, Time, Sky, Place)' (#183) from void/ridge-scene-view into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m4s
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m4s
This commit is contained in:
commit
b1f7d5c1b5
35 changed files with 2112 additions and 365 deletions
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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<typeof Icon>['src'];
|
||||
|
||||
|
|
@ -389,7 +389,7 @@ export function EstateNavigator() {
|
|||
{title}
|
||||
</Text>
|
||||
</Box>
|
||||
<SkyStateControl />
|
||||
<SceneViewEntry />
|
||||
<IconButton
|
||||
variant="Background"
|
||||
aria-label="Find a room"
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { useClientConfig } from '../../hooks/useClientConfig';
|
|||
import { getFallbackSession } from '../../state/sessions';
|
||||
import { mountBackgroundScene } from './host';
|
||||
import { setSceneDrawn } from './sceneDrawn';
|
||||
import { SceneViewHost } from './SceneViewHost';
|
||||
import { readCapabilities, resolveTier } from './tier';
|
||||
import './sceneShell.css';
|
||||
import './sceneButtons.css';
|
||||
|
|
@ -12,7 +13,7 @@ import './sceneButtons.css';
|
|||
* (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 +36,24 @@ export function BackgroundScene() {
|
|||
};
|
||||
}, [config, enabled]);
|
||||
|
||||
if (!enabled) return null;
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
style={{ position: 'fixed', inset: 0, zIndex: -1, pointerEvents: 'none', overflow: 'hidden' }}
|
||||
>
|
||||
<canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
|
||||
</div>
|
||||
<>
|
||||
{enabled && (
|
||||
<div
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
zIndex: -1,
|
||||
pointerEvents: 'none',
|
||||
overflow: 'hidden',
|
||||
visibility: 'visible', // the scene is what the scene view shows: it stays when the app (#root, its ancestor) is hidden
|
||||
}}
|
||||
>
|
||||
<canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
|
||||
</div>
|
||||
)}
|
||||
<SceneViewHost />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
18
src/app/features/scene/SceneViewEntry.test.tsx
Normal file
18
src/app/features/scene/SceneViewEntry.test.tsx
Normal file
|
|
@ -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<string, unknown> }).props['aria-label']).toBe(
|
||||
'Scene view'
|
||||
);
|
||||
});
|
||||
it('is not offered when the scene tier is off', () => {
|
||||
offered.value = false;
|
||||
expect(SceneViewEntry()).toBeNull();
|
||||
});
|
||||
});
|
||||
31
src/app/features/scene/SceneViewEntry.tsx
Normal file
31
src/app/features/scene/SceneViewEntry.tsx
Normal file
|
|
@ -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 (
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
variant="Background"
|
||||
aria-label="Scene view"
|
||||
title="Scene view"
|
||||
onMouseEnter={preload}
|
||||
onFocus={preload}
|
||||
onClick={openSceneView}
|
||||
>
|
||||
<Icon src={Icons.Photo} size="200" />
|
||||
</IconButton>
|
||||
);
|
||||
}
|
||||
156
src/app/features/scene/SceneViewHost.test.tsx
Normal file
156
src/app/features/scene/SceneViewHost.test.tsx
Normal file
|
|
@ -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<typeof import('react')>();
|
||||
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<string, unknown> };
|
||||
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<string, (e: unknown) => 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);
|
||||
});
|
||||
});
|
||||
72
src/app/features/scene/SceneViewHost.tsx
Normal file
72
src/app/features/scene/SceneViewHost.tsx
Normal file
|
|
@ -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 (
|
||||
<IconButton
|
||||
className={`${PhoneHit} ${css.LoadingReturn}`}
|
||||
variant="Background"
|
||||
aria-label="Return"
|
||||
title="Return"
|
||||
autoFocus
|
||||
onClick={closeSceneView}
|
||||
>
|
||||
<Icon src={Icons.ArrowLeft} size="200" />
|
||||
</IconButton>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ? <view.View /> : <SceneViewLoading />, portal);
|
||||
}
|
||||
|
|
@ -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<MomentId, string> = {
|
||||
dawn: 'Dawn',
|
||||
morning: 'Morning',
|
||||
noon: 'Noon',
|
||||
golden: 'Golden hour',
|
||||
dusk: 'Dusk',
|
||||
night: 'Night',
|
||||
};
|
||||
|
||||
const hhmm = (minutes: number): string =>
|
||||
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
|
||||
/** What the button and the menu call a choice: Auto, the moment's name, or the free moment's place-local date and time. */
|
||||
export const choiceLabel = (c: SkyChoice): string =>
|
||||
c.kind === 'auto'
|
||||
? 'Auto'
|
||||
: c.kind === 'named'
|
||||
? MOMENT_LABEL[c.id]
|
||||
: `${c.date} ${hhmm(c.minutes)}`;
|
||||
|
||||
/** The choices the menu lists, in order. */
|
||||
export const MENU_CHOICES: readonly SkyChoice[] = [
|
||||
{ kind: 'auto' },
|
||||
...MOMENT_IDS.map((id): SkyChoice => ({ kind: 'named', id })),
|
||||
];
|
||||
|
||||
const sameChoice = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
/**
|
||||
* Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
|
||||
* input event). Each commit rebuilds the scene, so a drag must commit once.
|
||||
*/
|
||||
export function useNativeChange<T extends HTMLElement>(onChange: (el: T) => void) {
|
||||
const ref = useRef<T>(null);
|
||||
const latest = useRef(onChange);
|
||||
latest.current = onChange;
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return undefined;
|
||||
const handler = () => latest.current(el);
|
||||
el.addEventListener('change', handler);
|
||||
return () => el.removeEventListener('change', handler);
|
||||
}, []);
|
||||
return ref;
|
||||
}
|
||||
|
||||
type Free = Extract<SkyChoice, { kind: 'free' }>;
|
||||
|
||||
/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
|
||||
export function SkyMomentPicker({
|
||||
seed,
|
||||
tz,
|
||||
onCommit,
|
||||
}: {
|
||||
seed: Free;
|
||||
tz: string;
|
||||
onCommit: (c: Free) => void;
|
||||
}) {
|
||||
const [minutes, setMinutes] = useState(seed.minutes);
|
||||
const at = useRef({ date: seed.date, minutes: seed.minutes });
|
||||
const dateRef = useNativeChange<HTMLInputElement>((el) => {
|
||||
if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
|
||||
at.current.date = el.value;
|
||||
onCommit({ kind: 'free', ...at.current });
|
||||
});
|
||||
const sliderRef = useNativeChange<HTMLInputElement>((el) => {
|
||||
at.current.minutes = Number(el.value);
|
||||
onCommit({ kind: 'free', ...at.current });
|
||||
});
|
||||
const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
|
||||
return (
|
||||
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
|
||||
<input
|
||||
ref={dateRef}
|
||||
type="date"
|
||||
aria-label="Date"
|
||||
min={FREE_DATE_MIN}
|
||||
max={FREE_DATE_MAX}
|
||||
defaultValue={seed.date}
|
||||
/>
|
||||
<input
|
||||
ref={sliderRef}
|
||||
type="range"
|
||||
aria-label="Time of day"
|
||||
min={0}
|
||||
max={1439}
|
||||
step={5}
|
||||
defaultValue={seed.minutes}
|
||||
onInput={(evt) => setMinutes(Number(evt.currentTarget.value))}
|
||||
/>
|
||||
<Text size="T200" priority="300">
|
||||
{hhmm(minutes)} {zone}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One title-bar button that opens the sky choices: Auto, the six named moments of today at the place, and a free date and time. A single
|
||||
* button, not a row, so the bar still fits a 320 px phone beside the search button; the menu items carry the names.
|
||||
*/
|
||||
export function SkyStateControl() {
|
||||
const choice = useSkyChoice();
|
||||
const drawn = useDrawnPlace();
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [cords, setCords] = useState<RectCords>();
|
||||
const backgroundScene = useClientConfig().backgroundScene;
|
||||
|
||||
const placeId = backgroundScene?.place;
|
||||
const place = drawn ?? FALLBACK_VIEW.place;
|
||||
const [credit, setCredit] = useState<string>();
|
||||
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
|
||||
useEffect(() => {
|
||||
if (!ridgeOn) return undefined;
|
||||
let live = true;
|
||||
loadManifest(import.meta.env.BASE_URL, placeId).then(
|
||||
(m) => live && setCredit(terrainCredit(m)),
|
||||
() => live && setCredit(undefined)
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [ridgeOn, placeId]);
|
||||
const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||
setCords(evt.currentTarget.getBoundingClientRect());
|
||||
};
|
||||
|
||||
return (
|
||||
<PopOut
|
||||
anchor={cords}
|
||||
position="Bottom"
|
||||
align="End"
|
||||
content={
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: '[aria-checked="true"]',
|
||||
returnFocusOnDeactivate: true,
|
||||
onDeactivate: () => {
|
||||
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 role="menu" aria-label="Sky">
|
||||
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
|
||||
{MENU_CHOICES.map((c) => {
|
||||
const checked = sameChoice(c, choice);
|
||||
return (
|
||||
<MenuItem
|
||||
key={choiceLabel(c)}
|
||||
size="300"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
role="menuitemradio"
|
||||
aria-checked={checked}
|
||||
onClick={() => {
|
||||
pickSkyChoice(c);
|
||||
setCords(undefined);
|
||||
}}
|
||||
after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="T300">{choiceLabel(c)}</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
<MenuItem
|
||||
size="300"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
role="menuitemradio"
|
||||
aria-checked={choice.kind === 'free'}
|
||||
aria-expanded={picking}
|
||||
onClick={() => setPicking(!picking)}
|
||||
after={choice.kind === 'free' ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="T300">Pick a moment</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
{picking && (
|
||||
<SkyMomentPicker
|
||||
seed={seedFree(choice, place, skyNow())}
|
||||
tz={place.tz}
|
||||
onCommit={pickSkyChoice}
|
||||
/>
|
||||
)}
|
||||
{ridgeOn && (
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="100"
|
||||
style={{ padding: `${config.space.S200}`, maxWidth: '20rem' }}
|
||||
>
|
||||
<Text size="L400" priority="300">
|
||||
Data
|
||||
</Text>
|
||||
{credit && (
|
||||
<Text size="T200" priority="300">
|
||||
{credit}
|
||||
</Text>
|
||||
)}
|
||||
<Text size="T200" priority="300">
|
||||
Datenquelle: GeoSphere Austria -{' '}
|
||||
<a href={WEATHER_CREDIT_URL} target="_blank" rel="noreferrer noopener">
|
||||
{WEATHER_CREDIT_URL}
|
||||
</a>
|
||||
. {WEATHER_DATASET}.
|
||||
</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{STARS_CREDIT}.
|
||||
</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{LINES_CREDIT}.
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
<IconButton
|
||||
className={PhoneHit}
|
||||
variant="Background"
|
||||
aria-label={`Sky: ${choiceLabel(choice)}`}
|
||||
title={`Sky: ${choiceLabel(choice)}`}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={!!cords}
|
||||
onClick={open}
|
||||
>
|
||||
<Icon src={Icons.Bulb} size="200" />
|
||||
</IconButton>
|
||||
</PopOut>
|
||||
);
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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))',
|
||||
});
|
||||
|
|
|
|||
193
src/app/features/scene/sceneView.test.ts
Normal file
193
src/app/features/scene/sceneView.test.ts
Normal file
|
|
@ -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 (<html>, #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<string>;
|
||||
let rootAttrs: Set<string>;
|
||||
let stack: Array<Record<string, unknown> | 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<string, unknown>) => 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<ReturnType<typeof loadSceneView>>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
129
src/app/features/scene/sceneView.ts
Normal file
129
src/app/features/scene/sceneView.ts
Normal file
|
|
@ -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 <html> 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<Awaited<ReturnType<typeof loadSceneView>> | undefined> {
|
||||
try {
|
||||
return await load();
|
||||
} catch (e) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('Scene view unavailable:', e);
|
||||
closeSceneView();
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -335,54 +335,58 @@ describe('Auto follows the clock', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('the constellation lines toggle', () => {
|
||||
describe('the constellation lines', () => {
|
||||
let storage: ReturnType<typeof fakeStorage>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<string, SkyChoice>([
|
||||
['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. */
|
||||
|
|
|
|||
52
src/app/features/scene/view/PlaceSubmenu.test.tsx
Normal file
52
src/app/features/scene/view/PlaceSubmenu.test.tsx
Normal file
|
|
@ -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
|
||||
});
|
||||
});
|
||||
53
src/app/features/scene/view/PlaceSubmenu.tsx
Normal file
53
src/app/features/scene/view/PlaceSubmenu.tsx
Normal file
|
|
@ -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 (
|
||||
<Box direction="Column" gap="300">
|
||||
<Text size="T300">{place.id}</Text>
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400" priority="300">
|
||||
Data
|
||||
</Text>
|
||||
{credit && (
|
||||
<Text size="T200" priority="300">
|
||||
{credit}
|
||||
</Text>
|
||||
)}
|
||||
<Text size="T200" priority="300">
|
||||
{STARS_CREDIT}.
|
||||
</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{LINES_CREDIT}.
|
||||
</Text>
|
||||
{weatherServes(place) && (
|
||||
<Text size="T200" priority="300">
|
||||
Datenquelle: GeoSphere Austria -{' '}
|
||||
<a href={WEATHER_CREDIT_URL} target="_blank" rel="noreferrer noopener">
|
||||
{WEATHER_CREDIT_URL}
|
||||
</a>
|
||||
. {WEATHER_DATASET}.
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
80
src/app/features/scene/view/SceneView.css.ts
Normal file
80
src/app/features/scene/view/SceneView.css.ts
Normal file
|
|
@ -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)' } },
|
||||
},
|
||||
]);
|
||||
241
src/app/features/scene/view/SceneView.test.tsx
Normal file
241
src/app/features/scene/view/SceneView.test.tsx
Normal file
|
|
@ -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<typeof import('react')>();
|
||||
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<string, unknown> };
|
||||
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<string, unknown>;
|
||||
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<string, (e: unknown) => 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<string, unknown>) =>
|
||||
(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'");
|
||||
});
|
||||
});
|
||||
236
src/app/features/scene/view/SceneView.tsx
Normal file
236
src/app/features/scene/view/SceneView.tsx
Normal file
|
|
@ -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<typeof Icon>['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 (
|
||||
<IconButton
|
||||
ref={buttonRef}
|
||||
className={PhoneHit}
|
||||
variant="Background"
|
||||
aria-label={label}
|
||||
title={label}
|
||||
aria-pressed={pressed}
|
||||
tabIndex={tabIndex}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Icon src={icon} size="200" />
|
||||
</IconButton>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Array<HTMLButtonElement | null>>([]);
|
||||
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<string, number | undefined> = {
|
||||
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 (
|
||||
<div
|
||||
className={css.Rail}
|
||||
role="toolbar"
|
||||
aria-label="Scene view"
|
||||
aria-orientation="vertical"
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
<RailButton
|
||||
label="Return"
|
||||
icon={Icons.ArrowLeft}
|
||||
tabIndex={stop === 0 ? 0 : -1}
|
||||
buttonRef={(el) => {
|
||||
buttons.current[0] = el;
|
||||
}}
|
||||
onClick={onReturn}
|
||||
/>
|
||||
{items.map((item, i) => (
|
||||
<RailButton
|
||||
key={item.id}
|
||||
label={item.label}
|
||||
icon={item.icon}
|
||||
pressed={active === item.id}
|
||||
tabIndex={stop === i + 1 ? 0 : -1}
|
||||
buttonRef={(el) => {
|
||||
buttons.current[i + 1] = el;
|
||||
}}
|
||||
onClick={() => {
|
||||
setStop(i + 1);
|
||||
onPick(item.id);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<HTMLDivElement>(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 (
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: '[aria-label="Return"]',
|
||||
fallbackFocus: '[aria-label="Return"]',
|
||||
escapeDeactivates: false,
|
||||
returnFocusOnDeactivate: false,
|
||||
allowOutsideClick: true,
|
||||
}}
|
||||
>
|
||||
<div className={css.Root} data-turning={turning}>
|
||||
<div
|
||||
ref={surface}
|
||||
className={css.Surface}
|
||||
onPointerDown={(evt) => {
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
<div className={css.Chrome}>
|
||||
<Rail items={SUBMENUS} active={submenu} onReturn={closeSceneView} onPick={setSubmenu} />
|
||||
{submenu && (
|
||||
<section
|
||||
className={css.Panel}
|
||||
aria-label={SUBMENUS.find((s) => s.id === submenu)?.label}
|
||||
>
|
||||
{submenu === 'view' && <ViewSubmenu manifest={manifest} size={size} />}
|
||||
{submenu === 'time' && <TimeSubmenu />}
|
||||
{submenu === 'sky' && <SkySubmenu />}
|
||||
{submenu === 'place' && <PlaceSubmenu manifest={manifest} />}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</FocusTrap>
|
||||
);
|
||||
}
|
||||
26
src/app/features/scene/view/SkySubmenu.tsx
Normal file
26
src/app/features/scene/view/SkySubmenu.tsx
Normal file
|
|
@ -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 (
|
||||
<Box direction="Column" gap="300">
|
||||
<Box alignItems="Center" justifyContent="SpaceBetween" gap="300">
|
||||
<Text as="label" id="scene-view-lines" size="T300">
|
||||
Constellation lines
|
||||
</Text>
|
||||
<Switch
|
||||
aria-labelledby="scene-view-lines"
|
||||
value={lines}
|
||||
onChange={(on: boolean) => setConstellationLines(on)}
|
||||
/>
|
||||
</Box>
|
||||
<Text size="T200" priority="300">
|
||||
Drawn over the stars of a night sky.
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<string, unknown> };
|
||||
/** 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: <date> <time>'", () => {
|
||||
const label = () =>
|
||||
tree().find((e) => e.props?.['aria-haspopup'] === 'menu')?.props?.['aria-label'];
|
||||
expect(label()).toBe('Sky: Auto');
|
||||
held.choice = { kind: 'named', id: 'dawn' };
|
||||
expect(label()).toBe('Sky: Dawn');
|
||||
held.choice = { kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 };
|
||||
expect(label()).toBe('Sky: 2026-12-21 06:40');
|
||||
});
|
||||
});
|
||||
|
||||
describe('committing on change, not on input', () => {
|
||||
164
src/app/features/scene/view/TimeSubmenu.tsx
Normal file
164
src/app/features/scene/view/TimeSubmenu.tsx
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Box, config, Icon, Icons, MenuItem, Text } from 'folds';
|
||||
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';
|
||||
|
||||
export const MOMENT_LABEL: Record<MomentId, string> = {
|
||||
dawn: 'Dawn',
|
||||
morning: 'Morning',
|
||||
noon: 'Noon',
|
||||
golden: 'Golden hour',
|
||||
dusk: 'Dusk',
|
||||
night: 'Night',
|
||||
};
|
||||
|
||||
const hhmm = (minutes: number): string =>
|
||||
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
|
||||
/** What the panel calls a choice: Auto, the moment's name, or the free moment's place-local date and time. */
|
||||
export function choiceLabel(c: SkyChoice): string {
|
||||
if (c.kind === 'auto') return 'Auto';
|
||||
return c.kind === 'named' ? MOMENT_LABEL[c.id] : `${c.date} ${hhmm(c.minutes)}`;
|
||||
}
|
||||
|
||||
/** The choices the panel 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 or re-issues the rig, so a drag must commit once.
|
||||
*/
|
||||
export function useNativeChange<T extends HTMLElement>(onChange: (el: T) => void) {
|
||||
const ref = useRef<T>(null);
|
||||
const latest = useRef(onChange);
|
||||
latest.current = onChange;
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return undefined;
|
||||
const handler = () => latest.current(el);
|
||||
el.addEventListener('change', handler);
|
||||
return () => el.removeEventListener('change', handler);
|
||||
}, []);
|
||||
return ref;
|
||||
}
|
||||
|
||||
type Free = Extract<SkyChoice, { kind: 'free' }>;
|
||||
|
||||
/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
|
||||
export function SkyMomentPicker({
|
||||
seed,
|
||||
tz,
|
||||
onCommit,
|
||||
}: {
|
||||
seed: Free;
|
||||
tz: string;
|
||||
onCommit: (c: Free) => void;
|
||||
}) {
|
||||
const [minutes, setMinutes] = useState(seed.minutes);
|
||||
const at = useRef({ date: seed.date, minutes: seed.minutes });
|
||||
const dateRef = useNativeChange<HTMLInputElement>((el) => {
|
||||
if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
|
||||
at.current.date = el.value;
|
||||
onCommit({ kind: 'free', ...at.current });
|
||||
});
|
||||
const sliderRef = useNativeChange<HTMLInputElement>((el) => {
|
||||
at.current.minutes = Number(el.value);
|
||||
onCommit({ kind: 'free', ...at.current });
|
||||
});
|
||||
const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
|
||||
return (
|
||||
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
|
||||
<input
|
||||
ref={dateRef}
|
||||
type="date"
|
||||
aria-label="Date"
|
||||
min={FREE_DATE_MIN}
|
||||
max={FREE_DATE_MAX}
|
||||
defaultValue={seed.date}
|
||||
/>
|
||||
<input
|
||||
ref={sliderRef}
|
||||
type="range"
|
||||
aria-label="Time of day"
|
||||
min={0}
|
||||
max={1439}
|
||||
step={5}
|
||||
defaultValue={seed.minutes}
|
||||
onInput={(evt) => setMinutes(Number(evt.currentTarget.value))}
|
||||
/>
|
||||
<Text size="T200" priority="300">
|
||||
{hhmm(minutes)} {zone}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Time submenu of the scene view: Auto, the six named moments of today at the place, and a free date and time (ruling ridge-sky-menu-moments, unchanged;
|
||||
* this is that menu's contents). A pick goes to the sky choice store, as the menu's did.
|
||||
*/
|
||||
export function TimeSubmenu() {
|
||||
const choice = useSkyChoice();
|
||||
const drawn = useDrawnPlace();
|
||||
const [picking, setPicking] = useState(false);
|
||||
const place = drawn ?? FALLBACK_VIEW.place;
|
||||
return (
|
||||
<Box direction="Column" gap="100" role="radiogroup" aria-label="Time">
|
||||
{MENU_CHOICES.map((c) => {
|
||||
const checked = sameChoice(c, choice);
|
||||
return (
|
||||
<MenuItem
|
||||
key={choiceLabel(c)}
|
||||
size="300"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
role="radio"
|
||||
aria-checked={checked}
|
||||
onClick={() => setSkyChoice(c)}
|
||||
after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="T300">{choiceLabel(c)}</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
<MenuItem
|
||||
size="300"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
role="radio"
|
||||
aria-checked={choice.kind === 'free'}
|
||||
onClick={() => setPicking(!picking)}
|
||||
after={choice.kind === 'free' ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="T300">Pick a moment</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
{picking && (
|
||||
<SkyMomentPicker
|
||||
seed={seedFree(choice, place, skyNow())}
|
||||
tz={place.tz}
|
||||
onCommit={setSkyChoice}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
153
src/app/features/scene/view/ViewSubmenu.test.tsx
Normal file
153
src/app/features/scene/view/ViewSubmenu.test.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { parseManifest } from '../ridge/manifest';
|
||||
import { wireManifest } from '../ridge/manifest.fixture';
|
||||
import { maxSpeed, offsetRange, SPEED_CEILING_DEG_S, windowFor } from '../ridge/view';
|
||||
import type { CameraChoice } from '../cameraState';
|
||||
import { ViewSubmenu, floorToTenth, offsetBounds, speedBounds } from './ViewSubmenu';
|
||||
|
||||
// The hooks are held still, as in TimeSubmenu.test.tsx: the element tree is read, a function component is expanded by calling it, and the native events
|
||||
// are dispatched on a fake input.
|
||||
const held = vi.hoisted(() => ({
|
||||
effects: [] as Array<() => unknown>,
|
||||
cam: { mode: 'both', speedDegPerS: 0.6, offsetM: 200 } as unknown,
|
||||
heldView: false,
|
||||
commits: [] as unknown[],
|
||||
}));
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>();
|
||||
const useState = (init: unknown) => [
|
||||
typeof init === 'function' ? (init as () => unknown)() : init,
|
||||
() => undefined,
|
||||
];
|
||||
const useRef = (init: unknown) => ({ current: init });
|
||||
const useEffect = (fn: () => unknown) => {
|
||||
held.effects.push(fn);
|
||||
};
|
||||
return {
|
||||
...actual,
|
||||
default: { ...actual, useState, useRef, useEffect },
|
||||
useState,
|
||||
useRef,
|
||||
useEffect,
|
||||
};
|
||||
});
|
||||
vi.mock('../../../hooks/useSceneView', () => ({
|
||||
useCamera: () => held.cam,
|
||||
useCameraHeld: () => held.heldView,
|
||||
}));
|
||||
vi.mock('../cameraState', () => ({ setCamera: (c: unknown) => held.commits.push(c) }));
|
||||
|
||||
type El = { type?: unknown; ref?: unknown; props?: Record<string, unknown> };
|
||||
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 fakeInput = (value: string) => Object.assign(new EventTarget(), { value });
|
||||
const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type));
|
||||
|
||||
const manifest = parseManifest(wireManifest(), 'http://x/ridge/vienna/');
|
||||
const SIZE = { w: 1920, h: 1080 };
|
||||
const tree = () => walk(ViewSubmenu({ manifest, size: SIZE }));
|
||||
const slider = (label: string) => tree().find((e) => e.props?.label === label);
|
||||
|
||||
beforeEach(() => {
|
||||
held.effects.length = 0;
|
||||
held.commits.length = 0;
|
||||
held.cam = { mode: 'both', speedDegPerS: 0.6, offsetM: 200 } satisfies CameraChoice;
|
||||
held.heldView = false;
|
||||
});
|
||||
|
||||
describe('the View submenu', () => {
|
||||
it('lists the three rotation modes, the chosen one checked, and picking one sets the camera mode', () => {
|
||||
const radios = () => tree().filter((e) => e.props?.role === 'radio');
|
||||
expect(radios().map((e) => e.props?.['aria-checked'])).toEqual([false, false, true]);
|
||||
held.cam = { mode: 'still', speedDegPerS: 0.6, offsetM: 0 };
|
||||
expect(radios().map((e) => e.props?.['aria-checked'])).toEqual([true, false, false]);
|
||||
(radios()[1].props?.onClick as () => void)();
|
||||
expect(held.commits).toEqual([{ mode: 'offset' }]);
|
||||
});
|
||||
|
||||
it('the speed slider is bounded by what the baked place sustains in the mode, never past the ceiling', () => {
|
||||
for (const mode of ['still', 'offset', 'both'] as const) {
|
||||
const [lo, hi] = speedBounds(manifest, mode);
|
||||
expect(lo).toBe(0);
|
||||
expect(hi).toBeLessThanOrEqual(maxSpeed(manifest, mode));
|
||||
expect(hi).toBeLessThanOrEqual(SPEED_CEILING_DEG_S);
|
||||
expect(hi).toBeGreaterThan(maxSpeed(manifest, mode) - 0.1 - 1e-9);
|
||||
}
|
||||
held.cam = { mode: 'both', speedDegPerS: 99, offsetM: 0 };
|
||||
const s = slider('Rotation speed');
|
||||
expect(s?.props?.max).toBe(speedBounds(manifest, 'both')[1]);
|
||||
expect(s?.props?.value).toBe(speedBounds(manifest, 'both')[1]); // a stored speed past the bound shows at the bound
|
||||
expect(speedBounds(undefined, 'both')).toEqual([0, SPEED_CEILING_DEG_S]);
|
||||
});
|
||||
|
||||
it('the speed bound is the place\'s own, far under the global ceiling, when the ring is cut as the baker cuts it', () => {
|
||||
const ring = parseManifest(wireManifest({}, 3, 32), 'http://x/ridge/vienna/');
|
||||
const slow = maxSpeed(ring, 'both');
|
||||
expect(slow).toBeLessThan(SPEED_CEILING_DEG_S / 4);
|
||||
const [, hi] = speedBounds(ring, 'both');
|
||||
expect(hi).toBeLessThanOrEqual(slow);
|
||||
expect(hi).toBeGreaterThan(slow - 0.1);
|
||||
expect(hi).toBeLessThan(SPEED_CEILING_DEG_S);
|
||||
expect(speedBounds(ring, 'offset')[1]).toBe(SPEED_CEILING_DEG_S); // the modes with no bound take the ceiling
|
||||
held.cam = { mode: 'both', speedDegPerS: 99, offsetM: 0 };
|
||||
const s = walk(ViewSubmenu({ manifest: ring, size: SIZE })).find(
|
||||
(e) => e.props?.label === 'Rotation speed'
|
||||
);
|
||||
expect(s?.props?.max).toBe(hi);
|
||||
expect(s?.props?.value).toBe(hi);
|
||||
});
|
||||
|
||||
it('no stepped bound exceeds the speed it bounds: a tenth multiplied in floats is not trusted', () => {
|
||||
for (let k = 0; k <= 120; k += 1) {
|
||||
const v = Number(`${k / 10}`);
|
||||
expect(floorToTenth(v)).toBeLessThanOrEqual(v);
|
||||
expect(floorToTenth(v + 0.04)).toBeGreaterThanOrEqual(v);
|
||||
}
|
||||
expect(floorToTenth(0.3)).toBeLessThanOrEqual(0.3);
|
||||
expect(floorToTenth(0.975)).toBe(0.9);
|
||||
});
|
||||
|
||||
it('the offset slider spans offsetRange for the mode on this viewport, signed, and follows the mode', () => {
|
||||
const win = windowFor(manifest.view, SIZE.w, SIZE.h);
|
||||
const [lo, hi] = offsetRange(manifest, win, 'both');
|
||||
const s = slider('Parallax offset');
|
||||
expect(s?.props?.min).toBeLessThanOrEqual(0);
|
||||
expect(s?.props?.min).toBeGreaterThanOrEqual(lo);
|
||||
expect(s?.props?.min as number).toBeGreaterThan(lo - 5);
|
||||
expect(s?.props?.max).toBeLessThanOrEqual(hi);
|
||||
expect(s?.props?.max as number).toBeGreaterThan(hi - 5);
|
||||
expect(offsetBounds(manifest, SIZE, 'offset')[1]).toBeLessThanOrEqual(manifest.camera.rMaxM);
|
||||
held.cam = { mode: 'offset', speedDegPerS: 0.6, offsetM: 200 };
|
||||
const [, ohi] = offsetRange(manifest, win, 'offset');
|
||||
expect((slider('Parallax offset')?.props?.max as number) <= ohi).toBe(true);
|
||||
});
|
||||
|
||||
it('a slider commits once, on release, not on each input tick', () => {
|
||||
const s = slider('Parallax offset') as El;
|
||||
const expanded = walk((s.type as (p: unknown) => unknown)(s.props));
|
||||
const range = expanded.find((e) => e.type === 'input') as El;
|
||||
const input = fakeInput('120');
|
||||
(range.ref as { current: unknown }).current = input;
|
||||
held.effects.forEach((run) => run());
|
||||
for (let i = 0; i < 5; i += 1) fire(input, 'input');
|
||||
expect(held.commits).toEqual([]);
|
||||
fire(input, 'change');
|
||||
expect(held.commits).toEqual([{ offsetM: 120 }]);
|
||||
});
|
||||
|
||||
it('says so while a manual turn holds the view', () => {
|
||||
const text = () =>
|
||||
walk(ViewSubmenu({ manifest, size: SIZE }))
|
||||
.map((e) => e.props?.children)
|
||||
.filter((c) => typeof c === 'string' && /Held/.test(c));
|
||||
expect(text()).toEqual([]);
|
||||
held.heldView = true;
|
||||
expect(text()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
156
src/app/features/scene/view/ViewSubmenu.tsx
Normal file
156
src/app/features/scene/view/ViewSubmenu.tsx
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import React, { useState } from 'react';
|
||||
import { Box, Icon, Icons, MenuItem, Text } from 'folds';
|
||||
import { setCamera } from '../cameraState';
|
||||
import type { CameraChoice } from '../cameraState';
|
||||
import { useCamera, useCameraHeld } from '../../../hooks/useSceneView';
|
||||
import type { RotationMode } from '../ridge/heading';
|
||||
import type { RidgeManifest } from '../ridge/manifest';
|
||||
import { maxSpeed, offsetRange, SPEED_CEILING_DEG_S, windowFor } from '../ridge/view';
|
||||
import { useNativeChange } from './TimeSubmenu';
|
||||
|
||||
export const MODE_CHOICES: ReadonlyArray<{ mode: RotationMode; label: string }> = [
|
||||
{ mode: 'still', label: 'No rotation' },
|
||||
{ mode: 'offset', label: 'Rotate parallax offset only' },
|
||||
{ mode: 'both', label: 'Rotate offset and view direction' },
|
||||
];
|
||||
|
||||
const SPEED_STEP = 0.1;
|
||||
const OFFSET_STEP = 5;
|
||||
|
||||
/** `v` rounded down to a tenth of a degree a second, never above `v` (a step multiplied in floats can overshoot: 3 x 0.1 is more than 0.3). */
|
||||
export const floorToTenth = (v: number): number => Math.min(v, Math.floor(v * 10) / 10);
|
||||
|
||||
/** The speed slider's bounds: nothing to the fastest the baked place sustains in the mode picked (`view.ts` `maxSpeed`), the ceiling with no bake to ask; the top never exceeds it. */
|
||||
export const speedBounds = (
|
||||
manifest: RidgeManifest | undefined,
|
||||
mode: RotationMode
|
||||
): [number, number] => [
|
||||
0,
|
||||
floorToTenth(manifest ? maxSpeed(manifest, mode) : SPEED_CEILING_DEG_S),
|
||||
];
|
||||
|
||||
/** The offset slider's bounds in metres, signed: `view.ts` `offsetRange` for the mode on this viewport, rounded in to the slider's step. */
|
||||
export const offsetBounds = (
|
||||
manifest: RidgeManifest,
|
||||
size: { w: number; h: number },
|
||||
mode: RotationMode
|
||||
): [number, number] => {
|
||||
const [lo, hi] = offsetRange(manifest, windowFor(manifest.view, size.w, size.h), mode);
|
||||
return [Math.ceil(lo / OFFSET_STEP) * OFFSET_STEP, Math.floor(hi / OFFSET_STEP) * OFFSET_STEP];
|
||||
};
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v));
|
||||
const signed = (m: number): string => `${m > 0 ? '+' : ''}${m} m`;
|
||||
|
||||
/** A slider that commits on release (the native change event), the readout following the drag. */
|
||||
function Slider({
|
||||
label,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
value,
|
||||
readout,
|
||||
onCommit,
|
||||
}: {
|
||||
label: string;
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
value: number;
|
||||
readout: (v: number) => string;
|
||||
onCommit: (v: number) => void;
|
||||
}) {
|
||||
const [shown, setShown] = useState(value);
|
||||
const ref = useNativeChange<HTMLInputElement>((el) => onCommit(Number(el.value)));
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Box justifyContent="SpaceBetween" gap="200">
|
||||
<Text size="T300">{label}</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{readout(shown)}
|
||||
</Text>
|
||||
</Box>
|
||||
<input
|
||||
ref={ref}
|
||||
type="range"
|
||||
aria-label={label}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
defaultValue={value}
|
||||
onInput={(evt) => setShown(Number(evt.currentTarget.value))}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The View submenu of the scene view: the rotation mode, its speed and the camera's parallax offset, written to the camera store (`cameraState.ts`), which the
|
||||
* heading owner reads. The sliders commit on release; the speed is bounded by what the baked place sustains in the mode, the offset by `offsetRange`, which
|
||||
* is signed (ruling ridge-camera-offset-signed). Picking a mode resumes a rotation a manual turn held (ruling ridge-view-turn-handback).
|
||||
*/
|
||||
export function ViewSubmenu({
|
||||
manifest,
|
||||
size,
|
||||
}: {
|
||||
manifest: RidgeManifest | undefined;
|
||||
/** The viewport the scene is drawn on, px: the offset's bound depends on it. */
|
||||
size: { w: number; h: number };
|
||||
}) {
|
||||
const cam: CameraChoice = useCamera();
|
||||
const held = useCameraHeld();
|
||||
const [, speedMax] = speedBounds(manifest, cam.mode);
|
||||
const range = manifest ? offsetBounds(manifest, size, cam.mode) : undefined;
|
||||
return (
|
||||
<Box direction="Column" gap="300">
|
||||
<Box direction="Column" gap="100" role="radiogroup" aria-label="Rotation">
|
||||
{MODE_CHOICES.map(({ mode, label }) => {
|
||||
const checked = cam.mode === mode;
|
||||
return (
|
||||
<MenuItem
|
||||
key={mode}
|
||||
size="300"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
role="radio"
|
||||
aria-checked={checked}
|
||||
onClick={() => setCamera({ mode })}
|
||||
after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="T300">{label}</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{held && (
|
||||
<Text size="T200" priority="300">
|
||||
Held where you turned it. Pick a rotation to let it turn again.
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Slider
|
||||
key={`speed:${speedMax}`}
|
||||
label="Rotation speed"
|
||||
min={0}
|
||||
max={speedMax}
|
||||
step={SPEED_STEP}
|
||||
value={clamp(Math.abs(cam.speedDegPerS), 0, speedMax)}
|
||||
readout={(v) => `${v.toFixed(1)} deg/s`}
|
||||
onCommit={(speedDegPerS) => setCamera({ speedDegPerS })}
|
||||
/>
|
||||
{range && (
|
||||
<Slider
|
||||
key={`offset:${range[0]}:${range[1]}`}
|
||||
label="Parallax offset"
|
||||
min={range[0]}
|
||||
max={range[1]}
|
||||
step={OFFSET_STEP}
|
||||
value={Math.round(clamp(cam.offsetM, range[0], range[1]))}
|
||||
readout={signed}
|
||||
onCommit={(offsetM) => setCamera({ offsetM })}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
80
src/app/features/scene/view/turning.test.ts
Normal file
80
src/app/features/scene/view/turning.test.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { isHeld, resetCamera } from '../cameraState';
|
||||
import { poseAt, resetHeading } from '../ridge/heading';
|
||||
import { FALLBACK_VIEW } from '../ridge/view';
|
||||
import { createTurner, dragHeading, keyTurn, pxPerDegreeOf } from './turning';
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
});
|
||||
resetCamera();
|
||||
resetHeading();
|
||||
});
|
||||
|
||||
const PX = FALLBACK_VIEW.pxPerDegH * 1.65; // 17.78 px per degree of plane at the scale 1.65
|
||||
|
||||
describe('manual turning', () => {
|
||||
it('a drag turns the view against the finger, one for one with the far sky: 100 px at plane scale 1.65', () => {
|
||||
expect(dragHeading(100, 100, PX)).toBeCloseTo(100 - 100 / (17.7777778 * 1.65), 6);
|
||||
expect(dragHeading(100, -100, PX)).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it('pxPerDegreeOf is the plane pixels per degree at the viewport scale (windowFor)', () => {
|
||||
// 1280 x 720 on the fallback plane: scale max(0.6 x 720 / 600, 1280 / (65.45 x 17.78)) = 1.1
|
||||
expect(pxPerDegreeOf(FALLBACK_VIEW, 1280, 720)).toBeCloseTo(FALLBACK_VIEW.pxPerDegH * 1.1, 1);
|
||||
});
|
||||
|
||||
it('the heading owner holds the view where the drag leaves it, on every move, and not before a move', () => {
|
||||
let t = 0;
|
||||
const turner = createTurner(
|
||||
() => PX,
|
||||
() => t
|
||||
);
|
||||
poseAt(0); // a fresh page: the owner is anchored at heading 0
|
||||
turner.down(500);
|
||||
expect(isHeld()).toBe(false); // a tap that does not move holds nothing
|
||||
t = 16;
|
||||
turner.move(400);
|
||||
expect(isHeld()).toBe(true);
|
||||
expect(poseAt(16).h).toBeCloseTo(100 / PX, 6);
|
||||
t = 32;
|
||||
turner.move(300);
|
||||
expect(poseAt(32).h).toBeCloseTo(200 / PX, 6);
|
||||
turner.up();
|
||||
t = 48;
|
||||
turner.move(0); // no finger down: nothing moves
|
||||
expect(poseAt(48).h).toBeCloseTo(200 / PX, 6);
|
||||
});
|
||||
|
||||
it('arrows turn 5 degrees and with Shift 15; other keys are not turns', () => {
|
||||
expect(keyTurn('ArrowRight', false)).toBe(5);
|
||||
expect(keyTurn('ArrowLeft', false)).toBe(-5);
|
||||
expect(keyTurn('ArrowLeft', true)).toBe(-15);
|
||||
expect(keyTurn('ArrowUp', false)).toBeUndefined();
|
||||
const turner = createTurner(
|
||||
() => PX,
|
||||
() => 0
|
||||
);
|
||||
poseAt(0);
|
||||
expect(turner.key('ArrowRight', false)).toBe(true);
|
||||
expect(poseAt(0).h).toBeCloseTo(5, 9);
|
||||
expect(turner.key('ArrowLeft', true)).toBe(true);
|
||||
expect(poseAt(0).h).toBeCloseTo(-10, 9);
|
||||
expect(turner.key('Enter', false)).toBe(false);
|
||||
});
|
||||
|
||||
it('a horizontal wheel or swipe turns one for one the other way from a drag', () => {
|
||||
const turner = createTurner(
|
||||
() => PX,
|
||||
() => 0
|
||||
);
|
||||
poseAt(0);
|
||||
turner.wheel(PX * 3);
|
||||
expect(poseAt(0).h).toBeCloseTo(3, 9);
|
||||
turner.wheel(0);
|
||||
expect(poseAt(0).h).toBeCloseTo(3, 9);
|
||||
});
|
||||
});
|
||||
61
src/app/features/scene/view/turning.ts
Normal file
61
src/app/features/scene/view/turning.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// Manual turning, inside the scene view only: the one place a pointer, a key or a wheel becomes a heading. The sky is at infinity and pans one for one with the
|
||||
// view direction, so a drag of `dx` px is `dx / (pxPerDegH x plane.scale)` degrees (`view.ts` `windowFor`), against the finger: the sky follows it. Every turn goes to
|
||||
// the heading owner (`ridge/heading.ts` `hold`), which holds the view where it was left until a rotation mode is picked or Return is pressed (ruling
|
||||
// ridge-view-turn-handback). The rig is re-issued by the owner on each hold, so while a finger is down this is the one script that moves the ridge besides the
|
||||
// twinkle. Pitch is never turned (ruling ridge-frame-more-sky-fixed-pitch).
|
||||
import { hold, poseAt } from '../ridge/heading';
|
||||
import { windowFor } from '../ridge/view';
|
||||
import type { View } from '../ridge/view';
|
||||
|
||||
/** Degrees an arrow key turns the view, and with Shift. */
|
||||
export const KEY_STEP_DEG = 5;
|
||||
export const KEY_STEP_SHIFT_DEG = 15;
|
||||
|
||||
/** Screen pixels per degree of the far sky on a viewport `w` x `h`: the plane's pixels per degree at the scale the viewport gives it. */
|
||||
export const pxPerDegreeOf = (view: View, w: number, h: number): number =>
|
||||
view.pxPerDegH * windowFor(view, w, h).plane.scale;
|
||||
|
||||
/** The heading after a drag of `dxPx` from where it began at `h0`: against the finger, one for one with the sky. */
|
||||
export const dragHeading = (h0: number, dxPx: number, pxPerDeg: number): number =>
|
||||
h0 - dxPx / pxPerDeg;
|
||||
|
||||
/** The turn an arrow key asks, degrees (right positive), or undefined for any other key. */
|
||||
export function keyTurn(key: string, shift: boolean): number | undefined {
|
||||
const step = shift ? KEY_STEP_SHIFT_DEG : KEY_STEP_DEG;
|
||||
if (key === 'ArrowRight') return step;
|
||||
return key === 'ArrowLeft' ? -step : undefined;
|
||||
}
|
||||
|
||||
/** What the view's surface does with the events it is given: `pxPerDeg` is read at each event (a resize or a place changes it), `now` is the heading owner's clock. */
|
||||
export function createTurner(pxPerDeg: () => number, now: () => number = () => performance.now()) {
|
||||
let drag: { x0: number; h0: number } | undefined;
|
||||
const turnBy = (deg: number) => {
|
||||
const t = now();
|
||||
hold(poseAt(t).h + deg, t);
|
||||
};
|
||||
return {
|
||||
/** A finger or the mouse went down at `x`. */
|
||||
down(x: number): void {
|
||||
drag = { x0: x, h0: poseAt(now()).h };
|
||||
},
|
||||
/** It moved to `x`: the view faces where the drag puts it. Nothing before `down`. */
|
||||
move(x: number): void {
|
||||
if (drag) hold(dragHeading(drag.h0, x - drag.x0, pxPerDeg()), now());
|
||||
},
|
||||
up(): void {
|
||||
drag = undefined;
|
||||
},
|
||||
isDown: (): boolean => drag !== undefined,
|
||||
/** A horizontal wheel or trackpad swipe of `deltaX` px: the sky follows the fingers, so the view turns the other way from a drag. */
|
||||
wheel(deltaX: number): void {
|
||||
if (deltaX !== 0) turnBy(deltaX / pxPerDeg());
|
||||
},
|
||||
/** An arrow key; true when it turned the view. */
|
||||
key(key: string, shift: boolean): boolean {
|
||||
const deg = keyTurn(key, shift);
|
||||
if (deg === undefined) return false;
|
||||
turnBy(deg);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
30
src/app/hooks/useSceneView.test.ts
Normal file
30
src/app/hooks/useSceneView.test.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useSceneViewOffered } from './useSceneView';
|
||||
|
||||
const held = vi.hoisted(() => ({ config: undefined as unknown }));
|
||||
vi.mock('./useClientConfig', () => ({ useClientConfig: () => ({ backgroundScene: held.config }) }));
|
||||
|
||||
const device = (nav: Record<string, unknown>) => vi.stubGlobal('navigator', nav);
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('whether the scene view is offered', () => {
|
||||
it('is not with the tier off or absent, and is with any tier on', () => {
|
||||
device({});
|
||||
held.config = undefined;
|
||||
expect(useSceneViewOffered()).toBe(false);
|
||||
held.config = { tier: 'off' };
|
||||
expect(useSceneViewOffered()).toBe(false);
|
||||
for (const tier of ['still', 'low', 'full']) {
|
||||
held.config = { tier };
|
||||
expect(useSceneViewOffered()).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('follows the tier the device allows, not the one configured: no device ceiling turns a configured tier off', () => {
|
||||
device({ connection: { saveData: true } });
|
||||
held.config = { tier: 'full' };
|
||||
expect(useSceneViewOffered()).toBe(true); // lowered to still, still a scene
|
||||
});
|
||||
});
|
||||
56
src/app/hooks/useSceneView.ts
Normal file
56
src/app/hooks/useSceneView.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import { getCamera, isHeld, subscribe as subscribeCamera } from '../features/scene/cameraState';
|
||||
import type { CameraChoice } from '../features/scene/cameraState';
|
||||
import { getSceneView, subscribeSceneView } from '../features/scene/sceneView';
|
||||
import type { SceneViewState } from '../features/scene/sceneView';
|
||||
import { getConstellationLines, subscribe as subscribeSky } from '../features/scene/skyState';
|
||||
import { loadManifest } from '../features/scene/ridge/manifest';
|
||||
import type { RidgeManifest } from '../features/scene/ridge/manifest';
|
||||
import { readCapabilities, resolveTier } from '../features/scene/tier';
|
||||
import { useClientConfig } from './useClientConfig';
|
||||
|
||||
/** Whether the scene view is open and which submenu is up (sceneView.ts). */
|
||||
export const useSceneViewState = (): SceneViewState =>
|
||||
useSyncExternalStore(subscribeSceneView, getSceneView);
|
||||
|
||||
const onCamera = (cb: () => void): (() => void) => {
|
||||
const off = subscribeCamera(() => cb());
|
||||
return () => {
|
||||
off();
|
||||
};
|
||||
};
|
||||
|
||||
/** The viewer's rotation mode, speed and offset (cameraState.ts). */
|
||||
export const useCamera = (): CameraChoice => useSyncExternalStore(onCamera, getCamera);
|
||||
|
||||
/** Whether a manual turn holds the view (cameraState.ts): the rotation waits for a mode pick or Return. */
|
||||
export const useCameraHeld = (): boolean => useSyncExternalStore(onCamera, isHeld);
|
||||
|
||||
/** Whether the constellation lines are on (skyState.ts). */
|
||||
export const useConstellationLines = (): boolean =>
|
||||
useSyncExternalStore(subscribeSky, getConstellationLines);
|
||||
|
||||
/** The manifest of the configured place when the ridge scene is on and it has loaded (memoised by `loadManifest`, so this fetches nothing the scene did not). */
|
||||
export function useRidgeManifest(): RidgeManifest | undefined {
|
||||
const config = useClientConfig().backgroundScene;
|
||||
const ridgeOn = !!config && config.style !== 'raymarch';
|
||||
const [manifest, setManifest] = useState<RidgeManifest>();
|
||||
useEffect(() => {
|
||||
if (!ridgeOn) return undefined;
|
||||
let live = true;
|
||||
loadManifest(import.meta.env.BASE_URL, config?.place).then(
|
||||
(m) => live && setManifest(m),
|
||||
() => live && setManifest(undefined)
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [ridgeOn, config?.place]);
|
||||
return ridgeOn ? manifest : undefined;
|
||||
}
|
||||
|
||||
/** Whether the scene view is offered: the background scene is not switched off (tier). The one answer, for the entry and the host. */
|
||||
export function useSceneViewOffered(): boolean {
|
||||
const config = useClientConfig().backgroundScene;
|
||||
return resolveTier(config, readCapabilities(navigator)) !== 'off';
|
||||
}
|
||||
|
|
@ -22,7 +22,7 @@ import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
|
|||
import { LOGIN_PATH, REGISTER_PATH, RESET_PASSWORD_PATH } from '../paths';
|
||||
import RatatoskrSVG from '../../../../public/res/svg/ratatoskr.svg';
|
||||
import { LogoMark } from '../../components/logo/logoMark.css';
|
||||
import { SkyStateControl } from '../../features/scene/SkyStateControl';
|
||||
import { SceneViewEntry } from '../../features/scene/SceneViewEntry';
|
||||
import { ServerPicker } from './ServerPicker';
|
||||
import { AutoDiscoveryAction, autoDiscovery } from '../../cs-api';
|
||||
import { SpecVersionsLoader } from '../../components/SpecVersionsLoader';
|
||||
|
|
@ -144,7 +144,7 @@ export function AuthLayout() {
|
|||
/>
|
||||
<Text size="H3">Ratatoskr</Text>
|
||||
</Box>
|
||||
<SkyStateControl />
|
||||
<SceneViewEntry />
|
||||
</Header>
|
||||
<Box className={css.AuthCardContent} direction="Column">
|
||||
<Box direction="Column" gap="100">
|
||||
|
|
|
|||
|
|
@ -200,7 +200,9 @@ describe('icon buttons in the room view', () => {
|
|||
// Buttons that were fixed with #125 and had no test.
|
||||
'components/password-input/PasswordInput.tsx': ['PhoneHit'],
|
||||
'features/desk/Desk.tsx': ['PhoneHit'],
|
||||
'features/scene/SkyStateControl.tsx': ['PhoneHit'],
|
||||
'features/scene/SceneViewEntry.tsx': ['PhoneHit'], // the scene view's entry
|
||||
'features/scene/SceneViewHost.tsx': ['PhoneHit'], // Return while the scene view loads
|
||||
'features/scene/view/SceneView.tsx': ['PhoneHit'], // one rail button, five icons
|
||||
'pages/auth/login/PasswordLoginForm.tsx': ['PhoneHit'],
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue