Add theme selector with persisted context
This commit is contained in:
parent
8fc8361390
commit
16d42daf54
4 changed files with 115 additions and 5 deletions
48
apps/web/app/providers/theme.tsx
Normal file
48
apps/web/app/providers/theme.tsx
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
|
||||
const STORAGE_KEY = "theme";
|
||||
|
||||
export type Theme = "default" | "bbg" | "system";
|
||||
|
||||
type ThemeContextValue = {
|
||||
theme: Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
};
|
||||
|
||||
const isTheme = (value: string | null): value is Theme => {
|
||||
return value === "default" || value === "bbg" || value === "system";
|
||||
};
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue | null>(null);
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>("default");
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (isTheme(stored)) {
|
||||
setTheme(stored);
|
||||
} else if (stored !== null && !isTheme(stored)) {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
localStorage.setItem(STORAGE_KEY, theme);
|
||||
}, [theme]);
|
||||
|
||||
const value = useMemo<ThemeContextValue>(() => ({ theme, setTheme }), [theme]);
|
||||
|
||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useTheme(): ThemeContextValue {
|
||||
const context = useContext(ThemeContext);
|
||||
if (!context) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue