Home | History | Annotate | Download | only in util
      1 /*
      2   SortTable
      3   version 2
      4   7th April 2007
      5   Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
      6 
      7   Instructions:
      8   Download this file
      9   Add <script src="sorttable.js"></script> to your HTML
     10   Add class="sortable" to any table you'd like to make sortable
     11   Click on the headers to sort
     12 
     13   Thanks to many, many people for contributions and suggestions.
     14   Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
     15   This basically means: do what you want with it.
     16 */
     17 
     18 /*
     19 Changes by jning:
     20 -Specify which coloumns to sort or not by changing index in makeSortable().
     21 -To avoid including the non-data rows (e.g., radio buttions) into sorting,
     22  add index and row handling (deletion and appending) in makeSortable() and
     23  reverse().
     24 -Remove the init parts for other browsers.
     25 */
     26 
     27 var stIsIE = /*@cc_on!@*/false;
     28 
     29 sorttable = {
     30   init: function() {
     31     // quit if this function has already been called
     32     if (arguments.callee.done) return;
     33     // flag this function so we don't do the same thing twice
     34     arguments.callee.done = true;
     35     // kill the timer
     36     if (_timer) clearInterval(_timer);
     37 
     38     if (!document.createElement || !document.getElementsByTagName) return;
     39 
     40     sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
     41 
     42     forEach(document.getElementsByTagName('table'), function(table) {
     43       if (table.className.search(/\bsortable\b/) != -1) {
     44         sorttable.makeSortable(table);
     45       }
     46     });
     47 
     48   },
     49 
     50   makeSortable: function(table) {
     51     if (table.getElementsByTagName('thead').length == 0) {
     52       // table doesn't have a tHead. Since it should have, create one and
     53       // put the first table row in it.
     54       the = document.createElement('thead');
     55       the.appendChild(table.rows[0]);
     56       table.insertBefore(the,table.firstChild);
     57     }
     58     // Safari doesn't support table.tHead, sigh
     59     if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
     60 
     61     if (table.tHead.rows.length != 1) return; // can't cope with two header rows
     62 
     63     // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
     64     // "total" rows, for example). This is B&R, since what you're supposed
     65     // to do is put them in a tfoot. So, if there are sortbottom rows,
     66     // for backwards compatibility, move them to tfoot (creating it if needed).
     67     sortbottomrows = [];
     68     for (var i=0; i<table.rows.length; i++) {
     69       if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
     70         sortbottomrows[sortbottomrows.length] = table.rows[i];
     71       }
     72     }
     73     if (sortbottomrows) {
     74       if (table.tFoot == null) {
     75         // table doesn't have a tfoot. Create one.
     76         tfo = document.createElement('tfoot');
     77         table.appendChild(tfo);
     78       }
     79       for (var i=0; i<sortbottomrows.length; i++) {
     80         tfo.appendChild(sortbottomrows[i]);
     81       }
     82       delete sortbottomrows;
     83     }
     84 
     85     // work through each column and calculate its type
     86     headrow = table.tHead.rows[0].cells;
     87     for (var i=5; i<headrow.length-1; i++) {
     88       // manually override the type with a sorttable_type attribute
     89       if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
     90         mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
     91         if (mtch) { override = mtch[1]; }
     92 	      if (mtch && typeof sorttable["sort_"+override] == 'function') {
     93 	        headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
     94 	      } else {
     95 	        headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
     96 	      }
     97 	      // make it clickable to sort
     98 	      headrow[i].sorttable_columnindex = i;
     99 	      headrow[i].sorttable_tbody = table.tBodies[0];
    100 	      dean_addEvent(headrow[i],"click", function(e) {
    101 
    102           if (this.className.search(/\bsorttable_sorted\b/) != -1) {
    103             // if we're already sorted by this column, just
    104             // reverse the table, which is quicker
    105             sorttable.reverse(this.sorttable_tbody);
    106             this.className = this.className.replace('sorttable_sorted',
    107                                                     'sorttable_sorted_reverse');
    108             this.removeChild(document.getElementById('sorttable_sortfwdind'));
    109             sortrevind = document.createElement('span');
    110             sortrevind.id = "sorttable_sortrevind";
    111             sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
    112             this.appendChild(sortrevind);
    113             return;
    114           }
    115           if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
    116             // if we're already sorted by this column in reverse, just
    117             // re-reverse the table, which is quicker
    118             sorttable.reverse(this.sorttable_tbody);
    119             this.className = this.className.replace('sorttable_sorted_reverse',
    120                                                     'sorttable_sorted');
    121             this.removeChild(document.getElementById('sorttable_sortrevind'));
    122             sortfwdind = document.createElement('span');
    123             sortfwdind.id = "sorttable_sortfwdind";
    124             sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
    125             this.appendChild(sortfwdind);
    126             return;
    127           }
    128 
    129           // remove sorttable_sorted classes
    130           theadrow = this.parentNode;
    131           forEach(theadrow.childNodes, function(cell) {
    132             if (cell.nodeType == 1) { // an element
    133               cell.className = cell.className.replace('sorttable_sorted_reverse','');
    134               cell.className = cell.className.replace('sorttable_sorted','');
    135             }
    136           });
    137           sortfwdind = document.getElementById('sorttable_sortfwdind');
    138           if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
    139           sortrevind = document.getElementById('sorttable_sortrevind');
    140           if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
    141 
    142           this.className += ' sorttable_sorted';
    143           sortfwdind = document.createElement('span');
    144           sortfwdind.id = "sorttable_sortfwdind";
    145           sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
    146           this.appendChild(sortfwdind);
    147 
    148 	        // build an array to sort. This is a Schwartzian transform thing,
    149 	        // i.e., we "decorate" each row with the actual sort key,
    150 	        // sort based on the sort keys, and then put the rows back in order
    151 	        // which is a lot faster because you only do getInnerText once per row
    152 	        row_array = [];
    153 	        col = this.sorttable_columnindex;
    154 	        rows = this.sorttable_tbody.rows;
    155 	        for (var j=1; j<rows.length-3; j++) {
    156 	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
    157 	        }
    158 	        /* If you want a stable sort, uncomment the following line */
    159 	        sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
    160 	        /* and comment out this one */
    161 	        //row_array.sort(this.sorttable_sortfunction);
    162 
    163 	        tb = this.sorttable_tbody;
    164                 var noTestRow = tb.rows[tb.rows.length-3];
    165                 var radioRow = tb.rows[tb.rows.length-2];
    166                 var compareRow = tb.rows[tb.rows.length-1];
    167                 tb.deleteRow(tb.rows.length-1);
    168                 tb.deleteRow(tb.rows.length-1);
    169                 tb.deleteRow(tb.rows.length-1);
    170                 for (var j=0; j<row_array.length; j++) {
    171                    tb.appendChild(row_array[j][1]);
    172 	        }
    173                 tb.appendChild(noTestRow);
    174                 tb.appendChild(radioRow);
    175                 tb.appendChild(compareRow);
    176 	        delete row_array;
    177                 delete noTestRow;
    178                 delete radioRow;
    179                 delete compareRow;
    180 	      });
    181 	    }
    182     }
    183   },
    184 
    185   guessType: function(table, column) {
    186     // guess the type of a column based on its first non-blank row
    187     sortfn = sorttable.sort_numeric;
    188     for (var i=0; i<table.tBodies[0].rows.length-3; i++) {
    189       text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
    190       if (text != '') {
    191         if (text.match(/^-?[$]?[\d,.]+%?$/)) {
    192           return sorttable.sort_numeric;
    193         }
    194         // check for a date: dd/mm/yyyy or dd/mm/yy
    195         // can have / or . or - as separator
    196         // can be mm/dd as well
    197         possdate = text.match(sorttable.DATE_RE)
    198         if (possdate) {
    199           // looks like a date
    200           first = parseInt(possdate[1]);
    201           second = parseInt(possdate[2]);
    202           if (first > 12) {
    203             // definitely dd/mm
    204             return sorttable.sort_ddmm;
    205           } else if (second > 12) {
    206             return sorttable.sort_mmdd;
    207           } else {
    208             // looks like a date, but we can't tell which, so assume
    209             // that it's dd/mm (English imperialism!) and keep looking
    210             sortfn = sorttable.sort_ddmm;
    211           }
    212         }
    213       }
    214     }
    215     return sortfn;
    216   },
    217 
    218   getInnerText: function(node) {
    219     // gets the text we want to use for sorting for a cell.
    220     // strips leading and trailing whitespace.
    221     // this is *not* a generic getInnerText function; it's special to sorttable.
    222     // for example, you can override the cell text with a customkey attribute.
    223     // it also gets .value for <input> fields.
    224 
    225     hasInputs = (typeof node.getElementsByTagName == 'function') &&
    226                  node.getElementsByTagName('input').length;
    227 
    228     if (node.getAttribute("sorttable_customkey") != null) {
    229       return node.getAttribute("sorttable_customkey");
    230     }
    231     else if (typeof node.textContent != 'undefined' && !hasInputs) {
    232       return node.textContent.replace(/^\s+|\s+$/g, '');
    233     }
    234     else if (typeof node.innerText != 'undefined' && !hasInputs) {
    235       return node.innerText.replace(/^\s+|\s+$/g, '');
    236     }
    237     else if (typeof node.text != 'undefined' && !hasInputs) {
    238       return node.text.replace(/^\s+|\s+$/g, '');
    239     }
    240     else {
    241       switch (node.nodeType) {
    242         case 3:
    243           if (node.nodeName.toLowerCase() == 'input') {
    244             return node.value.replace(/^\s+|\s+$/g, '');
    245           }
    246         case 4:
    247           return node.nodeValue.replace(/^\s+|\s+$/g, '');
    248           break;
    249         case 1:
    250         case 11:
    251           var innerText = '';
    252           for (var i = 0; i < node.childNodes.length; i++) {
    253             innerText += sorttable.getInnerText(node.childNodes[i]);
    254           }
    255           return innerText.replace(/^\s+|\s+$/g, '');
    256           break;
    257         default:
    258           return '';
    259       }
    260     }
    261   },
    262 
    263   reverse: function(tbody) {
    264     // reverse the rows in a tbody
    265     newrows = [];
    266     for (var i=0; i<tbody.rows.length; i++) {
    267       newrows[newrows.length] = tbody.rows[i];
    268     }
    269     tbody.appendChild(newrows[0]);
    270     for (var i=newrows.length-4; i>0; i--) {
    271        tbody.appendChild(newrows[i]);
    272     }
    273     tbody.appendChild(newrows[newrows.length-3]);
    274     tbody.appendChild(newrows[newrows.length-2]);
    275     tbody.appendChild(newrows[newrows.length-1]);
    276     delete newrows;
    277   },
    278 
    279   /* sort functions
    280      each sort function takes two parameters, a and b
    281      you are comparing a[0] and b[0] */
    282   sort_numeric: function(a,b) {
    283     aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    284     if (isNaN(aa)) aa = 0;
    285     bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
    286     if (isNaN(bb)) bb = 0;
    287     return aa-bb;
    288   },
    289   sort_alpha: function(a,b) {
    290     if (a[0]==b[0]) return 0;
    291     if (a[0]<b[0]) return -1;
    292     return 1;
    293   },
    294   sort_ddmm: function(a,b) {
    295     mtch = a[0].match(sorttable.DATE_RE);
    296     y = mtch[3]; m = mtch[2]; d = mtch[1];
    297     if (m.length == 1) m = '0'+m;
    298     if (d.length == 1) d = '0'+d;
    299     dt1 = y+m+d;
    300     mtch = b[0].match(sorttable.DATE_RE);
    301     y = mtch[3]; m = mtch[2]; d = mtch[1];
    302     if (m.length == 1) m = '0'+m;
    303     if (d.length == 1) d = '0'+d;
    304     dt2 = y+m+d;
    305     if (dt1==dt2) return 0;
    306     if (dt1<dt2) return -1;
    307     return 1;
    308   },
    309   sort_mmdd: function(a,b) {
    310     mtch = a[0].match(sorttable.DATE_RE);
    311     y = mtch[3]; d = mtch[2]; m = mtch[1];
    312     if (m.length == 1) m = '0'+m;
    313     if (d.length == 1) d = '0'+d;
    314     dt1 = y+m+d;
    315     mtch = b[0].match(sorttable.DATE_RE);
    316     y = mtch[3]; d = mtch[2]; m = mtch[1];
    317     if (m.length == 1) m = '0'+m;
    318     if (d.length == 1) d = '0'+d;
    319     dt2 = y+m+d;
    320     if (dt1==dt2) return 0;
    321     if (dt1<dt2) return -1;
    322     return 1;
    323   },
    324 
    325   shaker_sort: function(list, comp_func) {
    326     // A stable sort function to allow multi-level sorting of data
    327     // see: http://en.wikipedia.org/wiki/Cocktail_sort
    328     // thanks to Joseph Nahmias
    329     var b = 0;
    330     var t = list.length - 1;
    331     var swap = true;
    332 
    333     while(swap) {
    334         swap = false;
    335         for(var i = b; i < t; ++i) {
    336             if ( comp_func(list[i], list[i+1]) > 0 ) {
    337                 var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
    338                 swap = true;
    339             }
    340         } // for
    341         t--;
    342 
    343         if (!swap) break;
    344 
    345         for(var i = t; i > b; --i) {
    346             if ( comp_func(list[i], list[i-1]) < 0 ) {
    347                 var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
    348                 swap = true;
    349             }
    350         } // for
    351         b++;
    352 
    353     } // while(swap)
    354   }
    355 }
    356 
    357 /* ******************************************************************
    358    Supporting functions: bundled here to avoid depending on a library
    359    ****************************************************************** */
    360 
    361 // Dean Edwards/Matthias Miller/John Resig
    362 
    363 /* for other browsers */
    364 window.onload = sorttable.init;
    365 
    366 // written by Dean Edwards, 2005
    367 // with input from Tino Zijdel, Matthias Miller, Diego Perini
    368 
    369 // http://dean.edwards.name/weblog/2005/10/add-event/
    370 
    371 function dean_addEvent(element, type, handler) {
    372 	if (element.addEventListener) {
    373 		element.addEventListener(type, handler, false);
    374 	} else {
    375 		// assign each event handler a unique ID
    376 		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
    377 		// create a hash table of event types for the element
    378 		if (!element.events) element.events = {};
    379 		// create a hash table of event handlers for each element/event pair
    380 		var handlers = element.events[type];
    381 		if (!handlers) {
    382 			handlers = element.events[type] = {};
    383 			// store the existing event handler (if there is one)
    384 			if (element["on" + type]) {
    385 				handlers[0] = element["on" + type];
    386 			}
    387 		}
    388 		// store the event handler in the hash table
    389 		handlers[handler.$$guid] = handler;
    390 		// assign a global event handler to do all the work
    391 		element["on" + type] = handleEvent;
    392 	}
    393 };
    394 // a counter used to create unique IDs
    395 dean_addEvent.guid = 1;
    396 
    397 function removeEvent(element, type, handler) {
    398 	if (element.removeEventListener) {
    399 		element.removeEventListener(type, handler, false);
    400 	} else {
    401 		// delete the event handler from the hash table
    402 		if (element.events && element.events[type]) {
    403 			delete element.events[type][handler.$$guid];
    404 		}
    405 	}
    406 };
    407 
    408 function handleEvent(event) {
    409 	var returnValue = true;
    410 	// grab the event object (IE uses a global event object)
    411 	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
    412 	// get a reference to the hash table of event handlers
    413 	var handlers = this.events[event.type];
    414 	// execute each event handler
    415 	for (var i in handlers) {
    416 		this.$$handleEvent = handlers[i];
    417 		if (this.$$handleEvent(event) === false) {
    418 			returnValue = false;
    419 		}
    420 	}
    421 	return returnValue;
    422 };
    423 
    424 function fixEvent(event) {
    425 	// add W3C standard event methods
    426 	event.preventDefault = fixEvent.preventDefault;
    427 	event.stopPropagation = fixEvent.stopPropagation;
    428 	return event;
    429 };
    430 fixEvent.preventDefault = function() {
    431 	this.returnValue = false;
    432 };
    433 fixEvent.stopPropagation = function() {
    434   this.cancelBubble = true;
    435 }
    436 
    437 // Dean's forEach: http://dean.edwards.name/base/forEach.js
    438 /*
    439 	forEach, version 1.0
    440 	Copyright 2006, Dean Edwards
    441 	License: http://www.opensource.org/licenses/mit-license.php
    442 */
    443 
    444 // array-like enumeration
    445 if (!Array.forEach) { // mozilla already supports this
    446 	Array.forEach = function(array, block, context) {
    447 		for (var i = 0; i < array.length; i++) {
    448 			block.call(context, array[i], i, array);
    449 		}
    450 	};
    451 }
    452 
    453 // generic enumeration
    454 Function.prototype.forEach = function(object, block, context) {
    455 	for (var key in object) {
    456 		if (typeof this.prototype[key] == "undefined") {
    457 			block.call(context, object[key], key, object);
    458 		}
    459 	}
    460 };
    461 
    462 // character enumeration
    463 String.forEach = function(string, block, context) {
    464 	Array.forEach(string.split(""), function(chr, index) {
    465 		block.call(context, chr, index, string);
    466 	});
    467 };
    468 
    469 // globally resolve forEach enumeration
    470 var forEach = function(object, block, context) {
    471 	if (object) {
    472 		var resolve = Object; // default
    473 		if (object instanceof Function) {
    474 			// functions have a "length" property
    475 			resolve = Function;
    476 		} else if (object.forEach instanceof Function) {
    477 			// the object implements a custom forEach method so use that
    478 			object.forEach(block, context);
    479 			return;
    480 		} else if (typeof object == "string") {
    481 			// the object is a string
    482 			resolve = String;
    483 		} else if (typeof object.length == "number") {
    484 			// the object is array-like
    485 			resolve = Array;
    486 		}
    487 		resolve.forEach(object, block, context);
    488 	}
    489 };
    490