index.mjs 2.2 KB

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