refactor toggle theme

This commit is contained in:
TF Mukles
2023-10-18 10:19:56 +06:00
parent 9d1ac829f8
commit cff66f7478
2 changed files with 15 additions and 8 deletions
+4
View File
@@ -6,6 +6,8 @@ import { plainify } from "@/lib/utils/textConverter";
import Footer from "@/partials/Footer.astro";
import Header from "@/partials/Header.astro";
import "@/styles/main.scss";
import { ViewTransitions } from 'astro:transitions';
// font families
const pf = theme.fonts.font_family.primary;
@@ -82,6 +84,8 @@ const { title, meta_title, description, image, noindex, canonical } =
)}
/>
<ViewTransitions />
<!-- author from config.json -->
<meta name="author" content={config.metadata.meta_author} />
+11 -8
View File
@@ -45,24 +45,27 @@ const { className }: { className?: string } = Astro.props;
}
<script>
function toggleTheme(themeSwitch: NodeListOf<Element>) {
const currentTheme = localStorage.getItem("theme");
const isDarkTheme = currentTheme === "dark";
import { settings } from "@/config/config.json";
const matchMedia = window.matchMedia("(prefers-color-scheme: dark)");
matchMedia.addEventListener('change', () => toggleTheme(document.querySelectorAll("[data-theme-switcher]")));
function toggleTheme(themeSwitch: NodeListOf<Element>) {
const defaulTheme = settings.default_theme ==="system" ? matchMedia.matches ? "dark" : "light" : settings.default_theme;
const currentTheme = localStorage.getItem("theme") || defaulTheme;
const isDarkTheme = currentTheme === "dark";
themeSwitch.forEach((sw: any) => (sw.checked = isDarkTheme));
document.documentElement.classList.toggle("dark", isDarkTheme);
}
const setDarkMode = () => {
const themeSwitch = document.querySelectorAll("[data-theme-switcher]");
toggleTheme(themeSwitch);
themeSwitch.forEach((sw) => {
sw.addEventListener("click", function () {
const currentTheme = localStorage.getItem("theme");
const newTheme = currentTheme === "dark" ? "light" : "dark";
const defaulTheme = settings.default_theme ==="system" ? matchMedia.matches ? "dark" : "light" : settings.default_theme;
const currentTheme = localStorage.getItem("theme") || defaulTheme;
const newTheme = currentTheme === "light" ? "dark" : "light";
localStorage.setItem("theme", newTheme);
toggleTheme(themeSwitch);
});