From 4754607fb558dbe2d515286b80bbf00bc581c77b Mon Sep 17 00:00:00 2001 From: James Panther <4462786+jpanther@users.noreply.github.com> Date: Wed, 12 Jan 2022 10:15:41 +1100 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor=20dark=20mode=20i?= =?UTF-8?q?nline=20JS=20to=20dark.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + assets/js/dark.js | 54 ++++++++++++++++++++++++++++++++++++ layouts/partials/footer.html | 4 --- layouts/partials/head.html | 26 ++--------------- 4 files changed, 58 insertions(+), 27 deletions(-) create mode 100644 assets/js/dark.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dbc9c5c..dbbc8504 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed - Upgrade to Tailwind v3.0.12 +- Inline Javascript moved to external files - Author images are now Hugo assets - Required Hugo version is now 0.87.0 or later - Minor style and layout improvements diff --git a/assets/js/dark.js b/assets/js/dark.js new file mode 100644 index 00000000..8f07fd32 --- /dev/null +++ b/assets/js/dark.js @@ -0,0 +1,54 @@ +function loadPreferredAppearance() { + if ( + localStorage.preferredAppearance === "dark" || + (!("preferredAppearance" in localStorage) && + window.matchMedia("(prefers-color-scheme: dark)").matches) + ) { + document.documentElement.classList.add("dark"); + } else { + document.documentElement.classList.remove("dark"); + } +} + +function setPreferredAppearance(scheme) { + if (scheme == "default") { + localStorage.removeItem("preferredAppearance"); + } else { + localStorage.preferredAppearance = scheme; + } + loadPreferredAppearance(); +} + +window.addEventListener("DOMContentLoaded", (event) => { + // Hook up toggle events + darkToggle = document.getElementById("dark-toggle"); + if (darkToggle) { + darkToggle.addEventListener("click", function (e) { + e.preventDefault(); + setPreferredAppearance("dark"); + }); + darkToggle.addEventListener("contextmenu", function (e) { + e.preventDefault(); + setPreferredAppearance("default"); + }); + } + lightToggle = document.getElementById("light-toggle"); + if (lightToggle) { + lightToggle.addEventListener("click", function (e) { + e.preventDefault(); + setPreferredAppearance("light"); + }); + lightToggle.addEventListener("contextmenu", function (e) { + e.preventDefault(); + setPreferredAppearance("default"); + }); + } + + // Load user's preset preference (if any) + loadPreferredAppearance(); + + // Allow browser media overrides + window + .matchMedia("(prefers-color-scheme: dark)") + .addEventListener("change", loadPreferredAppearance); +}); diff --git a/layouts/partials/footer.html b/layouts/partials/footer.html index 256b42d8..924354bc 100644 --- a/layouts/partials/footer.html +++ b/layouts/partials/footer.html @@ -43,8 +43,6 @@