initial commit 3??
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { createSignal, createContext, useContext, createEffect, type ParentComponent } from "solid-js";
|
||||
|
||||
type Theme = "dark" | "light" | "system";
|
||||
|
||||
interface ThemeProviderState {
|
||||
theme: () => Theme;
|
||||
setTheme: (theme: Theme) => void;
|
||||
}
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>();
|
||||
|
||||
export const ThemeProvider: ParentComponent = (props) => {
|
||||
const [theme, setTheme] = createSignal<Theme>("system");
|
||||
|
||||
// Load from local storage on mount
|
||||
const storedTheme = localStorage.getItem("tasgrid-theme") as Theme | null;
|
||||
if (storedTheme) {
|
||||
setTheme(storedTheme);
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove("light", "dark");
|
||||
|
||||
const currentTheme = theme();
|
||||
|
||||
if (currentTheme === "system") {
|
||||
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
root.classList.add(systemTheme);
|
||||
} else {
|
||||
root.classList.add(currentTheme);
|
||||
}
|
||||
|
||||
localStorage.setItem("tasgrid-theme", currentTheme);
|
||||
});
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider value={{ theme, setTheme }}>
|
||||
{props.children}
|
||||
</ThemeProviderContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext);
|
||||
if (!context) throw new Error("useTheme must be used within a ThemeProvider");
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user