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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
import type { Dispatch, ReactNode, SetStateAction } from "react";
import { useFetcher } from "@remix-run/react";
enum Theme {
DARK = "dark",
LIGHT = "light",
}
const themes: Array<Theme> = Object.values(Theme);
type ThemeContextType = [Theme | null, Dispatch<SetStateAction<Theme | null>>];
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
const prefersLightMQ = "(prefers-color-scheme: light)";
const getPreferredTheme = () =>
window.matchMedia(prefersLightMQ).matches ? Theme.LIGHT : Theme.DARK;
function ThemeProvider({
children,
specifiedTheme,
}: {
children: ReactNode;
specifiedTheme: Theme | null;
}) {
const [theme, setTheme] = useState<Theme | null>(() => {
if (specifiedTheme) {
if (themes.includes(specifiedTheme)) {
return specifiedTheme;
} else {
return null;
}
}
if (typeof window !== "object") {
return null;
}
return getPreferredTheme();
});
const persistTheme = useFetcher();
const mountRun = useRef(false);
useEffect(() => {
if (!mountRun.current) {
mountRun.current = true;
return;
}
if (!theme) {
return;
}
persistTheme.submit({ theme }, { action: "action/set-theme", method: "post" });
}, [theme]);
useEffect(() => {
const mediaQuery = window.matchMedia(prefersLightMQ);
const handleChange = () => {
setTheme(mediaQuery.matches ? Theme.LIGHT : Theme.DARK);
};
mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener("change", handleChange);
}, []);
const contextValue = useMemo<ThemeContextType>(() => [theme, setTheme], [theme, setTheme]);
return <ThemeContext.Provider value={contextValue}>{children}</ThemeContext.Provider>;
}
const clientThemeCode = `
// hi there dear reader 👋
// this is how I make certain we avoid a flash of the wrong theme. If you select
// a theme, then I'll know what you want in the future and you'll not see this
// script anymore.
;(() => {
const theme = window.matchMedia(${JSON.stringify(prefersLightMQ)}).matches
? 'light'
: 'dark';
const cl = document.documentElement.classList;
const themeAlreadyApplied = cl.contains('light') || cl.contains('dark');
if (themeAlreadyApplied) {
// this script shouldn't exist if the theme is already applied!
console.warn(
"Hi there, could you let Matt know you're seeing this message? Thanks!",
);
} else {
cl.add(theme);
}
const meta = document.querySelector('meta[name=color-scheme]');
if (meta) {
if (theme === 'dark') {
meta.content = 'dark light';
} else if (theme === 'light') {
meta.content = 'light dark';
}
} else {
console.warn(
"Hey, could you let Matt know you're seeing this message? Thanks!",
);
}
})();
`;
function NonFlashOfWrongThemeEls({ ssrTheme }: { ssrTheme: boolean }) {
const [theme] = useTheme();
return (
<>
<meta name="color-scheme" content={theme === "light" ? "light dark" : "dark light"} />
{ssrTheme ? null : <script dangerouslySetInnerHTML={{ __html: clientThemeCode }} />}
</>
);
}
function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
}
function isTheme(value: unknown): value is Theme {
return typeof value === "string" && themes.includes(value as Theme);
}
export { isTheme, NonFlashOfWrongThemeEls, Theme, ThemeProvider, useTheme };
|