1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-27 21:10:29 -04:00

clean up scripts

This commit is contained in:
Jake Jarvis 2020-05-04 21:25:07 -04:00
parent 759bae4f14
commit 9e1a053d39
Signed by: jake
GPG Key ID: 2B0C9CF251E69A39
5 changed files with 154 additions and 116 deletions

View File

@ -6,28 +6,31 @@
// improve variable mangling when minifying // improve variable mangling when minifying
var win = window; var win = window;
var doc = win.document; var doc = win.document;
var bod = doc.body; var body = doc.body;
var cls = bod.classList; var classes = body.classList;
var sto = localStorage; var storage = localStorage;
// check for preset `dark_mode_pref` preference in localStorage // check for preset `dark_mode_pref` preference in local storage
var pref_key = 'dark_mode_pref'; var pref_key = 'dark_mode_pref';
var pref = sto.getItem(pref_key); var pref = storage.getItem(pref_key);
// change CSS via these <body> classes: // change CSS via these <body> classes:
var dark = 'dark'; var dark = 'dark';
var light = 'light'; var light = 'light';
// which class is <body> set to initially?
var default_theme = light;
// use an element with class `dark-mode-toggle` to trigger swap when clicked // use an element with class `dark-mode-toggle` to trigger swap when clicked
var toggle = doc.querySelector('.dark-mode-toggle'); var toggle = doc.querySelector('.dark-mode-toggle');
// keep track of current state (light by default) no matter how we got there // keep track of current state no matter how we got there
var active = false; var active = (default_theme === dark);
// receives a class name and switches <body> to it // receives a class name and switches <body> to it
var activateTheme = function (theme) { var activateTheme = function (theme) {
cls.remove(dark, light); classes.remove(dark, light);
cls.add(theme); classes.add(theme);
active = (theme === dark); active = (theme === dark);
}; };
@ -37,18 +40,23 @@
// user has never clicked the button, so go by their OS preference until/if they do so // user has never clicked the button, so go by their OS preference until/if they do so
if (!pref) { if (!pref) {
// check for OS dark mode setting and switch accordingly // returns media query selector syntax
var prefers_dark = '(prefers-color-scheme: dark)'; var prefers = function (theme) {
var prefers_light = '(prefers-color-scheme: light)'; return '(prefers-color-scheme: ' + theme + ')';
};
if (win.matchMedia(prefers_dark).matches) // check for OS dark/light mode preference and switch accordingly
// default to `default_theme` set above if unsupported
if (win.matchMedia(prefers(dark)).matches)
activateTheme(dark); activateTheme(dark);
else else if (win.matchMedia(prefers(light)).matches)
activateTheme(light); activateTheme(light);
else
activateTheme(default_theme);
// real-time switching if supported by OS/browser // real-time switching if supported by OS/browser
win.matchMedia(prefers_dark).addListener(function(e) { if (e.matches) activateTheme(dark); }); win.matchMedia(prefers(dark)).addListener(function (e) { if (e.matches) activateTheme(dark); });
win.matchMedia(prefers_light).addListener(function(e) { if (e.matches) activateTheme(light); }); win.matchMedia(prefers(light)).addListener(function (e) { if (e.matches) activateTheme(light); });
} }
// don't freak out if page happens not to have a toggle // don't freak out if page happens not to have a toggle
@ -59,16 +67,16 @@
// handle toggle click // handle toggle click
toggle.addEventListener('click', function () { toggle.addEventListener('click', function () {
// switch to the opposite theme & save preference in local storage // switch to the opposite theme & save preference in local storage
if (!active) { if (active) {
activateTheme(dark);
sto.setItem(pref_key, dark);
// send click event to analytics
sa_event('triggered_dark_mode');
} else {
activateTheme(light); activateTheme(light);
sto.setItem(pref_key, light); storage.setItem(pref_key, light);
// send click event to analytics // send event to SA
sa_event('triggered_light_mode'); sa_event('triggered_light_mode');
} else {
activateTheme(dark);
storage.setItem(pref_key, dark);
// send event to SA
sa_event('triggered_dark_mode');
} }
}, true); }, true);
} }

View File

@ -1,9 +1,9 @@
/* jshint browser: true, laxbreak:true, -W080 */ /* jshint browser: true, laxbreak:true, -W080 */
/*! Simple Analytics - Privacy friendly analytics (docs.simpleanalytics.com/script; 2020-03-02; 21e2) */ /*! Simple Analytics - Privacy friendly analytics (docs.simpleanalytics.com/script; 2020-05-03; d98d) */
// https://github.com/simpleanalytics/scripts/blob/3918189e9137b55522a2dbeb3d7cb4bc2c26c52a/src/default.js // https://github.com/simpleanalytics/scripts/blob/915d98d39868cbb578619f64b5e2374a5af60c2b/src/default.js
(function(window, baseUrl, apiUrlPrefix, version, saGlobal) { (function (window, baseUrl) {
if (!window) return; if (!window) return;
// Generate the needed variables, this seems like a lot of repetition, but it // Generate the needed variables, this seems like a lot of repetition, but it
@ -17,6 +17,7 @@
var slash = "/"; var slash = "/";
var nav = window.navigator; var nav = window.navigator;
var loc = window.location; var loc = window.location;
var hostname = loc.hostname;
var doc = window.document; var doc = window.document;
var notSending = "Not sending requests "; var notSending = "Not sending requests ";
var encodeURIComponentFunc = encodeURIComponent; var encodeURIComponentFunc = encodeURIComponent;
@ -26,14 +27,18 @@
var addEventListenerFunc = window.addEventListener; var addEventListenerFunc = window.addEventListener;
var fullApiUrl = protocol + baseUrl; var fullApiUrl = protocol + baseUrl;
var undefinedVar = undefined; var undefinedVar = undefined;
var hostname = loc.hostname;
var functionName = "sa_event"; var functionName = "sa_event";
var payload = { var payload = {
version: 2 version: 2,
}; };
payload.hostname = hostname; var options = {
hostname: hostname,
functionName: functionName,
};
payload.hostname = options.hostname;
// A simple log function so the user knows why a request is not being send // A simple log function so the user knows why a request is not being send
var warn = function (message) { var warn = function (message) {
@ -46,19 +51,19 @@
var cryptoObject = window.crypto || window.msCrypto; var cryptoObject = window.crypto || window.msCrypto;
var emptyUUID = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; var emptyUUID = [1e7] + -1e3 + -4e3 + -8e3 + -1e11;
if (!cryptoObject) if (cryptoObject && cryptoObject.getRandomValues)
return emptyUUID.replace(/[018]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c < 2 ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
return emptyUUID.replace(/[018]/g, function (c) { return emptyUUID.replace(/[018]/g, function (c) {
return ( return (
c ^ c ^
(cryptoObject.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) (cryptoObject.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16); ).toString(16);
}); });
return emptyUUID.replace(/[018]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c < 2 ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}; };
var assign = function () { var assign = function () {
@ -84,10 +89,15 @@
/* Do nothing */ /* Do nothing */
} }
// Send data via image of XHR request // Send data via image
function sendData(data) { function sendData(data, callback) {
data = assign(payload, data); data = assign(payload, data);
new Image().src = var image = new Image();
if (callback) {
image.onerror = callback;
image.onload = callback;
}
image.src =
fullApiUrl + fullApiUrl +
"/send.gif?" + "/send.gif?" +
Object.keys(data) Object.keys(data)
@ -111,7 +121,7 @@
sendData({ sendData({
type: errorText, type: errorText,
error: errorOrMessage, error: errorOrMessage,
url: hostname + loc.pathname url: options.hostname + loc.pathname,
}); });
} }
@ -136,10 +146,13 @@
var scrolled = 0; var scrolled = 0;
/** endif **/ /** endif **/
// When a customer overwrites the hostname, we need to know what the original
// hostname was to hide that domain from referrer traffic
if (options.hostname !== hostname) payload.hostname_original = hostname;
// Don't track when localhost // Don't track when localhost
/** unless testing **/ /** unless testing **/
if (loc.hostname.indexOf(".") == -1) if (hostname.indexOf(".") == -1) return warn(notSending + "from " + hostname);
return warn(notSending + "from localhost");
/** endunless **/ /** endunless **/
try { try {
@ -166,10 +179,12 @@
source: getParams(utmRegexPrefix + "source|source|ref"), source: getParams(utmRegexPrefix + "source|source|ref"),
medium: getParams(utmRegexPrefix + "medium"), medium: getParams(utmRegexPrefix + "medium"),
campaign: getParams(utmRegexPrefix + "campaign"), campaign: getParams(utmRegexPrefix + "campaign"),
term: getParams(utmRegexPrefix + "term"),
content: getParams(utmRegexPrefix + "content"),
referrer: referrer:
(doc.referrer || "") (doc.referrer || "")
.replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/, "$4") .replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/, "$4")
.replace(/^([^/]+)\/$/, "$1") || undefinedVar .replace(/^([^/]+)\/$/, "$1") || undefinedVar,
}; };
// We don't put msHidden in if duration block, because it's used outside of that functionality // We don't put msHidden in if duration block, because it's used outside of that functionality
@ -267,7 +282,7 @@
https: loc.protocol == https, https: loc.protocol == https,
timezone: timezone, timezone: timezone,
width: window.innerWidth, width: window.innerWidth,
type: pageviewsText type: pageviewsText,
}) })
); );
}; };
@ -282,7 +297,7 @@
lastSendPath = path; lastSendPath = path;
var data = { var data = {
path: path path: path,
}; };
// If a user does refresh we need to delete the referrer because otherwise it count double // If a user does refresh we need to delete the referrer because otherwise it count double
@ -310,7 +325,7 @@
isPushState || userNavigated isPushState || userNavigated
? false ? false
: doc.referrer : doc.referrer
? doc.referrer.split(slash)[2] != loc.hostname ? doc.referrer.split(slash)[2] != hostname
: true; : true;
/** endif **/ /** endif **/
@ -323,46 +338,60 @@
/** if events **/ /** if events **/
var sessionId = uuid(); var sessionId = uuid();
var validTypes = ["string", "number"];
var sendEvent = function(event) { var endEvent = function () {};
var sendEvent = function (event, callbackRaw) {
var isFunction = event instanceof Function; var isFunction = event instanceof Function;
if (["string", "number"].indexOf(typeof event) < 0 && !isFunction) var callback =
return warn("event is not a string: " + event); callbackRaw instanceof Function ? callbackRaw : function () {};
if (validTypes.indexOf(typeof event) < 0 && !isFunction) {
warn("event is not a string: " + event);
return callback();
}
try { try {
if (isFunction) { if (isFunction) {
event = event(); event = event();
if (["string", "number"].indexOf(typeof event) < 0) if (validTypes.indexOf(typeof event) < 0) {
return warn("event function output is not a string: " + event); warn("event function output is not a string: " + event);
return callback();
}
} }
} catch (error) { } catch (error) {
return warn("in your event function: " + error.message); warn("in your event function: " + error.message);
return callback();
} }
event = ("" + event).replace(/[^a-z0-9]+/gi, "_").replace(/(^_|_$)/g, ""); event = ("" + event).replace(/[^a-z0-9]+/gi, "_").replace(/(^_|_$)/g, "");
if (event) if (event)
sendData( sendData(
assign(source, { assign(source, {
type: "event", type: "event",
event: event, event: event,
session_id: sessionId session_id: sessionId,
}) }),
callback
); );
}; };
var defaultEventFunc = function(event) { var defaultEventFunc = function (event, callback) {
sendEvent(event); sendEvent(event, callback);
}; };
// Set default function if user didn't define a function // Set default function if user didn't define a function
if (!window[functionName]) window[functionName] = defaultEventFunc; if (!window[options.functionName])
window[options.functionName] = defaultEventFunc;
var eventFunc = window[functionName]; var eventFunc = window[options.functionName];
// Read queue of the user defined function // Read queue of the user defined function
var queue = eventFunc && eventFunc.q ? eventFunc.q : []; var queue = eventFunc && eventFunc.q ? eventFunc.q : [];
// Overwrite user defined function // Overwrite user defined function
window[functionName] = defaultEventFunc; window[options.functionName] = defaultEventFunc;
// Post events from the queue of the user defined function // Post events from the queue of the user defined function
for (var event in queue) sendEvent(queue[event]); for (var event in queue) sendEvent(queue[event]);

View File

@ -4,14 +4,7 @@
https://github.com/twitter/twemoji/blob/gh-pages/LICENSE https://github.com/twitter/twemoji/blob/gh-pages/LICENSE
*/ */
(function ( (function () {
// WARNING: this file is generated automatically via
// `node scripts/build.js`
// please update its `createTwemoji` function
// at the bottom of the same file instead.
) {
'use strict'; 'use strict';
/* jshint maxparams:4 */ /* jshint maxparams:4 */

View File

@ -44,11 +44,11 @@ A _very_ barebones example is embedded above ([view the source here](https://git
--- ---
### Minified JS: (392 bytes gzipped 📦) ### Minified JS: (410 bytes gzipped 📦)
```js ```js
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */ /*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
(function(){var e=window,t=e.document,i=t.body.classList,a=localStorage,c="dark_mode_pref",d=a.getItem(c),r="dark",o="light",s=t.querySelector(".dark-mode-toggle"),n=!1,m=function(e){i.remove(r,o);i.add(e);n=e===r};d===r&&m(r);d===o&&m(o);if(!d){var l="(prefers-color-scheme: dark)",f="(prefers-color-scheme: light)";e.matchMedia(l).matches?m(r):m(o);e.matchMedia(l).addListener((function(e){e.matches&&m(r)}));e.matchMedia(f).addListener((function(e){e.matches&&m(o)}))}if(s){s.style.visibility="visible";s.addEventListener("click",(function(){if(n){m(o);a.setItem(c,o)}else{m(r);a.setItem(c,r)}}),!0)}})(); (function(){var e=window,t=e.document,i=t.body.classList,a=localStorage,c="dark_mode_pref",d=a.getItem(c),n="dark",o="light",r=o,s=t.querySelector(".dark-mode-toggle"),m=r===n,l=function(e){i.remove(n,o);i.add(e);m=e===n};d===n&&l(n);d===o&&l(o);if(!d){var f=function(e){return"(prefers-color-scheme: "+e+")"};e.matchMedia(f(n)).matches?l(n):e.matchMedia(f(o)).matches?l(o):l(r);e.matchMedia(f(n)).addListener((function(e){e.matches&&l(n)}));e.matchMedia(f(o)).addListener((function(e){e.matches&&l(o)}))}if(s){s.style.visibility="visible";s.addEventListener("click",(function(){if(m){l(o);a.setItem(c,o)}else{l(n);a.setItem(c,n)}}),!0)}})();
``` ```
### Full JS: ### Full JS:
@ -60,28 +60,31 @@ A _very_ barebones example is embedded above ([view the source here](https://git
// improve variable mangling when minifying // improve variable mangling when minifying
var win = window; var win = window;
var doc = win.document; var doc = win.document;
var bod = doc.body; var body = doc.body;
var cls = bod.classList; var classes = body.classList;
var sto = localStorage; var storage = localStorage;
// check for preset `dark_mode_pref` preference in localStorage // check for preset `dark_mode_pref` preference in local storage
var pref_key = 'dark_mode_pref'; var pref_key = 'dark_mode_pref';
var pref = sto.getItem(pref_key); var pref = storage.getItem(pref_key);
// change CSS via these <body> classes: // change CSS via these <body> classes:
var dark = 'dark'; var dark = 'dark';
var light = 'light'; var light = 'light';
// which class is <body> set to initially?
var default_theme = light;
// use an element with class `dark-mode-toggle` to trigger swap when clicked // use an element with class `dark-mode-toggle` to trigger swap when clicked
var toggle = doc.querySelector('.dark-mode-toggle'); var toggle = doc.querySelector('.dark-mode-toggle');
// keep track of current state (light by default) no matter how we got there // keep track of current state no matter how we got there
var active = false; var active = (default_theme === dark);
// receives a class name and switches <body> to it // receives a class name and switches <body> to it
var activateTheme = function (theme) { var activateTheme = function (theme) {
cls.remove(dark, light); classes.remove(dark, light);
cls.add(theme); classes.add(theme);
active = (theme === dark); active = (theme === dark);
}; };
@ -91,18 +94,23 @@ A _very_ barebones example is embedded above ([view the source here](https://git
// user has never clicked the button, so go by their OS preference until/if they do so // user has never clicked the button, so go by their OS preference until/if they do so
if (!pref) { if (!pref) {
// check for OS dark mode setting and switch accordingly // returns media query selector syntax
var prefers_dark = '(prefers-color-scheme: dark)'; var prefers = function (theme) {
var prefers_light = '(prefers-color-scheme: light)'; return '(prefers-color-scheme: ' + theme + ')';
};
if (win.matchMedia(prefers_dark).matches) // check for OS dark/light mode preference and switch accordingly
// default to `default_theme` set above if unsupported
if (win.matchMedia(prefers(dark)).matches)
activateTheme(dark); activateTheme(dark);
else else if (win.matchMedia(prefers(light)).matches)
activateTheme(light); activateTheme(light);
else
activateTheme(default_theme);
// real-time switching if supported by OS/browser // real-time switching if supported by OS/browser
win.matchMedia(prefers_dark).addListener(function(e) { if (e.matches) activateTheme(dark); }); win.matchMedia(prefers(dark)).addListener(function (e) { if (e.matches) activateTheme(dark); });
win.matchMedia(prefers_light).addListener(function(e) { if (e.matches) activateTheme(light); }); win.matchMedia(prefers(light)).addListener(function (e) { if (e.matches) activateTheme(light); });
} }
// don't freak out if page happens not to have a toggle // don't freak out if page happens not to have a toggle
@ -113,12 +121,12 @@ A _very_ barebones example is embedded above ([view the source here](https://git
// handle toggle click // handle toggle click
toggle.addEventListener('click', function () { toggle.addEventListener('click', function () {
// switch to the opposite theme & save preference in local storage // switch to the opposite theme & save preference in local storage
if (!active) { if (active) {
activateTheme(dark);
sto.setItem(pref_key, dark);
} else {
activateTheme(light); activateTheme(light);
sto.setItem(pref_key, light); storage.setItem(pref_key, light);
} else {
activateTheme(dark);
storage.setItem(pref_key, dark);
} }
}, true); }, true);
} }

View File

@ -19,4 +19,4 @@ This website uses [**Simple Analytics**](https://simpleanalytics.com/?ref=jarv.i
**📈 Stats for this site are public! [View them here.](/stats/)** **📈 Stats for this site are public! [View them here.](/stats/)**
Pages and first-party assets on this website are served by [**Netlify**](https://www.netlify.com/). Refer to their [privacy policy](https://www.netlify.com/privacy/) and [GDPR statement](https://www.netlify.com/privacy/) for more information. Pages and first-party assets on this website are served by [**Netlify**](https://www.netlify.com/). Refer to their [privacy policy](https://www.netlify.com/privacy/) and [GDPR statement](https://www.netlify.com/gdpr/) for more information.