tablesorter/js/jquery.tablesorter.widgets.js

433 lines
15 KiB
JavaScript
Raw Normal View History

/*! tableSorter 2.3 widgets - updated 5/8/2012
2011-10-26 06:50:02 +00:00
*
* jQuery UI Theme
* Column Styles
* Column Filters
* Sticky Header
* Column Resizing
2012-02-01 05:14:28 +00:00
* Save Sort
2011-10-26 06:50:02 +00:00
*
*/
;(function($){
2011-10-26 06:50:02 +00:00
2012-03-07 18:06:35 +00:00
// *** Store data in local storage, with a cookie fallback ***
/* IE7 needs JSON library for JSON.stringify - (http://caniuse.com/#search=json)
if you need it, then include https://github.com/douglascrockford/JSON-js
2012-03-27 01:49:48 +00:00
$.parseJSON is not available is jQuery versions older than 1.4.1, using older
versions will only allow storing information for one page at a time
2012-03-07 18:06:35 +00:00
// *** Save data (JSON format only) ***
// val must be valid JSON... use http://jsonlint.com/ to ensure it is valid
var val = { "mywidget" : "data1" }; // valid JSON uses double quotes
// $.tablesorter.storage(table, key, val);
$.tablesorter.storage(table, 'tablesorter-mywidget', val);
// *** Get data: $.tablesorter.storage(table, key); ***
v = $.tablesorter.storage(table, 'tablesorter-mywidget');
// val may be empty, so also check for your data
val = (v && v.hasOwnProperty('mywidget')) ? v.mywidget : '';
alert(val); // "data1" if saved, or "" if not
*/
$.tablesorter.storage = function(table, key, val){
2012-04-02 19:19:17 +00:00
var d, k, ls = false, v = {},
2012-03-07 18:06:35 +00:00
id = table.id || $('.tablesorter').index( $(table) ),
url = window.location.pathname;
try { ls = !!(localStorage.getItem); } catch(e) {}
2012-03-27 01:49:48 +00:00
// *** get val ***
if ($.parseJSON) {
if (ls) {
2012-04-02 19:19:17 +00:00
v = $.parseJSON(localStorage[key]) || {};
2012-03-27 01:49:48 +00:00
} else {
k = document.cookie.split(/[;\s|=]/); // cookie
d = $.inArray(key, k) + 1; // add one to get from the key to the value
2012-04-02 19:19:17 +00:00
v = (d !== 0) ? $.parseJSON(k[d]) || {} : {};
2012-03-27 01:49:48 +00:00
}
}
if (val && JSON && JSON.hasOwnProperty('stringify')) {
2012-03-07 18:06:35 +00:00
// add unique identifiers = url pathname > table ID/index on page > data
2012-04-02 19:19:17 +00:00
if (v[url] && v[url][id]) {
v[url][id] = val;
} else {
if (v[url]) {
v[url][id] = val;
} else {
v[url] = {};
v[url][id] = val;
}
}
2012-03-07 18:06:35 +00:00
// *** set val ***
if (ls) {
localStorage[key] = JSON.stringify(v);
} else {
d = new Date();
d.setTime(d.getTime()+(31536e+6)); // 365 days
document.cookie = key + '=' + (JSON.stringify(v)).replace(/\"/g,'\"') + '; expires=' + d.toGMTString() + '; path=/';
}
2012-03-27 01:49:48 +00:00
} else {
2012-04-02 19:19:17 +00:00
return ( v && v.hasOwnProperty(url) && v[url].hasOwnProperty(id) ) ? v[url][id] : {};
2012-03-07 18:06:35 +00:00
}
};
// Widget: jQuery UI theme
// "uitheme" option in "widgetOptions"
2011-09-13 22:55:31 +00:00
// **************************
2011-09-11 17:51:02 +00:00
$.tablesorter.addWidget({
id: "uitheme",
format: function(table) {
2012-03-07 18:06:35 +00:00
var time, klass, rmv, $t, t, $table = $(table),
c = table.config, wo = c.widgetOptions,
2011-09-11 17:51:02 +00:00
// ["up/down arrow (cssHeaders, unsorted)", "down arrow (cssDesc, descending)", "up arrow (cssAsc, ascending)" ]
2011-09-16 15:43:09 +00:00
icons = ["ui-icon-arrowthick-2-n-s", "ui-icon-arrowthick-1-s", "ui-icon-arrowthick-1-n"];
2012-03-07 18:06:35 +00:00
// keep backwards compatibility, for now
icons = (c.widgetUitheme && c.widgetUitheme.hasOwnProperty('css')) ? c.widgetUitheme.css || icons :
(wo && wo.hasOwnProperty('uitheme')) ? wo.uitheme : icons;
2011-09-16 15:43:09 +00:00
rmv = icons.join(' ');
2011-09-11 17:51:02 +00:00
if (c.debug) {
time = new Date();
}
2012-03-07 18:06:35 +00:00
if (!$table.hasClass('ui-theme')) {
2011-12-14 17:37:55 +00:00
$table.addClass('ui-widget ui-widget-content ui-corner-all ui-theme');
2011-09-11 17:51:02 +00:00
$.each(c.headerList, function(){
$(this)
// using "ui-theme" class in case the user adds their own ui-icon using onRenderHeader
2012-03-07 18:06:35 +00:00
.addClass('ui-widget-header ui-corner-all ui-state-default')
2011-12-14 17:37:55 +00:00
.append('<span class="ui-icon"/>')
2012-03-07 18:06:35 +00:00
.wrapInner('<div class="tablesorter-inner"/>')
2011-09-14 14:20:15 +00:00
.hover(function(){
$(this).addClass('ui-state-hover');
}, function(){
$(this).removeClass('ui-state-hover');
2011-12-14 17:37:55 +00:00
});
2011-09-11 17:51:02 +00:00
});
}
$.each(c.headerList, function(i){
2011-12-14 17:37:55 +00:00
$t = $(this);
2011-12-16 00:17:57 +00:00
if (this.sortDisabled) {
2011-09-11 17:51:02 +00:00
// no sort arrows for disabled columns!
2011-12-14 17:37:55 +00:00
$t.find('span.ui-icon').removeClass(rmv + ' ui-icon');
2011-09-11 17:51:02 +00:00
} else {
2011-12-14 17:37:55 +00:00
klass = ($t.hasClass(c.cssAsc)) ? icons[1] : ($t.hasClass(c.cssDesc)) ? icons[2] : $t.hasClass(c.cssHeader) ? icons[0] : '';
2012-03-27 01:49:48 +00:00
t = ($table.hasClass('hasStickyHeaders')) ? $table.find('tr.' + (wo.stickyHeaders || 'tablesorter-stickyHeader')).find('th').eq(i).add($t) : $t;
2011-12-14 17:37:55 +00:00
t[klass === icons[0] ? 'removeClass' : 'addClass']('ui-state-active')
2011-09-14 14:20:15 +00:00
.find('span.ui-icon').removeClass(rmv).addClass(klass);
2011-09-11 17:51:02 +00:00
}
});
if (c.debug) {
$.tablesorter.benchmark("Applying uitheme widget", time);
}
}
});
2012-03-07 18:06:35 +00:00
// Widget: Column styles
// "columns" option in "widgetOptions"
2011-09-13 22:55:31 +00:00
// **************************
2011-09-11 17:51:02 +00:00
$.tablesorter.addWidget({
id: "columns",
format: function(table) {
var $tr, $td, time, last, rmv, k,
2011-09-11 17:51:02 +00:00
c = table.config,
b = $(table).children('tbody:not(' + c.cssInfoBlock + ')'),
2011-09-11 17:51:02 +00:00
list = c.sortList,
len = list.length,
2012-03-07 18:06:35 +00:00
css = [ "primary", "secondary", "tertiary" ]; // default options
// keep backwards compatibility, for now
css = (c.widgetColumns && c.widgetColumns.hasOwnProperty('css')) ? c.widgetColumns.css || css :
(c.widgetOptions && c.widgetOptions.hasOwnProperty('columns')) ? c.widgetOptions.columns || css : css;
2011-09-16 15:43:09 +00:00
last = css.length-1;
2011-09-11 17:51:02 +00:00
rmv = css.join(' ');
if (c.debug) {
time = new Date();
}
2011-09-13 22:55:31 +00:00
// check if there is a sort (on initialization there may not be one)
if (list && list[0]) {
2012-05-03 14:46:31 +00:00
for (k = 0; k < b.length; k++ ) {
// loop through the visible rows
$tr = $(b[k]).children('tr:visible');
$tr.each(function(i) {
2012-05-03 14:46:31 +00:00
$td = $(this).children().removeClass(rmv);
// primary sort column class
$td.eq(list[0][0]).addClass(css[0]);
if (len > 1) {
for (i=1; i<len; i++){
// secondary, tertiary, etc sort column classes
$td.eq(list[i][0]).addClass( css[i] || css[last] );
}
2011-09-13 22:55:31 +00:00
}
2012-05-03 14:46:31 +00:00
});
}
2012-02-27 11:59:20 +00:00
} else {
// remove all column classes if sort is cleared (sortReset)
$(table).find('td').removeClass(rmv);
2011-09-13 22:55:31 +00:00
}
2011-09-11 17:51:02 +00:00
if (c.debug) {
$.tablesorter.benchmark("Applying Columns widget", time);
}
}
2011-09-13 22:55:31 +00:00
});
2012-03-07 18:06:35 +00:00
// Widget: Filter
// "filter_startsWith" & "filter_childRows" options in "widgetOptions"
2011-09-13 22:55:31 +00:00
// **************************
$.tablesorter.addWidget({
id: "filter",
format: function(table) {
2012-03-07 18:06:35 +00:00
if (!$(table).hasClass('hasFilters')) {
var i, v, r, t, x, cr, $td, c = table.config,
wo = c.widgetOptions,
css = wo.filter_cssFilter || 'tablesorter-filter',
$t = $(table).addClass('hasFilters'),
cols = c.parsers.length,
2012-03-07 18:06:35 +00:00
fr = '<tr class="' + css + '">',
2011-09-13 22:55:31 +00:00
time;
if (c.debug) {
time = new Date();
}
for (i=0; i < cols; i++){
2012-03-07 18:06:35 +00:00
fr += '<td><input type="search" data-col="' + i + '" class="' + css;
2011-09-16 18:39:03 +00:00
// use header option - headers: { 1: { filter: false } } OR add class="filter-false"
fr += ((c.headers[i] && c.headers[i].hasOwnProperty('filter') && c.headers[i].filter === false) || $(c.headerList[i]).is('.filter-false') ) ? ' disabled" disabled' : '"';
fr += '></td>';
2011-09-13 22:55:31 +00:00
}
2012-03-07 18:06:35 +00:00
$t
.find('thead').eq(0).append(fr += '</tr>')
2012-03-07 18:06:35 +00:00
.find('input.' + css).bind('keyup search', function(e){
v = $t.find('thead').eq(0).children('tr').find('input.' + css).map(function(){ return ($(this).val() || '').toLowerCase(); }).get();
2011-09-13 22:55:31 +00:00
if (v.join('') === '') {
2012-03-07 18:06:35 +00:00
$t.find('tr').show();
2011-09-13 22:55:31 +00:00
} else {
$t.children('tbody:not(.' + c.cssInfoBlock + ')').children('tr:not(.' + c.cssChildRow + ')').each(function(){
2011-09-13 22:55:31 +00:00
r = true;
2012-03-07 18:06:35 +00:00
cr = $(this).nextUntil('tr:not(.' + c.cssChildRow + ')');
// so, if "table.config.widgetOptions.filter_childRows" is true and there is
2011-11-08 03:47:46 +00:00
// a match anywhere in the child row, then it will make the row visible
// checked here so the option can be changed dynamically
2012-03-07 18:06:35 +00:00
t = (cr.length && (wo && wo.hasOwnProperty('filter_childRows') &&
typeof wo.filter_childRows !== 'undefined' ? wo.filter_childRows : true)) ? cr.text() : '';
$td = $(this).children('td');
2011-09-13 22:55:31 +00:00
for (i=0; i < cols; i++){
2012-04-24 03:16:06 +00:00
x = $.trim(($td.eq(i).text() + t)).toLowerCase().indexOf(v[i]);
if (v[i] !== '' && ( (!wo.filter_startsWith && x >= 0) || (wo.filter_startsWith && x === 0) ) ) {
2011-09-13 22:55:31 +00:00
r = (r) ? true : false;
} else if (v[i] !== '') {
r = false;
}
}
$(this)[r ? 'show' : 'hide']();
2011-11-08 03:47:46 +00:00
if (cr.length) { cr[r ? 'show' : 'hide'](); }
2011-09-13 22:55:31 +00:00
});
}
2012-03-07 18:06:35 +00:00
$t.trigger('applyWidgets'); // make sure zebra widget is applied
2011-09-13 22:55:31 +00:00
});
if (c.debug) {
$.tablesorter.benchmark("Applying Filter widget", time);
}
}
}
});
2011-09-16 15:43:09 +00:00
2012-03-07 18:06:35 +00:00
// Widget: Sticky headers
2011-10-11 05:48:34 +00:00
// based on this awesome article:
// http://css-tricks.com/13465-persistent-headers/
// **************************
$.tablesorter.addWidget({
id: "stickyHeaders",
format: function(table) {
2011-12-14 17:37:55 +00:00
if ($(table).hasClass('hasStickyHeaders')) { return; }
var $table = $(table).addClass('hasStickyHeaders'),
2012-03-07 18:06:35 +00:00
wo = table.config.widgetOptions,
2011-12-06 15:25:51 +00:00
win = $(window),
header = $(table).children('thead'),
hdrCells = header.children('tr:not(.sticky-false)').children(),
2012-03-27 01:49:48 +00:00
css = wo.stickyHeaders || 'tablesorter-stickyHeader',
innr = '.tablesorter-header-inner',
firstCell = hdrCells.eq(0),
2012-05-03 14:46:31 +00:00
tfoot = $table.find('tfoot'),
2012-04-23 19:24:45 +00:00
sticky = header.find('tr.tablesorter-header:not(.sticky-false)').clone()
.removeClass('tablesorter-header')
2012-03-07 18:06:35 +00:00
.addClass(css)
2011-10-11 05:48:34 +00:00
.css({
2012-03-27 01:49:48 +00:00
width : header.outerWidth(true),
2011-10-11 05:48:34 +00:00
position : 'fixed',
left : firstCell.offset().left,
2012-03-22 14:58:43 +00:00
margin : 0,
top : 0,
2011-10-26 06:50:02 +00:00
visibility : 'hidden',
zIndex : 10
2011-10-11 05:48:34 +00:00
}),
stkyCells = sticky.children(),
2012-03-27 01:49:48 +00:00
laststate = '';
// update sticky header class names to match real header after sorting
2011-12-06 15:25:51 +00:00
$table.bind('sortEnd', function(e,t){
2011-10-11 05:48:34 +00:00
var th = $(t).find('thead tr'),
2012-03-07 18:06:35 +00:00
sh = th.filter('.' + css).children();
th.filter(':not(.' + css + ')').children().each(function(i){
2011-10-11 05:48:34 +00:00
sh.eq(i).attr('class', $(this).attr('class'));
});
2012-01-27 20:03:41 +00:00
}).bind('pagerComplete', function(){
win.resize(); // trigger window resize to make sure column widths & position are correct
2011-10-11 05:48:34 +00:00
});
// set sticky header cell width and link clicks to real header
hdrCells.each(function(i){
var t = $(this),
s = stkyCells.eq(i)
// clicking on sticky will trigger sort
.bind('click', function(e){
t.trigger(e);
})
// prevent sticky header text selection
.bind('mousedown', function(){
this.onselectstart = function(){ return false; };
return false;
2012-03-27 01:49:48 +00:00
})
// set cell widths
.find(innr).width( t.find(innr).width() );
2011-10-11 05:48:34 +00:00
});
header.prepend( sticky );
// make it sticky!
2011-10-15 14:58:44 +00:00
win
.scroll(function(){
var offset = firstCell.offset(),
2011-10-15 14:58:44 +00:00
sTop = win.scrollTop(),
2012-05-03 14:46:31 +00:00
tableHt = $table.height() - (firstCell.height() + (tfoot.height() || 0)),
vis = (sTop > offset.top) && (sTop < offset.top + tableHt) ? 'visible' : 'hidden';
2011-12-06 15:25:51 +00:00
sticky.css({
left : offset.left - win.scrollLeft(),
visibility : vis
});
if (vis !== laststate) {
// trigger resize to make sure the column widths match
win.resize();
laststate = vis;
}
2011-10-15 14:58:44 +00:00
})
.resize(function(){
var ht = 0;
2011-12-06 15:25:51 +00:00
sticky.css({
left : firstCell.offset().left - win.scrollLeft(),
2012-03-27 01:49:48 +00:00
width: header.outerWidth()
}).each(function(i){
$(this).css('top', ht);
ht += header.find('tr').eq(i).outerHeight();
2011-12-06 15:25:51 +00:00
});
stkyCells.find(innr).each(function(i){
$(this).width( hdrCells.eq(i).find(innr).width() );
2011-10-15 14:58:44 +00:00
});
});
2011-10-11 05:48:34 +00:00
}
});
2011-10-26 06:50:02 +00:00
// Add Column resizing widget
2012-03-07 18:06:35 +00:00
// this widget saves the column widths if
// $.tablesorter.storage function is included
2011-10-26 06:50:02 +00:00
// **************************
$.tablesorter.addWidget({
id: "resizable",
format: function(table) {
2012-03-07 18:06:35 +00:00
if ($(table).hasClass('hasResizable')) { return; }
$(table).addClass('hasResizable');
var i, j, w, s, c = table.config,
$cols = $(c.headerList).filter(':gt(0)'),
position = 0,
$target = null,
$prev = null,
len = $cols.length,
stopResize = function(){
position = 0;
$target = $prev = null;
$(window).trigger('resize'); // will update stickyHeaders, just in case
};
s = ($.tablesorter.storage) ? $.tablesorter.storage(table, 'tablesorter-resizable') : '';
// process only if table ID or url match
if (s) {
for (j in s) {
if (!isNaN(j) && j < c.headerList.length) {
$(c.headerList[j]).width(s[j]); // set saved resizable widths
}
2011-10-26 06:50:02 +00:00
}
2012-03-07 18:06:35 +00:00
}
$cols
.each(function(){
$(this)
.append('<div class="tablesorter-resizer" style="cursor:w-resize;position:absolute;height:100%;width:20px;left:-20px;top:0;z-index:1;"></div>')
.wrapInner('<div style="position:relative;height:100%;width:100%"></div>');
})
.bind('mousemove', function(e){
// ignore mousemove if no mousedown
if (position === 0 || !$target) { return; }
var w = e.pageX - position,
n = $prev;
// make sure
if ( $target.width() < -w || ( $prev && $prev.width() <= w )) { return; }
// resize current column
$prev.width( $prev.width() + w );
position = e.pageX;
})
.bind('mouseup', function(){
if (s && $.tablesorter.storage && $target) {
s[$prev.index()] = $prev.width();
$.tablesorter.storage(table, 'tablesorter-resizable', s);
}
2011-10-26 06:50:02 +00:00
stopResize();
2012-03-07 18:06:35 +00:00
return false;
})
.find('.tablesorter-resizer')
.bind('mousedown', function(e){
// save header cell and mouse position
$target = $(e.target).closest('th');
$prev = $target.prev();
position = e.pageX;
2011-10-26 06:50:02 +00:00
});
2012-03-07 18:06:35 +00:00
$(table).find('thead').bind('mouseup mouseleave', function(){
stopResize();
});
2011-10-26 06:50:02 +00:00
}
});
2012-02-01 05:14:28 +00:00
// Save table sort widget
2012-03-07 18:06:35 +00:00
// this widget saves the last sort only if the
// $.tablesorter.storage function is included
2012-02-01 05:14:28 +00:00
// **************************
$.tablesorter.addWidget({
id: 'saveSort',
init: function(table, allWidgets, thisWidget){
// run widget format before all other widgets are applied to the table
thisWidget.format(table, true);
},
format: function(table, init) {
2012-03-07 18:06:35 +00:00
var n, d, k, sl, time, c = table.config, sortList = { "sortList" : c.sortList };
2012-02-01 05:14:28 +00:00
if (c.debug) {
time = new Date();
}
2012-03-07 18:06:35 +00:00
if ($(table).hasClass('hasSaveSort')) {
if (table.hasInitialized && $.tablesorter.storage) {
$.tablesorter.storage( table, 'tablesorter-savesort', sortList );
2012-02-21 00:14:25 +00:00
if (c.debug) {
2012-03-07 18:06:35 +00:00
$.tablesorter.benchmark('saveSort widget: Saving last sort: ' + c.sortList, time);
2012-02-21 00:14:25 +00:00
}
2012-02-01 05:14:28 +00:00
}
} else {
// set table sort on initial run of the widget
2012-03-07 18:06:35 +00:00
$(table).addClass('hasSaveSort');
sortList = '';
2012-02-01 05:14:28 +00:00
// get data
2012-03-07 18:06:35 +00:00
if ($.tablesorter.storage) {
sl = $.tablesorter.storage( table, 'tablesorter-savesort' );
sortList = (sl && sl.hasOwnProperty('sortList') && $.isArray(sl.sortList)) ? sl.sortList : '';
if (c.debug) {
$.tablesorter.benchmark('saveSort: Last sort loaded: ' + sortList, time);
}
2012-02-01 05:14:28 +00:00
}
// init is true when widget init is run, this will run this widget before all other widgets have initialized
// this method allows using this widget in the original tablesorter plugin; but then it will run all widgets twice.
if (init && sortList && sortList.length > 0) {
c.sortList = sortList;
2012-02-21 00:14:25 +00:00
} else if (table.hasInitialized && sortList && sortList.length > 0) {
// update sort change
$(table).trigger('sorton', [sortList]);
2012-02-01 05:14:28 +00:00
}
}
}
});
2011-09-16 15:43:09 +00:00
})(jQuery);