index.js
2.26 KB
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
'use strict';
const colorIndexRegExp = /((?:not )?all and )?(\(color-index: *(22|48|70)\))/i;
const prefersColorSchemeRegExp = /prefers-color-scheme:/i;
const prefersColorSchemeInit = initialColorScheme => {
const mediaQueryString = '(prefers-color-scheme: dark)';
const mediaQueryList = window.matchMedia && matchMedia(mediaQueryString);
const hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;
const mediaQueryListener = () => {
set(mediaQueryList.matches ? 'dark' : 'light');
};
const removeListener = () => {
if (mediaQueryList) {
mediaQueryList.removeListener(mediaQueryListener);
}
};
const set = colorScheme => {
if (colorScheme !== currentColorScheme) {
currentColorScheme = colorScheme;
if (typeof result.onChange === 'function') {
result.onChange();
}
}
[].forEach.call(document.styleSheets || [], styleSheet => {
[].forEach.call(styleSheet.cssRules || [], cssRule => {
const colorSchemeMatch = prefersColorSchemeRegExp.test(Object(cssRule.media).mediaText);
if (colorSchemeMatch) {
const index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);
cssRule.parentStyleSheet.deleteRule(index);
} else {
const colorIndexMatch = (Object(cssRule.media).mediaText || '').match(colorIndexRegExp);
if (colorIndexMatch) {
cssRule.media.mediaText = ((/^dark$/i.test(colorScheme) ? colorIndexMatch[3] === '48' : /^light$/i.test(colorScheme) ? colorIndexMatch[3] === '70' : colorIndexMatch[3] === '22') ? 'not all and ' : '') + cssRule.media.mediaText.replace(colorIndexRegExp, '$2');
}
}
});
});
};
const result = Object.defineProperty({
hasNativeSupport,
removeListener
}, 'scheme', {
get: () => currentColorScheme,
set
}); // initialize the color scheme using the provided value, the system value, or light
let currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');
set(currentColorScheme); // listen for system changes
if (mediaQueryList) {
mediaQueryList.addListener(mediaQueryListener);
}
return result;
};
module.exports = prefersColorSchemeInit;
//# sourceMappingURL=index.js.map