TableSorter

Client-side table sorting with ease

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

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

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

QingJ © 2025

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