From d3ff6297c4034bbf45f4a60e287e12cfa1f0ad1a Mon Sep 17 00:00:00 2001 From: Prat <616399+pt2121@users.noreply.github.com> Date: Tue, 9 Aug 2022 08:34:47 -0700 Subject: Use OS color scheme to init light/dark mode (#2611) Closes #2591 --- .../resources/dokka/scripts/platform-content-handler.js | 5 +++-- plugins/base/src/main/resources/dokka/templates/base.ftl | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) (limited to 'plugins/base/src') diff --git a/plugins/base/src/main/resources/dokka/scripts/platform-content-handler.js b/plugins/base/src/main/resources/dokka/scripts/platform-content-handler.js index de5c6b15..def9dae8 100644 --- a/plugins/base/src/main/resources/dokka/scripts/platform-content-handler.js +++ b/plugins/base/src/main/resources/dokka/scripts/platform-content-handler.js @@ -31,9 +31,10 @@ window.addEventListener('load', () => { const darkModeSwitch = () => { const localStorageKey = "dokka-dark-mode" const storage = localStorage.getItem(localStorageKey) - const savedDarkMode = storage ? JSON.parse(storage) : false + const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches + const darkModeEnabled = storage ? JSON.parse(storage) : osDarkSchemePreferred const element = document.getElementById("theme-toggle-button") - initPlayground(savedDarkMode ? samplesDarkThemeName : samplesLightThemeName) + initPlayground(darkModeEnabled ? samplesDarkThemeName : samplesLightThemeName) element.addEventListener('click', () => { const enabledClasses = document.getElementsByTagName("html")[0].classList diff --git a/plugins/base/src/main/resources/dokka/templates/base.ftl b/plugins/base/src/main/resources/dokka/templates/base.ftl index 78ce21e2..ed19d5f3 100644 --- a/plugins/base/src/main/resources/dokka/templates/base.ftl +++ b/plugins/base/src/main/resources/dokka/templates/base.ftl @@ -12,10 +12,18 @@ <#-- This script doesn't need to be there but it is nice to have since app in dark mode doesn't 'blink' (class is added before it is rendered) --> + if (storage == null) { + const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches + if (osDarkSchemePreferred === true) { + document.getElementsByTagName("html")[0].classList.add("theme-dark") + } + } else { + const savedDarkMode = JSON.parse(storage) + if(savedDarkMode === true) { + document.getElementsByTagName("html")[0].classList.add("theme-dark") + } + } + <#-- Resources (scripts, stylesheets) are handled by Dokka. Use customStyleSheets and customAssets to change them. --> <@resources/> -- cgit