TableSorter

Client-side table sorting with ease

当前为 2015-12-22 提交的版本,查看 最新版本

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

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

QingJ © 2025

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