TableSorter

Client-side table sorting with ease

当前为 2015-10-27 提交的版本,查看 最新版本

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

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

QingJ © 2025

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