useSceneOn reads whether a scene is drawn, not whether one is configured
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m50s

sceneDrawn.ts owns the flag and html[data-scene] together; BackgroundScene
publishes through it (start, stop, context loss and restore). A failed or
lost scene leaves the person's stored theme in force.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 23:08:32 +01:00
commit 8567439786
7 changed files with 175 additions and 13 deletions

View file

@ -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 <html> 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]);

View file

@ -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<string>();
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);
});
});

View file

@ -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 <html> 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());
}

View file

@ -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);

View file

@ -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<string, string> = {};
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}');
});
});

View file

@ -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<string, unknown>;
expect(s.themeId).toBe('dark-theme');
expect(s.useSystemTheme).toBe(false);
expect(defaultThemeId).toBeDefined();
});
});

View file

@ -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;