From 10b067e80586fae0649720d9994234605a1d2226 Mon Sep 17 00:00:00 2001 From: Lea Verou Date: Sat, 25 Jan 2025 14:52:53 -0500 Subject: [PATCH] Add JS snppet for setting `wa-dark` based on OS default --- docs/_layouts/theme.njk | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/_layouts/theme.njk b/docs/_layouts/theme.njk index dfa90a01c..03be52f24 100644 --- a/docs/_layouts/theme.njk +++ b/docs/_layouts/theme.njk @@ -138,6 +138,7 @@ You can apply the class to the `` element on your page to activate the dar Web Awesome's themes have both light and dark styles built in. However, Web Awesome doesn't try to auto-detect the user's light/dark mode preference. This should be done at the application level. + As a best practice, to provide a dark theme in your app, you should: - Check for [`prefers-color-scheme`](https://stackoverflow.com/a/57795495/567486) and use its value by default @@ -146,5 +147,18 @@ As a best practice, to provide a dark theme in your app, you should: Web Awesome avoids using the `prefers-color-scheme` media query because not all apps support dark mode, and it would break things for the ones that don't. +Assuming the user's preference is in a variable called `colorScheme` (values: `auto`, `light`, `dark`), +you can use the following JS snippet to apply the `wa-dark` class to the `` element accordingly: + +```js +const systemDark = window.matchMedia('(prefers-color-scheme: dark)'); +const applyDark = function (event = systemDark) { + const isDark = colorScheme === 'auto' ? event.matches : colorScheme === 'dark'; + document.documentElement.classList.toggle('wa-dark', isDark); +}; +systemDark.addEventListener('change', applyDark); +applyDark(); +``` + {% endmarkdown %} {% endblock %}