From eb8748ff17996f04ee8a472ad997a2d4ae9410f6 Mon Sep 17 00:00:00 2001 From: George Cushen Date: Sun, 23 Aug 2020 20:24:15 +0100 Subject: [PATCH] fix: page flickers when user's dark/light pref differs to theme's default Fix by setting dark/light theme as soon as body tag exists. Highlight JS and Mermaid JS theming must still occur later during page load. Opportunity to refactor this fix and existing OnReady theme code to avoid duplicate JS and reuse code. Fix #1601 --- assets/js/load-theme.js | 31 +++++++++++++++++++++++++++++++ layouts/_default/baseof.html | 10 ++++++++++ layouts/partials/site_js.html | 7 ------- 3 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 assets/js/load-theme.js diff --git a/assets/js/load-theme.js b/assets/js/load-theme.js new file mode 100644 index 00000000..cf44d798 --- /dev/null +++ b/assets/js/load-theme.js @@ -0,0 +1,31 @@ +function getThemeMode() { + return parseInt(localStorage.getItem('dark_mode') || 2); +} + +let currentThemeMode = getThemeMode(); +let isDarkTheme; +switch (currentThemeMode) { + case 0: + isDarkTheme = false; + break; + case 1: + isDarkTheme = true; + break; + default: + if (window.matchMedia('(prefers-color-scheme: dark)').matches) { + // The visitor prefers dark themes and switching to the dark variation is allowed by admin. + isDarkTheme = true; + } else if (window.matchMedia('(prefers-color-scheme: light)').matches) { + // The visitor prefers light themes and switching to the dark variation is allowed by admin. + isDarkTheme = false; + } else { + // Use the site's default theme variation based on `light` in the theme file. + isDarkTheme = isSiteThemeDark; + } + break; +} +if (isDarkTheme) { + document.body.classList.add("dark"); +} else { + document.body.classList.remove("dark"); +} diff --git a/layouts/_default/baseof.html b/layouts/_default/baseof.html index c56ef110..b1d28da3 100644 --- a/layouts/_default/baseof.html +++ b/layouts/_default/baseof.html @@ -8,6 +8,16 @@ {{- $highlight_active_link := site.Params.main_menu.highlight_active_link | default true -}} + {{/* Load day/night theme. */}} + {{/* Initialise default theme. */}} + {{ if eq (.Scratch.Get "light") true }} + + {{ else }} + + {{ end }} + {{ $load_theme := resources.Get "js/load-theme.js" }} + + {{ partial "search" . }} {{ partial "navbar" . }} diff --git a/layouts/partials/site_js.html b/layouts/partials/site_js.html index 2988340a..7373cdd0 100644 --- a/layouts/partials/site_js.html +++ b/layouts/partials/site_js.html @@ -42,13 +42,6 @@ {{ end }} - {{/* Initialise default theme. */}} - {{ if eq ($scr.Get "light") true }} - - {{ else }} - - {{ end }} - {{ if ne site.Params.search.engine 0 }} {{/* Configure search engine. */}} {{ $min_length := site.Params.search.academic.min_length | default 1 }}