@solid-primitives/mutation-observer
Version:
Primitive providing the ability to watch for changes made to the DOM tree.
53 lines (52 loc) • 1.65 kB
JavaScript
import { onCleanup, onMount } from "solid-js";
import { access, asArray } from "@solid-primitives/utils";
export function createMutationObserver(initial, b, c) {
let defaultOptions, callback;
const isSupported = typeof window !== "undefined" && "MutationObserver" in window;
if (typeof b === "function") {
defaultOptions = {};
callback = b;
}
else {
defaultOptions = b;
callback = c;
}
const instance = isSupported ? new MutationObserver(callback) : undefined;
const add = (el, options) => instance?.observe(el, access(options) ?? defaultOptions);
const start = () => {
asArray(access(initial)).forEach(item => {
item instanceof Node ? add(item, defaultOptions) : add(item[0], item[1]);
});
};
const stop = () => instance?.disconnect();
onMount(start);
onCleanup(stop);
return [
add,
{
start,
stop,
instance: instance,
isSupported,
},
];
}
/**
* Primitive providing the ability to watch for changes being made to the DOM tree.
* A Standalone Directive.
*
* @param props [MutationObserver options, callback]
*
* @see https://github.com/solidjs-community/solid-primitives/tree/main/packages/mutation-observer
* @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
*
* @example
* ```tsx
* <div use:mutationObserver={[{ childList: true }, e => {...}]}></div>
* ```
*/
export const mutationObserver = (target, props) => {
const [config, cb] = props();
const [add] = createMutationObserver([], cb);
add(target, config);
};