appearance.tsx
This file
Path
apps/web/src/features/settings/appearance.tsx
196 lines · 5.5 KiB · TypeScript
Last changed by
Merge redesign into mainoscabrielbefore adoptioncaedd21
History of this fileTake it
Merge redesign into mainoscabrielbefore adoptioncaedd21
lines 1–196why, one step back1/**2 * Appearance (ADR 0042): the theme follows the system, or its opposite. Each3 * choice shows what it gives on this machine now, and follows the system as4 * it turns. The choice is kept in this browser's `localStorage` alone.5 */6import { Result } from "effect";7import { useCallback, useMemo, useSyncExternalStore } from "react";89import {10 applyTheme,11 DARK_SCHEME_QUERY,12 readPreference,13 resolveTheme,14 THEME_PREFERENCE_KEY,15 THEME_PREFERENCES,16 writePreference,17} from "../shared/theme.ts";18import type { Theme, ThemeDocument, ThemePreference } from "../shared/theme.ts";1920const CHOICE_LABELS: Readonly<Record<ThemePreference, string>> = {21 opposite: "Opposite of system",22 same: "Same as system",23};2425const THEME_LABELS: Readonly<Record<Theme, string>> = {26 dark: "Dark",27 light: "Light",28};2930/** Where a choice lands: the browser's storage and the page it is made on. */31export interface ThemePlace {32 readonly document: ThemeDocument;33 readonly storage: Storage | undefined;34 readonly system: Theme;35}3637/** Keeps the choice, then draws the page in it at once, as the head script would. */38export const choosePreference = (39 preference: ThemePreference,40 place: ThemePlace41) => {42 writePreference(place.storage, preference);43 applyTheme(place.document, resolveTheme(place.system, preference));44};4546export const AppearanceView = ({47 onChoose,48 preference,49 system,50}: {51 readonly onChoose: (preference: ThemePreference) => void;52 readonly preference: ThemePreference;53 /** Unknown on the server, which cannot see the reader's system. */54 readonly system: Theme | undefined;55}) => (56 <fieldset className="flex flex-col gap-2">57 <legend className="text-ui mb-2 font-semibold">Theme</legend>58 {THEME_PREFERENCES.map((choice) => (59 <label60 className="border-rule bg-card text-ui hover:bg-surface has-checked:border-foreground flex min-h-11 cursor-pointer items-center gap-3 border px-3 py-2 transition-colors duration-[120ms]"61 key={choice}62 >63 <input64 checked={choice === preference}65 className="accent-primary size-4 shrink-0"66 name="theme"67 onChange={() => {68 onChoose(choice);69 }}70 type="radio"71 value={choice}72 />73 <span className="font-medium">{CHOICE_LABELS[choice]}</span>74 {/* Before React knows the system, the head script's `data-system` names it through the stylesheet. */}75 {system === undefined ? (76 <span77 className="text-muted-foreground ml-auto"78 data-system-resolves={choice}79 />80 ) : (81 <span className="text-muted-foreground ml-auto">82 {THEME_LABELS[resolveTheme(system, choice)]}83 </span>84 )}85 </label>86 ))}87 </fieldset>88);8990// Not `useMedia` from `features/code/media.ts`: its server snapshot is91// `false`, and this page must name no theme the server cannot see.92const subscribeToSystem = (changed: () => void) => {93 const scheme = globalThis.matchMedia(DARK_SCHEME_QUERY);9495 scheme.addEventListener("change", changed);9697 return () => {98 scheme.removeEventListener("change", changed);99 };100};101102const systemNow = (): Theme =>103 globalThis.matchMedia(DARK_SCHEME_QUERY).matches ? "dark" : "light";104105const systemOnServer = (): Theme | undefined => undefined;106107type StorageListener = (event: { readonly key: string | null }) => void;108109/** The window's storage events, by which this tab hears another one write. */110export interface StorageEvents {111 readonly addEventListener: (112 type: "storage",113 listener: StorageListener114 ) => void;115 readonly removeEventListener: (116 type: "storage",117 listener: StorageListener118 ) => void;119}120121/**122 * The choice as this tab shows it: the one made here, or what storage holds123 * once another tab writes one. A browser that refuses storage keeps the one124 * made here, which storage cannot give back.125 */126export const preferenceStore = (127 storage: () => Storage | undefined,128 events: StorageEvents129) => {130 let chosen: ThemePreference | undefined;131 const listeners = new Set<() => void>();132133 return {134 choose: (preference: ThemePreference) => {135 chosen = preference;136137 for (const changed of listeners) {138 changed();139 }140 },141 current: (): ThemePreference => chosen ?? readPreference(storage()),142 subscribe: (changed: () => void) => {143 const heard: StorageListener = ({ key }) => {144 if (key === THEME_PREFERENCE_KEY) {145 chosen = undefined;146 changed();147 }148 };149150 listeners.add(changed);151 events.addEventListener("storage", heard);152153 return () => {154 listeners.delete(changed);155 events.removeEventListener("storage", heard);156 };157 },158 };159};160161const localStorageOf = (): Storage | undefined =>162 Result.getOrUndefined(Result.try(() => globalThis.localStorage));163164const storedOnServer = (): ThemePreference => "same";165166export const Appearance = () => {167 const system = useSyncExternalStore(168 subscribeToSystem,169 systemNow,170 systemOnServer171 );172173 const store = useMemo(() => preferenceStore(localStorageOf, globalThis), []);174175 const preference = useSyncExternalStore(176 store.subscribe,177 store.current,178 storedOnServer179 );180181 const choose = useCallback(182 (chosen: ThemePreference) => {183 choosePreference(chosen, {184 document: globalThis.document,185 storage: localStorageOf(),186 system: systemNow(),187 });188 store.choose(chosen);189 },190 [store]191 );192193 return (194 <AppearanceView onChoose={choose} preference={preference} system={system} />195 );196};