refactor: scope dedupe to parent container
This commit is contained in:
@@ -1,26 +1,41 @@
|
|||||||
const dedupe = (): void => {
|
const dedupeWithin = (root: ParentNode): void => {
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const elements = document.querySelectorAll("[data-id]");
|
const elements = root.querySelectorAll<HTMLElement>(":scope > [data-id]");
|
||||||
|
|
||||||
elements.forEach((item) => {
|
elements.forEach((item) => {
|
||||||
const id = item.getAttribute("data-id");
|
const id = item.dataset.id;
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (seen.has(id)) {
|
if (seen.has(id)) {
|
||||||
item.remove(); // duplicate, remove it
|
item.remove();
|
||||||
} else {
|
return;
|
||||||
seen.add(id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
seen.add(id);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const dedupe = (): void => {
|
||||||
|
const containers = new Set<ParentNode>();
|
||||||
|
const elements = document.querySelectorAll<HTMLElement>("[data-id]");
|
||||||
|
|
||||||
|
elements.forEach((item) => {
|
||||||
|
if (item.parentElement) {
|
||||||
|
containers.add(item.parentElement);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
containers.forEach((container) => {
|
||||||
|
dedupeWithin(container);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// run on DOM ready or immediately if already loaded
|
|
||||||
if (document.readyState === "loading") {
|
if (document.readyState === "loading") {
|
||||||
document.addEventListener("DOMContentLoaded", dedupe);
|
document.addEventListener("DOMContentLoaded", dedupe);
|
||||||
} else {
|
} else {
|
||||||
dedupe();
|
dedupe();
|
||||||
}
|
}
|
||||||
|
|
||||||
// also run on load as a fallback (e.g. htmx swaps)
|
|
||||||
window.addEventListener("load", dedupe);
|
window.addEventListener("load", dedupe);
|
||||||
|
|||||||
Reference in New Issue
Block a user