TableSorter

Client-side table sorting with ease

当前为 2016-05-11 提交的版本,查看 最新版本

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

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

QingJ © 2025

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