Browse Source

feat: automatically turn on night mode if visitor prefers dark themes (#1041)

Mingyu Derek MA 6 năm trước cách đây
mục cha
commit
8ddf0ca406
1 tập tin đã thay đổi với 12 bổ sung5 xóa
  1. 12 5
      assets/js/academic.js

+ 12 - 5
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;