TableSorter

Client-side table sorting with ease

当前为 2015-11-03 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/5844/84286/TableSorter.js

  1. /*! TableSorter (FORK) v2.24.2 *//*
  2. * Client-side table sorting with ease!
  3. * @requires jQuery v1.2.6+
  4. *
  5. * Copyright (c) 2007 Christian Bach
  6. * fork maintained by Rob Garrison
  7. *
  8. * Examples and docs at: http://tablesorter.com
  9. * Dual licensed under the MIT and GPL licenses:
  10. * http://www.opensource.org/licenses/mit-license.php
  11. * http://www.gnu.org/licenses/gpl.html
  12. *
  13. * @type jQuery
  14. * @name tablesorter (FORK)
  15. * @cat Plugins/Tablesorter
  16. * @author Christian Bach - christian.bach@polyester.se
  17. * @contributor Rob Garrison - https://github.com/Mottie/tablesorter
  18. */
  19. /*jshint browser:true, jquery:true, unused:false, expr: true */
  20. ;( function( $ ) {
  21. 'use strict';
  22. var ts = $.tablesorter = {
  23.  
  24. version : '2.24.2',
  25.  
  26. parsers : [],
  27. widgets : [],
  28. defaults : {
  29.  
  30. // *** appearance
  31. theme : 'default', // adds tablesorter-{theme} to the table for styling
  32. widthFixed : false, // adds colgroup to fix widths of columns
  33. showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered.
  34.  
  35. headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> // class from cssIcon
  36. onRenderTemplate : null, // function( index, template ){ return template; }, // template is a string
  37. onRenderHeader : null, // function( index ){}, // nothing to return
  38.  
  39. // *** functionality
  40. cancelSelection : true, // prevent text selection in the header
  41. tabIndex : true, // add tabindex to header for keyboard accessibility
  42. dateFormat : 'mmddyyyy', // other options: 'ddmmyyy' or 'yyyymmdd'
  43. sortMultiSortKey : 'shiftKey', // key used to select additional columns
  44. sortResetKey : 'ctrlKey', // key used to remove sorting on a column
  45. usNumberFormat : true, // false for German '1.234.567,89' or French '1 234 567,89'
  46. delayInit : false, // if false, the parsed table contents will not update until the first sort
  47. 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.
  48. resort : true, // default setting to trigger a resort after an 'update', 'addRows', 'updateCell', etc has completed
  49.  
  50. // *** sort options
  51. headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc.
  52. ignoreCase : true, // ignore case while sorting
  53. sortForce : null, // column(s) first sorted; always applied
  54. sortList : [], // Initial sort order; applied initially; updated when manually sorted
  55. sortAppend : null, // column(s) sorted last; always applied
  56. sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained
  57.  
  58. sortInitialOrder : 'asc', // sort direction on first click
  59. sortLocaleCompare: false, // replace equivalent character (accented characters)
  60. sortReset : false, // third click on the header will reset column to default - unsorted
  61. sortRestart : false, // restart sort to 'sortInitialOrder' when clicking on previously unsorted columns
  62.  
  63. emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero, emptyMax, emptyMin
  64. stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero
  65. textExtraction : 'basic', // text extraction method/function - function( node, table, cellIndex ){}
  66. textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in default textExtraction function)
  67. textSorter : null, // choose overall or specific column sorter function( a, b, direction, table, columnIndex ) [alt: ts.sortText]
  68. numberSorter : null, // choose overall numeric sorter function( a, b, direction, maxColumnValue )
  69.  
  70. // *** widget options
  71. widgets: [], // method to add widgets, e.g. widgets: ['zebra']
  72. widgetOptions : {
  73. zebra : [ 'even', 'odd' ] // zebra widget alternating row class names
  74. },
  75. initWidgets : true, // apply widgets on tablesorter initialization
  76. widgetClass : 'widget-{name}', // table class name template to match to include a widget
  77.  
  78. // *** callbacks
  79. initialized : null, // function( table ){},
  80.  
  81. // *** extra css class names
  82. tableClass : '',
  83. cssAsc : '',
  84. cssDesc : '',
  85. cssNone : '',
  86. cssHeader : '',
  87. cssHeaderRow : '',
  88. cssProcessing : '', // processing icon applied to header during sort/filter
  89.  
  90. cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent
  91. cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!)
  92. cssNoSort : 'tablesorter-noSort', // class name added to element inside header; clicking on it won't cause a sort
  93. cssIgnoreRow : 'tablesorter-ignoreRow', // header row to ignore; cells within this row will not be added to c.$headers
  94.  
  95. cssIcon : 'tablesorter-icon', // if this class does not exist, the {icon} will not be added from the headerTemplate
  96. cssIconNone : '', // class name added to the icon when there is no column sort
  97. cssIconAsc : '', // class name added to the icon when the column has an ascending sort
  98. cssIconDesc : '', // class name added to the icon when the column has a descending sort
  99.  
  100. // *** events
  101. pointerClick : 'click',
  102. pointerDown : 'mousedown',
  103. pointerUp : 'mouseup',
  104.  
  105. // *** selectors
  106. selectorHeaders : '> thead th, > thead td',
  107. selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort
  108. selectorRemove : '.remove-me',
  109.  
  110. // *** advanced
  111. debug : false,
  112.  
  113. // *** Internal variables
  114. headerList: [],
  115. empties: {},
  116. strings: {},
  117. parsers: []
  118.  
  119. // removed: widgetZebra: { css: ['even', 'odd'] }
  120.  
  121. },
  122.  
  123. // internal css classes - these will ALWAYS be added to
  124. // the table and MUST only contain one class name - fixes #381
  125. css : {
  126. table : 'tablesorter',
  127. cssHasChild: 'tablesorter-hasChildRow',
  128. childRow : 'tablesorter-childRow',
  129. colgroup : 'tablesorter-colgroup',
  130. header : 'tablesorter-header',
  131. headerRow : 'tablesorter-headerRow',
  132. headerIn : 'tablesorter-header-inner',
  133. icon : 'tablesorter-icon',
  134. processing : 'tablesorter-processing',
  135. sortAsc : 'tablesorter-headerAsc',
  136. sortDesc : 'tablesorter-headerDesc',
  137. sortNone : 'tablesorter-headerUnSorted'
  138. },
  139.  
  140. // labels applied to sortable headers for accessibility (aria) support
  141. language : {
  142. sortAsc : 'Ascending sort applied, ',
  143. sortDesc : 'Descending sort applied, ',
  144. sortNone : 'No sort applied, ',
  145. nextAsc : 'activate to apply an ascending sort',
  146. nextDesc : 'activate to apply a descending sort',
  147. nextNone : 'activate to remove the sort'
  148. },
  149.  
  150. regex : {
  151. templateContent : /\{content\}/g,
  152. templateIcon : /\{icon\}/g,
  153. templateName : /\{name\}/i,
  154. spaces : /\s+/g,
  155. nonWord : /\W/g,
  156. formElements : /(input|select|button|textarea)/i,
  157.  
  158. // *** sort functions ***
  159. // regex used in natural sort
  160. // chunk/tokenize numbers & letters
  161. chunk : /(^([+\-]?(?:\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,
  162. // replace chunks @ ends
  163. chunks : /(^\\0|\\0$)/,
  164. hex : /^0x[0-9a-f]+$/i,
  165.  
  166. // *** formatFloat ***
  167. comma : /,/g,
  168. digitNonUS : /[\s|\.]/g,
  169. digitNegativeTest : /^\s*\([.\d]+\)/,
  170. digitNegativeReplace : /^\s*\(([.\d]+)\)/,
  171.  
  172. // *** isDigit ***
  173. digitTest : /^[\-+(]?\d+[)]?$/,
  174. digitReplace : /[,.'"\s]/g
  175.  
  176. },
  177.  
  178. // digit sort text location; keeping max+/- for backwards compatibility
  179. string : {
  180. max : 1,
  181. min : -1,
  182. emptymin : 1,
  183. emptymax : -1,
  184. zero : 0,
  185. none : 0,
  186. 'null' : 0,
  187. top : true,
  188. bottom : false
  189. },
  190.  
  191. // These methods can be applied on table.config instance
  192. instanceMethods : {},
  193.  
  194. /*
  195. ▄█████ ██████ ██████ ██ ██ █████▄
  196. ▀█▄ ██▄▄ ██ ██ ██ ██▄▄██
  197. ▀█▄ ██▀▀ ██ ██ ██ ██▀▀▀
  198. █████▀ ██████ ██ ▀████▀ ██
  199. */
  200.  
  201. setup : function( table, c ) {
  202. // if no thead or tbody, or tablesorter is already present, quit
  203. if ( !table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true ) {
  204. if ( c.debug ) {
  205. if ( table.hasInitialized ) {
  206. console.warn( 'Stopping initialization. Tablesorter has already been initialized' );
  207. } else {
  208. console.error( 'Stopping initialization! No table, thead or tbody' );
  209. }
  210. }
  211. return;
  212. }
  213.  
  214. var tmp = '',
  215. $table = $( table ),
  216. meta = $.metadata;
  217. // initialization flag
  218. table.hasInitialized = false;
  219. // table is being processed flag
  220. table.isProcessing = true;
  221. // make sure to store the config object
  222. table.config = c;
  223. // save the settings where they read
  224. $.data( table, 'tablesorter', c );
  225. if ( c.debug ) {
  226. console[ console.group ? 'group' : 'log' ]( 'Initializing tablesorter' );
  227. $.data( table, 'startoveralltimer', new Date() );
  228. }
  229.  
  230. // removing this in version 3 (only supports jQuery 1.7+)
  231. c.supportsDataObject = ( function( version ) {
  232. version[ 0 ] = parseInt( version[ 0 ], 10 );
  233. return ( version[ 0 ] > 1 ) || ( version[ 0 ] === 1 && parseInt( version[ 1 ], 10 ) >= 4 );
  234. })( $.fn.jquery.split( '.' ) );
  235. // ensure case insensitivity
  236. c.emptyTo = c.emptyTo.toLowerCase();
  237. c.stringTo = c.stringTo.toLowerCase();
  238. c.last = { sortList : [], clickedIndex : -1 };
  239. // add table theme class only if there isn't already one there
  240. if ( !/tablesorter\-/.test( $table.attr( 'class' ) ) ) {
  241. tmp = ( c.theme !== '' ? ' tablesorter-' + c.theme : '' );
  242. }
  243. c.table = table;
  244. c.$table = $table
  245. .addClass( ts.css.table + ' ' + c.tableClass + tmp )
  246. .attr( 'role', 'grid' );
  247. c.$headers = $table.find( c.selectorHeaders );
  248.  
  249. // give the table a unique id, which will be used in namespace binding
  250. if ( !c.namespace ) {
  251. c.namespace = '.tablesorter' + Math.random().toString( 16 ).slice( 2 );
  252. } else {
  253. // make sure namespace starts with a period & doesn't have weird characters
  254. c.namespace = '.' + c.namespace.replace( ts.regex.nonWord, '' );
  255. }
  256.  
  257. c.$table.children().children( 'tr' ).attr( 'role', 'row' );
  258. c.$tbodies = $table.children( 'tbody:not(.' + c.cssInfoBlock + ')' ).attr({
  259. 'aria-live' : 'polite',
  260. 'aria-relevant' : 'all'
  261. });
  262. if ( c.$table.children( 'caption' ).length ) {
  263. tmp = c.$table.children( 'caption' )[ 0 ];
  264. if ( !tmp.id ) { tmp.id = c.namespace.slice( 1 ) + 'caption'; }
  265. c.$table.attr( 'aria-labelledby', tmp.id );
  266. }
  267. c.widgetInit = {}; // keep a list of initialized widgets
  268. // change textExtraction via data-attribute
  269. c.textExtraction = c.$table.attr( 'data-text-extraction' ) || c.textExtraction || 'basic';
  270. // build headers
  271. ts.buildHeaders( c );
  272. // fixate columns if the users supplies the fixedWidth option
  273. // do this after theme has been applied
  274. ts.fixColumnWidth( table );
  275. // add widgets from class name
  276. ts.addWidgetFromClass( table );
  277. // add widget options before parsing (e.g. grouping widget has parser settings)
  278. ts.applyWidgetOptions( table );
  279. // try to auto detect column type, and store in tables config
  280. ts.setupParsers( c );
  281. // start total row count at zero
  282. c.totalRows = 0;
  283. // build the cache for the tbody cells
  284. // delayInit will delay building the cache until the user starts a sort
  285. if ( !c.delayInit ) { ts.buildCache( c ); }
  286. // bind all header events and methods
  287. ts.bindEvents( table, c.$headers, true );
  288. ts.bindMethods( c );
  289. // get sort list from jQuery data or metadata
  290. // in jQuery < 1.4, an error occurs when calling $table.data()
  291. if ( c.supportsDataObject && typeof $table.data().sortlist !== 'undefined' ) {
  292. c.sortList = $table.data().sortlist;
  293. } else if ( meta && ( $table.metadata() && $table.metadata().sortlist ) ) {
  294. c.sortList = $table.metadata().sortlist;
  295. }
  296. // apply widget init code
  297. ts.applyWidget( table, true );
  298. // if user has supplied a sort list to constructor
  299. if ( c.sortList.length > 0 ) {
  300. ts.sortOn( c, c.sortList, {}, !c.initWidgets );
  301. } else {
  302. ts.setHeadersCss( c );
  303. if ( c.initWidgets ) {
  304. // apply widget format
  305. ts.applyWidget( table, false );
  306. }
  307. }
  308.  
  309. // show processesing icon
  310. if ( c.showProcessing ) {
  311. $table
  312. .unbind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace )
  313. .bind( 'sortBegin' + c.namespace + ' sortEnd' + c.namespace, function( e ) {
  314. clearTimeout( c.processTimer );
  315. ts.isProcessing( table );
  316. if ( e.type === 'sortBegin' ) {
  317. c.processTimer = setTimeout( function() {
  318. ts.isProcessing( table, true );
  319. }, 500 );
  320. }
  321. });
  322. }
  323.  
  324. // initialized
  325. table.hasInitialized = true;
  326. table.isProcessing = false;
  327. if ( c.debug ) {
  328. console.log( 'Overall initialization time: ' + ts.benchmark( $.data( table, 'startoveralltimer' ) ) );
  329. if ( c.debug && console.groupEnd ) { console.groupEnd(); }
  330. }
  331. $table.trigger( 'tablesorter-initialized', table );
  332. if ( typeof c.initialized === 'function' ) {
  333. c.initialized( table );
  334. }
  335. },
  336.  
  337. bindMethods : function( c ) {
  338. var $table = c.$table,
  339. namespace = c.namespace,
  340. events = ( 'sortReset update updateRows updateAll updateHeaders addRows updateCell updateComplete ' +
  341. 'sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup ' +
  342. 'mouseleave ' ).split( ' ' )
  343. .join( namespace + ' ' );
  344. // apply easy methods that trigger bound events
  345. $table
  346. .unbind( events.replace( ts.regex.spaces, ' ' ) )
  347. .bind( 'sortReset' + namespace, function( e, callback ) {
  348. e.stopPropagation();
  349. // using this.config to ensure functions are getting a non-cached version of the config
  350. ts.sortReset( this.config, callback );
  351. })
  352. .bind( 'updateAll' + namespace, function( e, resort, callback ) {
  353. e.stopPropagation();
  354. ts.updateAll( this.config, resort, callback );
  355. })
  356. .bind( 'update' + namespace + ' updateRows' + namespace, function( e, resort, callback ) {
  357. e.stopPropagation();
  358. ts.update( this.config, resort, callback );
  359. })
  360. .bind( 'updateHeaders' + namespace, function( e, callback ) {
  361. e.stopPropagation();
  362. ts.updateHeaders( this.config, callback );
  363. })
  364. .bind( 'updateCell' + namespace, function( e, cell, resort, callback ) {
  365. e.stopPropagation();
  366. ts.updateCell( this.config, cell, resort, callback );
  367. })
  368. .bind( 'addRows' + namespace, function( e, $row, resort, callback ) {
  369. e.stopPropagation();
  370. ts.addRows( this.config, $row, resort, callback );
  371. })
  372. .bind( 'updateComplete' + namespace, function() {
  373. this.isUpdating = false;
  374. })
  375. .bind( 'sorton' + namespace, function( e, list, callback, init ) {
  376. e.stopPropagation();
  377. ts.sortOn( this.config, list, callback, init );
  378. })
  379. .bind( 'appendCache' + namespace, function( e, callback, init ) {
  380. e.stopPropagation();
  381. ts.appendCache( this.config, init );
  382. if ( $.isFunction( callback ) ) {
  383. callback( this );
  384. }
  385. })
  386. // $tbodies variable is used by the tbody sorting widget
  387. .bind( 'updateCache' + namespace, function( e, callback, $tbodies ) {
  388. e.stopPropagation();
  389. ts.updateCache( this.config, callback, $tbodies );
  390. })
  391. .bind( 'applyWidgetId' + namespace, function( e, id ) {
  392. e.stopPropagation();
  393. ts.getWidgetById( id ).format( this, this.config, this.config.widgetOptions );
  394. })
  395. .bind( 'applyWidgets' + namespace, function( e, init ) {
  396. e.stopPropagation();
  397. // apply widgets
  398. ts.applyWidget( this, init );
  399. })
  400. .bind( 'refreshWidgets' + namespace, function( e, all, dontapply ) {
  401. e.stopPropagation();
  402. ts.refreshWidgets( this, all, dontapply );
  403. })
  404. .bind( 'destroy' + namespace, function( e, removeClasses, callback ) {
  405. e.stopPropagation();
  406. ts.destroy( this, removeClasses, callback );
  407. })
  408. .bind( 'resetToLoadState' + namespace, function( e ) {
  409. e.stopPropagation();
  410. // remove all widgets
  411. ts.removeWidget( this, true, false );
  412. // restore original settings; this clears out current settings, but does not clear
  413. // values saved to storage.
  414. c = $.extend( true, ts.defaults, c.originalSettings );
  415. this.hasInitialized = false;
  416. // setup the entire table again
  417. ts.setup( this, c );
  418. });
  419. },
  420.  
  421. bindEvents : function( table, $headers, core ) {
  422. table = $( table )[ 0 ];
  423. var tmp,
  424. c = table.config,
  425. namespace = c.namespace,
  426. downTarget = null;
  427. if ( core !== true ) {
  428. $headers.addClass( namespace.slice( 1 ) + '_extra_headers' );
  429. tmp = $.fn.closest ? $headers.closest( 'table' )[ 0 ] : $headers.parents( 'table' )[ 0 ];
  430. if ( tmp && tmp.nodeName === 'TABLE' && tmp !== table ) {
  431. $( tmp ).addClass( namespace.slice( 1 ) + '_extra_table' );
  432. }
  433. }
  434. tmp = ( c.pointerDown + ' ' + c.pointerUp + ' ' + c.pointerClick + ' sort keyup ' )
  435. .replace( ts.regex.spaces, ' ' )
  436. .split( ' ' )
  437. .join( namespace + ' ' );
  438. // apply event handling to headers and/or additional headers (stickyheaders, scroller, etc)
  439. $headers
  440. // http://stackoverflow.com/questions/5312849/jquery-find-self;
  441. .find( c.selectorSort )
  442. .add( $headers.filter( c.selectorSort ) )
  443. .unbind( tmp )
  444. .bind( tmp, function( e, external ) {
  445. var $cell, cell, temp,
  446. $target = $( e.target ),
  447. // wrap event type in spaces, so the match doesn't trigger on inner words
  448. type = ' ' + e.type + ' ';
  449. // only recognize left clicks
  450. if ( ( ( e.which || e.button ) !== 1 && !type.match( ' ' + c.pointerClick + ' | sort | keyup ' ) ) ||
  451. // allow pressing enter
  452. ( type === ' keyup ' && e.which !== 13 ) ||
  453. // allow triggering a click event (e.which is undefined) & ignore physical clicks
  454. ( type.match( ' ' + c.pointerClick + ' ' ) && typeof e.which !== 'undefined' ) ) {
  455. return;
  456. }
  457. // ignore mouseup if mousedown wasn't on the same target
  458. if ( type.match( ' ' + c.pointerUp + ' ' ) && downTarget !== e.target && external !== true ) {
  459. return;
  460. }
  461. // set target on mousedown
  462. if ( type.match( ' ' + c.pointerDown + ' ' ) ) {
  463. downTarget = e.target;
  464. // preventDefault needed or jQuery v1.3.2 and older throws an
  465. // "Uncaught TypeError: handler.apply is not a function" error
  466. temp = $target.jquery.split( '.' );
  467. if ( temp[ 0 ] === '1' && temp[ 1 ] < 4 ) { e.preventDefault(); }
  468. return;
  469. }
  470. downTarget = null;
  471. // prevent sort being triggered on form elements
  472. if ( ts.regex.formElements.test( e.target.nodeName ) ||
  473. // nosort class name, or elements within a nosort container
  474. $target.hasClass( c.cssNoSort ) || $target.parents( '.' + c.cssNoSort ).length > 0 ||
  475. // elements within a button
  476. $target.parents( 'button' ).length > 0 ) {
  477. return !c.cancelSelection;
  478. }
  479. if ( c.delayInit && ts.isEmptyObject( c.cache ) ) {
  480. ts.buildCache( c );
  481. }
  482. // jQuery v1.2.6 doesn't have closest()
  483. $cell = $.fn.closest ? $( this ).closest( 'th, td' ) :
  484. /TH|TD/.test( this.nodeName ) ? $( this ) : $( this ).parents( 'th, td' );
  485. // reference original table headers and find the same cell
  486. // don't use $headers or IE8 throws an error - see #987
  487. temp = $headers.index( $cell );
  488. c.last.clickedIndex = ( temp < 0 ) ? $cell.attr( 'data-column' ) : temp;
  489. // use column index if $headers is undefined
  490. cell = c.$headers[ c.last.clickedIndex ];
  491. if ( cell && !cell.sortDisabled ) {
  492. ts.initSort( c, cell, e );
  493. }
  494. });
  495. if ( c.cancelSelection ) {
  496. // cancel selection
  497. $headers
  498. .attr( 'unselectable', 'on' )
  499. .bind( 'selectstart', false )
  500. .css({
  501. 'user-select' : 'none',
  502. 'MozUserSelect' : 'none' // not needed for jQuery 1.8+
  503. });
  504. }
  505. },
  506.  
  507. buildHeaders : function( c ) {
  508. var $temp, icon, timer, indx;
  509. c.headerList = [];
  510. c.headerContent = [];
  511. c.sortVars = [];
  512. if ( c.debug ) {
  513. timer = new Date();
  514. }
  515. // children tr in tfoot - see issue #196 & #547
  516. c.columns = ts.computeColumnIndex( c.$table.children( 'thead, tfoot' ).children( 'tr' ) );
  517. // add icon if cssIcon option exists
  518. icon = c.cssIcon ?
  519. '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' :
  520. '';
  521. // redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683
  522. c.$headers = $( $.map( c.$table.find( c.selectorHeaders ), function( elem, index ) {
  523. var configHeaders, header, column, template, tmp,
  524. $elem = $( elem );
  525. // ignore cell (don't add it to c.$headers) if row has ignoreRow class
  526. if ( $elem.parent().hasClass( c.cssIgnoreRow ) ) { return; }
  527. // make sure to get header cell & not column indexed cell
  528. configHeaders = ts.getColumnData( c.table, c.headers, index, true );
  529. // save original header content
  530. c.headerContent[ index ] = $elem.html();
  531. // if headerTemplate is empty, don't reformat the header cell
  532. if ( c.headerTemplate !== '' && !$elem.find( '.' + ts.css.headerIn ).length ) {
  533. // set up header template
  534. template = c.headerTemplate
  535. .replace( ts.regex.templateContent, $elem.html() )
  536. .replace( ts.regex.templateIcon, $elem.find( '.' + ts.css.icon ).length ? '' : icon );
  537. if ( c.onRenderTemplate ) {
  538. header = c.onRenderTemplate.apply( $elem, [ index, template ] );
  539. // only change t if something is returned
  540. if ( header && typeof header === 'string' ) {
  541. template = header;
  542. }
  543. }
  544. $elem.html( '<div class="' + ts.css.headerIn + '">' + template + '</div>' ); // faster than wrapInner
  545. }
  546. if ( c.onRenderHeader ) {
  547. c.onRenderHeader.apply( $elem, [ index, c, c.$table ] );
  548. }
  549. column = parseInt( $elem.attr( 'data-column' ), 10 );
  550. elem.column = column;
  551. tmp = ts.getData( $elem, configHeaders, 'sortInitialOrder' ) || c.sortInitialOrder;
  552. // this may get updated numerous times if there are multiple rows
  553. c.sortVars[ column ] = {
  554. count : -1, // set to -1 because clicking on the header automatically adds one
  555. order: ts.formatSortingOrder( tmp ) ?
  556. [ 1, 0, 2 ] : // desc, asc, unsorted
  557. [ 0, 1, 2 ], // asc, desc, unsorted
  558. lockedOrder : false
  559. };
  560. tmp = ts.getData( $elem, configHeaders, 'lockedOrder' ) || false;
  561. if ( typeof tmp !== 'undefined' && tmp !== false ) {
  562. c.sortVars[ column ].lockedOrder = true;
  563. c.sortVars[ column ].order = ts.formatSortingOrder( tmp ) ? [ 1, 1, 1 ] : [ 0, 0, 0 ];
  564. }
  565. // add cell to headerList
  566. c.headerList[ index ] = elem;
  567. // add to parent in case there are multiple rows
  568. $elem
  569. .addClass( ts.css.header + ' ' + c.cssHeader )
  570. .parent()
  571. .addClass( ts.css.headerRow + ' ' + c.cssHeaderRow )
  572. .attr( 'role', 'row' );
  573. // allow keyboard cursor to focus on element
  574. if ( c.tabIndex ) {
  575. $elem.attr( 'tabindex', 0 );
  576. }
  577. return elem;
  578. }) );
  579. // cache headers per column
  580. c.$headerIndexed = [];
  581. for ( indx = 0; indx < c.columns; indx++ ) {
  582. // colspan in header making a column undefined
  583. if ( ts.isEmptyObject( c.sortVars[ indx ] ) ) {
  584. c.sortVars[ indx ] = {};
  585. }
  586. $temp = c.$headers.filter( '[data-column="' + indx + '"]' );
  587. // target sortable column cells, unless there are none, then use non-sortable cells
  588. // .last() added in jQuery 1.4; use .filter(':last') to maintain compatibility with jQuery v1.2.6
  589. c.$headerIndexed[ indx ] = $temp.length ?
  590. $temp.not( '.sorter-false' ).length ?
  591. $temp.not( '.sorter-false' ).filter( ':last' ) :
  592. $temp.filter( ':last' ) :
  593. $();
  594. }
  595. c.$table.find( c.selectorHeaders ).attr({
  596. scope: 'col',
  597. role : 'columnheader'
  598. });
  599. // enable/disable sorting
  600. ts.updateHeader( c );
  601. if ( c.debug ) {
  602. console.log( 'Built headers:' + ts.benchmark( timer ) );
  603. console.log( c.$headers );
  604. }
  605. },
  606.  
  607. // Use it to add a set of methods to table.config which will be available for all tables.
  608. // This should be done before table initialization
  609. addInstanceMethods : function( methods ) {
  610. $.extend( ts.instanceMethods, methods );
  611. },
  612.  
  613. /*
  614. █████▄ ▄████▄ █████▄ ▄█████ ██████ █████▄ ▄█████
  615. ██▄▄██ ██▄▄██ ██▄▄██ ▀█▄ ██▄▄ ██▄▄██ ▀█▄
  616. ██▀▀▀ ██▀▀██ ██▀██ ▀█▄ ██▀▀ ██▀██ ▀█▄
  617. ██ ██ ██ ██ ██ █████▀ ██████ ██ ██ █████▀
  618. */
  619. setupParsers : function( c, $tbodies ) {
  620. var rows, list, span, max, colIndex, indx, header, configHeaders,
  621. noParser, parser, extractor, time, tbody, len,
  622. table = c.table,
  623. tbodyIndex = 0,
  624. debug = {};
  625. // update table bodies in case we start with an empty table
  626. c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' );
  627. tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies;
  628. len = tbody.length;
  629. if ( len === 0 ) {
  630. return c.debug ? console.warn( 'Warning: *Empty table!* Not building a parser cache' ) : '';
  631. } else if ( c.debug ) {
  632. time = new Date();
  633. console[ console.group ? 'group' : 'log' ]( 'Detecting parsers for each column' );
  634. }
  635. list = {
  636. extractors: [],
  637. parsers: []
  638. };
  639. while ( tbodyIndex < len ) {
  640. rows = tbody[ tbodyIndex ].rows;
  641. if ( rows.length ) {
  642. colIndex = 0;
  643. max = c.columns;
  644. for ( indx = 0; indx < max; indx++ ) {
  645. header = c.$headerIndexed[ colIndex ];
  646. if ( header && header.length ) {
  647. // get column indexed table cell
  648. configHeaders = ts.getColumnData( table, c.headers, colIndex );
  649. // get column parser/extractor
  650. extractor = ts.getParserById( ts.getData( header, configHeaders, 'extractor' ) );
  651. parser = ts.getParserById( ts.getData( header, configHeaders, 'sorter' ) );
  652. noParser = ts.getData( header, configHeaders, 'parser' ) === 'false';
  653. // empty cells behaviour - keeping emptyToBottom for backwards compatibility
  654. c.empties[colIndex] = (
  655. ts.getData( header, configHeaders, 'empty' ) ||
  656. c.emptyTo || ( c.emptyToBottom ? 'bottom' : 'top' ) ).toLowerCase();
  657. // text strings behaviour in numerical sorts
  658. c.strings[colIndex] = (
  659. ts.getData( header, configHeaders, 'string' ) ||
  660. c.stringTo ||
  661. 'max' ).toLowerCase();
  662. if ( noParser ) {
  663. parser = ts.getParserById( 'no-parser' );
  664. }
  665. if ( !extractor ) {
  666. // For now, maybe detect someday
  667. extractor = false;
  668. }
  669. if ( !parser ) {
  670. parser = ts.detectParserForColumn( c, rows, -1, colIndex );
  671. }
  672. if ( c.debug ) {
  673. debug[ '(' + colIndex + ') ' + header.text() ] = {
  674. parser : parser.id,
  675. extractor : extractor ? extractor.id : 'none',
  676. string : c.strings[ colIndex ],
  677. empty : c.empties[ colIndex ]
  678. };
  679. }
  680. list.parsers[ colIndex ] = parser;
  681. list.extractors[ colIndex ] = extractor;
  682. span = header[ 0 ].colSpan - 1;
  683. if ( span > 0 ) {
  684. colIndex += span;
  685. max += span;
  686. }
  687. }
  688. colIndex++;
  689. }
  690. }
  691. tbodyIndex += ( list.parsers.length ) ? len : 1;
  692. }
  693. if ( c.debug ) {
  694. if ( !ts.isEmptyObject( debug ) ) {
  695. console[ console.table ? 'table' : 'log' ]( debug );
  696. } else {
  697. console.warn( ' No parsers detected!' );
  698. }
  699. console.log( 'Completed detecting parsers' + ts.benchmark( time ) );
  700. if ( console.groupEnd ) { console.groupEnd(); }
  701. }
  702. c.parsers = list.parsers;
  703. c.extractors = list.extractors;
  704. },
  705.  
  706. addParser : function( parser ) {
  707. var indx,
  708. len = ts.parsers.length,
  709. add = true;
  710. for ( indx = 0; indx < len; indx++ ) {
  711. if ( ts.parsers[ indx ].id.toLowerCase() === parser.id.toLowerCase() ) {
  712. add = false;
  713. }
  714. }
  715. if ( add ) {
  716. ts.parsers.push( parser );
  717. }
  718. },
  719.  
  720. getParserById : function( name ) {
  721. /*jshint eqeqeq:false */
  722. if ( name == 'false' ) { return false; }
  723. var indx,
  724. len = ts.parsers.length;
  725. for ( indx = 0; indx < len; indx++ ) {
  726. if ( ts.parsers[ indx ].id.toLowerCase() === ( name.toString() ).toLowerCase() ) {
  727. return ts.parsers[ indx ];
  728. }
  729. }
  730. return false;
  731. },
  732.  
  733. detectParserForColumn : function( c, rows, rowIndex, cellIndex ) {
  734. var cur, $node,
  735. indx = ts.parsers.length,
  736. node = false,
  737. nodeValue = '',
  738. keepLooking = true;
  739. while ( nodeValue === '' && keepLooking ) {
  740. rowIndex++;
  741. if ( rows[ rowIndex ] ) {
  742. node = rows[ rowIndex ].cells[ cellIndex ];
  743. nodeValue = ts.getElementText( c, node, cellIndex );
  744. $node = $( node );
  745. if ( c.debug ) {
  746. console.log( 'Checking if value was empty on row ' + rowIndex + ', column: ' +
  747. cellIndex + ': "' + nodeValue + '"' );
  748. }
  749. } else {
  750. keepLooking = false;
  751. }
  752. }
  753. while ( --indx >= 0 ) {
  754. cur = ts.parsers[ indx ];
  755. // ignore the default text parser because it will always be true
  756. if ( cur && cur.id !== 'text' && cur.is && cur.is( nodeValue, c.table, node, $node ) ) {
  757. return cur;
  758. }
  759. }
  760. // nothing found, return the generic parser (text)
  761. return ts.getParserById( 'text' );
  762. },
  763.  
  764. getElementText : function( c, node, cellIndex ) {
  765. if ( !node ) { return ''; }
  766. var tmp,
  767. extract = c.textExtraction || '',
  768. // node could be a jquery object
  769. // http://jsperf.com/jquery-vs-instanceof-jquery/2
  770. $node = node.jquery ? node : $( node );
  771. if ( typeof extract === 'string' ) {
  772. // check data-attribute first when set to 'basic'; don't use node.innerText - it's really slow!
  773. // http://www.kellegous.com/j/2013/02/27/innertext-vs-textcontent/
  774. if ( extract === 'basic' && typeof ( tmp = $node.attr( c.textAttribute ) ) !== 'undefined' ) {
  775. return $.trim( tmp );
  776. }
  777. return $.trim( node.textContent || $node.text() );
  778. } else {
  779. if ( typeof extract === 'function' ) {
  780. return $.trim( extract( $node[ 0 ], c.table, cellIndex ) );
  781. } else if ( typeof ( tmp = ts.getColumnData( c.table, extract, cellIndex ) ) === 'function' ) {
  782. return $.trim( tmp( $node[ 0 ], c.table, cellIndex ) );
  783. }
  784. }
  785. // fallback
  786. return $.trim( $node[ 0 ].textContent || $node.text() );
  787. },
  788.  
  789. // centralized function to extract/parse cell contents
  790. getParsedText : function( c, cell, colIndex, txt ) {
  791. if ( typeof txt === 'undefined' ) {
  792. txt = ts.getElementText( c, cell, colIndex );
  793. }
  794. // if no parser, make sure to return the txt
  795. var val = '' + txt,
  796. parser = c.parsers[ colIndex ],
  797. extractor = c.extractors[ colIndex ];
  798. if ( parser ) {
  799. // do extract before parsing, if there is one
  800. if ( extractor && typeof extractor.format === 'function' ) {
  801. txt = extractor.format( txt, c.table, cell, colIndex );
  802. }
  803. // allow parsing if the string is empty, previously parsing would change it to zero,
  804. // in case the parser needs to extract data from the table cell attributes
  805. val = parser.id === 'no-parser' ? '' :
  806. // make sure txt is a string (extractor may have converted it)
  807. parser.format( '' + txt, c.table, cell, colIndex );
  808. if ( c.ignoreCase && typeof val === 'string' ) {
  809. val = val.toLowerCase();
  810. }
  811. }
  812. return val;
  813. },
  814.  
  815. /*
  816. ▄████▄ ▄████▄ ▄████▄ ██ ██ ██████
  817. ██ ▀▀ ██▄▄██ ██ ▀▀ ██▄▄██ ██▄▄
  818. ██ ▄▄ ██▀▀██ ██ ▄▄ ██▀▀██ ██▀▀
  819. ▀████▀ ██ ██ ▀████▀ ██ ██ ██████
  820. */
  821. buildCache : function( c, callback, $tbodies ) {
  822. var cache, val, txt, rowIndex, colIndex, tbodyIndex, $tbody, $row,
  823. cols, $cells, cell, cacheTime, totalRows, rowData, prevRowData,
  824. colMax, span, cacheIndex, max, len,
  825. table = c.table,
  826. parsers = c.parsers;
  827. // update tbody variable
  828. c.$tbodies = c.$table.children( 'tbody:not(.' + c.cssInfoBlock + ')' );
  829. $tbody = typeof $tbodies === 'undefined' ? c.$tbodies : $tbodies,
  830. c.cache = {};
  831. c.totalRows = 0;
  832. // if no parsers found, return - it's an empty table.
  833. if ( !parsers ) {
  834. return c.debug ? console.warn( 'Warning: *Empty table!* Not building a cache' ) : '';
  835. }
  836. if ( c.debug ) {
  837. cacheTime = new Date();
  838. }
  839. // processing icon
  840. if ( c.showProcessing ) {
  841. ts.isProcessing( table, true );
  842. }
  843. for ( tbodyIndex = 0; tbodyIndex < $tbody.length; tbodyIndex++ ) {
  844. colMax = []; // column max value per tbody
  845. cache = c.cache[ tbodyIndex ] = {
  846. normalized: [] // array of normalized row data; last entry contains 'rowData' above
  847. // colMax: # // added at the end
  848. };
  849.  
  850. totalRows = ( $tbody[ tbodyIndex ] && $tbody[ tbodyIndex ].rows.length ) || 0;
  851. for ( rowIndex = 0; rowIndex < totalRows; ++rowIndex ) {
  852. rowData = {
  853. // order: original row order #
  854. // $row : jQuery Object[]
  855. child: [], // child row text (filter widget)
  856. raw: [] // original row text
  857. };
  858. /** Add the table data to main data array */
  859. $row = $( $tbody[ tbodyIndex ].rows[ rowIndex ] );
  860. cols = [];
  861. // if this is a child row, add it to the last row's children and continue to the next row
  862. // ignore child row class, if it is the first row
  863. if ( $row.hasClass( c.cssChildRow ) && rowIndex !== 0 ) {
  864. len = cache.normalized.length - 1;
  865. prevRowData = cache.normalized[ len ][ c.columns ];
  866. prevRowData.$row = prevRowData.$row.add( $row );
  867. // add 'hasChild' class name to parent row
  868. if ( !$row.prev().hasClass( c.cssChildRow ) ) {
  869. $row.prev().addClass( ts.css.cssHasChild );
  870. }
  871. // save child row content (un-parsed!)
  872. $cells = $row.children( 'th, td' );
  873. len = prevRowData.child.length;
  874. prevRowData.child[ len ] = [];
  875. // child row content does not account for colspans/rowspans; so indexing may be off
  876. cacheIndex = 0;
  877. max = c.columns;
  878. for ( colIndex = 0; colIndex < max; colIndex++ ) {
  879. cell = $cells[ colIndex ];
  880. if ( cell ) {
  881. prevRowData.child[ len ][ colIndex ] = ts.getParsedText( c, cell, colIndex );
  882. span = $cells[ colIndex ].colSpan - 1;
  883. if ( span > 0 ) {
  884. cacheIndex += span;
  885. max += span;
  886. }
  887. }
  888. cacheIndex++;
  889. }
  890. // go to the next for loop
  891. continue;
  892. }
  893. rowData.$row = $row;
  894. rowData.order = rowIndex; // add original row position to rowCache
  895. cacheIndex = 0;
  896. max = c.columns;
  897. for ( colIndex = 0; colIndex < max; ++colIndex ) {
  898. cell = $row[ 0 ].cells[ colIndex ];
  899. if ( typeof parsers[ cacheIndex ] === 'undefined' ) {
  900. if ( c.debug ) {
  901. console.warn( 'No parser found for column ' + colIndex + '; cell:', cell, 'does it have a header?' );
  902. }
  903. } else if ( cell ) {
  904. val = ts.getElementText( c, cell, cacheIndex );
  905. rowData.raw[ cacheIndex ] = val; // save original row text
  906. txt = ts.getParsedText( c, cell, cacheIndex, val );
  907. cols[ cacheIndex ] = txt;
  908. if ( ( parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) {
  909. // determine column max value (ignore sign)
  910. colMax[ cacheIndex ] = Math.max( Math.abs( txt ) || 0, colMax[ cacheIndex ] || 0 );
  911. }
  912. // allow colSpan in tbody
  913. span = cell.colSpan - 1;
  914. if ( span > 0 ) {
  915. cacheIndex += span;
  916. max += span;
  917. }
  918. }
  919. cacheIndex++;
  920. }
  921. // ensure rowData is always in the same location (after the last column)
  922. cols[ c.columns ] = rowData;
  923. cache.normalized.push( cols );
  924. }
  925. cache.colMax = colMax;
  926. // total up rows, not including child rows
  927. c.totalRows += cache.normalized.length;
  928.  
  929. }
  930. if ( c.showProcessing ) {
  931. ts.isProcessing( table ); // remove processing icon
  932. }
  933. if ( c.debug ) {
  934. console.log( 'Building cache for ' + totalRows + ' rows' + ts.benchmark( cacheTime ) );
  935. }
  936. if ( $.isFunction( callback ) ) {
  937. callback( table );
  938. }
  939. },
  940.  
  941. getColumnText : function( table, column, callback, rowFilter ) {
  942. table = $( table )[0];
  943. var tbodyIndex, rowIndex, cache, row, tbodyLen, rowLen, raw, parsed, $cell, result,
  944. hasCallback = typeof callback === 'function',
  945. allColumns = column === 'all',
  946. data = { raw : [], parsed: [], $cell: [] },
  947. c = table.config;
  948. if ( ts.isEmptyObject( c ) ) {
  949. if ( c.debug ) {
  950. console.warn( 'No cache found - aborting getColumnText function!' );
  951. }
  952. } else {
  953. tbodyLen = c.$tbodies.length;
  954. for ( tbodyIndex = 0; tbodyIndex < tbodyLen; tbodyIndex++ ) {
  955. cache = c.cache[ tbodyIndex ].normalized;
  956. rowLen = cache.length;
  957. for ( rowIndex = 0; rowIndex < rowLen; rowIndex++ ) {
  958. row = cache[ rowIndex ];
  959. if ( rowFilter && !row[ c.columns ].$row.is( rowFilter ) ) {
  960. continue;
  961. }
  962. result = true;
  963. parsed = ( allColumns ) ? row.slice( 0, c.columns ) : row[ column ];
  964. row = row[ c.columns ];
  965. raw = ( allColumns ) ? row.raw : row.raw[ column ];
  966. $cell = ( allColumns ) ? row.$row.children() : row.$row.children().eq( column );
  967. if ( hasCallback ) {
  968. result = callback({
  969. tbodyIndex : tbodyIndex,
  970. rowIndex : rowIndex,
  971. parsed : parsed,
  972. raw : raw,
  973. $row : row.$row,
  974. $cell : $cell
  975. });
  976. }
  977. if ( result !== false ) {
  978. data.parsed.push( parsed );
  979. data.raw.push( raw );
  980. data.$cell.push( $cell );
  981. }
  982. }
  983. }
  984. // return everything
  985. return data;
  986. }
  987. },
  988.  
  989. /*
  990. ██ ██ █████▄ █████▄ ▄████▄ ██████ ██████
  991. ██ ██ ██▄▄██ ██ ██ ██▄▄██ ██ ██▄▄
  992. ██ ██ ██▀▀▀ ██ ██ ██▀▀██ ██ ██▀▀
  993. ▀████▀ ██ █████▀ ██ ██ ██ ██████
  994. */
  995. setHeadersCss : function( c ) {
  996. var $sorted, header, indx, column, $header, nextSort, txt, tmp,
  997. list = c.sortList,
  998. len = list.length,
  999. none = ts.css.sortNone + ' ' + c.cssNone,
  1000. css = [ ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc ],
  1001. cssIcon = [ c.cssIconAsc, c.cssIconDesc, c.cssIconNone ],
  1002. aria = [ 'ascending', 'descending' ],
  1003. // find the footer
  1004. $headers = c.$table
  1005. .find( 'tfoot tr' )
  1006. .children()
  1007. .add( $( c.namespace + '_extra_headers' ) )
  1008. .removeClass( css.join( ' ' ) );
  1009. // remove all header information
  1010. c.$headers
  1011. .removeClass( css.join( ' ' ) )
  1012. .addClass( none )
  1013. .attr( 'aria-sort', 'none' )
  1014. .find( '.' + ts.css.icon )
  1015. .removeClass( cssIcon.join( ' ' ) )
  1016. .addClass( cssIcon[ 2 ] );
  1017. for ( indx = 0; indx < len; indx++ ) {
  1018. // direction = 2 means reset!
  1019. if ( list[ indx ][ 1 ] !== 2 ) {
  1020. // multicolumn sorting updating - see #1005
  1021. // .not(function(){}) needs jQuery 1.4
  1022. $sorted = c.$headers.filter( function( i, el ) {
  1023. // only include headers that are in the sortList (this includes colspans)
  1024. var include = true,
  1025. $el = $( el ),
  1026. col = parseInt( $el.attr( 'data-column' ), 10 ),
  1027. end = col + el.colSpan;
  1028. for ( ; col < end; col++ ) {
  1029. include = include ? ts.isValueInArray( col, c.sortList ) > -1 : false;
  1030. }
  1031. return include;
  1032. });
  1033.  
  1034. // choose the :last in case there are nested columns
  1035. $sorted = $sorted
  1036. .not( '.sorter-false' )
  1037. .filter( '[data-column="' + list[ indx ][ 0 ] + '"]' + ( len === 1 ? ':last' : '' ) );
  1038. if ( $sorted.length ) {
  1039. for ( column = 0; column < $sorted.length; column++ ) {
  1040. if ( !$sorted[ column ].sortDisabled ) {
  1041. $sorted
  1042. .eq( column )
  1043. .removeClass( none )
  1044. .addClass( css[ list[ indx ][ 1 ] ] )
  1045. .attr( 'aria-sort', aria[ list[ indx ][ 1 ] ] )
  1046. .find( '.' + ts.css.icon )
  1047. .removeClass( cssIcon[ 2 ] )
  1048. .addClass( cssIcon[ list[ indx ][ 1 ] ] );
  1049. }
  1050. }
  1051. // add sorted class to footer & extra headers, if they exist
  1052. if ( $headers.length ) {
  1053. $headers
  1054. .filter( '[data-column="' + list[ indx ][ 0 ] + '"]' )
  1055. .removeClass( none )
  1056. .addClass( css[ list[ indx ][ 1 ] ] );
  1057. }
  1058. }
  1059. }
  1060. }
  1061. // add verbose aria labels
  1062. len = c.$headers.length;
  1063. $headers = c.$headers.not( '.sorter-false' );
  1064. for ( indx = 0; indx < len; indx++ ) {
  1065. $header = $headers.eq( indx );
  1066. if ( $header.length ) {
  1067. header = $headers[ indx ];
  1068. column = parseInt( $header.attr( 'data-column' ), 10 );
  1069. nextSort = c.sortVars[ column ].order[ ( c.sortVars[ column ].count + 1 ) % ( c.sortReset ? 3 : 2 ) ];
  1070. tmp = $header.hasClass( ts.css.sortAsc ) ?
  1071. 'sortAsc' :
  1072. $header.hasClass( ts.css.sortDesc ) ? 'sortDesc' : 'sortNone';
  1073. txt = $.trim( $header.text() ) + ': ' +
  1074. ts.language[ tmp ] +
  1075. ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ];
  1076. $header.attr( 'aria-label', txt );
  1077. }
  1078. }
  1079. },
  1080.  
  1081. updateHeader : function( c ) {
  1082. var index, isDisabled, $th, col,
  1083. table = c.table,
  1084. len = c.$headers.length;
  1085. for ( index = 0; index < len; index++ ) {
  1086. $th = c.$headers.eq( index );
  1087. col = ts.getColumnData( table, c.headers, index, true );
  1088. // add 'sorter-false' class if 'parser-false' is set
  1089. isDisabled = ts.getData( $th, col, 'sorter' ) === 'false' || ts.getData( $th, col, 'parser' ) === 'false';
  1090. $th[ 0 ].sortDisabled = isDisabled;
  1091. $th[ isDisabled ? 'addClass' : 'removeClass' ]( 'sorter-false' ).attr( 'aria-disabled', '' + isDisabled );
  1092. // disable tab index on disabled cells
  1093. if ( c.tabIndex ) {
  1094. if ( isDisabled ) {
  1095. $th.removeAttr( 'tabindex' );
  1096. } else {
  1097. $th.attr( 'tabindex', '0' );
  1098. }
  1099. }
  1100. // aria-controls - requires table ID
  1101. if ( table.id ) {
  1102. if ( isDisabled ) {
  1103. $th.removeAttr( 'aria-controls' );
  1104. } else {
  1105. $th.attr( 'aria-controls', table.id );
  1106. }
  1107. }
  1108. }
  1109. },
  1110.  
  1111. updateHeaderSortCount : function( c, list ) {
  1112. var col, dir, group, indx, primary, temp, val, order,
  1113. sortList = list || c.sortList,
  1114. len = sortList.length;
  1115. c.sortList = [];
  1116. for ( indx = 0; indx < len; indx++ ) {
  1117. val = sortList[ indx ];
  1118. // ensure all sortList values are numeric - fixes #127
  1119. col = parseInt( val[ 0 ], 10 );
  1120. // prevents error if sorton array is wrong
  1121. if ( col < c.columns ) {
  1122. order = c.sortVars[ col ].order;
  1123. dir = ( '' + val[ 1 ] ).match( /^(1|d|s|o|n)/ );
  1124. dir = dir ? dir[ 0 ] : '';
  1125. // 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext
  1126. switch ( dir ) {
  1127. case '1' : case 'd' : // descending
  1128. dir = 1;
  1129. break;
  1130. case 's' : // same direction (as primary column)
  1131. // if primary sort is set to 's', make it ascending
  1132. dir = primary || 0;
  1133. break;
  1134. case 'o' :
  1135. temp = order[ ( primary || 0 ) % ( c.sortReset ? 3 : 2 ) ];
  1136. // opposite of primary column; but resets if primary resets
  1137. dir = temp === 0 ? 1 : temp === 1 ? 0 : 2;
  1138. break;
  1139. case 'n' :
  1140. dir = order[ ( ++c.sortVars[ col ].count ) % ( c.sortReset ? 3 : 2 ) ];
  1141. break;
  1142. default : // ascending
  1143. dir = 0;
  1144. break;
  1145. }
  1146. primary = indx === 0 ? dir : primary;
  1147. group = [ col, parseInt( dir, 10 ) || 0 ];
  1148. c.sortList.push( group );
  1149. dir = $.inArray( group[ 1 ], order ); // fixes issue #167
  1150. c.sortVars[ col ].count = dir >= 0 ? dir : group[ 1 ] % ( c.sortReset ? 3 : 2 );
  1151. }
  1152. }
  1153. },
  1154.  
  1155. updateAll : function( c, resort, callback ) {
  1156. var table = c.table;
  1157. table.isUpdating = true;
  1158. ts.refreshWidgets( table, true, true );
  1159. ts.buildHeaders( c );
  1160. ts.bindEvents( table, c.$headers, true );
  1161. ts.bindMethods( c );
  1162. ts.commonUpdate( c, resort, callback );
  1163. },
  1164.  
  1165. update : function( c, resort, callback ) {
  1166. var table = c.table;
  1167. table.isUpdating = true;
  1168. // update sorting (if enabled/disabled)
  1169. ts.updateHeader( c );
  1170. ts.commonUpdate( c, resort, callback );
  1171. },
  1172.  
  1173. // simple header update - see #989
  1174. updateHeaders : function( c, callback ) {
  1175. c.table.isUpdating = true;
  1176. ts.buildHeaders( c );
  1177. ts.bindEvents( c.table, c.$headers, true );
  1178. ts.resortComplete( c, callback );
  1179. },
  1180.  
  1181. updateCell : function( c, cell, resort, callback ) {
  1182. c.table.isUpdating = true;
  1183. c.$table.find( c.selectorRemove ).remove();
  1184. // get position from the dom
  1185. var tmp, indx, row, icell, cache, len,
  1186. $tbodies = c.$tbodies,
  1187. $cell = $( cell ),
  1188. // update cache - format: function( s, table, cell, cellIndex )
  1189. // no closest in jQuery v1.2.6
  1190. tbodyIndex = $tbodies
  1191. .index( $.fn.closest ? $cell.closest( 'tbody' ) : $cell.parents( 'tbody' ).filter( ':first' ) ),
  1192. tbcache = c.cache[ tbodyIndex ],
  1193. $row = $.fn.closest ? $cell.closest( 'tr' ) : $cell.parents( 'tr' ).filter( ':first' );
  1194. cell = $cell[ 0 ]; // in case cell is a jQuery object
  1195. // tbody may not exist if update is initialized while tbody is removed for processing
  1196. if ( $tbodies.length && tbodyIndex >= 0 ) {
  1197. row = $tbodies.eq( tbodyIndex ).find( 'tr' ).index( $row );
  1198. cache = tbcache.normalized[ row ];
  1199. len = $row[ 0 ].cells.length;
  1200. if ( len !== c.columns ) {
  1201. // colspan in here somewhere!
  1202. icell = 0;
  1203. tmp = false;
  1204. for ( indx = 0; indx < len; indx++ ) {
  1205. if ( !tmp && $row[ 0 ].cells[ indx ] !== cell ) {
  1206. icell += $row[ 0 ].cells[ indx ].colSpan;
  1207. } else {
  1208. tmp = true;
  1209. }
  1210. }
  1211. } else {
  1212. icell = $cell.index();
  1213. }
  1214. tmp = ts.getElementText( c, cell, icell ); // raw
  1215. cache[ c.columns ].raw[ icell ] = tmp;
  1216. tmp = ts.getParsedText( c, cell, icell, tmp );
  1217. cache[ icell ] = tmp; // parsed
  1218. cache[ c.columns ].$row = $row;
  1219. if ( ( c.parsers[ icell ].type || '' ).toLowerCase() === 'numeric' ) {
  1220. // update column max value (ignore sign)
  1221. tbcache.colMax[ icell ] = Math.max( Math.abs( tmp ) || 0, tbcache.colMax[ icell ] || 0 );
  1222. }
  1223. tmp = resort !== 'undefined' ? resort : c.resort;
  1224. if ( tmp !== false ) {
  1225. // widgets will be reapplied
  1226. ts.checkResort( c, tmp, callback );
  1227. } else {
  1228. // don't reapply widgets is resort is false, just in case it causes
  1229. // problems with element focus
  1230. ts.resortComplete( c, callback );
  1231. }
  1232. }
  1233. },
  1234.  
  1235. addRows : function( c, $row, resort, callback ) {
  1236. var txt, val, tbodyIndex, rowIndex, rows, cellIndex, len,
  1237. cacheIndex, rowData, cells, cell, span,
  1238. // allow passing a row string if only one non-info tbody exists in the table
  1239. valid = typeof $row === 'string' && c.$tbodies.length === 1 && /<tr/.test( $row || '' ),
  1240. table = c.table;
  1241. if ( valid ) {
  1242. $row = $( $row );
  1243. c.$tbodies.append( $row );
  1244. } else if ( !$row ||
  1245. // row is a jQuery object?
  1246. !( $row instanceof jQuery ) ||
  1247. // row contained in the table?
  1248. ( $.fn.closest ? $row.closest( 'table' )[ 0 ] : $row.parents( 'table' )[ 0 ] ) !== c.table ) {
  1249. if ( c.debug ) {
  1250. console.error( 'addRows method requires (1) a jQuery selector reference to rows that have already ' +
  1251. 'been added to the table, or (2) row HTML string to be added to a table with only one tbody' );
  1252. }
  1253. return false;
  1254. }
  1255. table.isUpdating = true;
  1256. if ( ts.isEmptyObject( c.cache ) ) {
  1257. // empty table, do an update instead - fixes #450
  1258. ts.updateHeader( c );
  1259. ts.commonUpdate( c, resort, callback );
  1260. } else {
  1261. rows = $row.filter( 'tr' ).attr( 'role', 'row' ).length;
  1262. tbodyIndex = c.$tbodies.index( $row.parents( 'tbody' ).filter( ':first' ) );
  1263. // fixes adding rows to an empty table - see issue #179
  1264. if ( !( c.parsers && c.parsers.length ) ) {
  1265. ts.setupParsers( c );
  1266. }
  1267. // add each row
  1268. for ( rowIndex = 0; rowIndex < rows; rowIndex++ ) {
  1269. cacheIndex = 0;
  1270. len = $row[ rowIndex ].cells.length;
  1271. cells = [];
  1272. rowData = {
  1273. child : [],
  1274. raw : [],
  1275. $row : $row.eq( rowIndex ),
  1276. order : c.cache[ tbodyIndex ].normalized.length
  1277. };
  1278. // add each cell
  1279. for ( cellIndex = 0; cellIndex < len; cellIndex++ ) {
  1280. cell = $row[ rowIndex ].cells[ cellIndex ];
  1281. txt = ts.getElementText( c, cell, cacheIndex );
  1282. rowData.raw[ cacheIndex ] = txt;
  1283. val = ts.getParsedText( c, cell, cacheIndex, txt );
  1284. cells[ cacheIndex ] = val;
  1285. if ( ( c.parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) {
  1286. // update column max value (ignore sign)
  1287. c.cache[ tbodyIndex ].colMax[ cacheIndex ] =
  1288. Math.max( Math.abs( val ) || 0, c.cache[ tbodyIndex ].colMax[ cacheIndex ] || 0 );
  1289. }
  1290. span = cell.colSpan - 1;
  1291. if ( span > 0 ) {
  1292. cacheIndex += span;
  1293. }
  1294. cacheIndex++;
  1295. }
  1296. // add the row data to the end
  1297. cells[ c.columns ] = rowData;
  1298. // update cache
  1299. c.cache[ tbodyIndex ].normalized.push( cells );
  1300. }
  1301. // resort using current settings
  1302. ts.checkResort( c, resort, callback );
  1303. }
  1304. },
  1305.  
  1306. updateCache : function( c, callback, $tbodies ) {
  1307. // rebuild parsers
  1308. if ( !( c.parsers && c.parsers.length ) ) {
  1309. ts.setupParsers( c, $tbodies );
  1310. }
  1311. // rebuild the cache map
  1312. ts.buildCache( c, callback, $tbodies );
  1313. },
  1314.  
  1315. // init flag (true) used by pager plugin to prevent widget application
  1316. // renamed from appendToTable
  1317. appendCache : function( c, init ) {
  1318. var parsed, totalRows, $tbody, $curTbody, rowIndex, tbodyIndex, appendTime,
  1319. table = c.table,
  1320. wo = c.widgetOptions,
  1321. $tbodies = c.$tbodies,
  1322. rows = [],
  1323. cache = c.cache;
  1324. // empty table - fixes #206/#346
  1325. if ( ts.isEmptyObject( cache ) ) {
  1326. // run pager appender in case the table was just emptied
  1327. return c.appender ? c.appender( table, rows ) :
  1328. table.isUpdating ? c.$table.trigger( 'updateComplete', table ) : ''; // Fixes #532
  1329. }
  1330. if ( c.debug ) {
  1331. appendTime = new Date();
  1332. }
  1333. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
  1334. $tbody = $tbodies.eq( tbodyIndex );
  1335. if ( $tbody.length ) {
  1336. // detach tbody for manipulation
  1337. $curTbody = ts.processTbody( table, $tbody, true );
  1338. parsed = cache[ tbodyIndex ].normalized;
  1339. totalRows = parsed.length;
  1340. for ( rowIndex = 0; rowIndex < totalRows; rowIndex++ ) {
  1341. rows.push( parsed[ rowIndex ][ c.columns ].$row );
  1342. // removeRows used by the pager plugin; don't render if using ajax - fixes #411
  1343. if ( !c.appender || ( c.pager && ( !c.pager.removeRows || !wo.pager_removeRows ) && !c.pager.ajax ) ) {
  1344. $curTbody.append( parsed[ rowIndex ][ c.columns ].$row );
  1345. }
  1346. }
  1347. // restore tbody
  1348. ts.processTbody( table, $curTbody, false );
  1349. }
  1350. }
  1351. if ( c.appender ) {
  1352. c.appender( table, rows );
  1353. }
  1354. if ( c.debug ) {
  1355. console.log( 'Rebuilt table' + ts.benchmark( appendTime ) );
  1356. }
  1357. // apply table widgets; but not before ajax completes
  1358. if ( !init && !c.appender ) {
  1359. ts.applyWidget( table );
  1360. }
  1361. if ( table.isUpdating ) {
  1362. c.$table.trigger( 'updateComplete', table );
  1363. }
  1364. },
  1365.  
  1366. commonUpdate : function( c, resort, callback ) {
  1367. // remove rows/elements before update
  1368. c.$table.find( c.selectorRemove ).remove();
  1369. // rebuild parsers
  1370. ts.setupParsers( c );
  1371. // rebuild the cache map
  1372. ts.buildCache( c );
  1373. ts.checkResort( c, resort, callback );
  1374. },
  1375.  
  1376. /*
  1377. ▄█████ ▄████▄ █████▄ ██████ ██ █████▄ ▄████▄
  1378. ▀█▄ ██ ██ ██▄▄██ ██ ██ ██ ██ ██ ▄▄▄
  1379. ▀█▄ ██ ██ ██▀██ ██ ██ ██ ██ ██ ▀██
  1380. █████▀ ▀████▀ ██ ██ ██ ██ ██ ██ ▀████▀
  1381. */
  1382. initSort : function( c, cell, event ) {
  1383. if ( c.table.isUpdating ) {
  1384. // let any updates complete before initializing a sort
  1385. return setTimeout( function(){
  1386. ts.initSort( c, cell, event );
  1387. }, 50 );
  1388. }
  1389. var arry, indx, headerIndx, dir, temp, tmp, $header,
  1390. notMultiSort = !event[ c.sortMultiSortKey ],
  1391. table = c.table,
  1392. len = c.$headers.length,
  1393. // get current column index
  1394. col = parseInt( $( cell ).attr( 'data-column' ), 10 ),
  1395. order = c.sortVars[ col ].order;
  1396.  
  1397. // Only call sortStart if sorting is enabled
  1398. c.$table.trigger( 'sortStart', table );
  1399. // get current column sort order
  1400. c.sortVars[ col ].count =
  1401. event[ c.sortResetKey ] ? 2 : ( c.sortVars[ col ].count + 1 ) % ( c.sortReset ? 3 : 2 );
  1402. // reset all sorts on non-current column - issue #30
  1403. if ( c.sortRestart ) {
  1404. tmp = cell;
  1405. for ( headerIndx = 0; headerIndx < len; headerIndx++ ) {
  1406. $header = c.$headers.eq( headerIndx );
  1407. // only reset counts on columns that weren't just clicked on and if not included in a multisort
  1408. if ( $header[ 0 ] !== tmp &&
  1409. ( notMultiSort || !$header.is( '.' + ts.css.sortDesc + ',.' + ts.css.sortAsc ) ) ) {
  1410. c.sortVars[ col ].count = -1;
  1411. }
  1412. }
  1413. }
  1414. // user only wants to sort on one column
  1415. if ( notMultiSort ) {
  1416. // flush the sort list
  1417. c.sortList = [];
  1418. c.last.sortList = [];
  1419. if ( c.sortForce !== null ) {
  1420. arry = c.sortForce;
  1421. for ( indx = 0; indx < arry.length; indx++ ) {
  1422. if ( arry[ indx ][ 0 ] !== col ) {
  1423. c.sortList.push( arry[ indx ] );
  1424. }
  1425. }
  1426. }
  1427. // add column to sort list
  1428. dir = order[ c.sortVars[ col ].count ];
  1429. if ( dir < 2 ) {
  1430. c.sortList.push( [ col, dir ] );
  1431. // add other columns if header spans across multiple
  1432. if ( cell.colSpan > 1 ) {
  1433. for ( indx = 1; indx < cell.colSpan; indx++ ) {
  1434. c.sortList.push( [ col + indx, dir ] );
  1435. // update count on columns in colSpan
  1436. c.sortVars[ col + indx ].count = $.inArray( dir, order );
  1437. }
  1438. }
  1439. }
  1440. // multi column sorting
  1441. } else {
  1442. // get rid of the sortAppend before adding more - fixes issue #115 & #523
  1443. c.sortList = $.extend( [], c.last.sortList );
  1444.  
  1445. // the user has clicked on an already sorted column
  1446. if ( ts.isValueInArray( col, c.sortList ) >= 0 ) {
  1447. // reverse the sorting direction
  1448. for ( indx = 0; indx < c.sortList.length; indx++ ) {
  1449. tmp = c.sortList[ indx ];
  1450. if ( tmp[ 0 ] === col ) {
  1451. // order.count seems to be incorrect when compared to cell.count
  1452. tmp[ 1 ] = order[ c.sortVars[ col ].count ];
  1453. if ( tmp[1] === 2 ) {
  1454. c.sortList.splice( indx, 1 );
  1455. c.sortVars[ col ].count = -1;
  1456. }
  1457. }
  1458. }
  1459. } else {
  1460. // add column to sort list array
  1461. dir = order[ c.sortVars[ col ].count ];
  1462. if ( dir < 2 ) {
  1463. c.sortList.push( [ col, dir ] );
  1464. // add other columns if header spans across multiple
  1465. if ( cell.colSpan > 1 ) {
  1466. for ( indx = 1; indx < cell.colSpan; indx++ ) {
  1467. c.sortList.push( [ col + indx, dir ] );
  1468. // update count on columns in colSpan
  1469. c.sortVars[ col + indx ].count = $.inArray( dir, order );
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. // save sort before applying sortAppend
  1476. c.last.sortList = $.extend( [], c.sortList );
  1477. if ( c.sortList.length && c.sortAppend ) {
  1478. arry = $.isArray( c.sortAppend ) ? c.sortAppend : c.sortAppend[ c.sortList[ 0 ][ 0 ] ];
  1479. if ( !ts.isEmptyObject( arry ) ) {
  1480. for ( indx = 0; indx < arry.length; indx++ ) {
  1481. if ( arry[ indx ][ 0 ] !== col && ts.isValueInArray( arry[ indx ][ 0 ], c.sortList ) < 0 ) {
  1482. dir = arry[ indx ][ 1 ];
  1483. temp = ( '' + dir ).match( /^(a|d|s|o|n)/ );
  1484. if ( temp ) {
  1485. tmp = c.sortList[ 0 ][ 1 ];
  1486. switch ( temp[ 0 ] ) {
  1487. case 'd' :
  1488. dir = 1;
  1489. break;
  1490. case 's' :
  1491. dir = tmp;
  1492. break;
  1493. case 'o' :
  1494. dir = tmp === 0 ? 1 : 0;
  1495. break;
  1496. case 'n' :
  1497. dir = ( tmp + 1 ) % ( c.sortReset ? 3 : 2 );
  1498. break;
  1499. default:
  1500. dir = 0;
  1501. break;
  1502. }
  1503. }
  1504. c.sortList.push( [ arry[ indx ][ 0 ], dir ] );
  1505. }
  1506. }
  1507. }
  1508. }
  1509. // sortBegin event triggered immediately before the sort
  1510. c.$table.trigger( 'sortBegin', table );
  1511. // setTimeout needed so the processing icon shows up
  1512. setTimeout( function() {
  1513. // set css for headers
  1514. ts.setHeadersCss( c );
  1515. ts.multisort( c );
  1516. ts.appendCache( c );
  1517. c.$table.trigger( 'sortEnd', table );
  1518. }, 1 );
  1519. },
  1520.  
  1521. // sort multiple columns
  1522. multisort : function( c ) { /*jshint loopfunc:true */
  1523. var tbodyIndex, sortTime, colMax, rows,
  1524. table = c.table,
  1525. dir = 0,
  1526. textSorter = c.textSorter || '',
  1527. sortList = c.sortList,
  1528. sortLen = sortList.length,
  1529. len = c.$tbodies.length;
  1530. if ( c.serverSideSorting || ts.isEmptyObject( c.cache ) ) {
  1531. // empty table - fixes #206/#346
  1532. return;
  1533. }
  1534. if ( c.debug ) { sortTime = new Date(); }
  1535. for ( tbodyIndex = 0; tbodyIndex < len; tbodyIndex++ ) {
  1536. colMax = c.cache[ tbodyIndex ].colMax;
  1537. rows = c.cache[ tbodyIndex ].normalized;
  1538.  
  1539. rows.sort( function( a, b ) {
  1540. var sortIndex, num, col, order, sort, x, y;
  1541. // rows is undefined here in IE, so don't use it!
  1542. for ( sortIndex = 0; sortIndex < sortLen; sortIndex++ ) {
  1543. col = sortList[ sortIndex ][ 0 ];
  1544. order = sortList[ sortIndex ][ 1 ];
  1545. // sort direction, true = asc, false = desc
  1546. dir = order === 0;
  1547.  
  1548. if ( c.sortStable && a[ col ] === b[ col ] && sortLen === 1 ) {
  1549. return a[ c.columns ].order - b[ c.columns ].order;
  1550. }
  1551.  
  1552. // fallback to natural sort since it is more robust
  1553. num = /n/i.test( ts.getSortType( c.parsers, col ) );
  1554. if ( num && c.strings[ col ] ) {
  1555. // sort strings in numerical columns
  1556. if ( typeof ( ts.string[ c.strings[ col ] ] ) === 'boolean' ) {
  1557. num = ( dir ? 1 : -1 ) * ( ts.string[ c.strings[ col ] ] ? -1 : 1 );
  1558. } else {
  1559. num = ( c.strings[ col ] ) ? ts.string[ c.strings[ col ] ] || 0 : 0;
  1560. }
  1561. // fall back to built-in numeric sort
  1562. // var sort = $.tablesorter['sort' + s]( a[col], b[col], dir, colMax[col], table );
  1563. sort = c.numberSorter ? c.numberSorter( a[ col ], b[ col ], dir, colMax[ col ], table ) :
  1564. ts[ 'sortNumeric' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], num, colMax[ col ], col, c );
  1565. } else {
  1566. // set a & b depending on sort direction
  1567. x = dir ? a : b;
  1568. y = dir ? b : a;
  1569. // text sort function
  1570. if ( typeof textSorter === 'function' ) {
  1571. // custom OVERALL text sorter
  1572. sort = textSorter( x[ col ], y[ col ], dir, col, table );
  1573. } else if ( typeof textSorter === 'object' && textSorter.hasOwnProperty( col ) ) {
  1574. // custom text sorter for a SPECIFIC COLUMN
  1575. sort = textSorter[ col ]( x[ col ], y[ col ], dir, col, table );
  1576. } else {
  1577. // fall back to natural sort
  1578. sort = ts[ 'sortNatural' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], col, c );
  1579. }
  1580. }
  1581. if ( sort ) { return sort; }
  1582. }
  1583. return a[ c.columns ].order - b[ c.columns ].order;
  1584. });
  1585. }
  1586. if ( c.debug ) {
  1587. console.log( 'Applying sort ' + sortList.toString() + ts.benchmark( sortTime ) );
  1588. }
  1589. },
  1590.  
  1591. resortComplete : function( c, callback ) {
  1592. if ( c.table.isUpdating ) {
  1593. c.$table.trigger( 'updateComplete', c.table );
  1594. }
  1595. if ( $.isFunction( callback ) ) {
  1596. callback( c.table );
  1597. }
  1598. },
  1599.  
  1600. checkResort : function( c, resort, callback ) {
  1601. var sortList = $.isArray( resort ) ? resort : c.sortList,
  1602. // if no resort parameter is passed, fallback to config.resort (true by default)
  1603. resrt = typeof resort === 'undefined' ? c.resort : resort;
  1604. // don't try to resort if the table is still processing
  1605. // this will catch spamming of the updateCell method
  1606. if ( resrt !== false && !c.serverSideSorting && !c.table.isProcessing ) {
  1607. if ( sortList.length ) {
  1608. ts.sortOn( c, sortList, function() {
  1609. ts.resortComplete( c, callback );
  1610. }, true );
  1611. } else {
  1612. ts.sortReset( c, function() {
  1613. ts.resortComplete( c, callback );
  1614. ts.applyWidget( c.table, false );
  1615. } );
  1616. }
  1617. } else {
  1618. ts.resortComplete( c, callback );
  1619. ts.applyWidget( c.table, false );
  1620. }
  1621. },
  1622.  
  1623. sortOn : function( c, list, callback, init ) {
  1624. var table = c.table;
  1625. c.$table.trigger( 'sortStart', table );
  1626. // update header count index
  1627. ts.updateHeaderSortCount( c, list );
  1628. // set css for headers
  1629. ts.setHeadersCss( c );
  1630. // fixes #346
  1631. if ( c.delayInit && ts.isEmptyObject( c.cache ) ) {
  1632. ts.buildCache( c );
  1633. }
  1634. c.$table.trigger( 'sortBegin', table );
  1635. // sort the table and append it to the dom
  1636. ts.multisort( c );
  1637. ts.appendCache( c, init );
  1638. c.$table.trigger( 'sortEnd', table );
  1639. ts.applyWidget( table );
  1640. if ( $.isFunction( callback ) ) {
  1641. callback( table );
  1642. }
  1643. },
  1644.  
  1645. sortReset : function( c, callback ) {
  1646. c.sortList = [];
  1647. ts.setHeadersCss( c );
  1648. ts.multisort( c );
  1649. ts.appendCache( c );
  1650. if ( $.isFunction( callback ) ) {
  1651. callback( c.table );
  1652. }
  1653. },
  1654.  
  1655. getSortType : function( parsers, column ) {
  1656. return ( parsers && parsers[ column ] ) ? parsers[ column ].type || '' : '';
  1657. },
  1658.  
  1659. formatSortingOrder : function( val ) {
  1660. // look for 'd' in 'desc' order; return true
  1661. return ( /^d/i.test( val ) || val === 1 );
  1662. },
  1663.  
  1664. // Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed)
  1665. // this function will only accept strings, or you'll see 'TypeError: undefined is not a function'
  1666. // I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall
  1667. sortNatural : function( a, b ) {
  1668. if ( a === b ) { return 0; }
  1669. var aNum, bNum, aFloat, bFloat, indx, max,
  1670. regex = ts.regex;
  1671. // first try and sort Hex codes
  1672. if ( regex.hex.test( b ) ) {
  1673. aNum = parseInt( a.match( regex.hex ), 16 );
  1674. bNum = parseInt( b.match( regex.hex ), 16 );
  1675. if ( aNum < bNum ) { return -1; }
  1676. if ( aNum > bNum ) { return 1; }
  1677. }
  1678. // chunk/tokenize
  1679. aNum = a.replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
  1680. bNum = b.replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
  1681. max = Math.max( aNum.length, bNum.length );
  1682. // natural sorting through split numeric strings and default strings
  1683. for ( indx = 0; indx < max; indx++ ) {
  1684. // find floats not starting with '0', string or 0 if not defined
  1685. aFloat = isNaN( aNum[ indx ] ) ? aNum[ indx ] || 0 : parseFloat( aNum[ indx ] ) || 0;
  1686. bFloat = isNaN( bNum[ indx ] ) ? bNum[ indx ] || 0 : parseFloat( bNum[ indx ] ) || 0;
  1687. // handle numeric vs string comparison - number < string - (Kyle Adams)
  1688. if ( isNaN( aFloat ) !== isNaN( bFloat ) ) { return isNaN( aFloat ) ? 1 : -1; }
  1689. // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
  1690. if ( typeof aFloat !== typeof bFloat ) {
  1691. aFloat += '';
  1692. bFloat += '';
  1693. }
  1694. if ( aFloat < bFloat ) { return -1; }
  1695. if ( aFloat > bFloat ) { return 1; }
  1696. }
  1697. return 0;
  1698. },
  1699.  
  1700. sortNaturalAsc : function( a, b, col, c ) {
  1701. if ( a === b ) { return 0; }
  1702. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1703. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
  1704. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
  1705. return ts.sortNatural( a, b );
  1706. },
  1707.  
  1708. sortNaturalDesc : function( a, b, col, c ) {
  1709. if ( a === b ) { return 0; }
  1710. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1711. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
  1712. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
  1713. return ts.sortNatural( b, a );
  1714. },
  1715.  
  1716. // basic alphabetical sort
  1717. sortText : function( a, b ) {
  1718. return a > b ? 1 : ( a < b ? -1 : 0 );
  1719. },
  1720.  
  1721. // return text string value by adding up ascii value
  1722. // so the text is somewhat sorted when using a digital sort
  1723. // this is NOT an alphanumeric sort
  1724. getTextValue : function( val, num, max ) {
  1725. if ( max ) {
  1726. // make sure the text value is greater than the max numerical value (max)
  1727. var indx,
  1728. len = val ? val.length : 0,
  1729. n = max + num;
  1730. for ( indx = 0; indx < len; indx++ ) {
  1731. n += val.charCodeAt( indx );
  1732. }
  1733. return num * n;
  1734. }
  1735. return 0;
  1736. },
  1737.  
  1738. sortNumericAsc : function( a, b, num, max, col, c ) {
  1739. if ( a === b ) { return 0; }
  1740. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1741. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
  1742. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
  1743. if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
  1744. if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
  1745. return a - b;
  1746. },
  1747.  
  1748. sortNumericDesc : function( a, b, num, max, col, c ) {
  1749. if ( a === b ) { return 0; }
  1750. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1751. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
  1752. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
  1753. if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
  1754. if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
  1755. return b - a;
  1756. },
  1757.  
  1758. sortNumeric : function( a, b ) {
  1759. return a - b;
  1760. },
  1761.  
  1762. /*
  1763. ██ ██ ██ ██ █████▄ ▄████▄ ██████ ██████ ▄█████
  1764. ██ ██ ██ ██ ██ ██ ██ ▄▄▄ ██▄▄ ██ ▀█▄
  1765. ██ ██ ██ ██ ██ ██ ██ ▀██ ██▀▀ ██ ▀█▄
  1766. ███████▀ ██ █████▀ ▀████▀ ██████ ██ █████▀
  1767. */
  1768. addWidget : function( widget ) {
  1769. ts.widgets.push( widget );
  1770. },
  1771.  
  1772. hasWidget : function( $table, name ) {
  1773. $table = $( $table );
  1774. return $table.length && $table[ 0 ].config && $table[ 0 ].config.widgetInit[ name ] || false;
  1775. },
  1776.  
  1777. getWidgetById : function( name ) {
  1778. var indx, widget,
  1779. len = ts.widgets.length;
  1780. for ( indx = 0; indx < len; indx++ ) {
  1781. widget = ts.widgets[ indx ];
  1782. if ( widget && widget.id && widget.id.toLowerCase() === name.toLowerCase() ) {
  1783. return widget;
  1784. }
  1785. }
  1786. },
  1787.  
  1788. applyWidgetOptions : function( table ) {
  1789. var indx, widget,
  1790. c = table.config,
  1791. len = c.widgets.length;
  1792. if ( len ) {
  1793. for ( indx = 0; indx < len; indx++ ) {
  1794. widget = ts.getWidgetById( c.widgets[ indx ] );
  1795. if ( widget && widget.options ) {
  1796. c.widgetOptions = $.extend( true, {}, widget.options, c.widgetOptions );
  1797. }
  1798. }
  1799. }
  1800. },
  1801.  
  1802. addWidgetFromClass : function( table ) {
  1803. var len, indx,
  1804. c = table.config,
  1805. // look for widgets to apply from table class
  1806. // stop using \b otherwise this matches 'ui-widget-content' & adds 'content' widget
  1807. regex = '\\s' + c.widgetClass.replace( ts.regex.templateName, '([\\w-]+)' ) + '\\s',
  1808. widgetClass = new RegExp( regex, 'g' ),
  1809. // extract out the widget id from the table class (widget id's can include dashes)
  1810. widget = ( ' ' + c.table.className + ' ' ).match( widgetClass );
  1811. if ( widget ) {
  1812. len = widget.length;
  1813. for ( indx = 0; indx < len; indx++ ) {
  1814. c.widgets.push( widget[ indx ].replace( widgetClass, '$1' ) );
  1815. }
  1816. }
  1817. },
  1818.  
  1819. applyWidget : function( table, init, callback ) {
  1820. table = $( table )[ 0 ]; // in case this is called externally
  1821. var indx, len, names, widget, name, applied, time, time2,
  1822. c = table.config,
  1823. widgets = [];
  1824. // prevent numerous consecutive widget applications
  1825. if ( init !== false && table.hasInitialized && ( table.isApplyingWidgets || table.isUpdating ) ) {
  1826. return;
  1827. }
  1828. if ( c.debug ) { time = new Date(); }
  1829. ts.addWidgetFromClass( table );
  1830. if ( c.widgets.length ) {
  1831. table.isApplyingWidgets = true;
  1832. // ensure unique widget ids
  1833. c.widgets = $.grep( c.widgets, function( val, index ) {
  1834. return $.inArray( val, c.widgets ) === index;
  1835. });
  1836. names = c.widgets || [];
  1837. len = names.length;
  1838. // build widget array & add priority as needed
  1839. for ( indx = 0; indx < len; indx++ ) {
  1840. widget = ts.getWidgetById( names[ indx ] );
  1841. if ( widget && widget.id ) {
  1842. // set priority to 10 if not defined
  1843. if ( !widget.priority ) { widget.priority = 10; }
  1844. widgets[ indx ] = widget;
  1845. }
  1846. }
  1847. // sort widgets by priority
  1848. widgets.sort( function( a, b ) {
  1849. return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1;
  1850. });
  1851. // add/update selected widgets
  1852. len = widgets.length;
  1853. if ( c.debug ) {
  1854. console[ console.group ? 'group' : 'log' ]( 'Start ' + ( init ? 'initializing' : 'applying' ) + ' widgets' );
  1855. }
  1856. for ( indx = 0; indx < len; indx++ ) {
  1857. widget = widgets[ indx ];
  1858. if ( widget ) {
  1859. name = widget.id;
  1860. applied = false;
  1861. if ( c.debug ) { time2 = new Date(); }
  1862.  
  1863. if ( init || !( c.widgetInit[ name ] ) ) {
  1864. // set init flag first to prevent calling init more than once (e.g. pager)
  1865. c.widgetInit[ name ] = true;
  1866. if ( table.hasInitialized ) {
  1867. // don't reapply widget options on tablesorter init
  1868. ts.applyWidgetOptions( table );
  1869. }
  1870. if ( typeof widget.init === 'function' ) {
  1871. applied = true;
  1872. if ( c.debug ) {
  1873. console[ console.group ? 'group' : 'log' ]( 'Initializing ' + name + ' widget' );
  1874. }
  1875. widget.init( table, widget, table.config, table.config.widgetOptions );
  1876. }
  1877. }
  1878. if ( !init && typeof widget.format === 'function' ) {
  1879. applied = true;
  1880. if ( c.debug ) {
  1881. console[ console.group ? 'group' : 'log' ]( 'Updating ' + name + ' widget' );
  1882. }
  1883. widget.format( table, table.config, table.config.widgetOptions, false );
  1884. }
  1885. if ( c.debug ) {
  1886. if ( applied ) {
  1887. console.log( 'Completed ' + ( init ? 'initializing ' : 'applying ' ) + name + ' widget' + ts.benchmark( time2 ) );
  1888. if ( console.groupEnd ) { console.groupEnd(); }
  1889. }
  1890. }
  1891. }
  1892. }
  1893. if ( c.debug && console.groupEnd ) { console.groupEnd(); }
  1894. // callback executed on init only
  1895. if ( !init && typeof callback === 'function' ) {
  1896. callback( table );
  1897. }
  1898. }
  1899. setTimeout( function() {
  1900. table.isApplyingWidgets = false;
  1901. $.data( table, 'lastWidgetApplication', new Date() );
  1902. c.$table.trigger('tablesorter-ready');
  1903. }, 0 );
  1904. if ( c.debug ) {
  1905. widget = c.widgets.length;
  1906. console.log( 'Completed ' +
  1907. ( init === true ? 'initializing ' : 'applying ' ) + widget +
  1908. ' widget' + ( widget !== 1 ? 's' : '' ) + ts.benchmark( time ) );
  1909. }
  1910. },
  1911.  
  1912. removeWidget : function( table, name, refreshing ) {
  1913. table = $( table )[ 0 ];
  1914. var index, widget, indx, len,
  1915. c = table.config;
  1916. // if name === true, add all widgets from $.tablesorter.widgets
  1917. if ( name === true ) {
  1918. name = [];
  1919. len = ts.widgets.length;
  1920. for ( indx = 0; indx < len; indx++ ) {
  1921. widget = ts.widgets[ indx ];
  1922. if ( widget && widget.id ) {
  1923. name.push( widget.id );
  1924. }
  1925. }
  1926. } else {
  1927. // name can be either an array of widgets names,
  1928. // or a space/comma separated list of widget names
  1929. name = ( $.isArray( name ) ? name.join( ',' ) : name || '' ).toLowerCase().split( /[\s,]+/ );
  1930. }
  1931. len = name.length;
  1932. for ( index = 0; index < len; index++ ) {
  1933. widget = ts.getWidgetById( name[ index ] );
  1934. indx = $.inArray( name[ index ], c.widgets );
  1935. if ( widget && widget.remove ) {
  1936. if ( c.debug ) {
  1937. console.log( ( refreshing ? 'Refreshing' : 'Removing' ) + ' "' + name[ index ] + '" widget' );
  1938. }
  1939. widget.remove( table, c, c.widgetOptions, refreshing );
  1940. c.widgetInit[ name[ index ] ] = false;
  1941. }
  1942. // don't remove the widget from config.widget if refreshing
  1943. if ( indx >= 0 && refreshing !== true ) {
  1944. c.widgets.splice( indx, 1 );
  1945. }
  1946. }
  1947. },
  1948.  
  1949. refreshWidgets : function( table, doAll, dontapply ) {
  1950. table = $( table )[ 0 ]; // see issue #243
  1951. var indx, widget,
  1952. c = table.config,
  1953. curWidgets = c.widgets,
  1954. widgets = ts.widgets,
  1955. len = widgets.length,
  1956. list = [],
  1957. callback = function( table ) {
  1958. $( table ).trigger( 'refreshComplete' );
  1959. };
  1960. // remove widgets not defined in config.widgets, unless doAll is true
  1961. for ( indx = 0; indx < len; indx++ ) {
  1962. widget = widgets[ indx ];
  1963. if ( widget && widget.id && ( doAll || $.inArray( widget.id, curWidgets ) < 0 ) ) {
  1964. list.push( widget.id );
  1965. }
  1966. }
  1967. ts.removeWidget( table, list.join( ',' ), true );
  1968. if ( dontapply !== true ) {
  1969. // call widget init if
  1970. ts.applyWidget( table, doAll || false, callback );
  1971. if ( doAll ) {
  1972. // apply widget format
  1973. ts.applyWidget( table, false, callback );
  1974. }
  1975. } else {
  1976. callback( table );
  1977. }
  1978. },
  1979.  
  1980. /*
  1981. ██ ██ ██████ ██ ██ ██ ██████ ██ ██████ ▄█████
  1982. ██ ██ ██ ██ ██ ██ ██ ██ ██▄▄ ▀█▄
  1983. ██ ██ ██ ██ ██ ██ ██ ██ ██▀▀ ▀█▄
  1984. ▀████▀ ██ ██ ██████ ██ ██ ██ ██████ █████▀
  1985. */
  1986. benchmark : function( diff ) {
  1987. return ( ' ( ' + ( new Date().getTime() - diff.getTime() ) + 'ms )' );
  1988. },
  1989. // deprecated ts.log
  1990. log : function() {
  1991. console.log( arguments );
  1992. },
  1993.  
  1994. // $.isEmptyObject from jQuery v1.4
  1995. isEmptyObject : function( obj ) {
  1996. /*jshint forin: false */
  1997. for ( var name in obj ) {
  1998. return false;
  1999. }
  2000. return true;
  2001. },
  2002.  
  2003. isValueInArray : function( column, arry ) {
  2004. var indx,
  2005. len = arry && arry.length || 0;
  2006. for ( indx = 0; indx < len; indx++ ) {
  2007. if ( arry[ indx ][ 0 ] === column ) {
  2008. return indx;
  2009. }
  2010. }
  2011. return -1;
  2012. },
  2013.  
  2014. formatFloat : function( str, table ) {
  2015. if ( typeof str !== 'string' || str === '' ) { return str; }
  2016. // allow using formatFloat without a table; defaults to US number format
  2017. var num,
  2018. usFormat = table && table.config ? table.config.usNumberFormat !== false :
  2019. typeof table !== 'undefined' ? table : true;
  2020. if ( usFormat ) {
  2021. // US Format - 1,234,567.89 -> 1234567.89
  2022. str = str.replace( ts.regex.comma, '' );
  2023. } else {
  2024. // German Format = 1.234.567,89 -> 1234567.89
  2025. // French Format = 1 234 567,89 -> 1234567.89
  2026. str = str.replace( ts.regex.digitNonUS, '' ).replace( ts.regex.comma, '.' );
  2027. }
  2028. if ( ts.regex.digitNegativeTest.test( str ) ) {
  2029. // make (#) into a negative number -> (10) = -10
  2030. str = str.replace( ts.regex.digitNegativeReplace, '-$1' );
  2031. }
  2032. num = parseFloat( str );
  2033. // return the text instead of zero
  2034. return isNaN( num ) ? $.trim( str ) : num;
  2035. },
  2036.  
  2037. isDigit : function( str ) {
  2038. // replace all unwanted chars and match
  2039. return isNaN( str ) ?
  2040. ts.regex.digitTest.test( str.toString().replace( ts.regex.digitReplace, '' ) ) :
  2041. str !== '';
  2042. },
  2043.  
  2044. // computeTableHeaderCellIndexes from:
  2045. // http://www.javascripttoolbox.com/lib/table/examples.php
  2046. // http://www.javascripttoolbox.com/temp/table_cellindex.html
  2047. computeColumnIndex : function( $rows ) {
  2048. var i, j, k, l, $cell, cell, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol,
  2049. matrix = [],
  2050. matrixrow = [];
  2051. for ( i = 0; i < $rows.length; i++ ) {
  2052. cells = $rows[ i ].cells;
  2053. for ( j = 0; j < cells.length; j++ ) {
  2054. cell = cells[ j ];
  2055. $cell = $( cell );
  2056. rowIndex = cell.parentNode.rowIndex;
  2057. cellId = rowIndex + '-' + $cell.index();
  2058. rowSpan = cell.rowSpan || 1;
  2059. colSpan = cell.colSpan || 1;
  2060. if ( typeof matrix[ rowIndex ] === 'undefined' ) {
  2061. matrix[ rowIndex ] = [];
  2062. }
  2063. // Find first available column in the first row
  2064. for ( k = 0; k < matrix[ rowIndex ].length + 1; k++ ) {
  2065. if ( typeof matrix[ rowIndex ][ k ] === 'undefined' ) {
  2066. firstAvailCol = k;
  2067. break;
  2068. }
  2069. }
  2070. // add data-column (setAttribute = IE8+)
  2071. if ( cell.setAttribute ) {
  2072. cell.setAttribute( 'data-column', firstAvailCol );
  2073. } else {
  2074. $cell.attr( 'data-column', firstAvailCol );
  2075. }
  2076. for ( k = rowIndex; k < rowIndex + rowSpan; k++ ) {
  2077. if ( typeof matrix[ k ] === 'undefined' ) {
  2078. matrix[ k ] = [];
  2079. }
  2080. matrixrow = matrix[ k ];
  2081. for ( l = firstAvailCol; l < firstAvailCol + colSpan; l++ ) {
  2082. matrixrow[ l ] = 'x';
  2083. }
  2084. }
  2085. }
  2086. }
  2087. return matrixrow.length;
  2088. },
  2089.  
  2090. // automatically add a colgroup with col elements set to a percentage width
  2091. fixColumnWidth : function( table ) {
  2092. table = $( table )[ 0 ];
  2093. var overallWidth, percent, $tbodies, len, index,
  2094. c = table.config,
  2095. $colgroup = c.$table.children( 'colgroup' );
  2096. // remove plugin-added colgroup, in case we need to refresh the widths
  2097. if ( $colgroup.length && $colgroup.hasClass( ts.css.colgroup ) ) {
  2098. $colgroup.remove();
  2099. }
  2100. if ( c.widthFixed && c.$table.children( 'colgroup' ).length === 0 ) {
  2101. $colgroup = $( '<colgroup class="' + ts.css.colgroup + '">' );
  2102. overallWidth = c.$table.width();
  2103. // only add col for visible columns - fixes #371
  2104. $tbodies = c.$tbodies.find( 'tr:first' ).children( ':visible' );
  2105. len = $tbodies.length;
  2106. for ( index = 0; index < len; index++ ) {
  2107. percent = parseInt( ( $tbodies.eq( index ).width() / overallWidth ) * 1000, 10 ) / 10 + '%';
  2108. $colgroup.append( $( '<col>' ).css( 'width', percent ) );
  2109. }
  2110. c.$table.prepend( $colgroup );
  2111. }
  2112. },
  2113.  
  2114. // get sorter, string, empty, etc options for each column from
  2115. // jQuery data, metadata, header option or header class name ('sorter-false')
  2116. // priority = jQuery data > meta > headers option > header class name
  2117. getData : function( header, configHeader, key ) {
  2118. var meta, cl4ss,
  2119. val = '',
  2120. $header = $( header );
  2121. if ( !$header.length ) { return ''; }
  2122. meta = $.metadata ? $header.metadata() : false;
  2123. cl4ss = ' ' + ( $header.attr( 'class' ) || '' );
  2124. if ( typeof $header.data( key ) !== 'undefined' ||
  2125. typeof $header.data( key.toLowerCase() ) !== 'undefined' ) {
  2126. // 'data-lockedOrder' is assigned to 'lockedorder'; but 'data-locked-order' is assigned to 'lockedOrder'
  2127. // 'data-sort-initial-order' is assigned to 'sortInitialOrder'
  2128. val += $header.data( key ) || $header.data( key.toLowerCase() );
  2129. } else if ( meta && typeof meta[ key ] !== 'undefined' ) {
  2130. val += meta[ key ];
  2131. } else if ( configHeader && typeof configHeader[ key ] !== 'undefined' ) {
  2132. val += configHeader[ key ];
  2133. } else if ( cl4ss !== ' ' && cl4ss.match( ' ' + key + '-' ) ) {
  2134. // include sorter class name 'sorter-text', etc; now works with 'sorter-my-custom-parser'
  2135. val = cl4ss.match( new RegExp( '\\s' + key + '-([\\w-]+)' ) )[ 1 ] || '';
  2136. }
  2137. return $.trim( val );
  2138. },
  2139.  
  2140. getColumnData : function( table, obj, indx, getCell, $headers ) {
  2141. if ( typeof obj === 'undefined' || obj === null ) { return; }
  2142. table = $( table )[ 0 ];
  2143. var $header, key,
  2144. c = table.config,
  2145. $cells = ( $headers || c.$headers ),
  2146. // c.$headerIndexed is not defined initially
  2147. $cell = c.$headerIndexed && c.$headerIndexed[ indx ] ||
  2148. $cells.filter( '[data-column="' + indx + '"]:last' );
  2149. if ( obj[ indx ] ) {
  2150. return getCell ? obj[ indx ] : obj[ $cells.index( $cell ) ];
  2151. }
  2152. for ( key in obj ) {
  2153. if ( typeof key === 'string' ) {
  2154. $header = $cell
  2155. // header cell with class/id
  2156. .filter( key )
  2157. // find elements within the header cell with cell/id
  2158. .add( $cell.find( key ) );
  2159. if ( $header.length ) {
  2160. return obj[ key ];
  2161. }
  2162. }
  2163. }
  2164. return;
  2165. },
  2166.  
  2167. // *** Process table ***
  2168. // add processing indicator
  2169. isProcessing : function( $table, toggle, $ths ) {
  2170. $table = $( $table );
  2171. var c = $table[ 0 ].config,
  2172. // default to all headers
  2173. $header = $ths || $table.find( '.' + ts.css.header );
  2174. if ( toggle ) {
  2175. // don't use sortList if custom $ths used
  2176. if ( typeof $ths !== 'undefined' && c.sortList.length > 0 ) {
  2177. // get headers from the sortList
  2178. $header = $header.filter( function() {
  2179. // get data-column from attr to keep compatibility with jQuery 1.2.6
  2180. return this.sortDisabled ?
  2181. false :
  2182. ts.isValueInArray( parseFloat( $( this ).attr( 'data-column' ) ), c.sortList ) >= 0;
  2183. });
  2184. }
  2185. $table.add( $header ).addClass( ts.css.processing + ' ' + c.cssProcessing );
  2186. } else {
  2187. $table.add( $header ).removeClass( ts.css.processing + ' ' + c.cssProcessing );
  2188. }
  2189. },
  2190.  
  2191. // detach tbody but save the position
  2192. // don't use tbody because there are portions that look for a tbody index (updateCell)
  2193. processTbody : function( table, $tb, getIt ) {
  2194. table = $( table )[ 0 ];
  2195. if ( getIt ) {
  2196. table.isProcessing = true;
  2197. $tb.before( '<colgroup class="tablesorter-savemyplace"/>' );
  2198. return $.fn.detach ? $tb.detach() : $tb.remove();
  2199. }
  2200. var holdr = $( table ).find( 'colgroup.tablesorter-savemyplace' );
  2201. $tb.insertAfter( holdr );
  2202. holdr.remove();
  2203. table.isProcessing = false;
  2204. },
  2205.  
  2206. clearTableBody : function( table ) {
  2207. $( table )[ 0 ].config.$tbodies.children().detach();
  2208. },
  2209.  
  2210. // used when replacing accented characters during sorting
  2211. characterEquivalents : {
  2212. 'a' : '\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5', // áàâãäąå
  2213. 'A' : '\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5', // ÁÀÂÃÄĄÅ
  2214. 'c' : '\u00e7\u0107\u010d', // çćč
  2215. 'C' : '\u00c7\u0106\u010c', // ÇĆČ
  2216. 'e' : '\u00e9\u00e8\u00ea\u00eb\u011b\u0119', // éèêëěę
  2217. 'E' : '\u00c9\u00c8\u00ca\u00cb\u011a\u0118', // ÉÈÊËĚĘ
  2218. 'i' : '\u00ed\u00ec\u0130\u00ee\u00ef\u0131', // íìİîïı
  2219. 'I' : '\u00cd\u00cc\u0130\u00ce\u00cf', // ÍÌİÎÏ
  2220. 'o' : '\u00f3\u00f2\u00f4\u00f5\u00f6\u014d', // óòôõöō
  2221. 'O' : '\u00d3\u00d2\u00d4\u00d5\u00d6\u014c', // ÓÒÔÕÖŌ
  2222. 'ss': '\u00df', // ß (s sharp)
  2223. 'SS': '\u1e9e', // ẞ (Capital sharp s)
  2224. 'u' : '\u00fa\u00f9\u00fb\u00fc\u016f', // úùûüů
  2225. 'U' : '\u00da\u00d9\u00db\u00dc\u016e' // ÚÙÛÜŮ
  2226. },
  2227.  
  2228. replaceAccents : function( str ) {
  2229. var chr,
  2230. acc = '[',
  2231. eq = ts.characterEquivalents;
  2232. if ( !ts.characterRegex ) {
  2233. ts.characterRegexArray = {};
  2234. for ( chr in eq ) {
  2235. if ( typeof chr === 'string' ) {
  2236. acc += eq[ chr ];
  2237. ts.characterRegexArray[ chr ] = new RegExp( '[' + eq[ chr ] + ']', 'g' );
  2238. }
  2239. }
  2240. ts.characterRegex = new RegExp( acc + ']' );
  2241. }
  2242. if ( ts.characterRegex.test( str ) ) {
  2243. for ( chr in eq ) {
  2244. if ( typeof chr === 'string' ) {
  2245. str = str.replace( ts.characterRegexArray[ chr ], chr );
  2246. }
  2247. }
  2248. }
  2249. return str;
  2250. },
  2251.  
  2252. // restore headers
  2253. restoreHeaders : function( table ) {
  2254. var index, $cell,
  2255. c = $( table )[ 0 ].config,
  2256. $headers = c.$table.find( c.selectorHeaders ),
  2257. len = $headers.length;
  2258. // don't use c.$headers here in case header cells were swapped
  2259. for ( index = 0; index < len; index++ ) {
  2260. $cell = $headers.eq( index );
  2261. // only restore header cells if it is wrapped
  2262. // because this is also used by the updateAll method
  2263. if ( $cell.find( '.' + ts.css.headerIn ).length ) {
  2264. $cell.html( c.headerContent[ index ] );
  2265. }
  2266. }
  2267. },
  2268.  
  2269. destroy : function( table, removeClasses, callback ) {
  2270. table = $( table )[ 0 ];
  2271. if ( !table.hasInitialized ) { return; }
  2272. // remove all widgets
  2273. ts.removeWidget( table, true, false );
  2274. var events,
  2275. $t = $( table ),
  2276. c = table.config,
  2277. debug = c.debug,
  2278. $h = $t.find( 'thead:first' ),
  2279. $r = $h.find( 'tr.' + ts.css.headerRow ).removeClass( ts.css.headerRow + ' ' + c.cssHeaderRow ),
  2280. $f = $t.find( 'tfoot:first > tr' ).children( 'th, td' );
  2281. if ( removeClasses === false && $.inArray( 'uitheme', c.widgets ) >= 0 ) {
  2282. // reapply uitheme classes, in case we want to maintain appearance
  2283. $t.trigger( 'applyWidgetId', [ 'uitheme' ] );
  2284. $t.trigger( 'applyWidgetId', [ 'zebra' ] );
  2285. }
  2286. // remove widget added rows, just in case
  2287. $h.find( 'tr' ).not( $r ).remove();
  2288. // disable tablesorter
  2289. events = 'sortReset update updateRows updateAll updateHeaders updateCell addRows updateComplete sorton ' +
  2290. 'appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress ' +
  2291. 'sortBegin sortEnd resetToLoadState '.split( ' ' )
  2292. .join( c.namespace + ' ' );
  2293. $t
  2294. .removeData( 'tablesorter' )
  2295. .unbind( events.replace( ts.regex.spaces, ' ' ) );
  2296. c.$headers
  2297. .add( $f )
  2298. .removeClass( [ ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone ].join( ' ' ) )
  2299. .removeAttr( 'data-column' )
  2300. .removeAttr( 'aria-label' )
  2301. .attr( 'aria-disabled', 'true' );
  2302. $r
  2303. .find( c.selectorSort )
  2304. .unbind( ( 'mousedown mouseup keypress '.split( ' ' ).join( c.namespace + ' ' ) ).replace( ts.regex.spaces, ' ' ) );
  2305. ts.restoreHeaders( table );
  2306. $t.toggleClass( ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false );
  2307. // clear flag in case the plugin is initialized again
  2308. table.hasInitialized = false;
  2309. delete table.config.cache;
  2310. if ( typeof callback === 'function' ) {
  2311. callback( table );
  2312. }
  2313. if ( debug ) {
  2314. console.log( 'tablesorter has been removed' );
  2315. }
  2316. }
  2317.  
  2318. };
  2319.  
  2320. $.fn.tablesorter = function( settings ) {
  2321. return this.each( function() {
  2322. var table = this,
  2323. // merge & extend config options
  2324. c = $.extend( true, {}, ts.defaults, settings, ts.instanceMethods );
  2325. // save initial settings
  2326. c.originalSettings = settings;
  2327. // create a table from data (build table widget)
  2328. if ( !table.hasInitialized && ts.buildTable && this.nodeName !== 'TABLE' ) {
  2329. // return the table (in case the original target is the table's container)
  2330. ts.buildTable( table, c );
  2331. } else {
  2332. ts.setup( table, c );
  2333. }
  2334. });
  2335. };
  2336.  
  2337. // set up debug logs
  2338. if ( !( window.console && window.console.log ) ) {
  2339. // access $.tablesorter.logs for browsers that don't have a console...
  2340. ts.logs = [];
  2341. /*jshint -W020 */
  2342. console = {};
  2343. console.log = console.warn = console.error = console.table = function() {
  2344. var arg = arguments.length > 1 ? arguments : arguments[0];
  2345. ts.logs.push({ date: Date.now(), log: arg });
  2346. };
  2347. }
  2348.  
  2349. // add default parsers
  2350. ts.addParser({
  2351. id : 'no-parser',
  2352. is : function() {
  2353. return false;
  2354. },
  2355. format : function() {
  2356. return '';
  2357. },
  2358. type : 'text'
  2359. });
  2360.  
  2361. ts.addParser({
  2362. id : 'text',
  2363. is : function() {
  2364. return true;
  2365. },
  2366. format : function( str, table ) {
  2367. var c = table.config;
  2368. if ( str ) {
  2369. str = $.trim( c.ignoreCase ? str.toLocaleLowerCase() : str );
  2370. str = c.sortLocaleCompare ? ts.replaceAccents( str ) : str;
  2371. }
  2372. return str;
  2373. },
  2374. type : 'text'
  2375. });
  2376.  
  2377. ts.regex.nondigit = /[^\w,. \-()]/g;
  2378. ts.addParser({
  2379. id : 'digit',
  2380. is : function( str ) {
  2381. return ts.isDigit( str );
  2382. },
  2383. format : function( str, table ) {
  2384. var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
  2385. return str && typeof num === 'number' ? num :
  2386. str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
  2387. },
  2388. type : 'numeric'
  2389. });
  2390.  
  2391. ts.regex.currencyReplace = /[+\-,. ]/g;
  2392. ts.regex.currencyTest = /^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/;
  2393. ts.addParser({
  2394. id : 'currency',
  2395. is : function( str ) {
  2396. str = ( str || '' ).replace( ts.regex.currencyReplace, '' );
  2397. // test for £$€¤¥¢
  2398. return ts.regex.currencyTest.test( str );
  2399. },
  2400. format : function( str, table ) {
  2401. var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
  2402. return str && typeof num === 'number' ? num :
  2403. str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
  2404. },
  2405. type : 'numeric'
  2406. });
  2407.  
  2408. // too many protocols to add them all https://en.wikipedia.org/wiki/URI_scheme
  2409. // now, this regex can be updated before initialization
  2410. ts.regex.urlProtocolTest = /^(https?|ftp|file):\/\//;
  2411. ts.regex.urlProtocolReplace = /(https?|ftp|file):\/\//;
  2412. ts.addParser({
  2413. id : 'url',
  2414. is : function( str ) {
  2415. return ts.regex.urlProtocolTest.test( str );
  2416. },
  2417. format : function( str ) {
  2418. return str ? $.trim( str.replace( ts.regex.urlProtocolReplace, '' ) ) : str;
  2419. },
  2420. parsed : true, // filter widget flag
  2421. type : 'text'
  2422. });
  2423.  
  2424. ts.regex.dash = /-/g;
  2425. ts.regex.isoDate = /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/;
  2426. ts.addParser({
  2427. id : 'isoDate',
  2428. is : function( str ) {
  2429. return ts.regex.isoDate.test( str );
  2430. },
  2431. format : function( str, table ) {
  2432. var date = str ? new Date( str.replace( ts.regex.dash, '/' ) ) : str;
  2433. return date instanceof Date && isFinite( date ) ? date.getTime() : str;
  2434. },
  2435. type : 'numeric'
  2436. });
  2437.  
  2438. ts.regex.percent = /%/g;
  2439. ts.regex.percentTest = /(\d\s*?%|%\s*?\d)/;
  2440. ts.addParser({
  2441. id : 'percent',
  2442. is : function( str ) {
  2443. return ts.regex.percentTest.test( str ) && str.length < 15;
  2444. },
  2445. format : function( str, table ) {
  2446. return str ? ts.formatFloat( str.replace( ts.regex.percent, '' ), table ) : str;
  2447. },
  2448. type : 'numeric'
  2449. });
  2450.  
  2451. // added image parser to core v2.17.9
  2452. ts.addParser({
  2453. id : 'image',
  2454. is : function( str, table, node, $node ) {
  2455. return $node.find( 'img' ).length > 0;
  2456. },
  2457. format : function( str, table, cell ) {
  2458. return $( cell ).find( 'img' ).attr( table.config.imgAttr || 'alt' ) || str;
  2459. },
  2460. parsed : true, // filter widget flag
  2461. type : 'text'
  2462. });
  2463.  
  2464. ts.regex.dateReplace = /(\S)([AP]M)$/i; // used by usLongDate & time parser
  2465. ts.regex.usLongDateTest1 = /^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i;
  2466. ts.regex.usLongDateTest2 = /^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i;
  2467. ts.addParser({
  2468. id : 'usLongDate',
  2469. is : function( str ) {
  2470. // two digit years are not allowed cross-browser
  2471. // Jan 01, 2013 12:34:56 PM or 01 Jan 2013
  2472. return ts.regex.usLongDateTest1.test( str ) || ts.regex.usLongDateTest2.test( str );
  2473. },
  2474. format : function( str, table ) {
  2475. var date = str ? new Date( str.replace( ts.regex.dateReplace, '$1 $2' ) ) : str;
  2476. return date instanceof Date && isFinite( date ) ? date.getTime() : str;
  2477. },
  2478. type : 'numeric'
  2479. });
  2480.  
  2481. // testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included
  2482. ts.regex.shortDateTest = /(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/;
  2483. // escaped "-" because JSHint in Firefox was showing it as an error
  2484. ts.regex.shortDateReplace = /[\-.,]/g;
  2485. // XXY covers MDY & DMY formats
  2486. ts.regex.shortDateXXY = /(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/;
  2487. ts.regex.shortDateYMD = /(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/;
  2488. ts.convertFormat = function( dateString, format ) {
  2489. dateString = ( dateString || '' )
  2490. .replace( ts.regex.spaces, ' ' )
  2491. .replace( ts.regex.shortDateReplace, '/' );
  2492. if ( format === 'mmddyyyy' ) {
  2493. dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$1/$2' );
  2494. } else if ( format === 'ddmmyyyy' ) {
  2495. dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$2/$1' );
  2496. } else if ( format === 'yyyymmdd' ) {
  2497. dateString = dateString.replace( ts.regex.shortDateYMD, '$1/$2/$3' );
  2498. }
  2499. var date = new Date( dateString );
  2500. return date instanceof Date && isFinite( date ) ? date.getTime() : '';
  2501. };
  2502.  
  2503. ts.addParser({
  2504. id : 'shortDate', // 'mmddyyyy', 'ddmmyyyy' or 'yyyymmdd'
  2505. is : function( str ) {
  2506. str = ( str || '' ).replace( ts.regex.spaces, ' ' ).replace( ts.regex.shortDateReplace, '/' );
  2507. return ts.regex.shortDateTest.test( str );
  2508. },
  2509. format : function( str, table, cell, cellIndex ) {
  2510. if ( str ) {
  2511. var c = table.config,
  2512. $header = c.$headerIndexed[ cellIndex ],
  2513. format = $header.length && $header.data( 'dateFormat' ) ||
  2514. ts.getData( $header, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat' ) ||
  2515. c.dateFormat;
  2516. // save format because getData can be slow...
  2517. if ( $header.length ) {
  2518. $header.data( 'dateFormat', format );
  2519. }
  2520. return ts.convertFormat( str, format ) || str;
  2521. }
  2522. return str;
  2523. },
  2524. type : 'numeric'
  2525. });
  2526.  
  2527. // match 24 hour time & 12 hours time + am/pm - see http://regexr.com/3c3tk
  2528. ts.regex.timeTest = /^([1-9]|1[0-2]):([0-5]\d)(\s[AP]M)|((?:[01]\d|[2][0-4]):[0-5]\d)$/i;
  2529. ts.regex.timeMatch = /([1-9]|1[0-2]):([0-5]\d)(\s[AP]M)|((?:[01]\d|[2][0-4]):[0-5]\d)/i;
  2530. ts.addParser({
  2531. id : 'time',
  2532. is : function( str ) {
  2533. return ts.regex.timeTest.test( str );
  2534. },
  2535. format : function( str, table ) {
  2536. // isolate time... ignore month, day and year
  2537. var temp,
  2538. timePart = ( str || '' ).match( ts.regex.timeMatch ),
  2539. orig = new Date( str ),
  2540. // no time component? default to 00:00 by leaving it out, but only if str is defined
  2541. time = str && ( timePart !== null ? timePart[ 0 ] : '00:00 AM' ),
  2542. date = time ? new Date( '2000/01/01 ' + time.replace( ts.regex.dateReplace, '$1 $2' ) ) : time;
  2543. if ( date instanceof Date && isFinite( date ) ) {
  2544. temp = orig instanceof Date && isFinite( orig ) ? orig.getTime() : 0;
  2545. // if original string was a valid date, add it to the decimal so the column sorts in some kind of order
  2546. // luckily new Date() ignores the decimals
  2547. return temp ? parseFloat( date.getTime() + '.' + orig.getTime() ) : date.getTime();
  2548. }
  2549. return str;
  2550. },
  2551. type : 'numeric'
  2552. });
  2553.  
  2554. ts.addParser({
  2555. id : 'metadata',
  2556. is : function() {
  2557. return false;
  2558. },
  2559. format : function( str, table, cell ) {
  2560. var c = table.config,
  2561. p = ( !c.parserMetadataName ) ? 'sortValue' : c.parserMetadataName;
  2562. return $( cell ).metadata()[ p ];
  2563. },
  2564. type : 'numeric'
  2565. });
  2566.  
  2567. /*
  2568. ██████ ██████ █████▄ █████▄ ▄████▄
  2569. ▄█▀ ██▄▄ ██▄▄██ ██▄▄██ ██▄▄██
  2570. ▄█▀ ██▀▀ ██▀▀██ ██▀▀█ ██▀▀██
  2571. ██████ ██████ █████▀ ██ ██ ██ ██
  2572. */
  2573. // add default widgets
  2574. ts.addWidget({
  2575. id : 'zebra',
  2576. priority : 90,
  2577. format : function( table, c, wo ) {
  2578. var $visibleRows, $row, count, isEven, tbodyIndex, rowIndex, len,
  2579. child = new RegExp( c.cssChildRow, 'i' ),
  2580. $tbodies = c.$tbodies.add( $( c.namespace + '_extra_table' ).children( 'tbody:not(.' + c.cssInfoBlock + ')' ) );
  2581. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
  2582. // loop through the visible rows
  2583. count = 0;
  2584. $visibleRows = $tbodies.eq( tbodyIndex ).children( 'tr:visible' ).not( c.selectorRemove );
  2585. len = $visibleRows.length;
  2586. for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
  2587. $row = $visibleRows.eq( rowIndex );
  2588. // style child rows the same way the parent row was styled
  2589. if ( !child.test( $row[ 0 ].className ) ) { count++; }
  2590. isEven = ( count % 2 === 0 );
  2591. $row
  2592. .removeClass( wo.zebra[ isEven ? 1 : 0 ] )
  2593. .addClass( wo.zebra[ isEven ? 0 : 1 ] );
  2594. }
  2595. }
  2596. },
  2597. remove : function( table, c, wo, refreshing ) {
  2598. if ( refreshing ) { return; }
  2599. var tbodyIndex, $tbody,
  2600. $tbodies = c.$tbodies,
  2601. toRemove = ( wo.zebra || [ 'even', 'odd' ] ).join( ' ' );
  2602. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ){
  2603. $tbody = ts.processTbody( table, $tbodies.eq( tbodyIndex ), true ); // remove tbody
  2604. $tbody.children().removeClass( toRemove );
  2605. ts.processTbody( table, $tbody, false ); // restore tbody
  2606. }
  2607. }
  2608. });
  2609.  
  2610. })( jQuery );

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址