quixxd / BitBucket Rating

// ==UserScript==
// @name       BitBucket Rating
// @namespace  http://monotech.no/
// @version    0.3
// @description  Adding rating to BitBucket issues list: sorting by bracketed [number] in issues' Title field
// @match      https://bitbucket.org/*
// @copyright  2014, Monotech AS
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
  var script = document.createElement('script');
  script.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js');
  script.addEventListener('load', function() {
    var script = document.createElement('script');
    script.textContent = 'window.jQ=jQuery.noConflict(true);(' + callback.toString() + ')();';
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}



// the guts of this userscript
function main() {
  // jQ replaces $ to avoid conflicts.
    
    function getCellValue(row, index){ return $(row).children('td').eq(index).html() }
    
    function comparer(index) {
        return function(a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index)
            
            var subA = valA.substring(valA.indexOf('[')+1, valA.indexOf(']'));
            var subB = valB.substring(valB.indexOf('[')+1, valB.indexOf(']'));
            
            if (jQ.isNumeric(subA) && !jQ.isNumeric(subB))
                return -1;
            if (!jQ.isNumeric(subA) && jQ.isNumeric(subB))
                return 1;

            return jQ.isNumeric(subA) && jQ.isNumeric(subB) ? subA - subB : valA.localeCompare(valB);
        }
    }
    
    var listhref = jQ("#repo-issues-link").attr("href");
    jQ("#repo-issues-link").attr("href", listhref+"&sort=-priority");
    
    if (window.location.href.indexOf("/issues") != -1) {
        if (window.location.href.indexOf("sort=-priority") != -1) {
            var table = jQ('table.issues-list');
            var rows = table.find('tr:gt(0)').toArray().sort(comparer(0));
            for (var i = 0; i < rows.length; i++){table.append(rows[i])}
        }
	}

    jQ("#issues-toolbar").append("<small>BitBucket Rating Userscript enabled</small>");
    /*
    jQ(document).on('click', '#sortByRating', function() {
    });
    */
}

// load jQuery and execute the main function
addJQuery(main);