UNPKG

tablesorter

Version:

tablesorter (FORK) is a jQuery plugin for turning a standard HTML table with THEAD and TBODY tags into a sortable table without page refreshes. tablesorter can successfully parse and sort many types of data including linked data in a cell.

1,279 lines (1,216 loc) 111 kB
(function(factory){if (typeof define === 'function' && define.amd){define(['jquery'], factory);} else if (typeof module === 'object' && typeof module.exports === 'object'){module.exports = factory(require('jquery'));} else {factory(jQuery);}}(function(jQuery){ /*! TableSorter (FORK) v2.32.0 *//* * Client-side table sorting with ease! * @requires jQuery v1.2.6+ * * Copyright (c) 2007 Christian Bach * fork maintained by Rob Garrison * * Examples and original docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @type jQuery * @name tablesorter (FORK) * @cat Plugins/Tablesorter * @author Christian Bach - christian.bach@polyester.se * @contributor Rob Garrison - https://github.com/Mottie/tablesorter * @docs (fork) - https://mottie.github.io/tablesorter/docs/ */ /*jshint browser:true, jquery:true, unused:false, expr: true */ ;( function( $ ) { 'use strict'; var ts = $.tablesorter = { version : '2.32.0', parsers : [], widgets : [], defaults : { // *** appearance theme : 'default', // adds tablesorter-{theme} to the table for styling widthFixed : false, // adds colgroup to fix widths of columns showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered. headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i></i> // class from cssIcon onRenderTemplate : null, // function( index, template ) { return template; }, // template is a string onRenderHeader : null, // function( index ) {}, // nothing to return // *** functionality cancelSelection : true, // prevent text selection in the header tabIndex : true, // add tabindex to header for keyboard accessibility dateFormat : 'mmddyyyy', // other options: 'ddmmyyy' or 'yyyymmdd' sortMultiSortKey : 'shiftKey', // key used to select additional columns sortResetKey : 'ctrlKey', // key used to remove sorting on a column usNumberFormat : true, // false for German '1.234.567,89' or French '1 234 567,89' delayInit : false, // if false, the parsed table contents will not update until the first sort serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used. resort : true, // default setting to trigger a resort after an 'update', 'addRows', 'updateCell', etc has completed // *** sort options headers : null, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc. ignoreCase : true, // ignore case while sorting sortForce : null, // column(s) first sorted; always applied sortList : [], // Initial sort order; applied initially; updated when manually sorted sortAppend : null, // column(s) sorted last; always applied sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained sortInitialOrder : 'asc', // sort direction on first click sortLocaleCompare: false, // replace equivalent character (accented characters) sortReset : false, // third click on the header will reset column to default - unsorted sortRestart : false, // restart sort to 'sortInitialOrder' when clicking on previously unsorted columns emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero, emptyMax, emptyMin stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero duplicateSpan : true, // colspan cells in the tbody will have duplicated content in the cache for each spanned column textExtraction : 'basic', // text extraction method/function - function( node, table, cellIndex ) {} textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in default textExtraction function) textSorter : null, // choose overall or specific column sorter function( a, b, direction, table, columnIndex ) [alt: ts.sortText] numberSorter : null, // choose overall numeric sorter function( a, b, direction, maxColumnValue ) // *** widget options initWidgets : true, // apply widgets on tablesorter initialization widgetClass : 'widget-{name}', // table class name template to match to include a widget widgets : [], // method to add widgets, e.g. widgets: ['zebra'] widgetOptions : { zebra : [ 'even', 'odd' ] // zebra widget alternating row class names }, // *** callbacks initialized : null, // function( table ) {}, // *** extra css class names tableClass : '', cssAsc : '', cssDesc : '', cssNone : '', cssHeader : '', cssHeaderRow : '', cssProcessing : '', // processing icon applied to header during sort/filter cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to its parent cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!) cssNoSort : 'tablesorter-noSort', // class name added to element inside header; clicking on it won't cause a sort cssIgnoreRow : 'tablesorter-ignoreRow',// header row to ignore; cells within this row will not be added to c.$headers cssIcon : 'tablesorter-icon', // if this class does not exist, the {icon} will not be added from the headerTemplate cssIconNone : '', // class name added to the icon when there is no column sort cssIconAsc : '', // class name added to the icon when the column has an ascending sort cssIconDesc : '', // class name added to the icon when the column has a descending sort cssIconDisabled : '', // class name added to the icon when the column has a disabled sort // *** events pointerClick : 'click', pointerDown : 'mousedown', pointerUp : 'mouseup', // *** selectors selectorHeaders : '> thead th, > thead td', selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort selectorRemove : '.remove-me', // *** advanced debug : false, // *** Internal variables headerList: [], empties: {}, strings: {}, parsers: [], // *** parser options for validator; values must be falsy! globalize: 0, imgAttr: 0 // removed: widgetZebra: { css: ['even', 'odd'] } }, // internal css classes - these will ALWAYS be added to // the table and MUST only contain one class name - fixes #381 css : { table : 'tablesorter', cssHasChild: 'tablesorter-hasChildRow', childRow : 'tablesorter-childRow', colgroup : 'tablesorter-colgroup', header : 'tablesorter-header', headerRow : 'tablesorter-headerRow', headerIn : 'tablesorter-header-inner', icon : 'tablesorter-icon', processing : 'tablesorter-processing', sortAsc : 'tablesorter-headerAsc', sortDesc : 'tablesorter-headerDesc', sortNone : 'tablesorter-headerUnSorted' }, // labels applied to sortable headers for accessibility (aria) support language : { sortAsc : 'Ascending sort applied, ', sortDesc : 'Descending sort applied, ', sortNone : 'No sort applied, ', sortDisabled : 'sorting is disabled', nextAsc : 'activate to apply an ascending sort', nextDesc : 'activate to apply a descending sort', nextNone : 'activate to remove the sort' }, regex : { templateContent : /\{content\}/g, templateIcon : /\{icon\}/g, templateName : /\{name\}/i, spaces : /\s+/g, nonWord : /\W/g, formElements : /(input|select|button|textarea)/i, // *** sort functions *** // regex used in natural sort // chunk/tokenize numbers & letters chunk : /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // replace chunks @ ends chunks : /(^\\0|\\0$)/, hex : /^0x[0-9a-f]+$/i, // *** formatFloat *** comma : /,/g, digitNonUS : /[\s|\.]/g, digitNegativeTest : /^\s*\([.\d]+\)/, digitNegativeReplace : /^\s*\(([.\d]+)\)/, // *** isDigit *** digitTest : /^[\-+(]?\d+[)]?$/, digitReplace : /[,.'"\s]/g }, // digit sort, text location string : { max : 1, min : -1, emptymin : 1, emptymax : -1, zero : 0, none : 0, 'null' : 0, top : true, bottom : false }, keyCodes : { enter : 13 }, // placeholder date parser data (globalize) dates : {}, // These methods can be applied on table.config instance instanceMethods : {}, /* ▄█████ ██████ ██████ ██ ██ █████▄ ▀█▄ ██▄▄ ██ ██ ██ ██▄▄██ ▀█▄ ██▀▀ ██ ██ ██ ██▀▀▀ █████▀ ██████ ██ ▀████▀ ██ */ setup : function( table, c ) { // if no thead or tbody, or tablesorter is already present, quit if ( !table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true ) { if ( ts.debug(c, 'core') ) { if ( table.hasInitialized ) { console.warn( 'Stopping initialization. Tablesorter has already been initialized' ); } else { console.error( 'Stopping initialization! No table, thead or tbody', table ); } } return; } var tmp = '', $table = $( table ), meta = $.metadata; // initialization flag table.hasInitialized = false; // table is being processed flag table.isProcessing = true; // make sure to store the config object table.config = c; // save the settings where they read $.data( table, 'tablesorter', c ); if ( ts.debug(c, 'core') ) { console[ console.group ? 'group' : 'log' ]( 'Initializing tablesorter v' + ts.version ); $.data( table, 'startoveralltimer', new Date() ); } // removing this in version 3 (only supports jQuery 1.7+) c.supportsDataObject = ( function( version ) { version[ 0 ] = parseInt( version[ 0 ], 10 ); return ( version[ 0 ] > 1 ) || ( version[ 0 ] === 1 && parseInt( version[ 1 ], 10 ) >= 4 ); })( $.fn.jquery.split( '.' ) ); // ensure case insensitivity c.emptyTo = c.emptyTo.toLowerCase(); c.stringTo = c.stringTo.toLowerCase(); c.last = { sortList : [], clickedIndex : -1 }; // add table theme class only if there isn't already one there if ( !/tablesorter\-/.test( $table.attr( 'class' ) ) ) { tmp = ( c.theme !== '' ? ' tablesorter-' + c.theme : '' ); } // give the table a unique id, which will be used in namespace binding if ( !c.namespace ) { c.namespace = '.tablesorter' + Math.random().toString( 16 ).slice( 2 ); } else { // make sure namespace starts with a period & doesn't have weird characters c.namespace = '.' + c.namespace.replace( ts.regex.nonWord, '' ); } c.table = table; c.$table = $table // add namespace to table to allow bindings on extra elements to target // the parent table (e.g. parser-input-select) .addClass( ts.css.table + ' ' + c.tableClass + tmp + ' ' + c.namespace.slice(1) ) .attr( 'role', 'grid' ); c.$headers = $table.find( c.selectorHeaders ); c.$table.children().children( 'tr' ).attr( 'role', 'row' ); c.$tbodies = $table.children( 'tbody:not(.' + c.cssInfoBlock + ')' ).attr({ 'aria-live' : 'polite', 'aria-relevant' : 'all' }); if ( c.$table.children( 'caption' ).length ) { tmp = c.$table.children( 'caption' )[ 0 ]; if ( !tmp.id ) { tmp.id = c.namespace.slice( 1 ) + 'caption'; } c.$table.attr( 'aria-labelledby', tmp.id ); } c.widgetInit = {}; // keep a list of initialized widgets // change textExtraction via data-attribute c.textExtraction = c.$table.attr( 'data-text-extraction' ) || c.textExtraction || 'basic'; // build headers ts.buildHeaders( c ); // fixate columns if the users supplies the fixedWidth option // do this after theme has been applied ts.fixColumnWidth( table ); // add widgets from class name ts.addWidgetFromClass( table ); // add widget options before parsing (e.g. grouping widget has parser settings) ts.applyWidgetOptions( table ); // try to auto detect column type, and store in tables config ts.setupParsers( c ); // start total row count at zero c.totalRows = 0; // only validate options while debugging. See #1528 if (c.debug) { ts.validateOptions( c ); } // build the cache for the tbody cells // delayInit will delay building the cache until the user starts a sort if ( !c.delayInit ) { ts.buildCache( c ); } // bind all header events and methods ts.bindEvents( table, c.$headers, true ); ts.bindMethods( c ); // get sort list from jQuery data or metadata // in jQuery < 1.4, an error occurs when calling $table.data() if ( c.supportsDataObject && typeof $table.data().sortlist !== 'undefined' ) { c.sortList = $table.data().sortlist; } else if ( meta && ( $table.metadata() && $table.metadata().sortlist ) ) { c.sortList = $table.metadata().sortlist; } // apply widget init code ts.applyWidget( table, true ); // if user has supplied a sort list to constructor if ( c.sortList.length > 0 ) { // save sortList before any sortAppend is added c.last.sortList = c.sortList; ts.sortOn( c, c.sortList, {}, !c.initWidgets ); } else { ts.setHeadersCss( c ); if ( c.initWidgets ) { // apply widget format ts.applyWidget( table, false ); } } // show processesing icon if ( c.showProcessing ) { $table .unbind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace ) .bind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace, function( e ) { clearTimeout( c.timerProcessing ); ts.isProcessing( table ); if ( e.type === 'sortBegin' ) { c.timerProcessing = setTimeout( function() { ts.isProcessing( table, true ); }, 500 ); } }); } // initialized table.hasInitialized = true; table.isProcessing = false; if ( ts.debug(c, 'core') ) { console.log( 'Overall initialization time:' + ts.benchmark( $.data( table, 'startoveralltimer' ) ) ); if ( ts.debug(c, 'core') && console.groupEnd ) { console.groupEnd(); } } $table.triggerHandler( 'tablesorter-initialized', table ); if ( typeof c.initialized === 'function' ) { c.initialized( table ); } }, bindMethods : function( c ) { var $table = c.$table, namespace = c.namespace, events = ( 'sortReset update updateRows updateAll updateHeaders addRows updateCell updateComplete ' + 'sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup ' + 'mouseleave ' ).split( ' ' ) .join( namespace + ' ' ); // apply easy methods that trigger bound events $table .unbind( events.replace( ts.regex.spaces, ' ' ) ) .bind( 'sortReset' + namespace, function( e, callback ) { e.stopPropagation(); // using this.config to ensure functions are getting a non-cached version of the config ts.sortReset( this.config, function( table ) { if (table.isApplyingWidgets) { // multiple triggers in a row... filterReset, then sortReset - see #1361 // wait to update widgets setTimeout( function() { ts.applyWidget( table, '', callback ); }, 100 ); } else { ts.applyWidget( table, '', callback ); } }); }) .bind( 'updateAll' + namespace, function( e, resort, callback ) { e.stopPropagation(); ts.updateAll( this.config, resort, callback ); }) .bind( 'update' + namespace + ' updateRows' + namespace, function( e, resort, callback ) { e.stopPropagation(); ts.update( this.config, resort, callback ); }) .bind( 'updateHeaders' + namespace, function( e, callback ) { e.stopPropagation(); ts.updateHeaders( this.config, callback ); }) .bind( 'updateCell' + namespace, function( e, cell, resort, callback ) { e.stopPropagation(); ts.updateCell( this.config, cell, resort, callback ); }) .bind( 'addRows' + namespace, function( e, $row, resort, callback ) { e.stopPropagation(); ts.addRows( this.config, $row, resort, callback ); }) .bind( 'updateComplete' + namespace, function() { this.isUpdating = false; }) .bind( 'sorton' + namespace, function( e, list, callback, init ) { e.stopPropagation(); ts.sortOn( this.config, list, callback, init ); }) .bind( 'appendCache' + namespace, function( e, callback, init ) { e.stopPropagation(); ts.appendCache( this.config, init ); if ( $.isFunction( callback ) ) { callback( this ); } }) // $tbodies variable is used by the tbody sorting widget .bind( 'updateCache' + namespace, function( e, callback, $tbodies ) { e.stopPropagation(); ts.updateCache( this.config, callback, $tbodies ); }) .bind( 'applyWidgetId' + namespace, function( e, id ) { e.stopPropagation(); ts.applyWidgetId( this, id ); }) .bind( 'applyWidgets' + namespace, function( e, callback ) { e.stopPropagation(); // apply widgets (false = not initializing) ts.applyWidget( this, false, callback ); }) .bind( 'refreshWidgets' + namespace, function( e, all, dontapply ) { e.stopPropagation(); ts.refreshWidgets( this, all, dontapply ); }) .bind( 'removeWidget' + namespace, function( e, name, refreshing ) { e.stopPropagation(); ts.removeWidget( this, name, refreshing ); }) .bind( 'destroy' + namespace, function( e, removeClasses, callback ) { e.stopPropagation(); ts.destroy( this, removeClasses, callback ); }) .bind( 'resetToLoadState' + namespace, function( e ) { e.stopPropagation(); // remove all widgets ts.removeWidget( this, true, false ); var tmp = $.extend( true, {}, c.originalSettings ); // restore original settings; this clears out current settings, but does not clear // values saved to storage. c = $.extend( true, {}, ts.defaults, tmp ); c.originalSettings = tmp; this.hasInitialized = false; // setup the entire table again ts.setup( this, c ); }); }, bindEvents : function( table, $headers, core ) { table = $( table )[ 0 ]; var tmp, c = table.config, namespace = c.namespace, downTarget = null; if ( core !== true ) { $headers.addClass( namespace.slice( 1 ) + '_extra_headers' ); tmp = ts.getClosest( $headers, 'table' ); if ( tmp.length && tmp[ 0 ].nodeName === 'TABLE' && tmp[ 0 ] !== table ) { $( tmp[ 0 ] ).addClass( namespace.slice( 1 ) + '_extra_table' ); } } tmp = ( c.pointerDown + ' ' + c.pointerUp + ' ' + c.pointerClick + ' sort keyup ' ) .replace( ts.regex.spaces, ' ' ) .split( ' ' ) .join( namespace + ' ' ); // apply event handling to headers and/or additional headers (stickyheaders, scroller, etc) $headers // http://stackoverflow.com/questions/5312849/jquery-find-self; .find( c.selectorSort ) .add( $headers.filter( c.selectorSort ) ) .unbind( tmp ) .bind( tmp, function( e, external ) { var $cell, cell, temp, $target = $( e.target ), // wrap event type in spaces, so the match doesn't trigger on inner words type = ' ' + e.type + ' '; // only recognize left clicks if ( ( ( e.which || e.button ) !== 1 && !type.match( ' ' + c.pointerClick + ' | sort | keyup ' ) ) || // allow pressing enter ( type === ' keyup ' && e.which !== ts.keyCodes.enter ) || // allow triggering a click event (e.which is undefined) & ignore physical clicks ( type.match( ' ' + c.pointerClick + ' ' ) && typeof e.which !== 'undefined' ) ) { return; } // ignore mouseup if mousedown wasn't on the same target if ( type.match( ' ' + c.pointerUp + ' ' ) && downTarget !== e.target && external !== true ) { return; } // set target on mousedown if ( type.match( ' ' + c.pointerDown + ' ' ) ) { downTarget = e.target; // preventDefault needed or jQuery v1.3.2 and older throws an // "Uncaught TypeError: handler.apply is not a function" error temp = $target.jquery.split( '.' ); if ( temp[ 0 ] === '1' && temp[ 1 ] < 4 ) { e.preventDefault(); } return; } downTarget = null; $cell = ts.getClosest( $( this ), '.' + ts.css.header ); // prevent sort being triggered on form elements if ( ts.regex.formElements.test( e.target.nodeName ) || // nosort class name, or elements within a nosort container $target.hasClass( c.cssNoSort ) || $target.parents( '.' + c.cssNoSort ).length > 0 || // disabled cell directly clicked $cell.hasClass( 'sorter-false' ) || // elements within a button $target.parents( 'button' ).length > 0 ) { return !c.cancelSelection; } if ( c.delayInit && ts.isEmptyObject( c.cache ) ) { ts.buildCache( c ); } // use column index from data-attribute or index of current row; fixes #1116 c.last.clickedIndex = $cell.attr( 'data-column' ) || $cell.index(); cell = c.$headerIndexed[ c.last.clickedIndex ][0]; if ( cell && !cell.sortDisabled ) { ts.initSort( c, cell, e ); } }); if ( c.cancelSelection ) { // cancel selection $headers .attr( 'unselectable', 'on' ) .bind( 'selectstart', false ) .css({ 'user-select' : 'none', 'MozUserSelect' : 'none' // not needed for jQuery 1.8+ }); } }, buildHeaders : function( c ) { var $temp, icon, timer, indx; c.headerList = []; c.headerContent = []; c.sortVars = []; if ( ts.debug(c, 'core') ) { timer = new Date(); } // children tr in tfoot - see issue #196 & #547 // don't pass table.config to computeColumnIndex here - widgets (math) pass it to "quickly" index tbody cells c.columns = ts.computeColumnIndex( c.$table.children( 'thead, tfoot' ).children( 'tr' ) ); // add icon if cssIcon option exists icon = c.cssIcon ? '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' : ''; // redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683 c.$headers = $( $.map( c.$table.find( c.selectorHeaders ), function( elem, index ) { var configHeaders, header, column, template, tmp, $elem = $( elem ); // ignore cell (don't add it to c.$headers) if row has ignoreRow class if ( ts.getClosest( $elem, 'tr' ).hasClass( c.cssIgnoreRow ) ) { return; } // transfer data-column to element if not th/td - #1459 if ( !/(th|td)/i.test( elem.nodeName ) ) { tmp = ts.getClosest( $elem, 'th, td' ); $elem.attr( 'data-column', tmp.attr( 'data-column' ) ); } // make sure to get header cell & not column indexed cell configHeaders = ts.getColumnData( c.table, c.headers, index, true ); // save original header content c.headerContent[ index ] = $elem.html(); // if headerTemplate is empty, don't reformat the header cell if ( c.headerTemplate !== '' && !$elem.find( '.' + ts.css.headerIn ).length ) { // set up header template template = c.headerTemplate .replace( ts.regex.templateContent, $elem.html() ) .replace( ts.regex.templateIcon, $elem.find( '.' + ts.css.icon ).length ? '' : icon ); if ( c.onRenderTemplate ) { header = c.onRenderTemplate.apply( $elem, [ index, template ] ); // only change t if something is returned if ( header && typeof header === 'string' ) { template = header; } } $elem.html( '<div class="' + ts.css.headerIn + '">' + template + '</div>' ); // faster than wrapInner } if ( c.onRenderHeader ) { c.onRenderHeader.apply( $elem, [ index, c, c.$table ] ); } column = parseInt( $elem.attr( 'data-column' ), 10 ); elem.column = column; tmp = ts.getOrder( ts.getData( $elem, configHeaders, 'sortInitialOrder' ) || c.sortInitialOrder ); // this may get updated numerous times if there are multiple rows c.sortVars[ column ] = { count : -1, // set to -1 because clicking on the header automatically adds one order : tmp ? ( c.sortReset ? [ 1, 0, 2 ] : [ 1, 0 ] ) : // desc, asc, unsorted ( c.sortReset ? [ 0, 1, 2 ] : [ 0, 1 ] ), // asc, desc, unsorted lockedOrder : false, sortedBy : '' }; tmp = ts.getData( $elem, configHeaders, 'lockedOrder' ) || false; if ( typeof tmp !== 'undefined' && tmp !== false ) { c.sortVars[ column ].lockedOrder = true; c.sortVars[ column ].order = ts.getOrder( tmp ) ? [ 1, 1 ] : [ 0, 0 ]; } // add cell to headerList c.headerList[ index ] = elem; $elem.addClass( ts.css.header + ' ' + c.cssHeader ); // add to parent in case there are multiple rows ts.getClosest( $elem, 'tr' ) .addClass( ts.css.headerRow + ' ' + c.cssHeaderRow ) .attr( 'role', 'row' ); // allow keyboard cursor to focus on element if ( c.tabIndex ) { $elem.attr( 'tabindex', 0 ); } return elem; }) ); // cache headers per column c.$headerIndexed = []; for ( indx = 0; indx < c.columns; indx++ ) { // colspan in header making a column undefined if ( ts.isEmptyObject( c.sortVars[ indx ] ) ) { c.sortVars[ indx ] = {}; } // Use c.$headers.parent() in case selectorHeaders doesn't point to the th/td $temp = c.$headers.filter( '[data-column="' + indx + '"]' ); // target sortable column cells, unless there are none, then use non-sortable cells // .last() added in jQuery 1.4; use .filter(':last') to maintain compatibility with jQuery v1.2.6 c.$headerIndexed[ indx ] = $temp.length ? $temp.not( '.sorter-false' ).length ? $temp.not( '.sorter-false' ).filter( ':last' ) : $temp.filter( ':last' ) : $(); } c.$table.find( c.selectorHeaders ).attr({ scope: 'col', role : 'columnheader' }); // enable/disable sorting ts.updateHeader( c ); if ( ts.debug(c, 'core') ) { console.log( 'Built headers:' + ts.benchmark( timer ) ); console.log( c.$headers ); } }, // Use it to add a set of methods to table.config which will be available for all tables. // This should be done before table initialization addInstanceMethods : function( methods ) { $.extend( ts.instanceMethods, methods ); }, /* █████▄ ▄████▄ █████▄ ▄█████ ██████ █████▄ ▄█████ ██▄▄██ ██▄▄██ ██▄▄██ ▀█▄ ██▄▄ ██▄▄██ ▀█▄ ██▀▀▀ ██▀▀██ ██▀██ ▀█▄ ██▀▀ ██▀██ ▀█▄ ██ ██ ██ ██ ██ █████▀ ██████ ██ ██ █████▀ */ setupParsers : function( c, $tbodies ) { var rows, list, span, max, colIndex, indx, header, configHeaders, noParser, parser, extractor, time, tbody, len, table = c.table, tbodyIndex = 0, debug = ts.debug(c, 'core'), debugOutput = {}; // update table bodies in case we start with an empty table c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' ); tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies; len = tbody.length; if ( len === 0 ) { return debug ? console.warn( 'Warning: *Empty table!* Not building a parser cache' ) : ''; } else if ( debug ) { time = new Date(); console[ console.group ? 'group' : 'log' ]( 'Detecting parsers for each column' ); } list = { extractors: [], parsers: [] }; while ( tbodyIndex < len ) { rows = tbody[ tbodyIndex ].rows; if ( rows.length ) { colIndex = 0; max = c.columns; for ( indx = 0; indx < max; indx++ ) { header = c.$headerIndexed[ colIndex ]; if ( header && header.length ) { // get column indexed table cell; adding true parameter fixes #1362 but // it would break backwards compatibility... configHeaders = ts.getColumnData( table, c.headers, colIndex ); // , true ); // get column parser/extractor extractor = ts.getParserById( ts.getData( header, configHeaders, 'extractor' ) ); parser = ts.getParserById( ts.getData( header, configHeaders, 'sorter' ) ); noParser = ts.getData( header, configHeaders, 'parser' ) === 'false'; // empty cells behaviour - keeping emptyToBottom for backwards compatibility c.empties[colIndex] = ( ts.getData( header, configHeaders, 'empty' ) || c.emptyTo || ( c.emptyToBottom ? 'bottom' : 'top' ) ).toLowerCase(); // text strings behaviour in numerical sorts c.strings[colIndex] = ( ts.getData( header, configHeaders, 'string' ) || c.stringTo || 'max' ).toLowerCase(); if ( noParser ) { parser = ts.getParserById( 'no-parser' ); } if ( !extractor ) { // For now, maybe detect someday extractor = false; } if ( !parser ) { parser = ts.detectParserForColumn( c, rows, -1, colIndex ); } if ( debug ) { debugOutput[ '(' + colIndex + ') ' + header.text() ] = { parser : parser.id, extractor : extractor ? extractor.id : 'none', string : c.strings[ colIndex ], empty : c.empties[ colIndex ] }; } list.parsers[ colIndex ] = parser; list.extractors[ colIndex ] = extractor; span = header[ 0 ].colSpan - 1; if ( span > 0 ) { colIndex += span; max += span; while ( span + 1 > 0 ) { // set colspan columns to use the same parsers & extractors list.parsers[ colIndex - span ] = parser; list.extractors[ colIndex - span ] = extractor; span--; } } } colIndex++; } } tbodyIndex += ( list.parsers.length ) ? len : 1; } if ( debug ) { if ( !ts.isEmptyObject( debugOutput ) ) { console[ console.table ? 'table' : 'log' ]( debugOutput ); } else { console.warn( ' No parsers detected!' ); } console.log( 'Completed detecting parsers' + ts.benchmark( time ) ); if ( console.groupEnd ) { console.groupEnd(); } } c.parsers = list.parsers; c.extractors = list.extractors; }, addParser : function( parser ) { var indx, len = ts.parsers.length, add = true; for ( indx = 0; indx < len; indx++ ) { if ( ts.parsers[ indx ].id.toLowerCase() === parser.id.toLowerCase() ) { add = false; } } if ( add ) { ts.parsers[ ts.parsers.length ] = parser; } }, getParserById : function( name ) { /*jshint eqeqeq:false */ // eslint-disable-next-line eqeqeq if ( name == 'false' ) { return false; } var indx, len = ts.parsers.length; for ( indx = 0; indx < len; indx++ ) { if ( ts.parsers[ indx ].id.toLowerCase() === ( name.toString() ).toLowerCase() ) { return ts.parsers[ indx ]; } } return false; }, detectParserForColumn : function( c, rows, rowIndex, cellIndex ) { var cur, $node, row, indx = ts.parsers.length, node = false, nodeValue = '', debug = ts.debug(c, 'core'), keepLooking = true; while ( nodeValue === '' && keepLooking ) { rowIndex++; row = rows[ rowIndex ]; // stop looking after 50 empty rows if ( row && rowIndex < 50 ) { if ( row.className.indexOf( ts.cssIgnoreRow ) < 0 ) { node = rows[ rowIndex ].cells[ cellIndex ]; nodeValue = ts.getElementText( c, node, cellIndex ); $node = $( node ); if ( debug ) { console.log( 'Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': "' + nodeValue + '"' ); } } } else { keepLooking = false; } } while ( --indx >= 0 ) { cur = ts.parsers[ indx ]; // ignore the default text parser because it will always be true if ( cur && cur.id !== 'text' && cur.is && cur.is( nodeValue, c.table, node, $node ) ) { return cur; } } // nothing found, return the generic parser (text) return ts.getParserById( 'text' ); }, getElementText : function( c, node, cellIndex ) { if ( !node ) { return ''; } var tmp, extract = c.textExtraction || '', // node could be a jquery object // http://jsperf.com/jquery-vs-instanceof-jquery/2 $node = node.jquery ? node : $( node ); if ( typeof extract === 'string' ) { // check data-attribute first when set to 'basic'; don't use node.innerText - it's really slow! // http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/ if ( extract === 'basic' && typeof ( tmp = $node.attr( c.textAttribute ) ) !== 'undefined' ) { return $.trim( tmp ); } return $.trim( node.textContent || $node.text() ); } else { if ( typeof extract === 'function' ) { return $.trim( extract( $node[ 0 ], c.table, cellIndex ) ); } else if ( typeof ( tmp = ts.getColumnData( c.table, extract, cellIndex ) ) === 'function' ) { return $.trim( tmp( $node[ 0 ], c.table, cellIndex ) ); } } // fallback return $.trim( $node[ 0 ].textContent || $node.text() ); }, // centralized function to extract/parse cell contents getParsedText : function( c, cell, colIndex, txt ) { if ( typeof txt === 'undefined' ) { txt = ts.getElementText( c, cell, colIndex ); } // if no parser, make sure to return the txt var val = '' + txt, parser = c.parsers[ colIndex ], extractor = c.extractors[ colIndex ]; if ( parser ) { // do extract before parsing, if there is one if ( extractor && typeof extractor.format === 'function' ) { txt = extractor.format( txt, c.table, cell, colIndex ); } // allow parsing if the string is empty, previously parsing would change it to zero, // in case the parser needs to extract data from the table cell attributes val = parser.id === 'no-parser' ? '' : // make sure txt is a string (extractor may have converted it) parser.format( '' + txt, c.table, cell, colIndex ); if ( c.ignoreCase && typeof val === 'string' ) { val = val.toLowerCase(); } } return val; }, /* ▄████▄ ▄████▄ ▄████▄ ██ ██ ██████ ██ ▀▀ ██▄▄██ ██ ▀▀ ██▄▄██ ██▄▄ ██ ▄▄ ██▀▀██ ██ ▄▄ ██▀▀██ ██▀▀ ▀████▀ ██ ██ ▀████▀ ██ ██ ██████ */ buildCache : function( c, callback, $tbodies ) { var cache, val, txt, rowIndex, colIndex, tbodyIndex, $tbody, $row, cols, $cells, cell, cacheTime, totalRows, rowData, prevRowData, colMax, span, cacheIndex, hasParser, max, len, index, table = c.table, parsers = c.parsers, debug = ts.debug(c, 'core'); // update tbody variable c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' ); $tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies, c.cache = {}; c.totalRows = 0; // if no parsers found, return - it's an empty table. if ( !parsers ) { return debug ? console.warn( 'Warning: *Empty table!* Not building a cache' ) : ''; } if ( debug ) { cacheTime = new Date(); } // processing icon if ( c.showProcessing ) { ts.isProcessing( table, true ); } for ( tbodyIndex = 0; tbodyIndex < $tbody.length; tbodyIndex++ ) { colMax = []; // column max value per tbody cache = c.cache[ tbodyIndex ] = { normalized: [] // array of normalized row data; last entry contains 'rowData' above // colMax: # // added at the end }; totalRows = ( $tbody[ tbodyIndex ] && $tbody[ tbodyIndex ].rows.length ) || 0; for ( rowIndex = 0; rowIndex < totalRows; ++rowIndex ) { rowData = { // order: original row order # // $row : jQuery Object[] child: [], // child row text (filter widget) raw: [] // original row text }; /** Add the table data to main data array */ $row = $( $tbody[ tbodyIndex ].rows[ rowIndex ] ); cols = []; // ignore "remove-me" rows if ( $row.hasClass( c.selectorRemove.slice(1) ) ) { continue; } // if this is a child row, add it to the last row's children and continue to the next row // ignore child row class, if it is the first row if ( $row.hasClass( c.cssChildRow ) && rowIndex !== 0 ) { len = cache.normalized.length - 1; prevRowData = cache.normalized[ len ][ c.columns ]; prevRowData.$row = prevRowData.$row.add( $row ); // add 'hasChild' class name to parent row if ( !$row.prev().hasClass( c.cssChildRow ) ) { $row.prev().addClass( ts.css.cssHasChild ); } // save child row content (un-parsed!) $cells = $row.children( 'th, td' ); len = prevRowData.child.length; prevRowData.child[ len ] = []; // child row content does not account for colspans/rowspans; so indexing may be off cacheIndex = 0; max = c.columns; for ( colIndex = 0; colIndex < max; colIndex++ ) { cell = $cells[ colIndex ]; if ( cell ) { prevRowData.child[ len ][ colIndex ] = ts.getParsedText( c, cell, colIndex ); span = $cells[ colIndex ].colSpan - 1; if ( span > 0 ) { cacheIndex += span; max += span; } } cacheIndex++; } // go to the next for loop continue; } rowData.$row = $row; rowData.order = rowIndex; // add original row position to rowCache cacheIndex = 0; max = c.columns; for ( colIndex = 0; colIndex < max; ++colIndex ) { cell = $row[ 0 ].cells[ colIndex ]; if ( cell && cacheIndex < c.columns ) { hasParser = typeof parsers[ cacheIndex ] !== 'undefined'; if ( !hasParser && debug ) { console.warn( 'No parser found for row: ' + rowIndex + ', column: ' + colIndex + '; cell containing: "' + $(cell).text() + '"; does it have a header?' ); } val = ts.getElementText( c, cell, cacheIndex ); rowData.raw[ cacheIndex ] = val; // save original row text // save raw column text even if there is no parser set txt = ts.getParsedText( c, cell, cacheIndex, val ); cols[ cacheIndex ] = txt; if ( hasParser && ( parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) { // determine column max value (ignore sign) colMax[ cacheIndex ] = Math.max( Math.abs( txt ) || 0, colMax[ cacheIndex ] || 0 ); } // allow colSpan in tbody span = cell.colSpan - 1; if ( span > 0 ) { index = 0; while ( index <= span ) { // duplicate text (or not) to spanned columns // instead of setting duplicate span to empty string, use textExtraction to try to get a value // see http://stackoverflow.com/q/36449711/145346 txt = c.duplicateSpan || index === 0 ? txt : typeof c.textExtraction !== 'string' ? ts.getElementText( c, cell, cacheIndex + index ) || '' : ''; rowData.raw[ cacheIndex + index ] = txt; cols[ cacheIndex + index ] = txt; index++; } cacheIndex += span; max += span; } } cacheIndex++; } // ensure rowData is always in the same location (after the last column) cols[ c.columns ] = rowData; cache.normalized[ cache.normalized.length ] = cols; } cache.colMax = colMax; // total up rows, not including child rows c.totalRows += cache.normalized.length; } if ( c.showProcessing ) { ts.isProcessing( table ); // remove processing icon } if ( debug ) { len = Math.min( 5, c.cache[ 0 ].normalized.length ); console[ console.group ? 'group' : 'log' ]( 'Building cache for ' + c.totalRows + ' rows (showing ' + len + ' rows in log) and ' + c.columns + ' columns' + ts.benchmark( cacheTime ) ); val = {}; for ( colIndex = 0; colIndex < c.columns; colIndex++ ) { for ( cacheIndex = 0; cacheIndex < len; cacheIndex++ ) { if ( !val[ 'row: ' + cacheIndex ] ) { val[ 'row: ' + cacheIndex ] = {}; } val[ 'row: ' + cacheIndex ][ c.$headerIndexed[ colIndex ].text() ] = c.cache[ 0 ].normalized[ cacheIndex ][ colIndex ]; } } console[ console.table ? 'table' : 'log' ]( val ); if ( console.groupEnd ) { console.groupEnd(); } } if ( $.isFunction( callback ) ) { callback( table ); } }, getColumnText : function( table, column, callback, rowFilter ) { table = $( table )[0]; var tbodyIndex, rowIndex, cache, row, tbodyLen, rowLen, raw, parsed, $cell, result, hasCallback = typeof callback === 'function', allColumns = column === 'all', data = { raw : [], parsed: [], $cell: [] }, c = table.config; if ( ts.isEmptyObject( c ) ) { if ( ts.debug(c, 'core') ) { console.warn( 'No cache found - aborting getColumnText function!' ); } } else { tbodyLen = c.$tbodies.length; for ( tbodyIndex = 0; tbodyIndex < tbodyLen; tbodyIndex++ ) { cache = c.cache[ tbodyIndex ].normalized; rowLen = cache.length; for ( rowIndex = 0; rowIndex < rowLen; rowIndex++ ) { row = cache[ rowIndex ]; if ( rowFilter && !row[ c.columns ].$row.is( rowFilter ) ) { continue; } result = true; parsed = ( allColumns ) ? row.slice( 0, c.columns ) : row[ column ]; row = row[ c.columns ]; raw = ( allColumns ) ? row.raw : row.raw[ column ]; $cell = ( allColumns ) ? row.$row.children() : row.$row.children().eq( column ); if ( hasCallback ) { result = callback({ tbodyIndex : tbodyIndex, rowIndex : rowIndex, parsed : parsed, raw : raw, $row : row.$row, $cell : $cell }); } if ( result !== false ) { data.parsed[ data.parsed.length ] = parsed; data.raw[ data.raw.length ] = raw; data.$cell[ data.$cell.length ] = $cell; } } } // return everything return data; } }, /* ██ ██ █████▄ █████▄ ▄████▄ ██████ ██████ ██ ██ ██▄▄██ ██ ██ ██▄▄██ ██ ██▄▄ ██ ██ ██▀▀▀ ██ ██ ██▀▀██ ██ ██▀▀ ▀████▀ ██ █████▀ ██ ██ ██ ██████ */ setHeadersCss : function( c ) { var indx, column, list = c.sortList, len = list.length, none = ts.css.sortNone + ' ' + c.cssNone, css = [ ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc ], cssIcon = [ c.cssIconAsc, c.cssIconDesc, c.cssIconNone ], aria = [ 'ascending', 'descending' ], updateColumnSort = function($el, index) { $el .removeClass( none ) .addClass( css[ index ] ) .attr( 'aria-sort', aria[ index ] ) .find( '.' + ts.css.icon ) .removeClass( cssIcon[ 2 ] ) .addClass( cssIcon[ index ] ); }, // find the footer $extras = c.$table .find( 'tfoot tr' ) .children( 'td, th' ) .add( $( c.namespace + '_extra_headers' ) ) .removeClass( css.join( ' ' ) ), // remove all header information $sorted = c.$headers .add( $( 'thead ' + c.namespace + '_extra_headers' ) ) .removeClass( css.join( ' ' ) ) .addClass( none ) .attr( 'aria-sort', 'none' ) .find( '.' + ts.css.icon ) .removeClass( cssIcon.join( ' ' ) ) .end(); // add css none to all sortable headers $sorted .not( '.sorter-false' ) .find( '.' + ts.css.icon ) .addClass( cssIcon[ 2 ] ); // add disabled css icon class if ( c.cssIconDisabled ) { $sorted .filter( '.sorter-false' ) .find( '.' + ts.css.icon ) .addClass( c.cssIconDisabled ); } for ( indx = 0; indx < len; indx++ ) { // direction = 2 means reset! if ( list[ indx ][ 1 ] !== 2 ) { // multicolumn sorting updating - see #1005 // .not(function() {}) needs jQuery 1.4 // filter(function(i, el) {}) <- el is undefined in jQuery v1.2.6 $sorted = c.$headers.filter( function( i ) { // only include headers that are in the sortList (this includes colspans) var include = true, $el = c.$headers.eq( i ), col = parseInt( $el.attr( 'data-column' ), 10 ), end = col + ts.getClosest( $el, 'th, td' )[0].colSpan; for ( ; col < end; col++ ) { include = include ? include || ts.isValueInArray( col, c.sortList ) > -1 : false; } return include; }); // choose the :last in case there are nested columns $sorted = $sorted .not( '.sorter-false' ) .filter( '[data-column="' + list[ indx ][ 0 ] + '"]' + ( len === 1 ? ':last' : '' ) ); if ( $sorted.length ) { for ( column = 0; column < $sorted.length; column++ ) { if ( !$sorted[ column ].sortDisabled ) { updateColumnSort( $sorted.eq( column ), list[ indx ][ 1 ] ); } } } // add sorted class to footer & extra headers, if they exist if ( $extras.length ) { updateColumnSort( $extras.filter( '[data-column="' + list[ indx ][ 0 ] + '"]' ), list[ indx ][ 1 ] ); } } } // add verbose aria labels len = c.$headers.length; for ( indx = 0; indx < len; indx++ ) { ts.setColumnAriaLabel( c, c.$headers.eq( indx ) ); } }, getClosest : function( $el, selector ) { // jQuery v1.2.6 doesn't have closest() if ( $.fn.closest ) { return $el.closest( selector ); } return $el.is( selector ) ? $el : $el.parents( selector ).filter( ':first' ); }, // nextSort (optional), lets you disable next sort text setColumnAriaLabel : function( c, $header, nextSort ) { if ( $header.length ) { var column = parseInt( $header.attr( 'data-column' ), 10 ), vars = c.sortVars[ column ], tmp = $header.hasClass( ts.css.sortAsc ) ? 'sortAsc' : $header.hasClass( ts.css.sortDesc ) ? 'sortDesc' : 'sortNone', txt = $.trim( $header.text() ) + ': ' + ts.language[ tmp ]; if ( $header.hasClass( 'sorter-false' ) || nextSort === false ) { txt += ts.language.sortDisabled; } else { tmp = ( vars.count + 1 ) % vars.order.length; nextSort = vars.order[ tmp ]; // if nextSort txt += ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ]; } $header.attr( 'aria-label', txt ); if (vars.sortedBy) { $header.attr( 'data-sortedBy', vars.sortedBy ); } else { $header.removeAttr('data-sortedBy'); } } }, updateHeader : function( c ) { var index, isDisabled, $header, col, table = c.table, len = c.$headers.length; for ( index = 0; index < len; index++ ) { $header = c.$headers.eq( index ); col = ts.getColumnData( table, c.headers, index, true ); // add 'sorter-false' class if 'parser-false' is set isDisabled = ts.getData( $header, col, 'sorter' ) === 'false' || ts.getData( $header, col, 'parser' ) === 'false'; ts.setColumnSort( c, $header, isDisabled ); } }, setColumnSort : function( c, $header, isDisabled ) { var id = c.table.id; $header[ 0 ].sortDisabled = isDisabled; $header[ isDisabled ? 'addClass' : 'removeClass' ]( 'sorter-false' ) .attr( 'aria-disabled', '' + isDisabled ); // disable tab index on disabled cells if ( c.tabIndex ) { if ( isDisabled ) { $header.removeAttr( 'tabindex' ); } else { $header.attr( 'tabindex', '0' ); } } // aria-controls - requires table ID if ( id ) { if ( isDisabled ) { $header.removeAttr( 'aria-controls' ); } else { $header.attr( 'aria-controls', id ); } } }, updateHeaderSortCount : function( c, list ) { var col, dir, group, indx, primary, temp, val, order, sortList = list || c.sortList, len = sortList.length; c.sortList = []; for ( indx = 0; indx < len; indx++ ) { val = sortList[ indx ]; // ensure all sortList values are numeric - fixes #127 col = parseInt( val[ 0 ], 10 ); // prevents error if sorton array is wrong if ( col < c.columns ) { // set order if not already defined - due to colspan header without associated header cell // adding this check prevents a javascript error if ( !c.sortVars[ col ].order ) { if ( ts.getOrder( c.sortInitialOrder ) ) { order = c.sortReset ? [ 1, 0, 2 ] : [ 1, 0 ]; } else { order = c.sortReset ? [ 0, 1, 2 ] : [ 0, 1 ]; } c.sortVars[ col ].order = order; c.sortVars[ col ].count = 0; } order = c.sortVars[ col ].order; dir = ( '' + val[ 1 ] ).match( /^(1|d|s|o|n)/ ); dir = dir ? dir[ 0 ] : ''; // 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext switch ( dir ) { case '1' : case 'd' : // descending dir = 1; break; case '