Last active
May 19, 2018 16:40
-
-
Save rf5860/63fa2646331b1ac22dcde43fa47b224c to your computer and use it in GitHub Desktop.
[Gist Sorter] Adds a button to sort visible Gists by age #UserScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==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