1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-09-15 05:45:33 -04:00

minify inline theme script even more

This commit is contained in:
2022-04-23 21:04:50 -04:00
parent 4f0002af0f
commit 07562f625e
2 changed files with 18 additions and 18 deletions

View File

@@ -9,13 +9,7 @@ const ThemeScript = () => {
const functionString = String(clientScript) const functionString = String(clientScript)
.replace('"__MEDIA_QUERY__"', `"${darkModeQuery}"`) .replace('"__MEDIA_QUERY__"', `"${darkModeQuery}"`)
.replace('"__STORAGE_KEY__"', `"${themeStorageKey}"`) .replace('"__STORAGE_KEY__"', `"${themeStorageKey}"`)
.replace('"__CLASS_NAMES__"', JSON.stringify(themeClassNames)) .replace('"__CLASS_NAMES__"', JSON.stringify(themeClassNames));
.replace(
'"__LIST_OF_CLASSES__"',
Object.values(themeClassNames)
.map((t) => `"${t}"`)
.join(",")
);
// minify the final code, a bit hacky but this is ONLY done at build-time, so uglify-js is never bundled or sent to // minify the final code, a bit hacky but this is ONLY done at build-time, so uglify-js is never bundled or sent to
// the browser to execute: // the browser to execute:

View File

@@ -5,23 +5,29 @@
export const clientScript = () => { export const clientScript = () => {
// `try/catch` in case I messed something up here bigly... (will default to light theme) // `try/catch` in case I messed something up here bigly... (will default to light theme)
try { try {
// user's saved preference: // help minifier minify
var light = "light";
var dark = "dark";
var newTheme;
// user's saved preference
var pref = localStorage.getItem("__STORAGE_KEY__"); var pref = localStorage.getItem("__STORAGE_KEY__");
// map of theme -> classname: // map of theme -> classname
var classNames = "__CLASS_NAMES__"; var classNames = "__CLASS_NAMES__";
// the list of <html>'s current class(es)... // the list of <html>'s current class(es)...
var classList = document.documentElement.classList; var classList = document.documentElement.classList;
// ...from which `classNames` are removed to start fresh: // ...from which `classNames` are removed to start fresh
classList.remove("__LIST_OF_CLASSES__"); classList.remove(classNames[light], classNames[dark]);
if (pref === "light" || pref === "dark") { if (pref === light || pref === dark) {
classList.add(classNames[pref]); // simply restore the local storage preference
newTheme = pref;
} else { } else {
// CSS media query for system dark mode preference: // test CSS media query for system dark mode preference
var darkQuery = "__MEDIA_QUERY__"; // https://stackoverflow.com/a/57795495/1438024
// the listener which tests the above media query: newTheme = window.matchMedia("__MEDIA_QUERY__").matches ? dark : light;
var prefersDark = window.matchMedia(darkQuery);
classList.add(classNames[prefersDark.media !== darkQuery || prefersDark.matches ? "dark" : "light"]);
} }
// FINALLY set the root class
classList.add(classNames[newTheme]);
} catch (error) {} } catch (error) {}
}; };