From 5bd8d973265bd42906cdedc4afb61c1304f17e88 Mon Sep 17 00:00:00 2001
From: Per Lundberg <per.lundberg@mailbox.org>
Date: Thu, 1 Apr 2021 13:16:09 +0300
Subject: [PATCH] Implement media-matching to auto-detect client dark mode
 setting

Originally done as part of
https://github.com/perlang-org/perlang/commit/3178955f5dabc6c5b5105614acb708e352ed3d71.
I'm not fully convinced whether this is a good idea or not, or whether
it will just make people confused. Nonetheless, this keeps us in track
with the version we have deployed at https://perlang.org
---
 darkerfx/styles/toggle-theme.js | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/darkerfx/styles/toggle-theme.js b/darkerfx/styles/toggle-theme.js
index 0427b77..32bf512 100644
--- a/darkerfx/styles/toggle-theme.js
+++ b/darkerfx/styles/toggle-theme.js
@@ -1,7 +1,17 @@
 const sw = document.getElementById("switch-style"), b = document.body;
 
 if (sw && b) {
-    sw.checked = window.localStorage && localStorage.getItem("theme") === "theme-dark" || !window.localStorage;
+    if (window.localStorage && localStorage.getItem("theme") === "theme-dark") {
+        // Browser supports local storage and dark mode is configured.
+        sw.checked = true;
+    }
+    else {
+        // Browser does not support local storage, or no stored theme setting is
+        // present. Determine dark mode based on browser settings. Browsers
+        // which don't support media matching will default to light theme, in
+        // line with what most people would expect from a web page.
+        sw.checked = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
+    }
 
     b.classList.toggle("theme-dark", sw.checked)
     b.classList.toggle("theme-light", !sw.checked)