TableSorter

Client-side table sorting with ease

当前为 2018-03-19 提交的版本,查看 最新版本

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

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

QingJ © 2025

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