Skip to content

Instantly share code, notes, and snippets.

@rf5860
Last active May 19, 2018 16:40
Show Gist options
  • Save rf5860/63fa2646331b1ac22dcde43fa47b224c to your computer and use it in GitHub Desktop.
Save rf5860/63fa2646331b1ac22dcde43fa47b224c to your computer and use it in GitHub Desktop.
[Gist Sorter] Adds a button to sort visible Gists by age #UserScript
// ==UserScript==
// @name Gist Sorter
// @description Adds a button to sort visible Gists by age
// @version 0.2
// @author rjf89
// @match https://gist.github.com/search*
// @grant none
// ==/UserScript==
function getDate(e) {
return new Date(e.querySelector('time-ago').getAttribute('datetime'));
}
function addSortButtons(elem) {
const sortBar = elem.querySelector('div.sort-bar');
elem.insertBefore(createSortButton('Sort Ascending', true), sortBar);
elem.insertBefore(createSortButton('Sort Descending', false, 'margin-left: 10px'), sortBar);
}
function sortList(selector, ascending) {
const original = document.querySelector(selector);
const clone = original.cloneNode(false);
clone.appendChild(original.querySelector('div.sort-bar').cloneNode(true));
addSortButtons(clone);
[...original.querySelectorAll('div.gist-snippet')]
.sort((a, b) => getDate(ascending ? a : b) - getDate(ascending ? b : a))
.forEach(e => clone.appendChild(e));
clone.appendChild(original.lastChild);
original.parentNode.replaceChild(clone, original);
}
function createSortButton(text, ascending, style) {
const sortButton = document.createElement('button');
sortButton.type = 'button';
sortButton.style = style;
sortButton.classList.add('btn');
sortButton.onclick = function() { sortList('div.column.three-fourths', ascending); };
sortButton.textContent = text;
return sortButton;
}
addSortButtons(document.querySelector('div.column.three-fourths'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment