Skip to content
Myr

theme.ts

This file

Path

apps/web/src/features/shared/theme.ts

124 lines · 4.5 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 1why, one step back
1/**

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 2–9why, one step back
2 * The theme (ADR 0042): the system's colour scheme, or its opposite by the
3 * reader's choice on `/settings`. The choice lives in `localStorage`, never a4 * cookie: a cookie would mark every request as personal, and the edge cache5 * keeps only requests without one.6 */7import { Option, Result, Schema } from "effect";89/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 10–11why, one step back
10 * For the places that cannot read a CSS variable (the `theme-color` meta, the
11 * manifest). They equal `--background` in `src/styles.css`.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 12–13why, one step back
12 */
13export const themeColors = {

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 14–15why, one step back
14 dark: "#0a0a0a",
15 light: "#f8f7f4",

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 16why, one step back
16} as const;

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 17–124why, one step back
17
18export type Theme = keyof typeof themeColors;1920export const ThemePreference = Schema.Literals(["same", "opposite"]);2122export type ThemePreference = typeof ThemePreference.Type;2324export const THEME_PREFERENCES = ThemePreference.literals;2526export const THEME_PREFERENCE_KEY = "theme.preference";2728export const DARK_SCHEME_QUERY = "(prefers-color-scheme: dark)";2930export const resolveTheme = (31 system: Theme,32 preference: ThemePreference33): Theme => {34 if (preference === "same") {35 return system;36 }3738 return system === "dark" ? "light" : "dark";39};4041const decodePreference = Schema.decodeUnknownOption(ThemePreference);4243/** Unset, unreadable or a value it never wrote: the same as the system. */44export const readPreference = (storage?: Storage): ThemePreference =>45 Option.getOrElse(46 decodePreference(47 Result.getOrUndefined(48 Result.try(() => storage?.getItem(THEME_PREFERENCE_KEY))49 )50 ),51 (): ThemePreference => "same"52 );5354export const writePreference = (55 storage: Storage | undefined,56 preference: ThemePreference57) => {58 Result.try(() => storage?.setItem(THEME_PREFERENCE_KEY, preference));59};6061/** The `theme-color` meta the theme owns, as the head script writes it. */62export const THEME_META = '<meta name="theme-color" data-theme-color>';6364interface ThemeMeta {65 readonly setAttribute: (name: string, value: string) => void;66}6768/** As much of a document as the theme writes to. */69export interface ThemeDocument {70 readonly documentElement: { readonly dataset: DOMStringMap };71 readonly head: {72 readonly insertAdjacentHTML: (73 position: "afterbegin",74 html: typeof THEME_META75 ) => void;76 };77 readonly querySelector: (78 selector: "meta[data-theme-color]"79 ) => ThemeMeta | null;80}8182/**83 * The `theme-color` meta the theme owns. React's two, one per scheme, sit in84 * a noscript for a page without scripts, and any other meta is left as it is:85 * this one goes first in the head, and a browser takes the first that matches.86 */87const ownMeta = (document: ThemeDocument) => {88 const found = document.querySelector("meta[data-theme-color]");8990 if (found !== null) {91 return found;92 }9394 document.head.insertAdjacentHTML("afterbegin", THEME_META);9596 return document.querySelector("meta[data-theme-color]");97};9899/** What the head script does, for a page that changes the theme once it is up. */100export const applyTheme = (document: ThemeDocument, theme: Theme) => {101 document.documentElement.dataset.theme = theme;102 ownMeta(document)?.setAttribute("content", themeColors[theme]);103};104105/**106 * The one script the web runs before its own (ADR 0042), inlined in the head107 * by `routes/__root.tsx`. It does what `applyTheme` does, for the theme108 * `resolveTheme` gives: sets `data-theme` on `<html>` before first paint and109 * colours a `theme-color` meta of its own, and does it again when the110 * system's scheme changes or another tab writes the preference. Plain ES5111 * with no imports; where it never runs, the stylesheet's media query and the112 * rendered metas are the fallback. It also names the system's own scheme in113 * `data-system`, so /settings can show what each choice gives before React114 * runs. `test/theme.test.ts` runs it.115 */116export const THEME_SCRIPT = `(function(){var d=document,m=matchMedia(${JSON.stringify(DARK_SCHEME_QUERY)}),c=${JSON.stringify(themeColors)};function a(){var p,s,e=d.documentElement.dataset;try{p=localStorage.getItem(${JSON.stringify(THEME_PREFERENCE_KEY)})}catch(x){}var t=m.matches!==(p==="opposite")?"dark":"light";e.theme=t;e.system=m.matches?"dark":"light";s="meta[data-theme-color]";if(!d.querySelector(s))d.head.insertAdjacentHTML("afterbegin",${JSON.stringify(THEME_META)});d.querySelector(s).setAttribute("content",c[t])}a();m.addEventListener("change",a);addEventListener("storage",a)})()`;117118/**119 * The script's hash as a CSP source. The web sets no Content-Security-Policy120 * on its pages; one added later lists this in `script-src`. A test holds it121 * to the script's text.122 */123export const THEME_SCRIPT_SOURCE =124 "'sha256-wBIkzc5HrsCSaxUQgB2fHQqInWgTrPnNbdSjB9xjqnk='";