conditionalSlot.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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.82
  5. */
  6. import { forceUpdate } from "@stencil/core";
  7. import { createObserver } from "./observers";
  8. const observed = new Set();
  9. let mutationObserver;
  10. const observerOptions = { childList: true };
  11. /**
  12. * Helper to set up a conditional slot component on connectedCallback.
  13. */
  14. export function connectConditionalSlotComponent(component) {
  15. if (!mutationObserver) {
  16. mutationObserver = createObserver("mutation", processMutations);
  17. }
  18. mutationObserver.observe(component.el, observerOptions);
  19. }
  20. /**
  21. * Helper to tear down a conditional slot component on disconnectedCallback.
  22. */
  23. export function disconnectConditionalSlotComponent(component) {
  24. observed.delete(component.el);
  25. // we explicitly process queued mutations and disconnect and reconnect
  26. // the observer until MutationObserver gets an `unobserve` method
  27. // see https://github.com/whatwg/dom/issues/126
  28. processMutations(mutationObserver.takeRecords());
  29. mutationObserver.disconnect();
  30. for (const [element] of observed.entries()) {
  31. mutationObserver.observe(element, observerOptions);
  32. }
  33. }
  34. function processMutations(mutations) {
  35. mutations.forEach(({ target }) => {
  36. forceUpdate(target);
  37. });
  38. }