Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/frontend/packages/shared/src/settings/theme-apply.ts

46 lines
2 KiB
TypeScript

// Applies the stored theme choice by setting `data-theme="<theme id>"` on
// `<html>`, cleared for `auto` (so the `prefers-color-scheme` media query in
// `../colors.css` picks hyperhive light or dark). No palette values live
// here: `colors.css`'s `:root[data-theme="<id>"]` blocks apply the colours,
// and `./themes.ts` lists the ids.
//
// Callers own their own storage key (kept in their own small constant, not
// derived here) so two pages never silently share one browser-local setting
// by accident. The stored value is read through `themeChoice`, so a value
// from before themes existed (`system`, `light`, `dark`) still works. The
// default is hyperhive dark: `prefers-color-scheme` has no real "unset" value
// the way `prefers-reduced-motion` does, so a browser with no explicit
// dark-mode toggle reports `light`, and `auto` as a default read as
// light-by-default for most first-time visitors (mara: "light mode seems to be
// default").
import { useEffect } from "preact/hooks";
import { useLocalSetting } from "./settings-storage.js";
import { AUTO_THEME, DEFAULT_THEME, themeChoice } from "./themes.js";
/** `[choice, setChoice]`: `auto` or a theme id from `./themes.ts`. */
export function useThemeOverride(
key: string,
fallback: string = DEFAULT_THEME,
): [string, (choice: string) => void] {
const [stored, setStored] = useLocalSetting<string>(key, fallback);
return [themeChoice(stored, fallback), setStored];
}
// Mounted once, high in the tree — one mount point applies the choice
// regardless of what else is rendering, and `useLocalSetting`'s same-tab
// subscription means `SettingsMenu` changing the value re-runs this effect
// without either component needing to know about the other directly.
export function useApplyThemeOverride(
key: string,
fallback: string = DEFAULT_THEME,
): void {
const [choice] = useThemeOverride(key, fallback);
useEffect(() => {
const root = document.documentElement;
if (choice === AUTO_THEME) {
delete root.dataset.theme;
} else {
root.dataset.theme = choice;
}
}, [choice]);
}