Skip to content

Instantly share code, notes, and snippets.

@jakejarvis
Created February 15, 2024 00:28
Show Gist options
  • Save jakejarvis/79b0ec8506bc843023546d0d29861bf0 to your computer and use it in GitHub Desktop.
Save jakejarvis/79b0ec8506bc843023546d0d29861bf0 to your computer and use it in GitHub Desktop.
unminified version of script to restore theme
export const restoreTheme = () => {
// `try/catch` in case I messed something up here bigly... (will default to light theme)
try {
// help minifier minify
const htmlRoot = document.documentElement;
// the list of <html>'s current class(es)...
// eslint-disable-next-line prefer-destructuring
const classList = htmlRoot.classList;
// map of themes -> classnames ([0]=light, [1]=dark)
const classNames = ["__CLASS_NAMES__"];
// user's saved preference
const pref = typeof Storage !== "undefined" ? window.localStorage.getItem("__STORAGE_KEY__") : null;
// restore the local storage preference if it's set, otherwise test CSS media query for browser dark mode preference
// https://stackoverflow.com/a/57795495/1438024
const newTheme = (pref && pref === "dark") ?? window.matchMedia("__MEDIA_QUERY__").matches ? 1 : 0;
// remove both `classNames` to start fresh...
classList.remove(...classNames);
// ...and then FINALLY set the root class
classList.add(classNames[newTheme] || "");
// set "color-scheme" inline css property
htmlRoot.style.colorScheme = newTheme === 1 ? "dark" : "light";
} catch (error) {} // eslint-disable-line no-empty
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment