From 8ddf0ca40643401541d844a97df5542817fea1be Mon Sep 17 00:00:00 2001 From: Mingyu Derek MA Date: Mon, 8 Jul 2019 04:10:11 +0800 Subject: [PATCH] feat: automatically turn on night mode if visitor prefers dark themes (#1041) --- assets/js/academic.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/assets/js/academic.js b/assets/js/academic.js index 6d09e7d2..6930927c 100644 --- a/assets/js/academic.js +++ b/assets/js/academic.js @@ -91,7 +91,7 @@ event.preventDefault(); $('html, body').animate({ 'scrollTop': 0 - }, 800, function() { + }, 800, function() {default_m window.location.hash = ""; }); }); @@ -392,12 +392,19 @@ $('#TableOfContents li').addClass('nav-item'); $('#TableOfContents li a').addClass('nav-link'); - // Set dark mode if user chose it. - let default_mode = 0; + // Get theme variation (day/night). + let defaultThemeVariation; if ($('body').hasClass('dark')) { - default_mode = 1; + // The `color_theme` of the site is dark. + defaultThemeVariation = 1; + } else if ($('.js-dark-toggle').length && window.matchMedia('(prefers-color-scheme: dark)').matches) { + // The visitor prefers dark themes and switching to the dark variation is allowed by admin. + defaultThemeVariation = 1; + } else { + // Default to day (light) theme. + defaultThemeVariation = 0; } - let dark_mode = parseInt(localStorage.getItem('dark_mode') || default_mode); + let dark_mode = parseInt(localStorage.getItem('dark_mode') || defaultThemeVariation); // Is code highlighting enabled in site config? const codeHlEnabled = $('link[title=hl-light]').length > 0;