({
children,
specifiedTheme,
themeOverride,
}: {
children: ReactNode;
specifiedTheme?: Theme;
themeOverride?: Theme;
})
| 16 | window.matchMedia(prefersLightMQ).matches ? "light" : "dark"; |
| 17 | |
| 18 | export function ThemeProvider({ |
| 19 | children, |
| 20 | specifiedTheme, |
| 21 | themeOverride, |
| 22 | }: { |
| 23 | children: ReactNode; |
| 24 | specifiedTheme?: Theme; |
| 25 | themeOverride?: Theme; |
| 26 | }) { |
| 27 | const [theme, setTheme] = useState<Theme | undefined>(() => { |
| 28 | if (specifiedTheme) { |
| 29 | if (specifiedTheme === "light" || specifiedTheme === "dark") { |
| 30 | return specifiedTheme; |
| 31 | } else { |
| 32 | return; |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // there's no way for us to know what the theme should be in this context |
| 37 | // the client will have to figure it out before hydration. |
| 38 | if (typeof window !== "object") { |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | return getPreferredTheme(); |
| 43 | }); |
| 44 | |
| 45 | const mountRun = useRef(false); |
| 46 | const persistTheme = useFetcher(); |
| 47 | |
| 48 | useEffect(() => { |
| 49 | if (!mountRun.current) { |
| 50 | mountRun.current = true; |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | if (!theme) { |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | persistTheme.submit( |
| 59 | { theme }, |
| 60 | { action: "actions/setTheme", method: "post" } |
| 61 | ); |
| 62 | }, [theme]); |
| 63 | |
| 64 | return ( |
| 65 | <ThemeContext.Provider value={[themeOverride ?? theme, setTheme]}> |
| 66 | {children} |
| 67 | </ThemeContext.Provider> |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | export function useTheme(): ThemeContextType { |
| 72 | const context = useContext(ThemeContext); |
nothing calls this directly
no test coverage detected