Skip to content

Instantly share code, notes, and snippets.

@dting
Last active October 5, 2016 21:10
Show Gist options
  • Save dting/a1323a0b33d7391050bd7fcf45fbbebf to your computer and use it in GitHub Desktop.
Save dting/a1323a0b33d7391050bd7fcf45fbbebf to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Observe
// @namespace http://gist.github.com/dting
// @version 0.1
// @description Change non-link matches for /bug-\d+/ to a link
// @author You
// @match https://mail.google.com/mail/u/0/*
// ==/UserScript==
(function() {
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
const term = /BUG-\d+/g;
const replFn = function replFn(match) {
const link = document.createElement('a');
link.href = 'http://bugtracker.com/id/' + match;
link.target = '_blank';
link.innerHTML = match;
return link;
};
const observerOptions = {
attributes: false,
childList: true,
characterData: false,
subtree: true,
};
const replaceKW = function replaceKW(text) {
const matches = [];
let match = term.exec(text.data);
while (match) {
matches.push(match);
match = term.exec(text.data);
}
for (let i = matches.length - 1; i > -1; i--) {
const matched = matches[i];
text.splitText(matched.index);
text.nextSibling.splitText(matched[0].length);
text.parentNode.replaceChild(replFn(matched[0]), text.nextSibling);
}
};
const replace = function replace(obs) {
obs.disconnect();
const a = [];
const walk = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
let node = walk.nextNode();
while(node) {
a.push(node);
node = walk.nextNode();
}
a.forEach(replaceKW);
obs.observe(document.body, observerOptions);
};
const debounce = function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
};
const debouncedReplace = debounce(replace, 200);
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
debouncedReplace(observer);
}
});
});
observer.observe(document.body, observerOptions);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment