返回 slidev
dark.ts
根目录 / packages / client / logic / dark.ts
1 import { isClient, useLocalStorage, usePreferredDark, useToggle } from '@vueuse/core'
2 import { computed, watch } from 'vue'
3 import { configs } from '../env'
4
5 const preferredDark = usePreferredDark()
6 const store = useLocalStorage('slidev-color-schema', 'auto')
7
8 export const isColorSchemaConfigured = computed(() => configs.colorSchema !== 'auto')
9 export const isDark = computed<boolean>({
10 get() {
11 if (isColorSchemaConfigured.value)
12 return configs.colorSchema === 'dark'
13 return store.value === 'auto'
14 ? preferredDark.value
15 : store.value === 'dark'
16 },
17 set(v) {
18 if (isColorSchemaConfigured.value)
19 return
20 store.value = v === preferredDark.value
21 ? 'auto'
22 : v ? 'dark' : 'light'
23 },
24 })
25
26 export const toggleDark = useToggle(isDark)
27
28 if (isClient) {
29 const CSS_DISABLE_TRANS = '*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'
30
31 watch(
32 isDark,
33 (v) => {
34 const style = window!.document.createElement('style')
35 style.appendChild(document.createTextNode(CSS_DISABLE_TRANS))
36 window!.document.head.appendChild(style)
37
38 const html = document.querySelector('html')!
39 html.classList.toggle('dark', v)
40 html.classList.toggle('light', !v)
41
42 // Calling getComputedStyle forces the browser to redraw
43 // @ts-expect-error unused variable
44 const _ = window!.getComputedStyle(style!).opacity
45 document.head.removeChild(style!)
46 },
47 { immediate: true },
48 )
49 }
50
50 lines TYPESCRIPT