Skip to content

Instantly share code, notes, and snippets.

@romuald
Last active June 23, 2020 09:44
Show Gist options
  • Save romuald/8cd8ed587591b24dea78248038c6225f to your computer and use it in GitHub Desktop.
Save romuald/8cd8ed587591b24dea78248038c6225f to your computer and use it in GitHub Desktop.
This userscript will replace the default diff collapse of GitLab by a lighter version that doesn't hog CPU. Tested with GitLab CE 12.7.6
// ==UserScript==
// @name Gitlab diff collapse
// @version 1.0
// @description Will "properly" collapse gitlab diffs by hidding the HTML instead of using Javascript magic that hogs CPU for a long time. Tested with GitLab CE 12.7.6
// @author Romuald Brunet <[email protected]>
// @match https://gitlab.com/*
// @match https://-your-gitlab-instance-/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
const SEEN = 'seen-wgtrywW7L3SMXHjmP8IY';
function diffToggle(event) {
// May be another element
if ( event.target.classList.contains(SEEN) || event.target.contains('diff-toggle-caret') ) {
event.preventDefault();
const target = this.parentNode.querySelector('.diff-content');
if ( ! target ) {
return;
}
if (target.style.display !== 'none') {
target.style.display = 'none';
} else {
target.style.display = '';
}
}
}
function replaceElement(element) {
// Replace the diff toggle element and its click event by our own
if ( element.classList.contains(SEEN) ) {
return;
}
observer.disconnect(); // avoid recursion
// Remove previous listeners by cloning the element
const clone = element.cloneNode(true);
clone.classList.add(SEEN);
element.parentNode.replaceChild(clone, element);
clone.addEventListener('click', diffToggle);
observe();
}
const observer = new MutationObserver(function(mutationsList, observer) {
//console.time("Observe diff");
mutationsList.forEach((record) => {
record.addedNodes.forEach((node) => {
if ( ! node.querySelectorAll ) {
return;
}
node.querySelectorAll('.diff-file > .file-title').forEach(replaceElement);
});
});
//console.timeEnd("Observe diff");
});
function observe() {
observer.observe(document.querySelector('body'),
{childList: true, subtree: true});
}
observe();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment