mirror of
https://github.com/fabro-sh/fabro.git
synced 2026-09-24 00:51:19 +00:00
Remove the system color-scheme fallback from the web UI theme boot path. Fabro now uses a saved light/dark preference when present and otherwise starts in dark mode by default. Add a regression test for the shared theme selection helper and refresh the built web assets.
47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
|
import { STORAGE_KEY, resolveTheme } from "./theme-selection";
|
|
import type { Theme } from "./theme-selection";
|
|
|
|
function getInitialTheme(): Theme {
|
|
if (typeof window === "undefined") return "dark";
|
|
return resolveTheme(localStorage.getItem(STORAGE_KEY));
|
|
}
|
|
|
|
function applyThemeClass(theme: Theme) {
|
|
const root = document.documentElement;
|
|
root.classList.remove("light", "dark");
|
|
root.classList.add(theme);
|
|
}
|
|
|
|
const ThemeContext = createContext<{
|
|
theme: Theme;
|
|
toggle: () => void;
|
|
}>({ theme: "dark", toggle: () => {} });
|
|
|
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
|
const [theme, setTheme] = useState<Theme>(getInitialTheme);
|
|
|
|
useEffect(() => {
|
|
applyThemeClass(theme);
|
|
}, [theme]);
|
|
|
|
const toggle = useCallback(() => {
|
|
setTheme((prev) => {
|
|
const next = prev === "dark" ? "light" : "dark";
|
|
localStorage.setItem(STORAGE_KEY, next);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
return (
|
|
<ThemeContext value={{ theme, toggle }}>
|
|
{children}
|
|
</ThemeContext>
|
|
);
|
|
}
|
|
|
|
export function useTheme() {
|
|
return useContext(ThemeContext);
|
|
}
|
|
|
|
export type { Theme };
|