// The boot script that sets the stored theme and motion overrides before the // first paint: what it sets for each stored value, and that its keys are the // ones the shell reads. Run by `npm test`. import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { test } from "node:test"; import vm from "node:vm"; const script = readFileSync( new URL("../src/theme-boot.js", import.meta.url), "utf8", ); const shell = readFileSync( new URL("../src/shell/Shell.tsx", import.meta.url), "utf8", ); function boot(stored) { const dataset = {}; const localStorage = { getItem: (key) => (key in stored ? stored[key] : null), }; vm.runInNewContext(script, { localStorage, document: { documentElement: { dataset } }, }); return dataset; } test("nothing stored sets the dark default and leaves motion to the system", () => { assert.deepEqual(boot({}), { theme: "dark" }); }); test("a stored light theme and a motion override are set", () => { const set = boot({ "swarm-ui:theme-override": '"light"', "swarm-ui:motion-override": '"reduce"', }); assert.deepEqual(set, { theme: "light", motion: "reduce" }); }); test("system leaves the attribute off, so the media query decides", () => { assert.deepEqual(boot({ "swarm-ui:theme-override": '"system"' }), {}); }); test("a value that is not JSON, or not one of the choices, is ignored", () => { assert.deepEqual(boot({ "swarm-ui:theme-override": "light" }), { theme: "dark", }); assert.deepEqual(boot({ "swarm-ui:theme-override": '"blue"' }), {}); }); test("storage that throws behaves as if nothing were stored", () => { const dataset = {}; vm.runInNewContext(script, { localStorage: { getItem() { throw new Error("blocked"); }, }, document: { documentElement: { dataset } }, }); assert.deepEqual(dataset, { theme: "dark" }); }); test("the keys are the shell's", () => { assert.match(shell, /THEME_KEY = "swarm-ui:theme-override"/); assert.match(shell, /MOTION_KEY = "swarm-ui:motion-override"/); });