-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
211 lines (184 loc) · 5.67 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import type { Ref } from 'vue-demi'
import { computed, ref, watch } from 'vue-demi'
import { tryOnMounted } from '@vueuse/shared'
import type { StorageLike } from '../ssr-handlers'
import { getSSRHandler } from '../ssr-handlers'
import type { UseStorageOptions } from '../useStorage'
import { useStorage } from '../useStorage'
import { defaultWindow } from '../_configurable'
import { usePreferredDark } from '../usePreferredDark'
import type { MaybeElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
export type BasicColorSchema = 'light' | 'dark' | 'auto'
export interface UseColorModeOptions<T extends string = BasicColorSchema> extends UseStorageOptions<T | BasicColorSchema> {
/**
* CSS Selector for the target element applying to
*
* @default 'html'
*/
selector?: string | MaybeElementRef
/**
* HTML attribute applying the target element
*
* @default 'class'
*/
attribute?: string
/**
* The initial color mode
*
* @default 'auto'
*/
initialValue?: T | BasicColorSchema
/**
* Prefix when adding value to the attribute
*/
modes?: Partial<Record<T | BasicColorSchema, string>>
/**
* A custom handler for handle the updates.
* When specified, the default behavior will be overridden.
*
* @default undefined
*/
onChanged?: (mode: T | BasicColorSchema, defaultHandler:((mode: T | BasicColorSchema) => void)) => void
/**
* Custom storage ref
*
* When provided, `useStorage` will be skipped
*/
storageRef?: Ref<T | BasicColorSchema>
/**
* Key to persist the data into localStorage/sessionStorage.
*
* Pass `null` to disable persistence
*
* @default 'vueuse-color-scheme'
*/
storageKey?: string | null
/**
* Storage object, can be localStorage or sessionStorage
*
* @default localStorage
*/
storage?: StorageLike
/**
* Emit `auto` mode from state
*
* When set to `true`, preferred mode won't be translated into `light` or `dark`.
* This is useful when the fact that `auto` mode was selected needs to be known.
*
* @default undefined
*/
emitAuto?: boolean
/**
* Disable transition on switch
*
* @see https://paco.me/writing/disable-theme-transitions
* @default true
*/
disableTransition?: boolean
}
export type UseColorModeReturn<T extends string = BasicColorSchema> =
Ref<T> & {
store: Ref<T>
system: Ref<'light' | 'dark'>
}
/**
* Reactive color mode with auto data persistence.
*
* @see https://vueuse.org/useColorMode
* @param options
*/
export function useColorMode<T extends string = BasicColorSchema>(
options: UseColorModeOptions<T> = {},
): UseColorModeReturn<T> {
const {
selector = 'html',
attribute = 'class',
initialValue = 'auto',
window = defaultWindow,
storage,
storageKey = 'vueuse-color-scheme',
listenToStorageChanges = true,
storageRef,
emitAuto,
disableTransition = true,
} = options
const modes = {
auto: '',
light: 'light',
dark: 'dark',
...options.modes || {},
} as Record<BasicColorSchema | T, string>
const preferredDark = usePreferredDark({ window })
const system = computed(() => preferredDark.value ? 'dark' : 'light')
const store = storageRef || (storageKey == null
? ref(initialValue) as Ref<T | BasicColorSchema>
: useStorage<T | BasicColorSchema>(storageKey, initialValue as BasicColorSchema, storage, { window, listenToStorageChanges }))
const state = computed<T | BasicColorSchema>({
get() {
return (store.value === 'auto' && !emitAuto)
? system.value
: store.value
},
set(v) {
store.value = v
},
})
const updateHTMLAttrs = getSSRHandler(
'updateHTMLAttrs',
(selector, attribute, value) => {
const el = typeof selector === 'string'
? window?.document.querySelector(selector)
: unrefElement(selector)
if (!el)
return
let style: HTMLStyleElement | undefined
if (disableTransition) {
style = window!.document.createElement('style')
style.appendChild(document.createTextNode('*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'))
window!.document.head.appendChild(style)
}
if (attribute === 'class') {
const current = value.split(/\s/g)
Object.values(modes)
.flatMap(i => (i || '').split(/\s/g))
.filter(Boolean)
.forEach((v) => {
if (current.includes(v))
el.classList.add(v)
else
el.classList.remove(v)
})
}
else {
el.setAttribute(attribute, value)
}
if (disableTransition) {
// Calling getComputedStyle forces the browser to redraw
// @ts-expect-error unused variable
const _ = window!.getComputedStyle(style!).opacity
document.head.removeChild(style!)
}
})
function defaultOnChanged(mode: T | BasicColorSchema) {
const resolvedMode = mode === 'auto' ? system.value : mode
updateHTMLAttrs(selector, attribute, modes[resolvedMode] ?? resolvedMode)
}
function onChanged(mode: T | BasicColorSchema) {
if (options.onChanged)
options.onChanged(mode, defaultOnChanged)
else
defaultOnChanged(mode)
}
watch(state, onChanged, { flush: 'post', immediate: true })
if (emitAuto)
watch(system, () => onChanged(state.value), { flush: 'post' })
tryOnMounted(() => onChanged(state.value))
try {
return Object.assign(state, { store, system }) as UseColorModeReturn<T>
}
catch (e) {
// In Vue 2.6, ref might not be extensible
return state as any as UseColorModeReturn<T>
}
}