Skip to content

Commit

Permalink
Better snippet
Browse files Browse the repository at this point in the history
  • Loading branch information
bartoszhernas committed Sep 15, 2020
1 parent d5e4914 commit 7a71bb1
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# production
/build
/public/umami.js
/public/snippet.js
/lang-compiled
/lang-formatted

Expand Down
5 changes: 4 additions & 1 deletion components/forms/TrackingCodeForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@ export default function TrackingCodeForm({ values, onClose }) {
/>
</p>
<FormRow>
{/* Run `npm run build-snippet, and copy paste here the content of public/snippet.js */}
{/* TODO: use webpack importing function to import the content of the file here ? */}
<textarea
ref={ref}
rows={3}
cols={60}
spellCheck={false}
defaultValue={`<script async defer data-website-id="${values.website_uuid}" src="${document.location.origin}/umami.js"></script>`}
defaultValue={`!function(){"use strict";!function(e){var t=e.umami=e.umami||[];if(!t.registerAutoEvents)if(t.invoked)e.console&&console.error&&console.error("Umami snippet included twice.");else{t.invoked=!0,t.calls=[],t.methods=["registerAutoEvents","event","pageView"],t.factory=function(e){return function(){var r=Array.prototype.slice.call(arguments);return r.unshift(e),t.calls.push(r),t}};for(var r=0;r<t.methods.length;r++){var i=t.methods[r];t[i]=t.factory(i)}t.load=function(e,t,r,i){var o=document.createElement("script");o.type="text/javascript",o.defer=!0,o.async=!0,o.setAttribute("data-website-id",t),r&&o.setAttribute("data-skip-auto","true"),i&&o.setAttribute("data-debug","true"),o.src=e;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)},t.load("${document.location.origin}/umami.js","${values.website_uuid}",!1,!1)}}(window)}();
`}
readOnly
/>
</FormRow>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"start": "next start",
"build-app": "next build",
"build-tracker": "rollup -c rollup.tracker.config.js",
"build-snippet": "rollup -c rollup.snippet.config.js",
"copy-db-schema": "node scripts/copy-db-schema.js",
"build-db-schema": "dotenv prisma introspect",
"build-db-client": "dotenv prisma generate",
Expand Down
19 changes: 19 additions & 0 deletions rollup.snippet.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'dotenv/config';
import buble from '@rollup/plugin-buble';
import replace from '@rollup/plugin-replace';
import resolve from '@rollup/plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

export default {
input: 'tracker/snippet.js',
output: {
file: 'public/snippet.js',
format: 'iife',
},
plugins: [
replace({ __DNT__: !!process.env.ENABLE_DNT }),
resolve(),
buble(),
terser({ compress: { evaluate: false } }),
],
};
91 changes: 54 additions & 37 deletions tracker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import 'unfetch/polyfill';
import { doNotTrack, hook, post } from '../lib/web';
import { removeTrailingSlash } from '../lib/url';

function log(isDebug, messageFn) {
if (isDebug) {
return;
}
console.log(messageFn());
}

(window => {
const {
screen: { width, height },
Expand All @@ -20,6 +27,7 @@ import { removeTrailingSlash } from '../lib/url';
const website = script.getAttribute('data-website-id');
const hostUrl = script.getAttribute('data-host-url');
const skipAuto = script.getAttribute('data-skip-auto');
const isDebug = script.getAttribute('data-debug');
const root = hostUrl
? removeTrailingSlash(hostUrl)
: new URL(script.src).href.split('/').slice(0, -1).join('/');
Expand Down Expand Up @@ -72,45 +80,54 @@ import { removeTrailingSlash } from '../lib/url';
});
};

if (!window.umami) {
window.umami = event_value => window.umami.event('custom', event_value, currentUrl);
window.umami.collect = (type, params, id) => {
if (!id) {
id = website;
}
const payload = {
website: id,
hostname,
screen,
language,
};

if (params) {
Object.keys(params).forEach(key => {
payload[key] = params[key];
});
}

return post(`${root}/api/collect`, {
type,
payload,
});

const scheduledCalls = window.umami.calls;
window.umami = {};
window.umami.collect = (type, params, id) => {
if (!id) {
id = website;
}
const payload = {
website: id,
hostname,
screen,
language,
};
window.umami.pageView = (url = currentUrl, referrer = currentRef) => window.umami.collect('pageview', {
url,
referrer,
});
window.umami.event = (event_type, event_value, url = currentUrl) => window.umami.collect('event', {
url,
event_type,
event_value,

if (params) {
Object.keys(params).forEach(key => {
payload[key] = params[key];
});
}

log(isDebug, () => `Umami, collect ${type} with payload: ${JSON.stringify(payload, null, 2)}`);
return post(`${root}/api/collect`, {
type,
payload,
});
window.umami.registerAutoEvents = () => {
history.pushState = hook(history, 'pushState', handlePush);
history.replaceState = hook(history, 'replaceState', handlePush);
return pageViewWithAutoEvents(currentUrl, currentRef);
};
}
};
window.umami.pageView = (url = currentUrl, referrer = currentRef) => window.umami.collect('pageview', {
url,
referrer,
});
window.umami.event = (event_type, event_value, url = currentUrl) => window.umami.collect('event', {
url,
event_type,
event_value,
});
window.umami.registerAutoEvents = () => {
history.pushState = hook(history, 'pushState', handlePush);
history.replaceState = hook(history, 'replaceState', handlePush);
return pageViewWithAutoEvents(currentUrl, currentRef);
};

log(isDebug, () => 'Umami, calling scheduled invocations');
log(isDebug, () => scheduledCalls);

scheduledCalls.forEach(([fnName, ...params]) => {
log(isDebug, () => `Umami, calling ${fnName} fn with params: ${JSON.stringify(params)}`);
window.umami[fnName].apply(window.umami, params);
});

/* Start */
if (!skipAuto) {
Expand Down
42 changes: 42 additions & 0 deletions tracker/snippet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
(window => {
const umami = window.umami = window.umami || [];
if (!umami.registerAutoEvents) {
if (umami.invoked) {
window.console && console.error && console.error('Umami snippet included twice.');
} else {
umami.invoked = true;
umami.calls = [];
umami.methods = ['registerAutoEvents', 'event', 'pageView'];
umami.factory = t => {
return function() {
const e = Array.prototype.slice.call(arguments);
e.unshift(t);
umami.calls.push(e);
return umami;
};
};
for (let t = 0; t < umami.methods.length; t++) {
let e = umami.methods[t];
umami[e] = umami.factory(e);
}
umami.load = function(umamiScript, umamiUUID, skipAuto, isDebug) {
const scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.defer = true;
scriptElement.async = true;
scriptElement.setAttribute('data-website-id', umamiUUID);
if (skipAuto) {
scriptElement.setAttribute('data-skip-auto', 'true');
}
if (isDebug) {
scriptElement.setAttribute('data-debug', 'true');
}
scriptElement.src = umamiScript;
const otherScript = document.getElementsByTagName('script')[0];
otherScript.parentNode.insertBefore(scriptElement, otherScript);
};

umami.load('${document.location.origin}/umami.js', '${values.website_uuid}', false, false);
}
}
})(window);

0 comments on commit 7a71bb1

Please sign in to comment.