返回 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 === 'dark' || configs.colorSchema === 'light')
9 export const isDark = computed<boolean>({
10 get() {
11 if (isColorSchemaConfigured.value)
12 return configs.colorSchema === 'dark'
13 if (configs.colorSchema === 'light dark' || configs.colorSchema === 'dark light') {
14 if (store.value === 'dark')
15 return true
16 if (store.value === 'light')
17 return false
18 return configs.colorSchema === 'dark light'
19 }
20 return store.value === 'auto'
21 ? preferredDark.value
22 : store.value === 'dark'
23 },
24 set(v) {
25 if (isColorSchemaConfigured.value)
26 return
27 if (configs.colorSchema === 'light dark' || configs.colorSchema === 'dark light') {
28 store.value = v ? 'dark' : 'light'
29 return
30 }
31 store.value = v === preferredDark.value
32 ? 'auto'
33 : v ? 'dark' : 'light'
34 },
35 })
36
37 export const toggleDark = useToggle(isDark)
38
39 if (isClient) {
40 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}'
41
42 watch(
43 isDark,
44 (v) => {
45 const style = window!.document.createElement('style')
46 style.appendChild(document.createTextNode(CSS_DISABLE_TRANS))
47 window!.document.head.appendChild(style)
48
49 const html = document.querySelector('html')!
50 html.classList.toggle('dark', v)
51 html.classList.toggle('light', !v)
52
53 // Calling getComputedStyle forces the browser to redraw
54 // @ts-expect-error unused variable
55 const _ = window!.getComputedStyle(style!).opacity
56 document.head.removeChild(style!)
57 },
58 { immediate: true },
59 )
60 }
61
61 lines TYPESCRIPT