index.js 2.3 KB

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