1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 19:08:26 -04:00
jarv.is/contexts/ThemeContext.tsx
2025-03-21 12:02:14 -04:00

73 lines
2.8 KiB
TypeScript

"use client";
import { createContext, useEffect, useState } from "react";
import { useLocalStorage, useMediaQuery } from "../hooks";
import type { PropsWithChildren } from "react";
export const ThemeContext = createContext<{
/**
* If the user's theme preference is unset, this returns whether the system preference resolved to "light" or "dark".
* If the user's theme preference is set, the preference is returned instead, regardless of their system's theme.
*/
theme: string;
/** Update the theme manually and save to local storage. */
setTheme: (theme: string) => void;
}>({
theme: "",
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setTheme: (_) => {},
});
// provider used once in _app.tsx to wrap entire app
export const ThemeProvider = ({ children }: PropsWithChildren) => {
// keep track of if/when the user has set their theme *on this site*
const [preferredTheme, setPreferredTheme] = useLocalStorage("theme");
// keep track of changes to the user's OS/browser dark mode setting
const [systemTheme, setSystemTheme] = useState("");
// hook into system `prefers-dark-mode` setting
// https://web.dev/prefers-color-scheme/#the-prefers-color-scheme-media-query
const isSystemDark = useMediaQuery("(prefers-color-scheme: dark)");
// listen for changes in OS preference, but don't save it as a website preference to local storage
useEffect(() => {
setSystemTheme(isSystemDark ? "dark" : "light");
}, [isSystemDark]);
// actual DOM updates must be done in useEffect
useEffect(() => {
// only "light" and "dark" are valid themes
const resolvedTheme = preferredTheme && ["light", "dark"].includes(preferredTheme) ? preferredTheme : systemTheme;
// this is what actually changes the CSS variables
document.documentElement.dataset.theme = resolvedTheme;
// less important, but tells the browser how to render built-in elements like forms, scrollbars, etc.
document.documentElement.style?.setProperty("color-scheme", resolvedTheme);
}, [preferredTheme, systemTheme]);
const providerValues = {
theme: preferredTheme ?? systemTheme,
setTheme: setPreferredTheme,
};
return (
<ThemeContext.Provider value={providerValues}>
<script
id="restore-theme"
// unminified: https://gist.github.com/jakejarvis/79b0ec8506bc843023546d0d29861bf0
dangerouslySetInnerHTML={{
__html:
"(()=>{try{const e=document.documentElement,t='undefined'!=typeof Storage?window.localStorage.getItem('theme'):null,a=(t&&'dark'===t)??window.matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';e.dataset.theme=a,e.style.colorScheme=a}catch(e){}})()",
}}
/>
{children}
</ThemeContext.Provider>
);
};
// debugging help pls
if (process.env.NODE_ENV !== "production") {
ThemeContext.displayName = "ThemeContext";
}