TableSorter

Client-side table sorting with ease

当前为 2017-09-19 提交的版本,查看 最新版本

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

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

QingJ © 2025

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