TableSorter

Client-side table sorting with ease

当前为 2017-04-13 提交的版本,查看 最新版本

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

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

QingJ © 2025

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