xonecas.io
8058
Ir

irvc / files

irvc / web / src / lib / theme.ts

7.4 KB
1import { useCallback, useEffect, useLayoutEffect, useState } from "react";
2import { SKITTLES, isDark, schemeColors, skittlesPalette, toPalette, type Scheme } from "./scheme";
3
4export type Mode = "light" | "dark";
5
6// Every color the UI uses. Palettes and user overrides are both just maps of
7// these; the values live in index.css as CSS variables named "kebab of key".
8export const TOKENS = [
9  "bg",
10  "surface",
11  "raised",
12  "fg",
13  "muted",
14  "faint",
15  "line",
16  "accent",
17  "accentFg",
18  "danger",
19] as const;
20
21export type Token = (typeof TOKENS)[number];
22
23export const tokenLabels: Record<Token, string> = {
24  bg: "background",
25  surface: "sidebar",
26  raised: "panels & inputs",
27  fg: "text",
28  muted: "muted text",
29  faint: "faint text",
30  line: "borders",
31  accent: "accent",
32  accentFg: "text on accent",
33  danger: "danger",
34};
35
36// "custom" is not a palette of its own: it layers the user's color overrides on
37// top of `base`, the built-in palette that was active when custom was chosen.
38export const presets = [
39  { id: "nicotine", label: "80s nicotine" },
40  { id: "tuxedo", label: "tuxedo" },
41  { id: "custom", label: "custom" },
42] as const;
43
44export type PresetId = (typeof presets)[number]["id"];
45export type BasePreset = Exclude<PresetId, "custom">;
46
47export interface ThemePrefs {
48  mode: Mode;
49  preset: PresetId;
50  base: BasePreset;
51  overrides: Record<Mode, Partial<Record<Token, string>>>;
52  // Experimental: the terminal scheme the palette was seeded from (name, plus
53  // the colors it contributes to skittles), and per-username colors.
54  scheme: { name: string; colors: string[] } | null;
55  skittles: boolean;
56}
57
58const key = "irvc.theme";
59
60export const defaultPrefs: ThemePrefs = {
61  mode: "light",
62  preset: "nicotine",
63  base: "nicotine",
64  overrides: { light: {}, dark: {} },
65  scheme: null,
66  skittles: false,
67};
68
69const systemMode = (): Mode =>
70  matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
71
72const cssVar = (t: Token) => "--" + t.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
73
74// load reads prefs written by this module, and tolerates the old bare
75// "light"/"dark" value stored by earlier versions.
76export function loadPrefs(): ThemePrefs {
77  let raw: unknown;
78  try {
79    raw = JSON.parse(localStorage.getItem(key) ?? "null");
80  } catch {
81    raw = localStorage.getItem(key);
82  }
83  if (raw === "light" || raw === "dark") return { ...defaultPrefs, mode: raw };
84  // Older releases stored the bare preset id under the same key.
85  if (presets.some((p) => p.id === raw)) return { ...defaultPrefs, preset: raw as PresetId };
86  if (!raw || typeof raw !== "object") return { ...defaultPrefs, mode: systemMode() };
87  const p = raw as Partial<ThemePrefs>;
88  const mode: Mode = p.mode === "dark" ? "dark" : "light";
89  const overrides = { light: p.overrides?.light ?? {}, dark: p.overrides?.dark ?? {} };
90  let preset: PresetId = presets.some((x) => x.id === p.preset) ? (p.preset as PresetId) : defaultPrefs.preset;
91  let base: BasePreset = p.base === "tuxedo" || p.base === "nicotine" ? p.base : defaultPrefs.base;
92  // Overrides used to sit on top of any preset. They now only exist under
93  // "custom", so a saved palette with edits becomes a custom one.
94  if (preset !== "custom" && Object.keys(overrides[mode]).length > 0) {
95    base = preset;
96    preset = "custom";
97  }
98  return {
99    mode,
100    preset,
101    base,
102    overrides,
103    scheme: p.scheme?.name && Array.isArray(p.scheme.colors) ? p.scheme : null,
104    skittles: p.skittles === true,
105  };
106}
107
108// basePalette is the built-in palette whose CSS is in effect.
109const basePalette = (p: ThemePrefs): BasePreset => (p.preset === "custom" ? p.base : p.preset);
110
111// applyTheme writes the mode class, the preset attribute and the user's
112// overrides onto <html>. The palettes themselves live in CSS, so switching
113// preset is a single attribute change.
114export function applyTheme(prefs: ThemePrefs) {
115  const el = document.documentElement;
116  el.classList.toggle("dark", prefs.mode === "dark");
117  el.dataset.preset = basePalette(prefs);
118  for (const t of TOKENS) {
119    const v = prefs.preset === "custom" ? prefs.overrides[prefs.mode][t] : undefined;
120    if (v) el.style.setProperty(cssVar(t), v);
121    else el.style.removeProperty(cssVar(t));
122  }
123  // Skittles: --user-N are only defined while it is on; userColor() falls back
124  // to the accent otherwise. Needs the resolved bg/fg, hence after the loop.
125  const colors = prefs.skittles
126    ? skittlesPalette(prefs.scheme?.colors, effective("bg"), effective("fg"), basePalette(prefs))
127    : [];
128  for (let i = 0; i < SKITTLES; i++) {
129    if (colors[i]) el.style.setProperty(`--user-${i}`, colors[i]);
130    else el.style.removeProperty(`--user-${i}`);
131  }
132}
133
134// effective returns the color a token currently resolves to, so the theme
135// editor can seed its color inputs with the palette values.
136export function effective(t: Token): string {
137  const v = getComputedStyle(document.documentElement).getPropertyValue(cssVar(t)).trim();
138  if (v.startsWith("#")) return v.length === 4 ? expand(v) : v;
139  return rgbToHex(v);
140}
141
142function expand(hex: string) {
143  return "#" + hex.slice(1).replace(/./g, (c) => c + c);
144}
145
146function rgbToHex(color: string) {
147  const m = color.match(/(\d+)\D+(\d+)\D+(\d+)/);
148  if (!m) return "#000000";
149  return "#" + m.slice(1, 4).map((n) => Number(n).toString(16).padStart(2, "0")).join("");
150}
151
152export function useTheme() {
153  const [prefs, setPrefs] = useState<ThemePrefs>(loadPrefs);
154
155  // Applied before the browser paints so anything reading the computed
156  // palette (the settings color swatches) sees the new mode immediately.
157  useLayoutEffect(() => {
158    applyTheme(prefs);
159    localStorage.setItem(key, JSON.stringify(prefs));
160  }, [prefs]);
161
162  // Also react to OS changes while the user has not picked a side explicitly;
163  // the stored mode always wins once set.
164  useEffect(() => {
165    const mq = matchMedia("(prefers-color-scheme: dark)");
166    const on = () =>
167      setPrefs((p) =>
168        localStorage.getItem(key) ? p : { ...p, mode: mq.matches ? "dark" : "light" },
169      );
170    mq.addEventListener("change", on);
171    return () => mq.removeEventListener("change", on);
172  }, []);
173
174  const setMode = useCallback((mode: Mode) => setPrefs((p) => ({ ...p, mode })), []);
175  const setPreset = useCallback(
176    (preset: PresetId) =>
177      setPrefs((p) => {
178        if (preset === p.preset) return p;
179        // Custom starts from whatever built-in palette (and mode) is showing.
180        const base = preset === "custom" ? basePalette(p) : p.base;
181        return { ...p, preset, base, scheme: null, overrides: { light: {}, dark: {} } };
182      }),
183    [],
184  );
185  const setToken = useCallback(
186    (t: Token, color: string) =>
187      setPrefs((p) => ({
188        ...p,
189        overrides: { ...p.overrides, [p.mode]: { ...p.overrides[p.mode], [t]: color } },
190      })),
191    [],
192  );
193  // A scheme is dark or light by nature, so applying one switches to that mode
194  // and overrides every token there; the other mode keeps its palette.
195  const setScheme = useCallback(
196    (s: Scheme) =>
197      setPrefs((p) => {
198        const mode: Mode = isDark(s) ? "dark" : "light";
199        return {
200          ...p,
201          mode,
202          preset: "custom",
203          base: basePalette(p),
204          scheme: { name: s.n, colors: schemeColors(s) },
205          overrides: { ...p.overrides, [mode]: toPalette(s) },
206        };
207      }),
208    [],
209  );
210  const setSkittles = useCallback((skittles: boolean) => setPrefs((p) => ({ ...p, skittles })), []);
211
212  return { prefs, setMode, setPreset, setToken, setScheme, setSkittles };
213}