settings.test.tsx
This file
Path
apps/web/test/settings.test.tsx
280 lines · 8.3 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
Merge redesign into mainoscabrielbefore adoptioncaedd21
lines 1–280why, one step back1// ADR 0042: /settings → Appearance, "Same as system" or "Opposite of system", each shown as what it resolves to now.2import { describe, expect, it } from "@effect/vitest";3import { Effect } from "effect";45import {6 AppearanceView,7 choosePreference,8 preferenceStore,9} from "../src/features/settings/appearance.tsx";10import { SettingsView } from "../src/features/settings/settings-page.tsx";11import {12 readPreference,13 resolveTheme,14 THEME_PREFERENCE_KEY,15 THEME_PREFERENCES,16 writePreference,17} from "../src/features/shared/theme.ts";18import type { Theme, ThemePreference } from "../src/features/shared/theme.ts";19import { attributeOf, textIn } from "./markup.ts";20import { renderAt } from "./render.tsx";21import { keptStorage, refusingStorage } from "./storage.ts";22import { themePage } from "./theme-page.ts";2324import styles from "../src/styles.css?raw";2526const ignore = () => {};2728/** Each choice as its label reads, and the radio it holds. */29const choicesIn = (markup: string) =>30 [...markup.matchAll(/<label\b[^>]*>(?<body>[^]*?)<\/label>/gu)].map(31 ({ groups }) => {32 const body = groups?.body ?? "";33 const radio = /<input\b[^>]*type="radio"[^>]*>/u.exec(body)?.[0] ?? "";3435 return {36 checked: / checked=""/u.test(radio),37 text: textIn(body),38 value: attributeOf(radio, "value"),39 };40 }41 );4243/** The word the stylesheet draws after a choice's span on a system, before React can see it. */44const drawnBefore = (system: Theme, choice: ThemePreference) => {45 const css = styles.replaceAll(/\/\*[\s\S]*?\*\//gu, "");46 const selector = `:root[data-system="${system}"] [data-system-resolves="${choice}"]::after`;4748 return [49 ...css.matchAll(/(?<selectors>[^{}]+)\{\s*content: "(?<word>\w+)";\s*\}/gu),50 ].flatMap(({ groups }) =>51 groups?.selectors?.split(",").some((each) => each.trim() === selector) ===52 true53 ? [groups.word]54 : []55 );56};5758const appearanceAt = (system: Theme | undefined, preference: ThemePreference) =>59 renderAt(60 "/settings",61 <AppearanceView onChoose={ignore} preference={preference} system={system} />62 );6364describe(AppearanceView, () => {65 it.effect(66 "shows both choices, each with the theme it gives on a light system",67 () =>68 Effect.gen(function* () {69 const choices = choicesIn(yield* appearanceAt("light", "same"));7071 expect(choices).toStrictEqual([72 { checked: true, text: "Same as systemLight", value: "same" },73 { checked: false, text: "Opposite of systemDark", value: "opposite" },74 ]);75 })76 );7778 it.effect("turns each choice's theme round on a dark system", () =>79 Effect.gen(function* () {80 const choices = choicesIn(yield* appearanceAt("dark", "opposite"));8182 expect(choices).toStrictEqual([83 { checked: false, text: "Same as systemDark", value: "same" },84 { checked: true, text: "Opposite of systemLight", value: "opposite" },85 ]);86 })87 );8889 // The server cannot see the reader's system, so it names no theme it90 // would have to take back.91 it.effect("names no theme until the system is known", () =>92 Effect.gen(function* () {93 const choices = choicesIn(yield* appearanceAt(undefined, "same"));9495 expect(choices.map(({ text }) => text)).toStrictEqual([96 "Same as system",97 "Opposite of system",98 ]);99 })100 );101102 // The head script names the system before first paint, so the stylesheet103 // can show what each choice gives without waiting for React.104 it.effect(105 "marks each choice for the stylesheet until the system is known",106 () =>107 Effect.gen(function* () {108 const markup = yield* appearanceAt(undefined, "same");109110 expect(111 [...markup.matchAll(/data-system-resolves="(?<choice>\w+)"/gu)].map(112 ({ groups }) => groups?.choice113 )114 ).toStrictEqual([...THEME_PREFERENCES]);115 })116 );117118 it.each(["light", "dark"] as const)(119 "draws, before React runs, what each choice gives on a %s system",120 (system) => {121 expect(122 THEME_PREFERENCES.map((choice) => drawnBefore(system, choice))123 ).toStrictEqual(124 THEME_PREFERENCES.map((choice) => [125 resolveTheme(system, choice) === "dark" ? "Dark" : "Light",126 ])127 );128 }129 );130});131132describe(SettingsView, () => {133 it.effect(134 "is the settings page, with Appearance and the same as the system checked while nothing is stored",135 () =>136 Effect.gen(function* () {137 const markup = yield* renderAt("/settings", <SettingsView />);138139 expect(textIn(markup)).toContain("Settings");140 expect(textIn(markup)).toContain("Appearance");141 expect(142 choicesIn(markup).flatMap(({ checked, value }) =>143 checked ? [value] : []144 )145 ).toStrictEqual(["same"]);146 })147 );148});149150describe(choosePreference, () => {151 it("writes the choice to localStorage and applies it, writing no cookie", () => {152 const page = themePage("light");153 const storage = keptStorage();154155 choosePreference("opposite", {156 document: page.document,157 storage,158 system: "light",159 });160161 expect(storage.getItem(THEME_PREFERENCE_KEY)).toBe("opposite");162 expect(readPreference(storage)).toBe("opposite");163 expect(page.theme()).toBe("dark");164 expect(page.cookies).toStrictEqual([]);165 });166167 it("goes back to the system's theme", () => {168 const page = themePage("dark");169 const storage = keptStorage({ [THEME_PREFERENCE_KEY]: "opposite" });170171 choosePreference("same", {172 document: page.document,173 storage,174 system: "dark",175 });176177 expect(readPreference(storage)).toBe("same");178 expect(page.theme()).toBe("dark");179 expect(page.cookies).toStrictEqual([]);180 });181});182183/** The store over a page, with what it heard counted. */184const storeOn = (storage: Storage) => {185 const page = themePage("light");186 const store = preferenceStore(() => storage, page);187 const heard = { times: 0 };188189 store.subscribe(() => {190 heard.times += 1;191 });192193 return { heard, page, store };194};195196describe(preferenceStore, () => {197 it("shows the choice made here", () => {198 const storage = keptStorage();199 const { heard, store } = storeOn(storage);200201 writePreference(storage, "opposite");202 store.choose("opposite");203204 expect(store.current()).toBe("opposite");205 expect(heard.times).toBe(1);206 });207208 // The head script redraws the page in what the other tab wrote; the209 // checked radio says the same.210 it("shows what another tab writes after a choice made here", () => {211 const storage = keptStorage();212 const { heard, page, store } = storeOn(storage);213214 writePreference(storage, "opposite");215 store.choose("opposite");216 writePreference(storage, "same");217 page.storageWritten();218219 expect(store.current()).toBe("same");220 expect(heard.times).toBe(2);221 });222223 it("keeps the choice made here when another key is written", () => {224 const storage = keptStorage();225 const { page, store } = storeOn(storage);226227 store.choose("opposite");228 page.storageWritten("another.key");229230 expect(store.current()).toBe("opposite");231 });232233 it("keeps the choice made here where the browser refuses storage", () => {234 const { store } = storeOn(refusingStorage);235236 store.choose("opposite");237238 expect(store.current()).toBe("opposite");239 });240241 it("stops hearing another tab once unsubscribed", () => {242 const storage = keptStorage();243 const page = themePage("light");244 const store = preferenceStore(() => storage, page);245 const heard = { times: 0 };246247 store.subscribe(() => {248 heard.times += 1;249 })();250 page.storageWritten();251252 expect(heard.times).toBe(0);253 });254});255256describe("the preference's code", () => {257 const sources: Readonly<Record<string, string>> = import.meta.glob(258 [259 "../src/features/settings/**/*.{ts,tsx}",260 "../src/features/shared/theme.ts",261 "../src/routes/settings.tsx",262 ],263 { eager: true, import: "default", query: "?raw" }264 );265266 // A cookie would mark every request as personal, out of the edge cache.267 it("never reaches for a cookie", () => {268 const uncommented = Object.entries(sources).map(([path, source]) => [269 path,270 source.replaceAll(/\/\*[^]*?\*\/|\/\/.*$/gmu, ""),271 ]);272273 expect(uncommented.length).toBeGreaterThanOrEqual(4);274 expect(275 uncommented.flatMap(([path, source]) =>276 /cookie/iu.test(source ?? "") ? [path] : []277 )278 ).toStrictEqual([]);279 });280});