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 }}