UNPKG

@sv-use/core

Version:

A collection of Svelte 5 utilities.

40 lines (39 loc) 1.4 kB
import { watch } from '../watch/index.svelte.js'; import { isSupported } from '../__internal__/is.svelte.js'; import { defaultWindow } from '../__internal__/configurable.js'; import { normalizeValue, notNullish, toArray } from '../__internal__/utils.svelte.js'; import { onDestroy } from 'svelte'; export function observeMutation(targets, callback, options = {}) { const { autoCleanup = true, window = defaultWindow, ...mutationOptions } = options; let _observer; const _isSupported = isSupported(() => window !== undefined && 'MutationObserver' in window); const _targets = $derived(new Set(toArray(targets).map(normalizeValue).filter(notNullish))); watch(() => _targets, (targets) => { cleanup(); if (_isSupported.current && targets.size) { _observer = new MutationObserver(callback); targets.forEach((el) => _observer.observe(el, mutationOptions)); } }, { runOnMounted: true }); if (autoCleanup) { onDestroy(() => { cleanup(); }); } function takeRecords() { return _observer?.takeRecords(); } function cleanup() { if (!_observer) return; _observer.disconnect(); _observer = undefined; } return { get isSupported() { return _isSupported.current; }, cleanup, takeRecords }; }