1 | const colorIndexRegExp = /((?:not )?all and )?(\(color-index: *(22|48|70)\))/i;
|
---|
2 | const prefersColorSchemeRegExp = /prefers-color-scheme:/i;
|
---|
3 |
|
---|
4 | const prefersColorSchemeInit = initialColorScheme => {
|
---|
5 | const mediaQueryString = '(prefers-color-scheme: dark)';
|
---|
6 | const mediaQueryList = window.matchMedia && matchMedia(mediaQueryString);
|
---|
7 | const hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;
|
---|
8 |
|
---|
9 | const mediaQueryListener = () => {
|
---|
10 | set(mediaQueryList.matches ? 'dark' : 'light');
|
---|
11 | };
|
---|
12 |
|
---|
13 | const removeListener = () => {
|
---|
14 | if (mediaQueryList) {
|
---|
15 | mediaQueryList.removeListener(mediaQueryListener);
|
---|
16 | }
|
---|
17 | };
|
---|
18 |
|
---|
19 | const set = colorScheme => {
|
---|
20 | if (colorScheme !== currentColorScheme) {
|
---|
21 | currentColorScheme = colorScheme;
|
---|
22 |
|
---|
23 | if (typeof result.onChange === 'function') {
|
---|
24 | result.onChange();
|
---|
25 | }
|
---|
26 | }
|
---|
27 |
|
---|
28 | [].forEach.call(document.styleSheets || [], styleSheet => {
|
---|
29 | [].forEach.call(styleSheet.cssRules || [], cssRule => {
|
---|
30 | const colorSchemeMatch = prefersColorSchemeRegExp.test(Object(cssRule.media).mediaText);
|
---|
31 |
|
---|
32 | if (colorSchemeMatch) {
|
---|
33 | const index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);
|
---|
34 | cssRule.parentStyleSheet.deleteRule(index);
|
---|
35 | } else {
|
---|
36 | const colorIndexMatch = (Object(cssRule.media).mediaText || '').match(colorIndexRegExp);
|
---|
37 |
|
---|
38 | if (colorIndexMatch) {
|
---|
39 | 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');
|
---|
40 | }
|
---|
41 | }
|
---|
42 | });
|
---|
43 | });
|
---|
44 | };
|
---|
45 |
|
---|
46 | const result = Object.defineProperty({
|
---|
47 | hasNativeSupport,
|
---|
48 | removeListener
|
---|
49 | }, 'scheme', {
|
---|
50 | get: () => currentColorScheme,
|
---|
51 | set
|
---|
52 | }); // initialize the color scheme using the provided value, the system value, or light
|
---|
53 |
|
---|
54 | let currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');
|
---|
55 | set(currentColorScheme); // listen for system changes
|
---|
56 |
|
---|
57 | if (mediaQueryList) {
|
---|
58 | mediaQueryList.addListener(mediaQueryListener);
|
---|
59 | }
|
---|
60 |
|
---|
61 | return result;
|
---|
62 | };
|
---|
63 |
|
---|
64 | export default prefersColorSchemeInit;
|
---|
65 | //# sourceMappingURL=index.mjs.map
|
---|