maz-ui
Version:
A standalone components library for Vue.Js 3 & Nuxt.Js 3
38 lines (37 loc) • 1.38 kB
JavaScript
import { i as isClient } from "../chunks/isClient.WI4oSt66.js";
import { t as truthyFilter } from "../chunks/truthyFilter.C2WOKUCG.js";
import { ref, onMounted, computed, toValue, watch } from "vue";
function useMutationObserver(target, callback, options = {}) {
const {
internalWindow = isClient() ? globalThis : void 0,
...mutationOptions
} = options;
let observer;
const isSupported = ref((internalWindow && "MutationObserver" in internalWindow) ?? !1);
isSupported.value || onMounted(() => {
isSupported.value = (internalWindow && "MutationObserver" in internalWindow) ?? !1;
});
const cleanup = () => {
observer && (observer.disconnect(), observer = void 0);
}, targets = computed(() => {
const value = toValue(target);
let element;
return value && "$el" in value ? element = value.$el : value && (element = value), new Set([element].filter(truthyFilter));
}), stopWatch = watch(
[targets, isSupported],
([newTargets, isSupported2]) => {
cleanup(), isSupported2 && newTargets.size && (observer = new MutationObserver(callback), newTargets.forEach((el) => observer?.observe(el, mutationOptions)));
},
{ immediate: !0, flush: "post" }
);
return {
isSupported,
stop: () => {
stopWatch(), cleanup();
},
takeRecords: () => observer?.takeRecords()
};
}
export {
useMutationObserver
};