umami/lib/filters.js

99 lines
1.9 KiB
JavaScript
Raw Normal View History

export const urlFilter = data => {
const isValidUrl = url => {
return url !== '' && url !== null && !url.startsWith('#');
};
2020-08-01 12:34:56 +02:00
const cleanUrl = url => {
try {
2020-09-26 07:31:18 +02:00
const { pathname, search } = new URL(url, location.origin);
if (search.startsWith('?/')) {
return `${pathname}${search}`;
}
return pathname;
} catch {
return null;
}
};
const map = data.reduce((obj, { x, y }) => {
if (!isValidUrl(x)) {
return obj;
}
2020-09-26 07:31:18 +02:00
const url = cleanUrl(x);
if (url) {
if (!obj[url]) {
obj[url] = y;
} else {
obj[url] += y;
}
}
return obj;
}, {});
2020-10-22 01:14:51 +02:00
return Object.keys(map).map(key => ({ x: key, y: map[key] }));
};
export const refFilter = data => {
const links = {};
const map = data.reduce((obj, { x, y }) => {
let id;
try {
const url = new URL(x);
2022-08-29 05:20:54 +02:00
id = url.hostname.replace('www', '') || url.href;
} catch {
id = '';
}
links[id] = x;
if (!obj[id]) {
obj[id] = y;
} else {
obj[id] += y;
}
return obj;
}, {});
2020-10-22 01:14:51 +02:00
return Object.keys(map).map(key => ({ x: key, y: map[key], w: links[key] }));
2020-08-07 11:46:21 +02:00
};
2020-08-01 12:34:56 +02:00
export const percentFilter = data => {
const total = data.reduce((n, { y }) => n + y, 0);
2020-08-25 08:49:14 +02:00
return data.map(({ x, y, ...props }) => ({ x, y, z: total ? (y / total) * 100 : 0, ...props }));
2020-08-01 12:34:56 +02:00
};
2022-08-08 10:26:20 +02:00
export const paramFilter = data => {
const map = data.reduce((obj, { x, y }) => {
try {
const searchParams = new URLSearchParams(x.split('?')[1]);
for (const [key, value] of searchParams) {
if (!obj[key]) {
obj[key] = { [value]: y };
} else if (!obj[key][value]) {
obj[key][value] = y;
} else {
obj[key][value] += y;
}
}
} catch {
// Ignore
}
return obj;
}, {});
2022-08-29 05:20:54 +02:00
return Object.keys(map).flatMap(key =>
2022-08-08 10:26:20 +02:00
Object.keys(map[key]).map(n => ({ x: `${key}=${n}`, p: key, v: n, y: map[key][n] })),
);
};