Skip to content
Myr

theme.test.ts

This file

Path

apps/web/test/theme.test.ts

222 lines · 6.4 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 1–222why, one step back
1// ADR 0042: the system's scheme, or its opposite by the reader's choice, kept in localStorage and set before first paint.
2import { describe, expect, it } from "@effect/vitest";3import { Effect, Schema } from "effect";45import {6 readPreference,7 resolveTheme,8 THEME_PREFERENCE_KEY,9 THEME_SCRIPT,10 THEME_SCRIPT_SOURCE,11 themeColors,12 writePreference,13} from "../src/features/shared/theme.ts";14import type { Theme } from "../src/features/shared/theme.ts";15import { keptStorage, refusingStorage } from "./storage.ts";16import { themePage } from "./theme-page.ts";1718describe(resolveTheme, () => {19 it.each([20 ["light", "same", "light"],21 ["light", "opposite", "dark"],22 ["dark", "same", "dark"],23 ["dark", "opposite", "light"],24 ] as const)(25 "resolves a %s system with the %s preference to %s",26 (system, preference, theme) => {27 expect(resolveTheme(system, preference)).toBe(theme);28 }29 );30});3132describe(readPreference, () => {33 it("reads an unset preference as the same as the system", () => {34 expect(readPreference(keptStorage())).toBe("same");35 expect(readPreference()).toBe("same");36 });3738 it("reads a value it never wrote, or storage the browser refuses, as the same", () => {39 expect(40 readPreference(keptStorage({ [THEME_PREFERENCE_KEY]: "dark" }))41 ).toBe("same");42 expect(readPreference(refusingStorage)).toBe("same");43 });4445 it("reads back what was written", () => {46 const storage = keptStorage();4748 writePreference(storage, "opposite");4950 expect(readPreference(storage)).toBe("opposite");5152 writePreference(storage, "same");5354 expect(readPreference(storage)).toBe("same");55 });5657 it("writes nothing, and throws nothing, where the browser refuses storage", () => {58 expect(() => {59 writePreference(refusingStorage, "opposite");60 }).not.toThrow();61 });62});6364/** The head script as the browser runs it: its globals are the page's. */65const runHeadScript = (66 page: ReturnType<typeof themePage>,67 storage: Storage68) => {69 // oxlint-disable-next-line eslint/no-new-func, typescript/no-implied-eval, typescript/no-unsafe-call -- the test runs the inline head script's text as a browser does, with a fake page for its globals; the text is the module's own constant, and no DOM runs in these tests70 new Function(71 "document",72 "localStorage",73 "matchMedia",74 "addEventListener",75 THEME_SCRIPT76 )(page.document, storage, page.matchMedia, page.addEventListener);77};7879const storedAs = (stored: string | undefined) =>80 stored === undefined81 ? keptStorage()82 : keptStorage({ [THEME_PREFERENCE_KEY]: stored });8384describe("the head script", () => {85 it.each([86 ["light", undefined],87 ["light", "same"],88 ["light", "opposite"],89 ["dark", undefined],90 ["dark", "same"],91 ["dark", "opposite"],92 ] as const)(93 "sets data-theme on a %s system with %s stored as the resolver does",94 (system: Theme, stored) => {95 const page = themePage(system);96 const storage = storedAs(stored);9798 runHeadScript(page, storage);99100 const theme = resolveTheme(system, readPreference(storage));101102 expect(page.theme()).toBe(theme);103 expect(page.shownColour()).toBe(themeColors[theme]);104 }105 );106107 // A meta already in the head is left as it is: the script adds one of its108 // own ahead of it, which the browser takes first.109 it("colours the browser's bar with a meta of its own, leaving the head's as they were", () => {110 const page = themePage("light");111112 runHeadScript(page, storedAs("opposite"));113 page.turnSystem();114115 expect(page.metas()).toStrictEqual([116 {117 content: themeColors.light,118 "data-theme-color": "",119 name: "theme-color",120 },121 {122 content: "react-light",123 media: "(prefers-color-scheme: light)",124 name: "theme-color",125 },126 {127 content: "react-dark",128 media: "(prefers-color-scheme: dark)",129 name: "theme-color",130 },131 ]);132 });133134 it("follows the system as it changes", () => {135 const page = themePage("light");136137 runHeadScript(page, storedAs("opposite"));138139 expect(page.theme()).toBe("dark");140141 page.turnSystem();142143 expect(page.theme()).toBe("light");144 expect(page.shownColour()).toBe(themeColors.light);145 });146147 it("names the system's own scheme whatever the preference, as it turns", () => {148 const page = themePage("light");149150 runHeadScript(page, storedAs("opposite"));151152 expect(page.system()).toBe("light");153154 page.turnSystem();155156 expect(page.system()).toBe("dark");157 });158159 it("follows a preference another tab writes", () => {160 const page = themePage("light");161 const storage = storedAs("same");162163 runHeadScript(page, storage);164 writePreference(storage, "opposite");165 page.storageWritten();166167 expect(page.theme()).toBe("dark");168 });169170 it("follows the system where the browser refuses storage", () => {171 const page = themePage("dark");172173 runHeadScript(page, refusingStorage);174175 expect(page.theme()).toBe("dark");176 });177178 it("is tiny, imports nothing and never touches a cookie", () => {179 const page = themePage("light");180181 runHeadScript(page, storedAs("opposite"));182183 expect(new TextEncoder().encode(THEME_SCRIPT).length).toBeLessThan(640);184 expect(THEME_SCRIPT).not.toMatch(/\bimport\b|\brequire\b|cookie/u);185 expect(page.cookies).toStrictEqual([]);186 });187});188189// The web sets no Content-Security-Policy on its pages today; one that is190// added must allow the head script by this hash, or the theme never applies.191const encodeBase64 = Schema.encodeEffect(Schema.Uint8ArrayFromBase64);192193describe("the head script's CSP source", () => {194 const sources: Readonly<Record<string, string>> = import.meta.glob(195 ["../src/**/*.{ts,tsx}", "../public/_headers"],196 { eager: true, import: "default", query: "?raw" }197 );198199 it.effect("is the SHA-256 of the script's text", () =>200 Effect.gen(function* () {201 const digest = yield* Effect.promise(() =>202 crypto.subtle.digest("SHA-256", new TextEncoder().encode(THEME_SCRIPT))203 );204205 const hash = yield* encodeBase64(new Uint8Array(digest));206207 expect(THEME_SCRIPT_SOURCE).toBe(`'sha256-${hash}'`);208 })209 );210211 it("is named wherever the web sets a policy", () => {212 const setting = Object.entries(sources).flatMap(([path, source]) =>213 /content-security-policy/iu.test(source) ? [path] : []214 );215216 expect(217 setting.filter(218 (path) => sources[path]?.includes("THEME_SCRIPT_SOURCE") !== true219 )220 ).toStrictEqual([]);221 });222});