Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

Script simplification: Use `Element.closest` + less nesting

Ali Khaleqi Yekta671dcfceb5b4
diff --git a/src/tracker/index.js b/src/tracker/index.js
index 8b38c49d3..08d9c9173 100644
--- a/src/tracker/index.js
+++ b/src/tracker/index.js
@@ -89,73 +89,47 @@
document.addEventListener(
'click',
async e => {
- const isSpecialTag = tagName => ['BUTTON', 'A'].includes(tagName);
-
const trackElement = async el => {
const attr = el.getAttribute.bind(el);
const eventName = attr(eventNameAttribute);
-
if (eventName) {
const eventData = {};
el.getAttributeNames().forEach(name => {
const match = name.match(eventRegex);
-
- if (match) {
- eventData[match[1]] = attr(name);
- }
+ if (match) eventData[match[1]] = attr(name);
});
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 parentElement = isSpecialTag(el.tagName) ? el : findParentTag(el, 10);
-
- if (parentElement) {
- const { href, target } = parentElement;
- const eventName = parentElement.getAttribute(eventNameAttribute);
-
- if (eventName) {
- if (parentElement.tagName === 'A') {
- const external =
- target === '_blank' ||
- e.ctrlKey ||
- e.shiftKey ||
- e.metaKey ||
- (e.button && e.button === 1);
-
- if (eventName && href) {
- if (!external) {
- e.preventDefault();
- }
- return trackElement(parentElement).then(() => {
- if (!external) {
- (target === '_top' ? top.location : location).href = href;
- }
- });
+ const parentElement = el.closest('a,button');
+ if (!parentElement) return trackElement(el);
+
+ const { href, target } = parentElement;
+ const eventName = parentElement.getAttribute(eventNameAttribute);
+ if (!eventName) return;
+
+ if (parentElement.tagName === 'A') {
+ const external =
+ target === '_blank' ||
+ e.ctrlKey ||
+ e.shiftKey ||
+ e.metaKey ||
+ (e.button && e.button === 1);
+
+ if (eventName && href) {
+ if (!external) e.preventDefault();
+ return trackElement(parentElement).then(() => {
+ if (!external) {
+ (target === '_top' ? top.location : location).href = href;
}
- } else if (parentElement.tagName === 'BUTTON') {
- return trackElement(parentElement);
- }
+ });
}
- } else {
- return trackElement(el);
+ } else if (parentElement.tagName === 'BUTTON') {
+ return trackElement(parentElement);
}
},
true,