Debian Codegraph @

resources/sorttable.js

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