TableSorter

Client-side table sorting with ease

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

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

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

QingJ © 2025

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