diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index 4bd43e35..ba4246cb 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -55,7 +55,7 @@ import { activateEstateRoom, awaitMyJoin } from './joinEstateRoom'; import { useEstate, useEstateRootId } from './useEstate'; import * as css from './EstateNavigator.css'; import { DeskEntry } from '../desk'; -import { SceneViewEntry } from '../scene/SkyStateControl'; +import { SceneViewEntry } from '../scene/SceneViewEntry'; type IconSrc = ComponentProps['src']; diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx index 02fade9c..54d48f08 100644 --- a/src/app/features/scene/BackgroundScene.tsx +++ b/src/app/features/scene/BackgroundScene.tsx @@ -1,30 +1,13 @@ -import React, { Suspense, lazy, useEffect, useRef } from 'react'; -import { createPortal } from 'react-dom'; +import React, { useEffect, useRef } from 'react'; 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 { SceneViewHost } from './SceneViewHost'; 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( - - - , - 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 diff --git a/src/app/features/scene/SceneViewEntry.test.tsx b/src/app/features/scene/SceneViewEntry.test.tsx new file mode 100644 index 00000000..a7a4a9d6 --- /dev/null +++ b/src/app/features/scene/SceneViewEntry.test.tsx @@ -0,0 +1,18 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SceneViewEntry } from './SceneViewEntry'; + +const offered = vi.hoisted(() => ({ value: true })); +vi.mock('../../hooks/useSceneView', () => ({ useSceneViewOffered: () => offered.value })); + +describe('the scene view entry', () => { + it('is offered with the scene on', () => { + offered.value = true; + expect((SceneViewEntry() as { props: Record }).props['aria-label']).toBe( + 'Scene view' + ); + }); + it('is not offered when the scene tier is off', () => { + offered.value = false; + expect(SceneViewEntry()).toBeNull(); + }); +}); diff --git a/src/app/features/scene/SkyStateControl.tsx b/src/app/features/scene/SceneViewEntry.tsx similarity index 77% rename from src/app/features/scene/SkyStateControl.tsx rename to src/app/features/scene/SceneViewEntry.tsx index 86be7713..941b01b3 100644 --- a/src/app/features/scene/SkyStateControl.tsx +++ b/src/app/features/scene/SceneViewEntry.tsx @@ -1,15 +1,19 @@ 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. + * 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 + loadSceneView().catch(() => undefined); // a failed chunk is asked for again when the view opens (SceneViewHost) }; return ( ({ + effects: [] as Array<() => unknown>, + open: true, + offered: true, + view: undefined as unknown, + closed: 0, + loads: [] as Array<(m: unknown) => void>, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = () => [held.view, () => undefined]; + 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; + }, + loadSceneViewOrClose: () => new Promise((res) => held.loads.push(res)), +})); + +type El = { type?: unknown; props?: Record }; +const walk = (node: unknown): El[] => { + if (Array.isArray(node)) return node.flatMap(walk); + if (node && typeof node === 'object' && 'props' in node) { + const el = node as El; + return [el, ...Object.values(el.props ?? {}).flatMap(walk)]; + } + return []; +}; + +beforeEach(() => { + held.effects.length = 0; + held.open = true; + held.offered = true; + held.view = undefined; + held.closed = 0; + held.loads.length = 0; + vi.stubGlobal('document', { getElementById: () => ({}) }); +}); +afterEach(() => vi.unstubAllGlobals()); + +describe('the view while its code loads', () => { + it('shows a Return that closes the view, with the phone tap target', () => { + const ret = walk(SceneViewLoading()).find((e) => e.props?.['aria-label'] === 'Return'); + expect(String(ret?.props?.className)).toContain(PhoneHit); + (ret?.props?.onClick as () => void)(); + expect(held.closed).toBe(1); + }); + + it('closes on Escape, and takes its listener off', () => { + const on: Record void> = {}; + let off = 0; + vi.stubGlobal('window', { + addEventListener: (t: string, cb: (e: unknown) => void) => { + on[t] = cb; + }, + removeEventListener: () => { + off += 1; + }, + }); + SceneViewLoading(); + const cleanup = held.effects[0]() as () => void; + on.keydown({ key: 'a', stopPropagation: () => undefined }); + expect(held.closed).toBe(0); + on.keydown({ key: 'Escape', stopPropagation: () => undefined }); + expect(held.closed).toBe(1); + cleanup(); + expect(off).toBe(1); + }); + + it('the open host stands Return in the portal until the view is loaded', () => { + expect((SceneViewHost() as unknown as El).type).toBe(SceneViewLoading); + }); + + it('asks for the code when the view opens, and the failed load (which closes the view) is the loader, not the host', () => { + SceneViewHost(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(1); + }); +}); + +describe('the host', () => { + it('renders nothing and loads nothing while the view is closed', () => { + held.open = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.loads).toHaveLength(0); + expect(held.closed).toBe(0); + }); + + it('with the scene tier off an open view closes, shows nothing and loads nothing', () => { + held.offered = false; + expect(SceneViewHost()).toBeNull(); + held.effects.forEach((run) => run()); + expect(held.closed).toBe(1); + expect(held.loads).toHaveLength(0); + }); +}); diff --git a/src/app/features/scene/SceneViewHost.tsx b/src/app/features/scene/SceneViewHost.tsx new file mode 100644 index 00000000..6724081b --- /dev/null +++ b/src/app/features/scene/SceneViewHost.tsx @@ -0,0 +1,67 @@ +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 } from './sceneView'; +import * as css from './sceneShell.css'; + +/** + * What stands in the portal while the view's code loads: Return and Escape, so the view can be left before the rest of it is there. The app behind is hidden + * and inert already, so without this the screen is blank. + */ +export function SceneViewLoading() { + useEffect(() => { + const onKey = (evt: KeyboardEvent) => { + if (evt.key === 'Escape') { + evt.stopPropagation(); + closeSceneView(); + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, []); + return ( + + + + ); +} + +/** + * The scene view (sceneView.ts) in the portal layer while it is open: over the scene, outside the app it hides. Its code is a chunk of its own: until it has + * loaded, `SceneViewLoading` is what is shown, and a failed load closes the view (`loadSceneViewOrClose`). The view is not offered with the scene tier off, so an + * open view that finds the tier off closes. + */ +export function SceneViewHost() { + const { open } = useSceneViewState(); + const offered = useSceneViewOffered(); + const [view, setView] = useState<{ View: ComponentType } | undefined>(); + const shown = open && offered; + + useEffect(() => { + if (open && !offered) closeSceneView(); + }, [open, offered]); + + useEffect(() => { + if (!shown) return undefined; + let live = true; + loadSceneViewOrClose().then((m) => { + if (live && m) setView({ View: m.default }); + }); + return () => { + live = false; + }; + }, [shown]); + + const portal = document.getElementById('portalContainer'); + if (!shown || !portal) return null; + return createPortal(view ? : , portal); +} diff --git a/src/app/features/scene/sceneShell.css.ts b/src/app/features/scene/sceneShell.css.ts index 033f4703..2d2ef01d 100644 --- a/src/app/features/scene/sceneShell.css.ts +++ b/src/app/features/scene/sceneShell.css.ts @@ -1,4 +1,4 @@ -import { createVar, fallbackVar, globalStyle } from '@vanilla-extract/css'; +import { createVar, fallbackVar, globalStyle, style } from '@vanilla-extract/css'; import { color } from 'folds'; // While the background scene runs (html[data-scene], set by BackgroundScene) the signed-in shell @@ -31,3 +31,10 @@ export const surfaceInk = fallbackVar(surfaceInkVar, color.Surface.Container); // While the scene view is open (sceneView.ts) the app stays mounted, so the chat keeps its scroll and its composer, but it is hidden (and inert, set by sceneView.ts). globalStyle(':root[data-scene-view] #root', { visibility: 'hidden' }); + +// Return while the scene view's code is still loading (SceneViewHost.tsx): the view's own rail is not there yet, so this one button stands where its Return will be. +export const LoadingReturn = style({ + position: 'fixed', + top: 'max(0.5rem, env(safe-area-inset-top))', + left: 'max(0.5rem, env(safe-area-inset-left))', +}); diff --git a/src/app/features/scene/sceneView.test.ts b/src/app/features/scene/sceneView.test.ts index 0b221041..fab9625f 100644 --- a/src/app/features/scene/sceneView.test.ts +++ b/src/app/features/scene/sceneView.test.ts @@ -5,6 +5,8 @@ import { SCENE_VIEW_HISTORY_MARK, closeSceneView, getSceneView, + loadSceneView, + loadSceneViewOrClose, openSceneView, setSubmenu, subscribeSceneView, @@ -138,3 +140,24 @@ describe('the scene view', () => { expect(getCamera().mode).toBe(mode); }); }); + +describe('the view code failing to load', () => { + it('closes an open view: the app is live again, nothing stays hidden, and the next open can ask again', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + openSceneView(); + const got = await loadSceneViewOrClose(() => Promise.reject(new Error('chunk'))); + expect(got).toBeUndefined(); + expect(getSceneView().open).toBe(false); + expect(rootAttrs.size).toBe(0); + expect(attrs.size).toBe(0); + openSceneView(); + expect(getSceneView().open).toBe(true); + }); + + it('a load that succeeds leaves the view open and hands back the module', async () => { + openSceneView(); + const mod = { default: () => null } as unknown as Awaited>; + expect(await loadSceneViewOrClose(() => Promise.resolve(mod))).toBe(mod); + expect(getSceneView().open).toBe(true); + }); +}); diff --git a/src/app/features/scene/sceneView.ts b/src/app/features/scene/sceneView.ts index 90181198..56c72f0d 100644 --- a/src/app/features/scene/sceneView.ts +++ b/src/app/features/scene/sceneView.ts @@ -97,3 +97,20 @@ export function setSubmenu(submenu: Submenu | undefined): void { /** The view's code, a chunk of its own: asked for when the entry is hovered or focused, and by the host when the view opens. */ export const loadSceneView = () => import('./view/SceneView'); + +/** + * The view's code for the host: a failed load closes the view (the app live again, the focus back on the entry), so nothing stays hidden behind a view that + * will not come. The next open asks for the chunk again. Resolves to the module, or undefined when the load failed. + */ +export async function loadSceneViewOrClose( + load: typeof loadSceneView = loadSceneView +): Promise> | undefined> { + try { + return await load(); + } catch (e) { + // eslint-disable-next-line no-console + console.warn('Scene view unavailable:', e); + closeSceneView(); + return undefined; + } +} diff --git a/src/app/hooks/useSceneView.ts b/src/app/hooks/useSceneView.ts index 095510b1..d63323f8 100644 --- a/src/app/hooks/useSceneView.ts +++ b/src/app/hooks/useSceneView.ts @@ -6,6 +6,7 @@ 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). */ @@ -47,3 +48,9 @@ export function useRidgeManifest(): RidgeManifest | undefined { }, [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'; +} diff --git a/src/app/pages/auth/AuthLayout.tsx b/src/app/pages/auth/AuthLayout.tsx index 2573cbd1..1e812592 100644 --- a/src/app/pages/auth/AuthLayout.tsx +++ b/src/app/pages/auth/AuthLayout.tsx @@ -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 { SceneViewEntry } 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'; diff --git a/src/app/phoneTapTargets.test.ts b/src/app/phoneTapTargets.test.ts index 670f48a6..bbcde9e6 100644 --- a/src/app/phoneTapTargets.test.ts +++ b/src/app/phoneTapTargets.test.ts @@ -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'], // the scene view's entry + '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'], };