-
Notifications
You must be signed in to change notification settings - Fork 97
/
script.js
79 lines (69 loc) 路 2.08 KB
/
script.js
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
// @ts-check
// Add dark / light detection that runs before loading Nuxt
(() => {
// Global variable minimizers
const w = window
const de = document.documentElement
const ls = window.localStorage
const knownColorSchemes = ['dark', 'light']
const preference = (ls && ls.getItem && ls.getItem('<%= options.storageKey %>')) || '<%= options.preference %>'
let value = preference === 'system' ? getColorScheme() : preference
// Applied forced color mode
const forcedColorMode = de.getAttribute('data-color-mode-forced')
if (forcedColorMode) {
value = forcedColorMode
}
addColorScheme(value)
w['<%= options.globalName %>'] = {
preference,
value,
getColorScheme,
addColorScheme,
removeColorScheme,
}
/** @param {string} value */
function addColorScheme(value) {
const className = '<%= options.classPrefix %>' + value + '<%= options.classSuffix %>'
const dataValue = '<%= options.dataValue %>'
if (de.classList) {
de.classList.add(className)
}
else {
de.className += ' ' + className
}
if (dataValue) {
de.setAttribute('data-' + dataValue, value)
}
}
/** @param {string} value */
function removeColorScheme(value) {
const className = '<%= options.classPrefix %>' + value + '<%= options.classSuffix %>'
const dataValue = '<%= options.dataValue %>'
if (de.classList) {
de.classList.remove(className)
}
else {
de.className = de.className.replace(new RegExp(className, 'g'), '')
}
if (dataValue) {
de.removeAttribute('data-' + dataValue)
}
}
/** @param {string} suffix */
function prefersColorScheme(suffix) {
return w.matchMedia('(prefers-color-scheme' + suffix + ')')
}
function getColorScheme() {
if (
// @ts-expect-error TS assumes matchMedia is always defined
w.matchMedia
&& prefersColorScheme('').media !== 'not all') {
for (const colorScheme of knownColorSchemes) {
if (prefersColorScheme(':' + colorScheme).matches) {
return colorScheme
}
}
}
return '<%= options.fallback %>'
}
})()