diff --git a/src/app/features/scene/BackgroundScene.tsx b/src/app/features/scene/BackgroundScene.tsx index ff1045dd..23f50f04 100644 --- a/src/app/features/scene/BackgroundScene.tsx +++ b/src/app/features/scene/BackgroundScene.tsx @@ -2,13 +2,11 @@ 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 { readCapabilities, resolveTier } from './tier'; import './sceneShell.css'; import './sceneButtons.css'; -/** Set on while a scene runs, so signed-out screens can let it show through. */ -export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene'; - /** * 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 @@ -24,17 +22,16 @@ export function BackgroundScene() { useEffect(() => { const canvas = canvasRef.current; if (!enabled || !canvas) return undefined; - const root = document.documentElement; const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, { loggedIn: !!getFallbackSession(), - onActive: () => root.setAttribute(SCENE_ACTIVE_ATTRIBUTE, ''), - onInactive: () => root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE), + onActive: () => setSceneDrawn(true), + onInactive: () => setSceneDrawn(false), // eslint-disable-next-line no-console onFail: (e) => console.warn('Background scene unavailable:', e), }); return () => { dispose(); - root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE); + setSceneDrawn(false); }; }, [config, enabled]); diff --git a/src/app/features/scene/sceneDrawn.test.ts b/src/app/features/scene/sceneDrawn.test.ts new file mode 100644 index 00000000..5e51f7ce --- /dev/null +++ b/src/app/features/scene/sceneDrawn.test.ts @@ -0,0 +1,37 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + SCENE_ACTIVE_ATTRIBUTE, + getSceneDrawn, + setSceneDrawn, + subscribeSceneDrawn, +} from './sceneDrawn'; + +const attrs = new Set(); +vi.stubGlobal('document', { + documentElement: { + setAttribute: (n: string) => attrs.add(n), + removeAttribute: (n: string) => attrs.delete(n), + }, +}); + +afterEach(() => setSceneDrawn(false)); + +describe('sceneDrawn: one store owns the flag and html[data-scene]', () => { + it('starts off, and on/off move the flag, the attribute and the subscribers together', () => { + const cb = vi.fn(); + const off = subscribeSceneDrawn(cb); + expect(getSceneDrawn()).toBe(false); + setSceneDrawn(true); + expect(getSceneDrawn()).toBe(true); + expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(true); + setSceneDrawn(true); + expect(cb).toHaveBeenCalledTimes(1); + setSceneDrawn(false); + expect(getSceneDrawn()).toBe(false); + expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(false); + expect(cb).toHaveBeenCalledTimes(2); + off(); + setSceneDrawn(true); + expect(cb).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/app/features/scene/sceneDrawn.ts b/src/app/features/scene/sceneDrawn.ts new file mode 100644 index 00000000..ae7e47e0 --- /dev/null +++ b/src/app/features/scene/sceneDrawn.ts @@ -0,0 +1,29 @@ +// Whether a background scene is drawing a sky right now. BackgroundScene is the only writer: it sets this when the +// ridge scene starts, and clears it when the scene stops, fails to start, or loses its WebGL context (a restored +// context sets it again). This store also owns html[data-scene], so the attribute the CSS reads and the flag the theme +// hooks read cannot disagree. The configured tier only says a scene may run; this says one does. + +/** Set on while a scene is drawn, so signed-out screens can let it show through. */ +export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene'; + +let drawn = false; +const listeners = new Set<() => void>(); + +export const getSceneDrawn = (): boolean => drawn; + +export const subscribeSceneDrawn = (cb: () => void): (() => void) => { + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +}; + +export function setSceneDrawn(on: boolean): void { + if (typeof document !== 'undefined') { + if (on) document.documentElement.setAttribute(SCENE_ACTIVE_ATTRIBUTE, ''); + else document.documentElement.removeAttribute(SCENE_ACTIVE_ATTRIBUTE); + } + if (on === drawn) return; + drawn = on; + [...listeners].forEach((cb) => cb()); +} diff --git a/src/app/hooks/useSkyState.ts b/src/app/hooks/useSkyState.ts index 9aa390de..02cde126 100644 --- a/src/app/hooks/useSkyState.ts +++ b/src/app/hooks/useSkyState.ts @@ -6,8 +6,7 @@ import { type FixedSkyState, type SkyState, } from '../features/scene/skyState'; -import { readCapabilities, resolveTier } from '../features/scene/tier'; -import { useClientConfig } from './useClientConfig'; +import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn'; /** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */ export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState); @@ -16,6 +15,5 @@ export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSk export const useResolvedSkyState = (): FixedSkyState => useSyncExternalStore(subscribe, getResolvedSkyState); -/** Whether a background scene runs on this device and config (the tier the scene host will mount). */ -export const useSceneOn = (): boolean => - resolveTier(useClientConfig().backgroundScene, readCapabilities(navigator)) !== 'off'; +/** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */ +export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn); diff --git a/src/app/hooks/useTheme.test.ts b/src/app/hooks/useTheme.test.ts new file mode 100644 index 00000000..5707e5f1 --- /dev/null +++ b/src/app/hooks/useTheme.test.ts @@ -0,0 +1,88 @@ +import { createElement } from 'react'; +import { renderToString } from 'react-dom/server'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +// settings.ts reads localStorage when it loads; these suites run without a DOM. +const store: Record = {}; +vi.stubGlobal('localStorage', { + getItem: (k: string) => store[k] ?? null, + setItem: (k: string, v: string) => { + store[k] = v; + }, +}); +// Stored before settings.ts loads: a theme of the person's, and the themeChosen key old settings carry. +store['settings'] = JSON.stringify({ + themeId: 'dark-theme', + useSystemTheme: false, + themeChosen: true, +}); +vi.stubGlobal('window', { + matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }), +}); +// The skyState hooks are useSyncExternalStore reads of these two sources; the server renderer needs a snapshot of +// each, so the hooks read the same stores directly. +vi.mock('./useSkyState', async () => { + const drawn = await import('../features/scene/sceneDrawn'); + return { + useResolvedSkyState: () => 'night', + useSkyState: () => 'night', + useSceneOn: () => drawn.getSceneDrawn(), + }; +}); +// Style modules need a DOM to inject into; the class names are not what is under test. +vi.mock('folds', () => ({ lightTheme: 'light' })); +vi.mock('../../config.css', () => ({ onDarkFontWeight: 'dk', onLightFontWeight: 'lt' })); +vi.mock('../../colors.css', () => ({ + butterTheme: 'b', + darkTheme: 'd', + midnightSkyTheme: 'm', + noondaySkyTheme: 'n', + silverTheme: 's', +})); +vi.mock('../../gamecult.css', () => ({})); +vi.mock('../../sky.css', () => ({})); +vi.mock('./useScreenSize', () => ({ + ScreenSize: { Mobile: 'm' }, + useScreenSizeContext: () => 'd', +})); + +let useActiveTheme: typeof import('./useTheme').useActiveTheme; +let useSceneInk: typeof import('./useTheme').useSceneInk; +let setSceneDrawn: typeof import('../features/scene/sceneDrawn').setSceneDrawn; +beforeAll(async () => { + ({ useActiveTheme, useSceneInk } = await import('./useTheme')); + ({ setSceneDrawn } = await import('../features/scene/sceneDrawn')); +}); + +const read = () => { + let out = ''; + const Probe = () => { + out = `${useActiveTheme().id}|${JSON.stringify(useSceneInk() ?? null)}`; + return null; + }; + renderToString(createElement(Probe)); + return out; +}; + +describe('the drawn sky decides the theme and ink; the stored theme stands where none is drawn', () => { + beforeEach(() => { + setSceneDrawn(false); + }); + + it('a scene running over a stored theme wears the sky theme and ink', () => { + setSceneDrawn(true); + expect(read()).toBe('midnight-sky|{"state":"night","phone":false}'); + }); + + it('a scene that is not drawing (failed, or context lost) leaves the stored theme and its own ink', () => { + expect(read()).toBe('dark-theme|null'); + }); + + it('a restored context wears the sky again', () => { + setSceneDrawn(true); + setSceneDrawn(false); + expect(read()).toBe('dark-theme|null'); + setSceneDrawn(true); + expect(read()).toBe('midnight-sky|{"state":"night","phone":false}'); + }); +}); diff --git a/src/app/state/settings.test.ts b/src/app/state/settings.test.ts new file mode 100644 index 00000000..82e164cd --- /dev/null +++ b/src/app/state/settings.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it, vi } from 'vitest'; + +const stored = JSON.stringify({ themeId: 'dark-theme', themeChosen: true }); +vi.stubGlobal('localStorage', { getItem: () => stored, setItem: () => undefined }); + +describe('settings load', () => { + it('tolerates a themeChosen key stored by an older build: the rest loads, the key is inert', async () => { + const { getSettings, defaultThemeId } = await import('./settings'); + const s = getSettings() as unknown as Record; + expect(s.themeId).toBe('dark-theme'); + expect(s.useSystemTheme).toBe(false); + expect(defaultThemeId).toBeDefined(); + }); +}); diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index e5737196..b5165929 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -18,7 +18,6 @@ export enum MessageLayout { export interface Settings { themeId?: string; - /** Set when a theme is picked in the menu, so a picked default (Midnight Sky) reads as chosen. Absent until then. */ useSystemTheme: boolean; lightThemeId?: string; darkThemeId?: string;