]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
docs: follow prefered user scheme
authorEduardo San Martin Morote <posva13@gmail.com>
Mon, 8 Mar 2021 09:32:31 +0000 (10:32 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Mon, 8 Mar 2021 09:33:16 +0000 (10:33 +0100)
docs/.vitepress/components/ThemeToggle.vue

index 7147ddc2d492b47d7cbfb8b3e162bd2a9fd74ef1..dbb13e116390b947f71617d9b9c4d72ac9cf42fe 100644 (file)
@@ -60,16 +60,20 @@ import { computed, onMounted, ref, watchEffect } from 'vue'
 
 const isBrowser = typeof window !== 'undefined'
 
+const PREFERS_LIGHT = '(prefers-color-scheme: light)'
+
 function isDarkMode() {
-  const htmlElement = document.body.parentElement!
-  return !htmlElement.classList.contains('light')
+  if (!isBrowser) return true
+
+  const storedTheme = localStorage.getItem(storageKey)
+  if (storedTheme != null) return storedTheme !== 'light'
+
+  return !window.matchMedia(PREFERS_LIGHT).matches
 }
 
 const storageKey = 'pinia-color-scheme'
 
-const localIsDark = ref(
-  isBrowser ? localStorage.getItem(storageKey) !== 'light' : true
-)
+const localIsDark = ref(isDarkMode())
 
 const isDark = computed<boolean>({
   get() {
@@ -88,9 +92,17 @@ const label = computed(() =>
 onMounted(() => {
   window.addEventListener('storage', () => {
     const storedScheme = localStorage.getItem(storageKey)
-    isDark.value = storedScheme !== 'light'
+    localIsDark.value = storedScheme !== 'light'
   })
 
+  const mediaQuery = window.matchMedia(PREFERS_LIGHT)
+
+  if ('addEventListener' in mediaQuery) {
+    mediaQuery.addEventListener('change', (event) => {
+      localIsDark.value = !event.matches
+    })
+  }
+
   watchEffect(() => {
     const htmlElement = document.body.parentElement!
     if (isDark.value) {