Skip to content

Commit

Permalink
changing in script type to is:inline for astro directives, merging of…
Browse files Browse the repository at this point in the history
… getSystemPreference and getThemFromLocalStorage functions into a getThemePreference and domcontentloaded eventlistener removed to ensure JS runs before the document loads (#54)
  • Loading branch information
Xeuz27 authored Mar 10, 2024
1 parent 7380665 commit 2c8c61e
Showing 1 changed file with 14 additions and 32 deletions.
46 changes: 14 additions & 32 deletions src/layouts/PageHTML.astro
Original file line number Diff line number Diff line change
Expand Up @@ -26,51 +26,33 @@ const {
</head>

<body class="w-full text-texto-sft fondo-pts">
<Layout client:idle>
<slot />
</Layout>
<script>
function getSystemPreference() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
return "enabled";
}

return "disabled";
}
function getThemeFromLocalStorage() {
const themeStr = localStorage.getItem("theme");
if (!themeStr) {
return null;
}

try {
return JSON.parse(themeStr);
} catch (err) {
return null;
}
}

<script is:inline>
let getThemePreference = () => {
const localItem =
typeof localStorage !== "undefined" && localStorage.getItem("theme");
if (localItem) return localItem;
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "enabled"
: "disabled";
};
const {darkMode} = JSON.parse(getThemePreference());
function enableDarkMode() {
document.body.classList.add("oscuro");
}

function disableDarkMode() {
document.body.classList.remove("oscuro");
}

function setThemeOnNavigation() {
const {darkMode} = getThemeFromLocalStorage() || getSystemPreference();

if (darkMode === "enabled") {
enableDarkMode();
} else {
disableDarkMode();
}
}

document.addEventListener("DOMContentLoaded", () => {
setThemeOnNavigation();
});
setThemeOnNavigation();
</script>
<Layout client:idle>
<slot />
</Layout>
</body>
</html>

0 comments on commit 2c8c61e

Please sign in to comment.