From 52758459a220fde27f1519d3fd3e99f3f2a52f80 Mon Sep 17 00:00:00 2001 From: eltrac Date: Tue, 10 Feb 2026 15:39:50 +0800 Subject: feat: add theme switch --- assets/js/darkmode.js | 36 ++++++++++++++++++++++++++ layouts/_partials/head.html | 3 ++- layouts/_partials/head/scripts.html | 4 +++ layouts/_partials/header/other-navigation.html | 7 +++++ 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 assets/js/darkmode.js create mode 100644 layouts/_partials/head/scripts.html diff --git a/assets/js/darkmode.js b/assets/js/darkmode.js new file mode 100644 index 00000000..6057f357 --- /dev/null +++ b/assets/js/darkmode.js @@ -0,0 +1,36 @@ +(() => { + const THEME = 'geedeapro.theme' // auto | light | dakr + const mql = window.matchMedia('(prefers-color-scheme: dark)') + + function useDarkMode(store) { + document.documentElement.classList.add('dark') + if (localStorage.getItem(THEME) != 'auto') mql.onchange = null + if (store) localStorage.setItem(THEME, 'dark') + } + + function useLightMode(store) { + document.documentElement.classList.remove('dark') + if (localStorage.getItem(THEME) != 'auto') mql.onchange = null + if (store) localStorage.setItem(THEME, 'light') + } + + function useSystem(store) { + if (mql.matches) useDarkMode() + else useLightMode() + mql.onchange = e => { + console.log("changed when system changed") + if (e.matches) useDarkMode() + else useLightMode() + } + if (store) localStorage.setItem(THEME, 'auto') + } + + window.switchTheme = (theme, store) => { + if (!theme || theme === 'auto') useSystem(store) + else if (theme === 'dark') useDarkMode(store) + else if (theme === 'light') useLightMode(store) + } + + // use preferred theme immediately upon DOM loaded + window.switchTheme(localStorage.getItem(THEME), false) +})(); diff --git a/layouts/_partials/head.html b/layouts/_partials/head.html index a50dd333..3a8cd25c 100644 --- a/layouts/_partials/head.html +++ b/layouts/_partials/head.html @@ -4,6 +4,7 @@ {{ hugo.Generator }} {{ partial "head/siteinfo" . }} - {{ partial "head/css" . }} {{ partial "head/verification" . }} + {{ partial "head/css" . }} + {{ partial "head/scripts" . }} diff --git a/layouts/_partials/head/scripts.html b/layouts/_partials/head/scripts.html new file mode 100644 index 00000000..f067944c --- /dev/null +++ b/layouts/_partials/head/scripts.html @@ -0,0 +1,4 @@ +{{ with resources.Get "js/darkmode.js" }} + +{{ end }} + diff --git a/layouts/_partials/header/other-navigation.html b/layouts/_partials/header/other-navigation.html index 662f1076..ab6035f1 100644 --- a/layouts/_partials/header/other-navigation.html +++ b/layouts/_partials/header/other-navigation.html @@ -1,6 +1,13 @@ {{ $langButtonSize := "w-4 h-4" }}
+ + {{- $lang := .Site.Language.Lang -}} {{- $switch := dict -- cgit v1.2.3