/* Pager widget (beta) for TableSorter 10/18/2013 */ /*jshint browser:true, jquery:true, unused:false */ ;(function($){ "use strict"; var tsp, ts = $.tablesorter; ts.addWidget({ id: "pager", priority: 5, options : { // output default: '{page}/{totalPages}' // possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows} pager_output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}' // apply disabled classname to the pager arrows when the rows at either extreme is visible pager_updateArrows: true, // starting page of the pager (zero based index) pager_startPage: 0, // Number of visible rows pager_size: 10, // Save pager page & size if the storage script is loaded (requires $.tablesorter.storage in jquery.tablesorter.widgets.js) pager_savePages: true, // if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty // table row set to a height to compensate; default is false pager_fixedHeight: false, // remove rows from the table to speed up the sort of large tables. // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled. pager_removeRows: false, // removing rows in larger tables speeds up the sort // use this format: "http://mydatabase.com?page={page}&size={size}&{sortList:col}&{filterList:fcol}" // where {page} is replaced by the page number, {size} is replaced by the number of records to show, // {sortList:col} adds the sortList to the url into a "col" array, and {filterList:fcol} adds // the filterList to the url into an "fcol" array. // So a sortList = [[2,0],[3,0]] becomes "&col[2]=0&col[3]=0" in the url // and a filterList = [[2,Blue],[3,13]] becomes "&fcol[2]=Blue&fcol[3]=13" in the url pager_ajaxUrl: null, // modify the url after all processing has been applied pager_customAjaxUrl: function(table, url) { return url; }, // modify the $.ajax object to allow complete control over your ajax requests pager_ajaxObject: { dataType: 'json' }, // process ajax so that the following information is returned: // [ total_rows (number), rows (array of arrays), headers (array; optional) ] // example: // [ // 100, // total rows // [ // [ "row1cell1", "row1cell2", ... "row1cellN" ], // [ "row2cell1", "row2cell2", ... "row2cellN" ], // ... // [ "rowNcell1", "rowNcell2", ... "rowNcellN" ] // ], // [ "header1", "header2", ... "headerN" ] // optional // ] pager_ajaxProcessing: function(ajax){ return [ 0, [], null ]; }, // css class names of pager arrows pager_css: { container : 'tablesorter-pager', errorRow : 'tablesorter-errorRow', // error information row (don't include period at beginning) disabled : 'disabled' // class added to arrows @ extremes (i.e. prev/first arrows "disabled" on first page) }, // jQuery selectors pager_selectors: { container : '.pager', // target the pager markup first : '.first', // go to first page arrow prev : '.prev', // previous page arrow next : '.next', // next page arrow last : '.last', // go to last page arrow goto : '.gotoPage', // go to page selector - select dropdown that sets the current page pageDisplay : '.pagedisplay', // location of where the "output" is displayed pageSize : '.pagesize' // page size selector - select dropdown that sets the "size" option } }, init: function(table){ tsp.init(table); }, // only update to complete sorter initialization format: function(table, c){ if (!(c.pager && c.pager.initialized)){ return tsp.initComplete(table, c); } tsp.moveToPage(table, c.pager, false); }, remove: function(table, c, wo){ tsp.destroyPager(table, c); } }); /* pager widget functions */ tsp = ts.pager = { init: function(table) { // check if tablesorter has initialized if (table.hasInitialized && table.config.pager.initialized) { return; } var t, c = table.config, wo = c.widgetOptions, s = wo.pager_selectors, // save pager variables p = c.pager = $.extend({ totalPages: 0, filteredRows: 0, filteredPages: 0, currentFilters: [], page: wo.pager_startPage, size: wo.pager_size, startRow: 0, endRow: 0, $size: null, last: {} }, c.pager); // added in case the pager is reinitialized after being destroyed. p.$container = $(s.container).addClass(wo.pager_css.container).show(); // goto selector p.$goto = p.$container.find(s.goto); // page size selector p.$size = p.$container.find(s.pageSize); p.totalRows = c.$tbodies.eq(0).children().length; p.oldAjaxSuccess = p.oldAjaxSuccess || wo.pager_ajaxObject.success; c.appender = tsp.appender; if (wo.pager_savePages && ts.storage) { t = ts.storage(table, 'tablesorter-pager') || {}; // fixes #387 p.page = isNaN(t.page) ? p.page : t.page; p.size = ( isNaN(t.size) ? p.size : t.size ) || 10; } // clear initialized flag p.initialized = false; // before initialization event c.$table.trigger('pagerBeforeInitialized', c); tsp.enablePager(table, c, false); if ( typeof(wo.pager_ajaxUrl) === 'string' ) { // ajax pager; interact with database p.ajax = true; // When filtering with ajax, allow only custom filtering function, disable default filtering since it will be done server side. wo.filter_serversideFiltering = true; c.serverSideSorting = true; tsp.moveToPage(table, p); } else { p.ajax = false; // Regular pager; all rows stored in memory c.$table.trigger("appendCache", true); tsp.hideRowsSetup(table, c); } }, initComplete: function(table, c){ var p = c.pager; tsp.changeHeight(table, c); tsp.bindEvents(table, c); // pager initialized if (!p.ajax) { p.initialized = true; tsp.setPageSize(table, 0, c); // page size 0 is ignored c.$table.trigger('pagerInitialized', c); } }, bindEvents: function(table, c){ var ctrls, fxn, p = c.pager, wo = c.widgetOptions, s = wo.pager_selectors; c.$table .unbind('filterStart filterEnd sortEnd disable enable destroy update pageSize '.split(' ').join('.pager ')) .bind('filterStart.pager', function(e, filters) { $.data(table, 'pagerUpdateTriggered', false); p.currentFilters = filters; }) // update pager after filter widget completes .bind('filterEnd.pager sortEnd.pager', function(e) { //Prevent infinite event loops from occuring by setting this in all moveToPage calls and catching it here. if ($.data(table, 'pagerUpdateTriggered')) { $.data(table, 'pagerUpdateTriggered', false); return; } //only run the server side sorting if it has been enabled if (e.type === "filterEnd" || (e.type === "sortEnd" && c.serverSideSorting)) { tsp.moveToPage(table, p, false); } tsp.updatePageDisplay(table, c, false); tsp.fixHeight(table, c); }) .bind('disable.pager', function(e){ e.stopPropagation(); tsp.showAllRows(table, c); }) .on('enable.pager', function(e){ e.stopPropagation(); tsp.enablePager(table, c, true); }) .on('destroy.pager', function(e){ e.stopPropagation(); tsp.destroyPager(table, c); }) .on('update.pager', function(e){ e.stopPropagation(); tsp.hideRows(table, c); }) .on('pageSize.pager', function(e,v){ e.stopPropagation(); tsp.setPageSize(table, parseInt(v, 10) || 10, c); tsp.hideRows(table, c); tsp.updatePageDisplay(table, c, false); if (p.$size.length) { p.$size.val(p.size); } // twice? }) .on('pageSet.pager', function(e,v){ e.stopPropagation(); p.page = (parseInt(v, 10) || 1) - 1; if (p.$goto.length) { p.$goto.val(c.size); } // twice? tsp.moveToPage(table, p); tsp.updatePageDisplay(table, c, false); }); // clicked controls ctrls = [ s.first, s.prev, s.next, s.last ]; fxn = [ 'moveToFirstPage', 'moveToPrevPage', 'moveToNextPage', 'moveToLastPage' ]; p.$container.find(ctrls.join(',')) .unbind('click.pager') .bind('click.pager', function(){ var i, $c = $(this), l = ctrls.length; if ( !$c.hasClass(wo.pager_css.disabled) ) { for (i = 0; i < l; i++) { if ($c.is(ctrls[i])) { tsp[fxn[i]](table, p); break; } } } return false; }); if ( p.$goto.length ) { p.$goto .unbind('change') .bind('change', function(){ p.page = $(this).val() - 1; tsp.moveToPage(table, p); tsp.updatePageDisplay(table, c, false); }); } if ( p.$size.length ) { p.$size .unbind('change.pager') .bind('change.pager', function() { p.$size.val( $(this).val() ); // in case there are more than one pagers if ( !$(this).hasClass(wo.pager_css.disabled) ) { tsp.setPageSize(table, parseInt( $(this).val(), 10 ), c); tsp.changeHeight(table, c); } return false; }); } }, // hide arrows at extremes pagerArrows: function(c, disable) { var p = c.pager, dis = !!disable, wo = c.widgetOptions, s = wo.pager_selectors, tp = Math.min( p.totalPages, p.filteredPages ); if ( wo.pager_updateArrows ) { p.$container.find(s.first + ',' + s.prev).toggleClass(wo.pager_css.disabled, dis || p.page === 0); p.$container.find(s.next + ',' + s.last).toggleClass(wo.pager_css.disabled, dis || p.page === tp - 1); } }, updatePageDisplay: function(table, c, flag) { var i, pg, s, t, out, wo = c.widgetOptions, p = c.pager, f = c.$table.hasClass('hasFilters') && !wo.pager_ajaxUrl, t = (c.widgetOptions && c.widgetOptions.filter_filteredRow || 'filtered') + ',' + c.selectorRemove, sz = p.size || 10; // don't allow dividing by zero p.$size.removeClass(wo.pager_css.disabled).removeAttr('disabled'); p.$goto.removeClass(wo.pager_css.disabled).removeAttr('disabled'); p.totalPages = Math.ceil( p.totalRows / sz ); // needed for "pageSize" method p.filteredRows = (f) ? c.$tbodies.eq(0).children('tr:not(.' + t + ')').length : p.totalRows; p.filteredPages = (f) ? Math.ceil( p.filteredRows / sz ) || 1 : p.totalPages; if ( Math.min( p.totalPages, p.filteredPages ) >= 0 ) { t = (p.size * p.page > p.filteredRows); p.startRow = (t) ? 1 : (p.filteredRows === 0 ? 0 : p.size * p.page + 1); p.page = (t) ? 0 : p.page; p.endRow = Math.min( p.filteredRows, p.totalRows, p.size * ( p.page + 1 ) ); out = p.$container.find(wo.pager_selectors.pageDisplay); // form the output string (can now get a new output string from the server) s = ( p.ajaxData && p.ajaxData.output ? p.ajaxData.output || wo.pager_output : wo.pager_output ) // {page} = one-based index; {page+#} = zero based index +/- value .replace(/\{page([\-+]\d+)?\}/gi, function(m,n){ return p.page + (n ? parseInt(n, 10) : 1); }) // {totalPages}, {extra}, {extra:0} (array) or {extra : key} (object) .replace(/\{\w+(\s*:\s*\w+)?\}/gi, function(m){ var t = m.replace(/[{}\s]/g,''), a = t.split(':'), d = p.ajaxData; return a.length > 1 && d && d[a[0]] ? d[a[0]][a[1]] : p[t] || (d ? d[t] : '') || ''; }); if (out.length) { out[ (out[0].tagName === 'INPUT') ? 'val' : 'html' ](s); if ( p.$goto.length ) { t = ''; pg = Math.min( p.totalPages, p.filteredPages ); for ( i = 1; i <= pg; i++ ) { t += ''; } p.$goto.html(t).val( p.page + 1 ); } } } tsp.pagerArrows(c); if (p.initialized && flag !== false) { c.$table.trigger('pagerComplete', c); // save pager info to storage if (wo.pager_savePages && ts.storage) { ts.storage(table, 'tablesorter-pager', { page : p.page, size : p.size }); } } }, fixHeight: function(table, c) { var d, h, p = c.pager, wo = c.widgetOptions, $b = c.$tbodies.eq(0); if (wo.pager_fixedHeight) { $b.find('tr.pagerSavedHeightSpacer').remove(); h = $.data(table, 'pagerSavedHeight'); if (h) { d = h - $b.height(); if ( d > 5 && $.data(table, 'pagerLastSize') === p.size && $b.children('tr:visible').length < p.size ) { $b.append('