index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. export { setAssetPath, setPlatformOptions } from '@stencil/core/internal/client/index.js';
  7. import { d as darkTheme, a as autoTheme } from './dom.js';
  8. /**
  9. * Emits when the theme is dynamically toggled between light and dark on <body> or in OS preferences.
  10. */
  11. function initThemeChangeEvent() {
  12. const { classList } = document.body;
  13. const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  14. const getTheme = () => classList.contains(darkTheme) || (classList.contains(autoTheme) && prefersDark) ? "dark" : "light";
  15. const emitThemeChange = (theme) => document.body.dispatchEvent(new CustomEvent("calciteThemeChange", { bubbles: true, detail: { theme } }));
  16. const themeChangeHandler = (newTheme) => {
  17. currentTheme !== newTheme && emitThemeChange(newTheme);
  18. currentTheme = newTheme;
  19. };
  20. let currentTheme = getTheme();
  21. // emits event on page load
  22. emitThemeChange(currentTheme);
  23. // emits event when changing OS theme preferences
  24. window
  25. .matchMedia("(prefers-color-scheme: dark)")
  26. .addEventListener("change", (event) => themeChangeHandler(event.matches ? "dark" : "light"));
  27. // emits event when toggling between theme classes on <body>
  28. new MutationObserver(() => themeChangeHandler(getTheme())).observe(document.body, {
  29. attributes: true,
  30. attributeFilter: ["class"]
  31. });
  32. }
  33. /**
  34. * This file is imported in Stencil's `globalScript` config option.
  35. *
  36. * @see {@link https://stenciljs.com/docs/config#globalscript}
  37. */
  38. function appGlobalScript () {
  39. const isBrowser = typeof window !== "undefined" &&
  40. typeof location !== "undefined" &&
  41. typeof document !== "undefined" &&
  42. window.location === location &&
  43. window.document === document;
  44. if (isBrowser) {
  45. if (document.readyState === "interactive") {
  46. initThemeChangeEvent();
  47. }
  48. else {
  49. document.addEventListener("DOMContentLoaded", () => initThemeChangeEvent(), { once: true });
  50. }
  51. }
  52. }
  53. const globalScripts = appGlobalScript;
  54. globalScripts();