Skip to content

Instantly share code, notes, and snippets.

@alejandro5042
Last active February 28, 2025 12:37
Show Gist options
  • Save alejandro5042/af2ee5b0ad92b271cd2c71615a05da2c to your computer and use it in GitHub Desktop.
Save alejandro5042/af2ee5b0ad92b271cd2c71615a05da2c to your computer and use it in GitHub Desktop.
/*
MIT License
Copyright (c) 2020 National Instruments
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const eus = (function () {
'use strict';
//////////////////////////////////////////////////
class ObserverSession {
constructor() {
this.cleanupFuncs = [];
}
on(parent, selector, eventName, callback) {
const handler = function (event) {
const target = event.target.closest(selector);
if (target) {
callback(event, target);
}
};
parent.addEventListener(eventName, handler);
this.cleanupFuncs.push(() => parent.removeEventListener(eventName, handler)); // memory leak
}
onEveryNew(parent, selector, callback) {
for (const existingNode of parent.querySelectorAll(selector)) {
callback(existingNode, false);
}
const observer = new MutationObserver(function(mutations) {
const seenNodes = new Set();
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (!(node instanceof HTMLElement)) continue;
try {
this.disconnect();
if (node.matches(selector)) {
if (!seenNodes.has(node)) {
callback(node, true);
seenNodes.add(node);
}
}
for (const subNode of node.querySelectorAll(selector)) {
if (!seenNodes.has(node)) {
callback(subNode, true);
seenNodes.add(subNode);
}
}
} finally {
this.observe(parent, { subtree: true, childList: true });
}
}
}
});
observer.observe(parent, { subtree: true, childList: true });
this.cleanupFuncs.push(() => observer.disconnect());
return observer;
}
onAnyChangeTo(node, callback) {
const observeOptions = { subtree: true, childList: true, attributes: true, characterData: true };
const observer = new MutationObserver(function(mutations) {
try {
this.disconnect();
callback(node, true);
} finally {
this.observe(node, observeOptions);
}
});
observer.observe(node, observeOptions);
this.cleanupFuncs.push(() => observer.disconnect());
return observer;
}
onFirstAndAnyChangeTo(node, callback) {
callback(node, false);
this.onAnyChangeTo(node, callback);
}
onFirst(parent, selector, callback) {
const node = parent.querySelector(selector);
if (node) {
callback(node);
return null;
}
const observer = new MutationObserver(function(mutations) {
const node = parent.querySelector(selector);
if (node) {
this.disconnect();
callback(node);
return;
}
})
observer.observe(parent, { subtree: true, childList: true });
this.cleanupFuncs.push(() => observer.disconnect());
return observer;
}
reset() {
for (const f of this.cleanupFuncs) {
f();
}
this.cleanupFuncs.length = 0;
}
}
//////////////////////////////////////////////////
let registeredLocationChangeEvent = false;
function registerLocationChangeEvent() {
if (registeredLocationChangeEvent) return;
registeredLocationChangeEvent = true;
// From: https://stackoverflow.com/a/56760883
const originalPushState = history.pushstate;
history.pushstate = function(){
originalPushState.apply(history, arguments);
window.dispatchEvent(new CustomEvent("locationchange", arguments));
};
const originalReplaceState = history.replaceState;
history.replaceState = function(){
originalReplaceState.apply(history, arguments); // preserve normal functionality
window.dispatchEvent(new CustomEvent("locationchange", arguments));
};
window.addEventListener('popstate', () => window.dispatchEvent(new CustomEvent("locationchange", arguments)));
}
function onUrlChange(callback) {
registerLocationChangeEvent();
let previous = window.location.href;
callback("", previous);
window.addEventListener('locationchange', () => {
const current = window.location.href;
if (previous !== current) {
try {
callback(previous, current);
} finally {
previous = current;
}
}
});
}
function onUrl(urlMatch, callback) {
const session = new ObserverSession();
onUrlChange((oldUrl, newUrl) => {
session.reset();
const match = newUrl.match(urlMatch);
if (match) {
console.debug("eus: New matched URL", newUrl);
callback(session, match);
}
});
}
//////////////////////////////////////////////////
function addedClass(element, className) {
return !element.classList.contains(className) && element.classList.toggle(className, true);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function addCss(url, integrity) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.integrity = integrity;
link.crossOrigin = 'anonymous';
document.head.appendChild(link);
}
function addScript(url, integrity, callback = function () { }) {
const script = document.createElement('script');
script.src = url;
script.integrity = integrity;
script.crossOrigin = 'anonymous';
script.async = 'async';
script.addEventListener('load', callback);
document.head.appendChild(script);
}
function onReadyAsync() {
return new Promise(resolve => {
if (document.readyState != 'loading') resolve();
else document.addEventListener('DOMContentLoaded', resolve);
});
}
function seen(node, identifier = 'seen') {
const codedIdentifier = `eus_${identifier}`;
if (codedIdentifier in node.dataset) return true;
node.dataset[codedIdentifier] = true;
return false;
}
function toCss(value) {
return value.replace(/[^a-z0-9]/ig, ' ').trim().replace(' ', '-');
}
//////////////////////////////////////////////////
let newSwal;
async function loadSwalAsync(mixinArgs) {
// https://github.com/sweetalert2/sweetalert2
return new Promise(resolve => {
if (newSwal) resolve(newSwal);
//GM_addStyle('.swal2-container { zoom: 1.7; }');
addScript('https://cdn.jsdelivr.net/npm/sweetalert2', 'sha384-35mF1VNGiJWWhBir6a5ZTDD9j/bfDDFlzl7x6+8+eF2JnlCqcAWeOBvmeXgJktGF', () => {
newSwal = Swal.mixin(mixinArgs);
resolve(newSwal);
});
});
}
async function loadIziToast(iziToastSettings) {
// https://github.com/marcelodolza/iziToast
return new Promise(resolve => {
if (iziToast) resolve(iziToast);
addCss("https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/css/iziToast.min.css", "sha256-f6fW47QDm1m01HIep+UjpCpNwLVkBYKd+fhpb4VQ+gE=");
addScript("https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.4.0/js/iziToast.min.js", "sha256-321PxS+POvbvWcIVoRZeRmf32q7fTFQJ21bXwTNWREY=", () => {
const defaultSettings = {
//footer: GM_info.script.name, // would need to include: @grant GM_info
animateInside: false,
progressBar: false,
titleSize: '150%',
messageSize: '150%'
};
iziToast.settings(Object.assign(defaultSettings, iziToastSettings));
resolve(iziToast);
});
});
}
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function registerCssClassConfig(element, prompt, name, defaultClass, classesToDisplayNames) {
function applyValue(value) {
const newClasses = element.className.split(' ').filter(c => !(c in classesToDisplayNames));
newClasses.push(value);
element.className = newClasses.join(' ');
}
GM_registerMenuCommand(prompt, async () => {
const { value } = await swal.fire({
title: prompt,
footer: "May require a page refresh to fully apply.",
input: 'radio',
inputValue: GM_getValue(name, defaultClass),
inputOptions: classesToDisplayNames,
confirmButtonText: 'Apply',
showCancelButton: true
});
if (value) {
GM_setValue(name, value);
}
});
GM_addValueChangeListener(name, (_name, oldValue, newValue, remote) => applyValue(newValue));
const currentValue = GM_getValue(name, defaultClass);
if (currentValue in classesToDisplayNames) {
applyValue(currentValue);
} else {
GM_setValue(name, defaultClass);
}
}
async function showTipOnce(id, title, html) {
const key = `show-alert-${id}`;
if (GM_getValue(key, true)) {
await swal.fire({
title: title,
html: html,
footer: `Notification from&nbsp;<a target="_blank" href="${GM_info.script.homepageURL}">${GM_info.script.name}</a>`
});
GM_setValue(key, false);
return true;
}
return false;
}
// function replaceWithSingleClass(element, prefix, newClass = '') {
// element.className = element.className.replace(new RegExp(`/(^|\s)${prefix}-\S+/g`), '') + ' ' + newClass;
// }
//////////////////////////////////////////////////
const globalSession = new ObserverSession();
const toast = Swal ? Swal.mixin({
icon: 'info',
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3500,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
}) : null;
return {
onUrlChange: onUrlChange,
onUrl: onUrl,
addedClass: addedClass,
ObserverSession: ObserverSession,
globalSession: globalSession,
sleep: sleep,
addCss: addCss,
addScript: addScript,
onReadyAsync: onReadyAsync,
// loadNotyfAsync: loadNotyfAsync,
loadSwalAsync: loadSwalAsync,
loadIziToast: loadIziToast,
insertAfter: insertAfter,
registerCssClassConfig: registerCssClassConfig,
showTipOnce: showTipOnce,
toast: toast,
seen: seen,
toCss: toCss
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment