-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdata-on-remove.js
More file actions
51 lines (42 loc) · 1.16 KB
/
data-on-remove.js
File metadata and controls
51 lines (42 loc) · 1.16 KB
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
import { attribute, beginBatch, endBatch } from "datastar";
let onRemovalEntries = [];
let observer = new MutationObserver((mutations) => {
mutations.forEach((m) => {
if (!m.removedNodes.length) {
return;
}
const removedNodes = Array.from(m.removedNodes ?? []);
onRemovalEntries.forEach((e) => {
if (removedNodes.includes(e.node) && !document.body.contains(e.node)) {
e.callback(m.target);
}
});
});
// Clean up any entries that were marked as removed once we have executed their callback
onRemovalEntries = onRemovalEntries.filter((e) => !e.isRemoved);
});
observer.observe(document.body, { childList: true, subtree: true });
attribute({
name: "on-remove",
requirement: {
key: "denied",
value: "must",
},
argNames: ["parent"],
apply: ({ rx, el }) => {
let callback = (parent) => {
beginBatch();
rx(parent);
endBatch();
};
onRemovalEntries.push({ node: el, callback, isRemoved: false });
return () => {
onRemovalEntries = onRemovalEntries.map((e) => {
if (e.node === el) {
e.isRemoved = true;
}
return e;
});
};
},
});