From b1ae89fa08acb82daf903fa94d1a8a09df5846e4 Mon Sep 17 00:00:00 2001 From: Wessel Dankers Date: Thu, 1 Jul 2021 17:10:21 +0200 Subject: [PATCH] Add automatic dark mode detection Also switches automatically whenever the OS does --- nyaa/static/js/main.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/nyaa/static/js/main.js b/nyaa/static/js/main.js index efe41d9..feb66c0 100644 --- a/nyaa/static/js/main.js +++ b/nyaa/static/js/main.js @@ -4,8 +4,23 @@ document.addEventListener("DOMContentLoaded", function(event) { // wait for cont toggleDarkMode(); // toggle theme }); // needs to be done here as is not available when the script in the head runs - if (typeof(Storage) !== 'undefined' && localStorage.getItem('theme') === 'dark') + if (typeof(Storage) !== 'undefined' && localStorage.getItem('theme') === 'dark') { document.body.classList.add('dark'); + } else if (window.matchMedia) { + const darkMedia = window.matchMedia('(prefers-color-scheme: dark)'); + if (darkMedia.matches) + document.body.classList.add('dark'); + // Some operating systems switch to dark mode only during the evening/night: + darkMedia.addEventListener('change', function(event) { + // Do not overwrite if the user made a manual choice: + if (localStorage.getItem('theme') === null) { + if (event.matches) + document.body.classList.add('dark'); + else + document.body.classList.remove('dark'); + } + }); + } });