mirror of
https://github.com/umami-software/umami.git
synced 2026-02-04 12:47:13 +01:00
Moved code into src folder. Added build for component library.
This commit is contained in:
parent
7a7233ead4
commit
ede658771e
490 changed files with 749 additions and 442 deletions
153
src/tracker/index.d.ts
vendored
Normal file
153
src/tracker/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
export type TrackedProperties = {
|
||||
/**
|
||||
* Hostname of server
|
||||
*
|
||||
* @description extracted from `window.location.hostname`
|
||||
* @example 'analytics.umami.is'
|
||||
*/
|
||||
hostname: string;
|
||||
|
||||
/**
|
||||
* Browser language
|
||||
*
|
||||
* @description extracted from `window.navigator.language`
|
||||
* @example 'en-US', 'fr-FR'
|
||||
*/
|
||||
language: string;
|
||||
|
||||
/**
|
||||
* Page referrer
|
||||
*
|
||||
* @description extracted from `window.navigator.language`
|
||||
* @example 'https://analytics.umami.is/docs/getting-started'
|
||||
*/
|
||||
referrer: string;
|
||||
|
||||
/**
|
||||
* Screen dimensions
|
||||
*
|
||||
* @description extracted from `window.screen.width` and `window.screen.height`
|
||||
* @example '1920x1080', '2560x1440'
|
||||
*/
|
||||
screen: string;
|
||||
|
||||
/**
|
||||
* Page title
|
||||
*
|
||||
* @description extracted from `document.querySelector('head > title')`
|
||||
* @example 'umami'
|
||||
*/
|
||||
title: string;
|
||||
|
||||
/**
|
||||
* Page url
|
||||
*
|
||||
* @description built from `${window.location.pathname}${window.location.search}`
|
||||
* @example 'docs/getting-started'
|
||||
*/
|
||||
url: string;
|
||||
|
||||
/**
|
||||
* Website ID (required)
|
||||
*
|
||||
* @example 'b59e9c65-ae32-47f1-8400-119fcf4861c4'
|
||||
*/
|
||||
website: string;
|
||||
};
|
||||
|
||||
export type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
|
||||
|
||||
/**
|
||||
*
|
||||
* Event Data can work with any JSON data. There are a few rules in place to maintain performance.
|
||||
* - Numbers have a max precision of 4.
|
||||
* - Strings have a max length of 500.
|
||||
* - Arrays are converted to a String, with the same max length of 500.
|
||||
* - Objects have a max of 50 properties. Arrays are considered 1 property.
|
||||
*/
|
||||
export interface EventData {
|
||||
[key: string]: number | string | EventData | number[] | string[] | EventData[];
|
||||
}
|
||||
|
||||
export type EventProperties = {
|
||||
/**
|
||||
* NOTE: event names will be truncated past 50 characters
|
||||
*/
|
||||
name: string;
|
||||
data?: EventData;
|
||||
} & WithRequired<TrackedProperties, 'website'>;
|
||||
export type PageViewProperties = WithRequired<TrackedProperties, 'website'>;
|
||||
export type CustomEventFunction = (
|
||||
props: PageViewProperties,
|
||||
) => EventProperties | PageViewProperties;
|
||||
|
||||
export type UmamiTracker = {
|
||||
track: {
|
||||
/**
|
||||
* Track a page view
|
||||
*
|
||||
* @example ```
|
||||
* umami.track();
|
||||
* ```
|
||||
*/
|
||||
(): Promise<string>;
|
||||
|
||||
/**
|
||||
* Track an event with a given name
|
||||
*
|
||||
* NOTE: event names will be truncated past 50 characters
|
||||
*
|
||||
* @example ```
|
||||
* umami.track('signup-button');
|
||||
* ```
|
||||
*/
|
||||
(eventName: string): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tracks an event with dynamic data.
|
||||
*
|
||||
* NOTE: event names will be truncated past 50 characters
|
||||
*
|
||||
* When tracking events, the default properties are included in the payload. This is equivalent to running:
|
||||
*
|
||||
* ```js
|
||||
* umami.track(props => ({
|
||||
* ...props,
|
||||
* name: 'signup-button',
|
||||
* data: {
|
||||
* name: 'newsletter',
|
||||
* id: 123
|
||||
* }
|
||||
* }));
|
||||
* ```
|
||||
*
|
||||
* @example ```
|
||||
* umami.track('signup-button', { name: 'newsletter', id: 123 });
|
||||
* ```
|
||||
*/
|
||||
(eventName: string, obj: EventData): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tracks a page view with custom properties
|
||||
*
|
||||
* @example ```
|
||||
* umami.track({ website: 'e676c9b4-11e4-4ef1-a4d7-87001773e9f2', url: '/home', title: 'Home page' });
|
||||
* ```
|
||||
*/
|
||||
(properties: PageViewProperties): Promise<string>;
|
||||
|
||||
/**
|
||||
* Tracks an event with fully customizable dynamic data
|
||||
* Ilf you don't specify any `name` and/or `data`, it will be treated as a page view
|
||||
*
|
||||
* @example ```
|
||||
* umami.track((props) => ({ ...props, url: path }));
|
||||
* ```
|
||||
*/
|
||||
(eventFunction: CustomEventFunction): Promise<string>;
|
||||
};
|
||||
};
|
||||
|
||||
interface Window {
|
||||
umami: UmamiTracker;
|
||||
}
|
||||
242
src/tracker/index.js
Normal file
242
src/tracker/index.js
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
(window => {
|
||||
const {
|
||||
screen: { width, height },
|
||||
navigator: { language },
|
||||
location,
|
||||
localStorage,
|
||||
document,
|
||||
history,
|
||||
} = window;
|
||||
const { hostname, pathname, search } = location;
|
||||
const { currentScript } = document;
|
||||
|
||||
if (!currentScript) return;
|
||||
|
||||
const _data = 'data-';
|
||||
const _false = 'false';
|
||||
const attr = currentScript.getAttribute.bind(currentScript);
|
||||
const website = attr(_data + 'website-id');
|
||||
const hostUrl = attr(_data + 'host-url');
|
||||
const autoTrack = attr(_data + 'auto-track') !== _false;
|
||||
const dnt = attr(_data + 'do-not-track');
|
||||
const domain = attr(_data + 'domains') || '';
|
||||
const domains = domain.split(',').map(n => n.trim());
|
||||
const root = hostUrl
|
||||
? hostUrl.replace(/\/$/, '')
|
||||
: currentScript.src.split('/').slice(0, -1).join('/');
|
||||
const endpoint = `${root}/api/send`;
|
||||
const screen = `${width}x${height}`;
|
||||
const eventRegex = /data-umami-event-([\w-_]+)/;
|
||||
const eventNameAttribute = _data + 'umami-event';
|
||||
const delayDuration = 300;
|
||||
|
||||
/* Helper functions */
|
||||
|
||||
const hook = (_this, method, callback) => {
|
||||
const orig = _this[method];
|
||||
|
||||
return (...args) => {
|
||||
callback.apply(null, args);
|
||||
|
||||
return orig.apply(_this, args);
|
||||
};
|
||||
};
|
||||
|
||||
const getPath = url => {
|
||||
if (url.substring(0, 4) === 'http') {
|
||||
return '/' + url.split('/').splice(3).join('/');
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
const getPayload = () => ({
|
||||
website,
|
||||
hostname,
|
||||
screen,
|
||||
language,
|
||||
title,
|
||||
url: currentUrl,
|
||||
referrer: currentRef,
|
||||
});
|
||||
|
||||
/* Tracking functions */
|
||||
|
||||
const doNotTrack = () => {
|
||||
const { doNotTrack, navigator, external } = window;
|
||||
|
||||
const msTrackProtection = 'msTrackingProtectionEnabled';
|
||||
const msTracking = () => {
|
||||
return external && msTrackProtection in external && external[msTrackProtection]();
|
||||
};
|
||||
|
||||
const dnt = doNotTrack || navigator.doNotTrack || navigator.msDoNotTrack || msTracking();
|
||||
|
||||
return dnt == '1' || dnt === 'yes';
|
||||
};
|
||||
|
||||
const trackingDisabled = () =>
|
||||
(localStorage && localStorage.getItem('umami.disabled')) ||
|
||||
(dnt && doNotTrack()) ||
|
||||
(domain && !domains.includes(hostname));
|
||||
|
||||
const handlePush = (state, title, url) => {
|
||||
if (!url) return;
|
||||
|
||||
currentRef = currentUrl;
|
||||
currentUrl = getPath(url.toString());
|
||||
|
||||
if (currentUrl !== currentRef) {
|
||||
setTimeout(track, delayDuration);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
const trackElement = 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);
|
||||
}
|
||||
});
|
||||
|
||||
return track(eventName, eventData);
|
||||
}
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
const callback = e => {
|
||||
const findATagParent = (rootElem, maxSearchDepth) => {
|
||||
let currentElement = rootElem;
|
||||
for (let i = 0; i < maxSearchDepth; i++) {
|
||||
if (currentElement.tagName === 'A') {
|
||||
return currentElement;
|
||||
}
|
||||
currentElement = currentElement.parentElement;
|
||||
if (!currentElement) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const el = e.target;
|
||||
const anchor = el.tagName === 'A' ? el : findATagParent(el, 10);
|
||||
|
||||
if (anchor) {
|
||||
const { href, target } = anchor;
|
||||
const external =
|
||||
target === '_blank' ||
|
||||
e.ctrlKey ||
|
||||
e.shiftKey ||
|
||||
e.metaKey ||
|
||||
(e.button && e.button === 1);
|
||||
const eventName = anchor.getAttribute(eventNameAttribute);
|
||||
|
||||
if (eventName && href) {
|
||||
if (!external) {
|
||||
e.preventDefault();
|
||||
}
|
||||
return trackElement(anchor).then(() => {
|
||||
if (!external) location.href = href;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
trackElement(el);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', callback, true);
|
||||
};
|
||||
|
||||
const observeTitle = () => {
|
||||
const callback = ([entry]) => {
|
||||
title = entry && entry.target ? entry.target.text : undefined;
|
||||
};
|
||||
|
||||
const observer = new MutationObserver(callback);
|
||||
|
||||
const node = document.querySelector('head > title');
|
||||
|
||||
if (node) {
|
||||
observer.observe(node, {
|
||||
subtree: true,
|
||||
characterData: true,
|
||||
childList: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const send = (payload, type = 'event') => {
|
||||
if (trackingDisabled()) return;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (typeof cache !== 'undefined') {
|
||||
headers['x-umami-cache'] = cache;
|
||||
}
|
||||
return fetch(endpoint, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ type, payload }),
|
||||
headers,
|
||||
})
|
||||
.then(res => res.text())
|
||||
.then(text => (cache = text));
|
||||
};
|
||||
|
||||
const track = (obj, data) => {
|
||||
if (typeof obj === 'string') {
|
||||
return send({
|
||||
...getPayload(),
|
||||
name: obj,
|
||||
data: typeof data === 'object' ? data : undefined,
|
||||
});
|
||||
} else if (typeof obj === 'object') {
|
||||
return send(obj);
|
||||
} else if (typeof obj === 'function') {
|
||||
return send(obj(getPayload()));
|
||||
}
|
||||
return send(getPayload());
|
||||
};
|
||||
|
||||
const identify = data => send({ ...getPayload(), data }, 'identify');
|
||||
|
||||
/* Start */
|
||||
|
||||
if (!window.umami) {
|
||||
window.umami = {
|
||||
track,
|
||||
identify,
|
||||
};
|
||||
}
|
||||
|
||||
let currentUrl = `${pathname}${search}`;
|
||||
let currentRef = document.referrer;
|
||||
let title = document.title;
|
||||
let cache;
|
||||
let initialized;
|
||||
|
||||
if (autoTrack && !trackingDisabled()) {
|
||||
history.pushState = hook(history, 'pushState', handlePush);
|
||||
history.replaceState = hook(history, 'replaceState', handlePush);
|
||||
handleClick();
|
||||
observeTitle();
|
||||
|
||||
const init = () => {
|
||||
if (document.readyState === 'complete' && !initialized) {
|
||||
track();
|
||||
initialized = true;
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('readystatechange', init, true);
|
||||
|
||||
init();
|
||||
}
|
||||
})(window);
|
||||
Loading…
Add table
Add a link
Reference in a new issue