Last active
April 13, 2018 10:24
-
-
Save olmokramer/93befae060b755d900271fe14021ca69 to your computer and use it in GitHub Desktop.
Sort issues/prs by most recently updated on GitHub
This file contains 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 autosort-updated | |
// @namespace https://github.com/olmokramer | |
// @description Automatically sort by updated-desc | |
// @include *://github.com/* | |
// @version 2 | |
// @author Olmo Kramer | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
function initial(arr) { | |
return arr.slice(0, arr.length - 1); | |
} | |
function last(arr) { | |
return arr[arr.length - 1]; | |
} | |
function parseQuery(q) { | |
const ret = {}; | |
if (!q) { | |
return ret; | |
} | |
for (let word of q.split(' ')) { | |
if (!word) { | |
continue; | |
} | |
let [key, val] = word.split(':'); | |
if (!ret.hasOwnProperty(key)) { | |
ret[key] = []; | |
} | |
ret[key].push(val); | |
} | |
return ret; | |
} | |
function stringifyQuery(q) { | |
let ret = ''; | |
for (let [key, vals] of Object.entries(q)) { | |
for (let val of vals) { | |
ret += ' ' + key; | |
if (val) { | |
ret += ':' + val; | |
} | |
} | |
} | |
return ret.trim(); | |
} | |
function getPageType(path) { | |
const types = { | |
issues: 'issue', | |
pulls: 'pr', | |
}; | |
if (last(path) == '/') { | |
path = initial(path); | |
} | |
return types[last(path.split('/'))]; | |
} | |
function isIssuePage(path) { | |
return !!getPageType(path); | |
} | |
function sortByUpdatedDesc(href) { | |
const url = new URL(href); | |
if (!isIssuePage(url.pathname)) { | |
return; | |
} | |
const q = parseQuery(url.searchParams.get('q')); | |
// Stop if sort parameter already set. | |
if (q.sort && q.sort.any(x => x)) { | |
return; | |
} | |
q.is = q.is || [getPageType(url.pathname), 'open']; | |
q.sort = ['updated-desc']; | |
url.searchParams.set('q', stringifyQuery(q)); | |
// XXX: F-ing github doesn't respond to push/replace state... | |
// history.replaceState(history.state, document.title, url.href); | |
location.href = url.href; | |
} | |
if (MutationObserver) { | |
const observer = new MutationObserver((function() { | |
let href = location.href; | |
return function() { | |
if (location.href != href) { | |
href = location.href; | |
sortByUpdatedDesc(href); | |
} | |
}; | |
})()); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true, | |
}); | |
} | |
sortByUpdatedDesc(location.href); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment