@esri/calcite-components
Version:
Web Components for Esri's Calcite Design System.
49 lines (48 loc) • 1.61 kB
JavaScript
/*!
* All material copyright ESRI, All Rights Reserved, unless otherwise specified.
* See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
* v1.5.0-next.4
*/
import { Build } from "@stencil/core";
/**
* This utility ensures observers are created only for browser contexts.
*
* @param type - the type of observer to create
* @param callback - the observer callback
* @param options - the observer options
*/
export function createObserver(type, callback, options) {
if (!Build.isBrowser) {
return undefined;
}
const Observer = getObserver(type);
return new Observer(callback, options);
}
function getObserver(type) {
// based on https://github.com/whatwg/dom/issues/126#issuecomment-1049814948
class ExtendedMutationObserver extends window.MutationObserver {
constructor(callback) {
super(callback);
this.observedEntry = [];
this.callback = callback;
}
observe(target, options) {
this.observedEntry.push({ target, options });
return super.observe(target, options);
}
unobserve(target) {
const newObservedEntries = this.observedEntry.filter((observed) => observed.target !== target);
this.observedEntry = [];
this.callback(super.takeRecords(), this);
this.disconnect();
newObservedEntries.forEach((observed) => this.observe(observed.target, observed.options));
}
}
return (function () {
return (type === "intersection"
? window.IntersectionObserver
: type === "mutation"
? ExtendedMutationObserver
: window.ResizeObserver);
})();
}