observers.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import { Build } from '@stencil/core/internal/client/index.js';
  7. /**
  8. * This utility ensures observers are created only for browser contexts.
  9. *
  10. * @param type - the type of observer to create
  11. * @param callback - the observer callback
  12. * @param options - the observer options
  13. */
  14. function createObserver(type, callback, options) {
  15. if (!Build.isBrowser) {
  16. return undefined;
  17. }
  18. const Observer = getObserver(type);
  19. return new Observer(callback, options);
  20. }
  21. function getObserver(type) {
  22. // based on https://github.com/whatwg/dom/issues/126#issuecomment-1049814948
  23. class ExtendedMutationObserver extends window.MutationObserver {
  24. constructor(callback) {
  25. super(callback);
  26. this.observedEntry = [];
  27. this.callback = callback;
  28. }
  29. observe(target, options) {
  30. this.observedEntry.push({ target, options });
  31. return super.observe(target, options);
  32. }
  33. unobserve(target) {
  34. const newObservedEntries = this.observedEntry.filter((observed) => observed.target !== target);
  35. this.observedEntry = [];
  36. this.callback(super.takeRecords(), this);
  37. this.disconnect();
  38. newObservedEntries.forEach((observed) => this.observe(observed.target, observed.options));
  39. }
  40. }
  41. return (function () {
  42. return (type === "intersection"
  43. ? window.IntersectionObserver
  44. : type === "mutation"
  45. ? ExtendedMutationObserver
  46. : window.ResizeObserver);
  47. })();
  48. }
  49. export { createObserver as c };