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