Skip to content
refs
History
146 lines · 5.2 KBRaw
1import { DesktopIcon, MoonIcon, SunIcon } from "./icons";
2import { useEffect, useState } from "react";
3import { Button } from "./ui/button";
4import { DropdownMenu } from "./ui/overlay";
5
6export type ThemeMode = "system" | "light" | "dark";
7
8const KEY = "refs-theme";
9const CHANGED = "refs-theme";
10const RAIL_KEY = "refs-rail";
11const RAIL_CHANGED = "refs-rail";
12
13/**
14 * Runs before paint, so the page never flashes the wrong theme or the wrong layout. The theme follows the
15 * system until the reader picks one, and the rail shows until the reader hides it. Both choices live in this browser.
16 */
17export const BOOT_SCRIPT = `(() => {
18 const query = matchMedia("(prefers-color-scheme: dark)");
19 const apply = () => {
20 let saved = null;
21 try { saved = localStorage.getItem("${KEY}"); } catch {}
22 document.documentElement.dataset.mode = saved === "light" || saved === "dark" ? saved : query.matches ? "dark" : "light";
23 };
24 apply();
25 query.addEventListener("change", apply);
26 addEventListener("storage", apply);
27 addEventListener("${CHANGED}", apply);
28 const rail = () => {
29 let hidden = false;
30 try { hidden = localStorage.getItem("${RAIL_KEY}") === "hidden"; } catch {}
31 if (hidden) document.documentElement.dataset.rail = "hidden";
32 else delete document.documentElement.dataset.rail;
33 };
34 rail();
35 addEventListener("storage", rail);
36 addEventListener("${RAIL_CHANGED}", rail);
37})();`;
38
39/** Whether the reader has hidden the rail, and a switch for it. The change is instant: people use it often. */
40export function useRailHidden(): [boolean, () => void] {
41 const [hidden, setHidden] = useState(false);
42 useEffect(() => {
43 const sync = () => setHidden(document.documentElement.dataset.rail === "hidden");
44 sync();
45 addEventListener(RAIL_CHANGED, sync);
46 addEventListener("storage", sync);
47 return () => {
48 removeEventListener(RAIL_CHANGED, sync);
49 removeEventListener("storage", sync);
50 };
51 }, []);
52 const toggle = () => {
53 const next = !hidden;
54 try {
55 if (next) localStorage.setItem(RAIL_KEY, "hidden");
56 else localStorage.removeItem(RAIL_KEY);
57 } catch {
58 // Storage is blocked: the choice lasts for this page only.
59 }
60 if (next) document.documentElement.dataset.rail = "hidden";
61 else delete document.documentElement.dataset.rail;
62 dispatchEvent(new Event(RAIL_CHANGED));
63 };
64 return [hidden, toggle];
65}
66
67function saved(): ThemeMode {
68 try {
69 const value = localStorage.getItem(KEY);
70 return value === "light" || value === "dark" ? value : "system";
71 } catch {
72 return "system";
73 }
74}
75
76function store(mode: ThemeMode) {
77 try {
78 if (mode === "system") localStorage.removeItem(KEY);
79 else localStorage.setItem(KEY, mode);
80 } catch {
81 // Storage is blocked: the choice lasts for this page only.
82 document.documentElement.dataset.mode = mode === "system" ? (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light") : mode;
83 }
84 dispatchEvent(new Event(CHANGED));
85}
86
87/** The reader's theme choice and a setter. The swap cross-fades, so brightness never jumps. */
88export function useThemeMode(): [ThemeMode, (mode: ThemeMode) => void] {
89 const [mode, setMode] = useState<ThemeMode>("system");
90 useEffect(() => {
91 const sync = () => setMode(saved());
92 sync();
93 addEventListener(CHANGED, sync);
94 addEventListener("storage", sync);
95 return () => {
96 removeEventListener(CHANGED, sync);
97 removeEventListener("storage", sync);
98 };
99 }, []);
100 const choose = (next: ThemeMode) => {
101 const calm = matchMedia("(prefers-reduced-motion: reduce)").matches;
102 if (!calm && "startViewTransition" in document) document.startViewTransition(() => store(next));
103 else store(next);
104 };
105 return [mode, choose];
106}
107
108const MODES: { value: ThemeMode; label: string; icon: typeof SunIcon }[] = [
109 { value: "system", label: "System", icon: DesktopIcon },
110 { value: "light", label: "Light", icon: SunIcon },
111 { value: "dark", label: "Dark", icon: MoonIcon },
112];
113
114/** The three theme choices as menu rows, for use inside another menu. */
115export function ThemeChoices() {
116 const [mode, choose] = useThemeMode();
117 return (
118 <>
119 <DropdownMenu.Label>Theme</DropdownMenu.Label>
120 <DropdownMenu.RadioGroup value={mode} onValueChange={(value) => choose(value as ThemeMode)}>
121 {MODES.map(({ value, label, icon: Glyph }) => (
122 <DropdownMenu.RadioItem key={value} value={value}>
123 <Glyph />
124 {label}
125 </DropdownMenu.RadioItem>
126 ))}
127 </DropdownMenu.RadioGroup>
128 </>
129 );
130}
131
132/** A small control that opens the theme choices, for pages without an account menu. */
133export function ThemeMenu({ className, side = "bottom" }: { className?: string; side?: "top" | "bottom" }) {
134 const [mode] = useThemeMode();
135 const Glyph = MODES.find((item) => item.value === mode)?.icon ?? DesktopIcon;
136 return (
137 <DropdownMenu>
138 <DropdownMenu.Trigger render={<Button variant="ghost" size="sm" shape="square" aria-label="Theme" className={`hit-area ${className ?? ""}`} />}>
139 <Glyph />
140 </DropdownMenu.Trigger>
141 <DropdownMenu.Content align="end" side={side} className="min-w-40">
142 <ThemeChoices />
143 </DropdownMenu.Content>
144 </DropdownMenu>
145 );
146}