TableSorter

Client-side table sorting with ease

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

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

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

QingJ © 2025

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