-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
55 lines (46 loc) · 1.22 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { on_destroy, unstore } from "@sveu/shared"
import { support } from "../support"
/**
* Watch for changes being made to the DOM tree.
*
* @param target - The target node on which to observe DOM mutations.
*
* @param fn - The function to call when a mutation occurs.
*
* @param options - [See MutationObserver Options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe)
*
* @example
* ```ts
* const { supported, cleanup } = mutationObserver(document.body, () => {
* console.log("DOM changed!")
* })
* ```
*
* @returns
* - `supported` - Whether the browser supports the `MutationObserver` API.
* - `cleanup` - A function to stop watching for changes.
*/
export function mutationObserver(
target: HTMLElement | SVGElement | undefined | null,
fn: MutationCallback,
options: MutationObserverInit = {}
) {
let observer: MutationObserver | undefined
const supported = support("MutationObserver", "window")
function cleanup() {
if (observer) {
observer.disconnect()
observer = undefined
}
}
if (unstore(supported) && target) {
cleanup()
observer = new MutationObserver(fn)
observer.observe(target, options)
}
on_destroy(cleanup)
return {
supported,
cleanup,
}
}