first release

This commit is contained in:
Ferdinand Kuhl 2024-05-26 21:08:01 +02:00
parent 6bfe35da8b
commit 166a3a1b88
2 changed files with 70 additions and 0 deletions

18
package.json Normal file
View file

@ -0,0 +1,18 @@
{
"name": "@digicomp/now-and-later",
"version": "1.0.0",
"description": "an easy API for DOM MutationObserver",
"main": "src/nowAndLater.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@digital-competence.de:npm/now-and-later.git"
},
"keywords": [
"MutationObserver"
],
"author": "Ferdinand Kuhl",
"license": "MIT"
}

52
src/nowAndLater.js Normal file
View file

@ -0,0 +1,52 @@
const lateInits = [];
/**
* @callback NowAndLaterCallback
* @param {HTMLElement} element
* @param {string|undefined} selector
* @return void
*/
/**
* @param {string} selector
* @param {NowAndLaterCallback} callback
*/
export default function nowAndLater(selector, callback)
{
const nodes = document.querySelectorAll(selector);
const id = Date.now() + '_' + lateInits.length;
const wrappedCallback = (node) => {
node.dataset['nowAndLater' + id] = '';
callback(node, selector);
};
if (nodes.length > 0) {
[...nodes].forEach(node => {
wrappedCallback(node);
});
}
lateInits.push({selector: selector, callback: wrappedCallback, id: id});
}
const observer = new MutationObserver(function (mutationsList)
{
for (const mutation of mutationsList) {
for (const addedNode of mutation.addedNodes) {
for (const lateInit of lateInits) {
if (addedNode['querySelector'] === undefined) { // lets filter out text and comment nodes
continue;
}
const selector = lateInit.selector + ':not([data-now-and-later' + lateInit.id + '])';
// If the added node matches itself, it will not be found by querySelectorAll, so we have to check first
if (addedNode.matches(selector)) {
lateInit.callback(addedNode);
}
// NOTE: the added not selector prevents double calls
const nodes = addedNode.querySelectorAll(selector);
if (nodes.length > 0) {
[...nodes].forEach(node => lateInit.callback(node));
}
}
}
}
});
observer.observe(document.documentElement, {childList: true, subtree: true});