scene view: the fullscreen view replaces the sky menu
The entry button opens the view; its rail (Return, View, Time, Sky, Place) holds the moved time choices and picker, the rotation mode, speed and signed offset sliders (bounded by maxSpeed and offsetRange, committed on release through cameraState), the constellation lines switch and the credits. Dragging, arrows and a horizontal wheel turn the heading by hand through heading.hold; Return resumes the rotation via setCamera. The credit lives in the Place submenu per ruling ridge-view-credits-home. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3ea2370424
commit
ad13bb2c24
20 changed files with 1275 additions and 313 deletions
|
|
@ -55,7 +55,7 @@ import { activateEstateRoom, awaitMyJoin } from './joinEstateRoom';
|
|||
import { useEstate, useEstateRootId } from './useEstate';
|
||||
import * as css from './EstateNavigator.css';
|
||||
import { DeskEntry } from '../desk';
|
||||
import { SkyStateControl } from '../scene/SkyStateControl';
|
||||
import { SceneViewEntry } from '../scene/SkyStateControl';
|
||||
|
||||
type IconSrc = ComponentProps<typeof Icon>['src'];
|
||||
|
||||
|
|
@ -389,7 +389,7 @@ export function EstateNavigator() {
|
|||
{title}
|
||||
</Text>
|
||||
</Box>
|
||||
<SkyStateControl />
|
||||
<SceneViewEntry />
|
||||
<IconButton
|
||||
variant="Background"
|
||||
aria-label="Find a room"
|
||||
|
|
|
|||
|
|
@ -1,18 +1,36 @@
|
|||
import React, { useEffect, useRef } from 'react';
|
||||
import React, { Suspense, lazy, useEffect, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||
import { getFallbackSession } from '../../state/sessions';
|
||||
import { mountBackgroundScene } from './host';
|
||||
import { setSceneDrawn } from './sceneDrawn';
|
||||
import { loadSceneView } from './sceneView';
|
||||
import { useSceneViewState } from '../../hooks/useSceneView';
|
||||
import { readCapabilities, resolveTier } from './tier';
|
||||
import './sceneShell.css';
|
||||
import './sceneButtons.css';
|
||||
|
||||
const SceneView = lazy(loadSceneView);
|
||||
|
||||
/** The scene view (sceneView.ts) in the portal layer while it is open: over the scene, outside the app it hides. */
|
||||
function SceneViewHost() {
|
||||
const { open } = useSceneViewState();
|
||||
const portal = document.getElementById('portalContainer');
|
||||
if (!open || !portal) return null;
|
||||
return createPortal(
|
||||
<Suspense fallback={null}>
|
||||
<SceneView />
|
||||
</Suspense>,
|
||||
portal
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The one host for the background scene, mounted once at the app root. Fixed behind everything
|
||||
* (z-index -1 sits above the body's background and below all normal content; the signed-out
|
||||
* screens and the signed-in shell, see sceneShell.css.ts, are clear so the scene shows through). The ridge scene
|
||||
* draws its layers into this wrapper beside the canvas, so the wrapper is the positioned box.
|
||||
* Tier 'off' renders nothing and loads nothing.
|
||||
* Tier 'off' renders no scene and loads none; the scene view's host is here too, since the view is an overlay over this scene.
|
||||
*/
|
||||
export function BackgroundScene() {
|
||||
const config = useClientConfig().backgroundScene;
|
||||
|
|
@ -35,13 +53,17 @@ export function BackgroundScene() {
|
|||
};
|
||||
}, [config, enabled]);
|
||||
|
||||
if (!enabled) return null;
|
||||
return (
|
||||
<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' }}
|
||||
>
|
||||
<canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
|
||||
</div>
|
||||
)}
|
||||
<SceneViewHost />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,282 +1,27 @@
|
|||
import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
config,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Menu,
|
||||
MenuItem,
|
||||
PopOut,
|
||||
RectCords,
|
||||
Text,
|
||||
} from 'folds';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState';
|
||||
import { setSkyChoice, skyNow } from './skyState';
|
||||
import {
|
||||
FREE_DATE_MAX,
|
||||
FREE_DATE_MIN,
|
||||
MOMENT_IDS,
|
||||
isDate,
|
||||
seedFree,
|
||||
zoneName,
|
||||
zonedInstant,
|
||||
} from './ridge/skyMoment';
|
||||
import type { MomentId, SkyChoice } from './ridge/skyMoment';
|
||||
import { FALLBACK_VIEW } from './ridge/view';
|
||||
import { loadManifest } from './ridge/manifest';
|
||||
import {
|
||||
LINES_CREDIT,
|
||||
STARS_CREDIT,
|
||||
terrainCredit,
|
||||
WEATHER_CREDIT,
|
||||
WEATHER_CREDIT_URL,
|
||||
WEATHER_DATASET,
|
||||
} from './ridge/credits';
|
||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||
import React from 'react';
|
||||
import { Icon, IconButton, Icons } from 'folds';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
||||
export const MOMENT_LABEL: Record<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);
|
||||
import { loadSceneView, openSceneView } from './sceneView';
|
||||
|
||||
/**
|
||||
* Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
|
||||
* input event). Each commit rebuilds the scene, so a drag must commit once.
|
||||
* The title-bar button that opens the scene view, the fullscreen view of the background scene with its own controls (sceneView.ts). A single button, not a
|
||||
* row, so the bar still fits a 320 px phone beside the search button. The view's code loads when the button is hovered or focused.
|
||||
*/
|
||||
export function useNativeChange<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());
|
||||
export function SceneViewEntry() {
|
||||
const preload = () => {
|
||||
loadSceneView().catch(() => undefined); // a failed chunk is asked for again when the view opens
|
||||
};
|
||||
|
||||
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={() => {
|
||||
setSkyChoice(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={setSkyChoice}
|
||||
/>
|
||||
)}
|
||||
{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="Scene view"
|
||||
title="Scene view"
|
||||
onMouseEnter={preload}
|
||||
onFocus={preload}
|
||||
onClick={openSceneView}
|
||||
>
|
||||
<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>
|
||||
<Icon src={Icons.Photo} size="200" />
|
||||
</IconButton>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,3 +28,6 @@ globalStyle(':root[data-scene] #root', {
|
|||
const surfaceInkVar = createVar();
|
||||
globalStyle(':root[data-scene] body', { vars: { [surfaceInkVar]: color.Surface.Container } });
|
||||
export const surfaceInk = fallbackVar(surfaceInkVar, color.Surface.Container);
|
||||
|
||||
// While the scene view is open (sceneView.ts) the app stays mounted, so the chat keeps its scroll and its composer, but it is hidden (and inert, set by sceneView.ts).
|
||||
globalStyle(':root[data-scene-view] #root', { visibility: 'hidden' });
|
||||
|
|
|
|||
|
|
@ -40,10 +40,13 @@ beforeEach(() => {
|
|||
},
|
||||
getElementById: (id: string) =>
|
||||
id === 'root'
|
||||
? { setAttribute: (k: string) => rootAttrs.add(k), removeAttribute: (k: string) => rootAttrs.delete(k) }
|
||||
? {
|
||||
setAttribute: (k: string) => rootAttrs.add(k),
|
||||
removeAttribute: (k: string) => rootAttrs.delete(k),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
vi.stubGlobal('history', {
|
||||
const history = {
|
||||
get state() {
|
||||
return stack[stack.length - 1];
|
||||
},
|
||||
|
|
@ -53,12 +56,17 @@ beforeEach(() => {
|
|||
stack.pop();
|
||||
[...pops].forEach((cb) => cb());
|
||||
},
|
||||
});
|
||||
};
|
||||
vi.stubGlobal('window', {
|
||||
history,
|
||||
addEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.add(cb),
|
||||
removeEventListener: (t: string, cb: () => void) => t === 'popstate' && pops.delete(cb),
|
||||
});
|
||||
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined, removeItem: () => undefined });
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: () => null,
|
||||
setItem: () => undefined,
|
||||
removeItem: () => undefined,
|
||||
});
|
||||
resetCamera();
|
||||
});
|
||||
|
||||
|
|
@ -95,7 +103,7 @@ describe('the scene view', () => {
|
|||
openSceneView();
|
||||
const seen = vi.fn();
|
||||
subscribeSceneView(seen);
|
||||
history.back();
|
||||
window.history.back();
|
||||
expect(getSceneView().open).toBe(false);
|
||||
expect(stack).toHaveLength(1);
|
||||
expect(back).toBe(1); // that one was the browser's; the close did not go back again
|
||||
|
|
|
|||
|
|
@ -52,7 +52,10 @@ export function openSceneView(): void {
|
|||
if (state.open) return;
|
||||
entry = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
try {
|
||||
history.pushState({ ...(history.state ?? {}), [SCENE_VIEW_HISTORY_MARK]: true }, '');
|
||||
window.history.pushState(
|
||||
{ ...(window.history.state ?? {}), [SCENE_VIEW_HISTORY_MARK]: true },
|
||||
''
|
||||
);
|
||||
pushed = true;
|
||||
} catch {
|
||||
pushed = false; // no history to push to: Return and Escape still close it
|
||||
|
|
@ -82,7 +85,7 @@ export function closeSceneView(): void {
|
|||
if (!state.open) return;
|
||||
const wasPushed = pushed;
|
||||
finish(); // takes the popstate listener off first, so the back below does not close twice
|
||||
if (wasPushed && history.state?.[SCENE_VIEW_HISTORY_MARK]) history.back();
|
||||
if (wasPushed && window.history.state?.[SCENE_VIEW_HISTORY_MARK]) window.history.back();
|
||||
pushed = false;
|
||||
}
|
||||
|
||||
|
|
@ -91,3 +94,6 @@ export function setSubmenu(submenu: Submenu | undefined): void {
|
|||
if (!state.open) return;
|
||||
set({ open: true, submenu: submenu === state.submenu ? undefined : submenu });
|
||||
}
|
||||
|
||||
/** The view's code, a chunk of its own: asked for when the entry is hovered or focused, and by the host when the view opens. */
|
||||
export const loadSceneView = () => import('./view/SceneView');
|
||||
|
|
|
|||
38
src/app/features/scene/view/PlaceSubmenu.tsx
Normal file
38
src/app/features/scene/view/PlaceSubmenu.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import React from 'react';
|
||||
import { Box, Text } from 'folds';
|
||||
import { useDrawnPlace } from '../../../hooks/useSkyState';
|
||||
import { terrainCredit, WEATHER_CREDIT_URL, WEATHER_DATASET } from '../ridge/credits';
|
||||
import type { RidgeManifest } from '../ridge/manifest';
|
||||
import { FALLBACK_VIEW } from '../ridge/view';
|
||||
|
||||
/**
|
||||
* The Place submenu of the scene view: the shell and its credits. The carousel of baked places is cut ridge-places; until it lands this names the place shown.
|
||||
* The elevation credit lives here, under the place it credits (ruling ridge-view-credits-home), with the weather's, which GeoSphere asks for with any view of
|
||||
* its data.
|
||||
*/
|
||||
export function PlaceSubmenu({ manifest }: { manifest: RidgeManifest | undefined }) {
|
||||
const place = useDrawnPlace() ?? FALLBACK_VIEW.place;
|
||||
const credit = terrainCredit(manifest);
|
||||
return (
|
||||
<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">
|
||||
Datenquelle: GeoSphere Austria -{' '}
|
||||
<a href={WEATHER_CREDIT_URL} target="_blank" rel="noreferrer noopener">
|
||||
{WEATHER_CREDIT_URL}
|
||||
</a>
|
||||
. {WEATHER_DATASET}.
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
77
src/app/features/scene/view/SceneView.css.ts
Normal file
77
src/app/features/scene/view/SceneView.css.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { style } from '@vanilla-extract/css';
|
||||
import { color, config } from 'folds';
|
||||
import { PLATE_TINT, SKY_PLATE_FALLBACK } from '../skyPlate';
|
||||
import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize';
|
||||
|
||||
// The fullscreen scene view (sceneView.ts): the app is hidden behind it, so what is left over the scene is a turning surface and, top left, an icon rail and one
|
||||
// panel. The rail and the panel are plates, blurred and tinted toward the sky like the chat bubbles (skyPlate.css.ts, PLATE_TINT), so their text reads over any sky.
|
||||
const fill = `var(--sky-bubble, ${SKY_PLATE_FALLBACK.fill})`;
|
||||
const text = `var(--sky-bubble-text, ${SKY_PLATE_FALLBACK.text})`;
|
||||
const PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
|
||||
const GUTTER = 'max(0.5rem, env(safe-area-inset-top))';
|
||||
|
||||
export const Root = style({
|
||||
position: 'fixed',
|
||||
inset: 0,
|
||||
});
|
||||
|
||||
/** The whole viewport: a drag, a wheel or a swipe on it turns the view. A touch is never the page's (there is none to scroll). */
|
||||
export const Surface = style({
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
touchAction: 'none',
|
||||
overscrollBehavior: 'none',
|
||||
userSelect: 'none',
|
||||
cursor: 'grab',
|
||||
selectors: { '&:active': { cursor: 'grabbing' } },
|
||||
});
|
||||
|
||||
/** The rail and the panel, top left. It takes no pointer itself, so a drag over its gaps turns the view; its plates do. It fades while a finger is down. */
|
||||
export const Chrome = style({
|
||||
position: 'absolute',
|
||||
top: GUTTER,
|
||||
left: `max(0.5rem, env(safe-area-inset-left))`,
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
gap: config.space.S200,
|
||||
pointerEvents: 'none',
|
||||
transition: 'opacity 150ms',
|
||||
selectors: { [`${Root}[data-turning="true"] &`]: { opacity: 0.12 } },
|
||||
});
|
||||
|
||||
const Plate = style({
|
||||
pointerEvents: 'auto',
|
||||
backgroundColor: [fill, `color-mix(in srgb, ${fill} ${PLATE_TINT * 100}%, transparent)`],
|
||||
backdropFilter: 'blur(12px)',
|
||||
WebkitBackdropFilter: 'blur(12px)',
|
||||
color: text,
|
||||
borderRadius: config.radii.R400,
|
||||
vars: {
|
||||
[color.Background.OnContainer]: text,
|
||||
[color.Surface.OnContainer]: text,
|
||||
[color.SurfaceVariant.OnContainer]: text,
|
||||
},
|
||||
});
|
||||
|
||||
export const Rail = style([
|
||||
Plate,
|
||||
{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: config.space.S100,
|
||||
padding: config.space.S100,
|
||||
},
|
||||
]);
|
||||
|
||||
export const Panel = style([
|
||||
Plate,
|
||||
{
|
||||
boxSizing: 'border-box',
|
||||
width: '22rem',
|
||||
maxWidth: 'calc(100vw - 5.5rem)',
|
||||
maxHeight: `calc(100dvh - 2 * ${GUTTER})`,
|
||||
overflowY: 'auto',
|
||||
padding: config.space.S300,
|
||||
'@media': { [PHONE]: { width: 'calc(100vw - 5.5rem)' } },
|
||||
},
|
||||
]);
|
||||
162
src/app/features/scene/view/SceneView.test.tsx
Normal file
162
src/app/features/scene/view/SceneView.test.tsx
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { PhoneHit } from '../../../styles/PhoneHit.css';
|
||||
import SceneView, { Rail, SUBMENUS } from './SceneView';
|
||||
|
||||
// The hooks are held still (TimeSubmenu.test.tsx): the element tree is read, a function component is expanded by calling it.
|
||||
const held = vi.hoisted(() => ({
|
||||
effects: [] as Array<() => unknown>,
|
||||
submenu: undefined as unknown,
|
||||
closed: 0,
|
||||
picked: [] as unknown[],
|
||||
}));
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>();
|
||||
const useState = (init: unknown) => [
|
||||
typeof init === 'function' ? (init as () => unknown)() : init,
|
||||
() => undefined,
|
||||
];
|
||||
const useRef = (init: unknown) => ({ current: init });
|
||||
const useMemo = (fn: () => unknown) => fn();
|
||||
const useEffect = (fn: () => unknown) => {
|
||||
held.effects.push(fn);
|
||||
};
|
||||
return {
|
||||
...actual,
|
||||
default: { ...actual, useState, useRef, useEffect, useMemo },
|
||||
useState,
|
||||
useRef,
|
||||
useEffect,
|
||||
useMemo,
|
||||
};
|
||||
});
|
||||
vi.mock('../../../hooks/useSceneView', () => ({
|
||||
useSceneViewState: () => ({ open: true, submenu: held.submenu }),
|
||||
useRidgeManifest: () => undefined,
|
||||
}));
|
||||
vi.mock('../sceneView', () => ({
|
||||
closeSceneView: () => {
|
||||
held.closed += 1;
|
||||
},
|
||||
setSubmenu: (s: unknown) => held.picked.push(s),
|
||||
}));
|
||||
vi.mock('focus-trap-react', () => ({ default: ({ children }: { children: unknown }) => children }));
|
||||
|
||||
type El = { type?: unknown; ref?: unknown; key?: unknown; props?: Record<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;
|
||||
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);
|
||||
});
|
||||
});
|
||||
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>
|
||||
);
|
||||
}
|
||||
41
src/app/features/scene/view/SkySubmenu.tsx
Normal file
41
src/app/features/scene/view/SkySubmenu.tsx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import React from 'react';
|
||||
import { Box, Switch, Text } from 'folds';
|
||||
import { useConstellationLines } from '../../../hooks/useSceneView';
|
||||
import { setConstellationLines } from '../skyState';
|
||||
import { LINES_CREDIT, STARS_CREDIT } from '../ridge/credits';
|
||||
|
||||
/**
|
||||
* The Sky submenu of the scene view: the constellation lines (an explicit option, per viewer; it replaces the hidden re-pick of Night) and the credits of the
|
||||
* stars and the lines drawn over them.
|
||||
*/
|
||||
export function SkySubmenu() {
|
||||
const lines = useConstellationLines();
|
||||
return (
|
||||
<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 direction="Column" gap="100">
|
||||
<Text size="L400" priority="300">
|
||||
Data
|
||||
</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{STARS_CREDIT}.
|
||||
</Text>
|
||||
<Text size="T200" priority="300">
|
||||
{LINES_CREDIT}.
|
||||
</Text>
|
||||
</Box>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
126
src/app/features/scene/view/ViewSubmenu.test.tsx
Normal file
126
src/app/features/scene/view/ViewSubmenu.test.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
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, 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 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);
|
||||
});
|
||||
});
|
||||
153
src/app/features/scene/view/ViewSubmenu.tsx
Normal file
153
src/app/features/scene/view/ViewSubmenu.tsx
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
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;
|
||||
|
||||
/** 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. */
|
||||
export const speedBounds = (
|
||||
manifest: RidgeManifest | undefined,
|
||||
mode: RotationMode
|
||||
): [number, number] => [
|
||||
0,
|
||||
Math.floor((manifest ? maxSpeed(manifest, mode) : SPEED_CEILING_DEG_S) / SPEED_STEP) * SPEED_STEP,
|
||||
];
|
||||
|
||||
/** 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;
|
||||
},
|
||||
};
|
||||
}
|
||||
49
src/app/hooks/useSceneView.ts
Normal file
49
src/app/hooks/useSceneView.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
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 { 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;
|
||||
}
|
||||
|
|
@ -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/SkyStateControl';
|
||||
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,8 @@ 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/SkyStateControl.tsx': ['PhoneHit'], // the scene view's entry
|
||||
'features/scene/view/SceneView.tsx': ['PhoneHit'], // one rail button, five icons
|
||||
'pages/auth/login/PasswordLoginForm.tsx': ['PhoneHit'],
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue