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