Skip to content

Commit

Permalink
Refactor ThemeMenu to set icon theme based on system preference
Browse files Browse the repository at this point in the history
  • Loading branch information
madalinpopa committed Sep 29, 2024
1 parent 39599ca commit eec73c4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
4 changes: 2 additions & 2 deletions src/components/navigation/ThemeMenu.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ThemeButton from "../buttons/ThemeButton.astro";
import { Icon } from "astro-icon/components";
---

<div x-data="themeSwitcher" class="relative inline-block text-left">
<div x-data="themeSwitcher" x-data="themeSwitcher" x-init="$watch('theme', () => setIconTheme() )" class="relative inline-block text-left">
<div>
<ThemeButton />
</div>
Expand Down Expand Up @@ -45,7 +45,7 @@ import { Icon } from "astro-icon/components";
Dark
</button>
<button
x-on:click="setTheme('system'); location.reload();"
x-on:click="setTheme('system');"
class="flex gap-2 w-full items-center rounded-md px-4 py-2 text-sm hover:bg-gray-700 hover:text-white"
role="menuitem"
tabindex="-1"
Expand Down
34 changes: 23 additions & 11 deletions src/layouts/BaseLayout.astro
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
---
import "../styles/global.css";
import { ViewTransitions } from 'astro:transitions';
import { ViewTransitions } from "astro:transitions";
---

<html lang="en" x-data>
<html lang="en">
<head>
<meta charset="utf-8" />

Expand Down Expand Up @@ -73,16 +73,28 @@ import { ViewTransitions } from 'astro:transitions';
}
}
</script>
<script is:inline data-astro-rerun>
if (
localStorage.theme === "dark" ||
(!("theme" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches)
) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
<script is:inline>
function setSystemTheme() {
const theme = localStorage.getItem("theme") || "system";

if (theme === "system" || !(theme in localStorage)) {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}
}

// Set the system theme on page load
setSystemTheme();

// Set the system theme when the page is loaded
document.addEventListener('astro:page-load', e => setSystemTheme());

// Set the system theme when the user changes the system theme
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => setSystemTheme());

</script>
<title>Madalin Popa | DevOps Engineer</title>
<ViewTransitions />
Expand Down

0 comments on commit eec73c4

Please sign in to comment.