From f736a71d38e94beffa9c4806b9f467ecbede7fa8 Mon Sep 17 00:00:00 2001 From: Tostapunk Date: Fri, 12 Jul 2024 18:38:43 +0200 Subject: [PATCH 1/2] Add option to follow the system theme By using "system" as value of site.mode the theme will automatically follow the system one --- _config.yml | 2 +- assets/js/main.js | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/_config.yml b/_config.yml index 4a92f3e55..d886c326d 100644 --- a/_config.yml +++ b/_config.yml @@ -7,7 +7,7 @@ lang: en-US # default lang timezone: Asia/Jakarta # set your timezone image: assets/img/ogp.png # This image used for Open Graph more info https://ogp.me/ repo: https://github.com/piharpi/jekyll-klise # site repo [optional] -mode: dark # default theme "dark" | "light" +mode: dark # default theme "dark" | "light" | "system" (follow system theme) # Profile settings author: diff --git a/assets/js/main.js b/assets/js/main.js index b58aca9eb..45d8e9508 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -2,6 +2,8 @@ // Theme switch const body = document.body; const lamp = document.getElementById("mode"); + const themeMode = localStorage.getItem("theme"); + const systemDarkModePreference = window.matchMedia("(prefers-color-scheme: dark)"); const toggleTheme = (state) => { if (state === "dark") { @@ -14,10 +16,21 @@ initTheme(state); } }; - - lamp.addEventListener("click", () => - toggleTheme(localStorage.getItem("theme")) - ); + + if (themeMode !== "system") { + lamp.addEventListener("click", () => + toggleTheme(localStorage.getItem("theme")) + ); + } else { + lamp.remove(); + systemDarkModePreference.addEventListener("change", e => { + if (e.matches) { + toggleTheme("light") + } else { + toggleTheme("dark") + } + }); + } // Blur the content when the menu is open const cbox = document.getElementById("menu-trigger"); From 3796d831eeff9fb8057890fa93831178e0ecfe56 Mon Sep 17 00:00:00 2001 From: Tostapunk Date: Fri, 12 Jul 2024 18:54:38 +0200 Subject: [PATCH 2/2] Fix system theme init --- assets/js/main.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/assets/js/main.js b/assets/js/main.js index 45d8e9508..2ee48249c 100644 --- a/assets/js/main.js +++ b/assets/js/main.js @@ -16,6 +16,14 @@ initTheme(state); } }; + + const systemThemeToToggle = (e) => { + if (e.matches) { + toggleTheme("light") + } else { + toggleTheme("dark") + } + } if (themeMode !== "system") { lamp.addEventListener("click", () => @@ -23,12 +31,9 @@ ); } else { lamp.remove(); + systemThemeToToggle(systemDarkModePreference); systemDarkModePreference.addEventListener("change", e => { - if (e.matches) { - toggleTheme("light") - } else { - toggleTheme("dark") - } + systemThemeToToggle(e); }); }