forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThemeContext.tsx
More file actions
89 lines (74 loc) · 2.34 KB
/
Copy pathThemeContext.tsx
File metadata and controls
89 lines (74 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import React, {
createContext,
useContext,
useEffect,
useState,
useCallback,
} from "react";
type Theme = "light" | "dark" | "system";
type ResolvedTheme = "light" | "dark";
interface ThemeContextValue {
theme: Theme;
resolvedTheme: ResolvedTheme;
setTheme: (theme: Theme) => void;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
const STORAGE_KEY = "app-theme";
function getSystemTheme(): ResolvedTheme {
if (typeof window === "undefined") return "light";
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
function resolveTheme(theme: Theme): ResolvedTheme {
return theme === "system" ? getSystemTheme() : theme;
}
function applyTheme(resolved: ResolvedTheme) {
const root = document.documentElement;
if (resolved === "dark") {
root.classList.add("dark");
} else {
root.classList.remove("dark");
}
root.setAttribute("data-theme", resolved);
}
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setThemeState] = useState<Theme>(() => {
if (typeof window === "undefined") return "system";
return (localStorage.getItem(STORAGE_KEY) as Theme) ?? "system";
});
const resolvedTheme = resolveTheme(theme);
// Apply theme to DOM
useEffect(() => {
applyTheme(resolveTheme(theme));
}, [theme]);
// Listen for system preference changes (only relevant when theme === 'system')
useEffect(() => {
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const handler = () => {
if (theme === "system") applyTheme(getSystemTheme());
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [theme]);
const setTheme = useCallback((next: Theme) => {
localStorage.setItem(STORAGE_KEY, next);
setThemeState(next);
}, []);
const toggleTheme = useCallback(() => {
setTheme(resolvedTheme === "dark" ? "light" : "dark");
}, [resolvedTheme, setTheme]);
return (
<ThemeContext.Provider
value={{ theme, resolvedTheme, setTheme, toggleTheme }}
>
{children}
</ThemeContext.Provider>
);
}
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used within ThemeProvider");
return ctx;
}