Script simplification: Use Element.closest + less nesting

This commit is contained in:
Ali Khaleqi Yekta 2025-05-04 12:13:15 +03:30
parent e12e5b0d2e
commit 671dcfceb5
No known key found for this signature in database
GPG key ID: 8CE90F8CC149DE8C

View file

@ -89,73 +89,47 @@
document.addEventListener( document.addEventListener(
'click', 'click',
async e => { async e => {
const isSpecialTag = tagName => ['BUTTON', 'A'].includes(tagName);
const trackElement = async el => { const trackElement = async el => {
const attr = el.getAttribute.bind(el); const attr = el.getAttribute.bind(el);
const eventName = attr(eventNameAttribute); const eventName = attr(eventNameAttribute);
if (eventName) { if (eventName) {
const eventData = {}; const eventData = {};
el.getAttributeNames().forEach(name => { el.getAttributeNames().forEach(name => {
const match = name.match(eventRegex); const match = name.match(eventRegex);
if (match) eventData[match[1]] = attr(name);
if (match) {
eventData[match[1]] = attr(name);
}
}); });
return track(eventName, eventData); return track(eventName, eventData);
} }
}; };
const findParentTag = (rootElem, maxSearchDepth) => {
let currentElement = rootElem;
for (let i = 0; i < maxSearchDepth; i++) {
if (isSpecialTag(currentElement.tagName)) {
return currentElement;
}
currentElement = currentElement.parentElement;
if (!currentElement) {
return null;
}
}
return null;
};
const el = e.target; const el = e.target;
const parentElement = isSpecialTag(el.tagName) ? el : findParentTag(el, 10); const parentElement = el.closest('a,button');
if (!parentElement) return trackElement(el);
if (parentElement) { const { href, target } = parentElement;
const { href, target } = parentElement; const eventName = parentElement.getAttribute(eventNameAttribute);
const eventName = parentElement.getAttribute(eventNameAttribute); if (!eventName) return;
if (eventName) { if (parentElement.tagName === 'A') {
if (parentElement.tagName === 'A') { const external =
const external = target === '_blank' ||
target === '_blank' || e.ctrlKey ||
e.ctrlKey || e.shiftKey ||
e.shiftKey || e.metaKey ||
e.metaKey || (e.button && e.button === 1);
(e.button && e.button === 1);
if (eventName && href) { if (eventName && href) {
if (!external) { if (!external) e.preventDefault();
e.preventDefault(); return trackElement(parentElement).then(() => {
} if (!external) {
return trackElement(parentElement).then(() => { (target === '_top' ? top.location : location).href = href;
if (!external) {
(target === '_top' ? top.location : location).href = href;
}
});
} }
} else if (parentElement.tagName === 'BUTTON') { });
return trackElement(parentElement);
}
} }
} else { } else if (parentElement.tagName === 'BUTTON') {
return trackElement(el); return trackElement(parentElement);
} }
}, },
true, true,