TableSorter

Client-side table sorting with ease

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

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

  1. /*! TableSorter (FORK) v2.28.6 *//*
  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.6',
  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' ).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. cache[ c.columns ].$row = $row;
  1332. if ( ( c.parsers[ icell ].type || '' ).toLowerCase() === 'numeric' ) {
  1333. // update column max value (ignore sign)
  1334. tbcache.colMax[ icell ] = Math.max( Math.abs( tmp ) || 0, tbcache.colMax[ icell ] || 0 );
  1335. }
  1336. tmp = resort !== 'undefined' ? resort : c.resort;
  1337. if ( tmp !== false ) {
  1338. // widgets will be reapplied
  1339. ts.checkResort( c, tmp, callback );
  1340. } else {
  1341. // don't reapply widgets is resort is false, just in case it causes
  1342. // problems with element focus
  1343. ts.resortComplete( c, callback );
  1344. }
  1345. } else {
  1346. if ( c.debug ) {
  1347. console.error( 'updateCell aborted, tbody missing or not within the indicated table' );
  1348. }
  1349. c.table.isUpdating = false;
  1350. }
  1351. },
  1352.  
  1353. addRows : function( c, $row, resort, callback ) {
  1354. var txt, val, tbodyIndex, rowIndex, rows, cellIndex, len, order,
  1355. cacheIndex, rowData, cells, cell, span,
  1356. // allow passing a row string if only one non-info tbody exists in the table
  1357. valid = typeof $row === 'string' && c.$tbodies.length === 1 && /<tr/.test( $row || '' ),
  1358. table = c.table;
  1359. if ( valid ) {
  1360. $row = $( $row );
  1361. c.$tbodies.append( $row );
  1362. } else if ( !$row ||
  1363. // row is a jQuery object?
  1364. !( $row instanceof jQuery ) ||
  1365. // row contained in the table?
  1366. ( $.fn.closest ? $row.closest( 'table' )[ 0 ] : $row.parents( 'table' )[ 0 ] ) !== c.table ) {
  1367. if ( c.debug ) {
  1368. console.error( 'addRows method requires (1) a jQuery selector reference to rows that have already ' +
  1369. 'been added to the table, or (2) row HTML string to be added to a table with only one tbody' );
  1370. }
  1371. return false;
  1372. }
  1373. table.isUpdating = true;
  1374. if ( ts.isEmptyObject( c.cache ) ) {
  1375. // empty table, do an update instead - fixes #450
  1376. ts.updateHeader( c );
  1377. ts.commonUpdate( c, resort, callback );
  1378. } else {
  1379. rows = $row.filter( 'tr' ).attr( 'role', 'row' ).length;
  1380. tbodyIndex = c.$tbodies.index( $row.parents( 'tbody' ).filter( ':first' ) );
  1381. // fixes adding rows to an empty table - see issue #179
  1382. if ( !( c.parsers && c.parsers.length ) ) {
  1383. ts.setupParsers( c );
  1384. }
  1385. // add each row
  1386. for ( rowIndex = 0; rowIndex < rows; rowIndex++ ) {
  1387. cacheIndex = 0;
  1388. len = $row[ rowIndex ].cells.length;
  1389. order = c.cache[ tbodyIndex ].normalized.length;
  1390. cells = [];
  1391. rowData = {
  1392. child : [],
  1393. raw : [],
  1394. $row : $row.eq( rowIndex ),
  1395. order : order
  1396. };
  1397. // add each cell
  1398. for ( cellIndex = 0; cellIndex < len; cellIndex++ ) {
  1399. cell = $row[ rowIndex ].cells[ cellIndex ];
  1400. txt = ts.getElementText( c, cell, cacheIndex );
  1401. rowData.raw[ cacheIndex ] = txt;
  1402. val = ts.getParsedText( c, cell, cacheIndex, txt );
  1403. cells[ cacheIndex ] = val;
  1404. if ( ( c.parsers[ cacheIndex ].type || '' ).toLowerCase() === 'numeric' ) {
  1405. // update column max value (ignore sign)
  1406. c.cache[ tbodyIndex ].colMax[ cacheIndex ] =
  1407. Math.max( Math.abs( val ) || 0, c.cache[ tbodyIndex ].colMax[ cacheIndex ] || 0 );
  1408. }
  1409. span = cell.colSpan - 1;
  1410. if ( span > 0 ) {
  1411. cacheIndex += span;
  1412. }
  1413. cacheIndex++;
  1414. }
  1415. // add the row data to the end
  1416. cells[ c.columns ] = rowData;
  1417. // update cache
  1418. c.cache[ tbodyIndex ].normalized[ order ] = cells;
  1419. }
  1420. // resort using current settings
  1421. ts.checkResort( c, resort, callback );
  1422. }
  1423. },
  1424.  
  1425. updateCache : function( c, callback, $tbodies ) {
  1426. // rebuild parsers
  1427. if ( !( c.parsers && c.parsers.length ) ) {
  1428. ts.setupParsers( c, $tbodies );
  1429. }
  1430. // rebuild the cache map
  1431. ts.buildCache( c, callback, $tbodies );
  1432. },
  1433.  
  1434. // init flag (true) used by pager plugin to prevent widget application
  1435. // renamed from appendToTable
  1436. appendCache : function( c, init ) {
  1437. var parsed, totalRows, $tbody, $curTbody, rowIndex, tbodyIndex, appendTime,
  1438. table = c.table,
  1439. wo = c.widgetOptions,
  1440. $tbodies = c.$tbodies,
  1441. rows = [],
  1442. cache = c.cache;
  1443. // empty table - fixes #206/#346
  1444. if ( ts.isEmptyObject( cache ) ) {
  1445. // run pager appender in case the table was just emptied
  1446. return c.appender ? c.appender( table, rows ) :
  1447. table.isUpdating ? c.$table.triggerHandler( 'updateComplete', table ) : ''; // Fixes #532
  1448. }
  1449. if ( c.debug ) {
  1450. appendTime = new Date();
  1451. }
  1452. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
  1453. $tbody = $tbodies.eq( tbodyIndex );
  1454. if ( $tbody.length ) {
  1455. // detach tbody for manipulation
  1456. $curTbody = ts.processTbody( table, $tbody, true );
  1457. parsed = cache[ tbodyIndex ].normalized;
  1458. totalRows = parsed.length;
  1459. for ( rowIndex = 0; rowIndex < totalRows; rowIndex++ ) {
  1460. rows[rows.length] = parsed[ rowIndex ][ c.columns ].$row;
  1461. // removeRows used by the pager plugin; don't render if using ajax - fixes #411
  1462. if ( !c.appender || ( c.pager && ( !c.pager.removeRows || !wo.pager_removeRows ) && !c.pager.ajax ) ) {
  1463. $curTbody.append( parsed[ rowIndex ][ c.columns ].$row );
  1464. }
  1465. }
  1466. // restore tbody
  1467. ts.processTbody( table, $curTbody, false );
  1468. }
  1469. }
  1470. if ( c.appender ) {
  1471. c.appender( table, rows );
  1472. }
  1473. if ( c.debug ) {
  1474. console.log( 'Rebuilt table' + ts.benchmark( appendTime ) );
  1475. }
  1476. // apply table widgets; but not before ajax completes
  1477. if ( !init && !c.appender ) {
  1478. ts.applyWidget( table );
  1479. }
  1480. if ( table.isUpdating ) {
  1481. c.$table.triggerHandler( 'updateComplete', table );
  1482. }
  1483. },
  1484.  
  1485. commonUpdate : function( c, resort, callback ) {
  1486. // remove rows/elements before update
  1487. c.$table.find( c.selectorRemove ).remove();
  1488. // rebuild parsers
  1489. ts.setupParsers( c );
  1490. // rebuild the cache map
  1491. ts.buildCache( c );
  1492. ts.checkResort( c, resort, callback );
  1493. },
  1494.  
  1495. /*
  1496. ▄█████ ▄████▄ █████▄ ██████ ██ █████▄ ▄████▄
  1497. ▀█▄ ██ ██ ██▄▄██ ██ ██ ██ ██ ██ ▄▄▄
  1498. ▀█▄ ██ ██ ██▀██ ██ ██ ██ ██ ██ ▀██
  1499. █████▀ ▀████▀ ██ ██ ██ ██ ██ ██ ▀████▀
  1500. */
  1501. initSort : function( c, cell, event ) {
  1502. if ( c.table.isUpdating ) {
  1503. // let any updates complete before initializing a sort
  1504. return setTimeout( function(){
  1505. ts.initSort( c, cell, event );
  1506. }, 50 );
  1507. }
  1508.  
  1509. var arry, indx, headerIndx, dir, temp, tmp, $header,
  1510. notMultiSort = !event[ c.sortMultiSortKey ],
  1511. table = c.table,
  1512. len = c.$headers.length,
  1513. // get current column index
  1514. col = parseInt( $( cell ).attr( 'data-column' ), 10 ),
  1515. order = c.sortVars[ col ].order;
  1516.  
  1517. // Only call sortStart if sorting is enabled
  1518. c.$table.triggerHandler( 'sortStart', table );
  1519. // get current column sort order
  1520. tmp = ( c.sortVars[ col ].count + 1 ) % order.length;
  1521. c.sortVars[ col ].count = event[ c.sortResetKey ] ? 2 : tmp;
  1522. // reset all sorts on non-current column - issue #30
  1523. if ( c.sortRestart ) {
  1524. for ( headerIndx = 0; headerIndx < len; headerIndx++ ) {
  1525. $header = c.$headers.eq( headerIndx );
  1526. tmp = parseInt( $header.attr( 'data-column' ), 10 );
  1527. // only reset counts on columns that weren't just clicked on and if not included in a multisort
  1528. if ( col !== tmp && ( notMultiSort || $header.hasClass( ts.css.sortNone ) ) ) {
  1529. c.sortVars[ tmp ].count = -1;
  1530. }
  1531. }
  1532. }
  1533. // user only wants to sort on one column
  1534. if ( notMultiSort ) {
  1535. // flush the sort list
  1536. c.sortList = [];
  1537. c.last.sortList = [];
  1538. if ( c.sortForce !== null ) {
  1539. arry = c.sortForce;
  1540. for ( indx = 0; indx < arry.length; indx++ ) {
  1541. if ( arry[ indx ][ 0 ] !== col ) {
  1542. c.sortList[ c.sortList.length ] = arry[ indx ];
  1543. }
  1544. }
  1545. }
  1546. // add column to sort list
  1547. dir = order[ c.sortVars[ col ].count ];
  1548. if ( dir < 2 ) {
  1549. c.sortList[ c.sortList.length ] = [ col, dir ];
  1550. // add other columns if header spans across multiple
  1551. if ( cell.colSpan > 1 ) {
  1552. for ( indx = 1; indx < cell.colSpan; indx++ ) {
  1553. c.sortList[ c.sortList.length ] = [ col + indx, dir ];
  1554. // update count on columns in colSpan
  1555. c.sortVars[ col + indx ].count = $.inArray( dir, order );
  1556. }
  1557. }
  1558. }
  1559. // multi column sorting
  1560. } else {
  1561. // get rid of the sortAppend before adding more - fixes issue #115 & #523
  1562. c.sortList = $.extend( [], c.last.sortList );
  1563.  
  1564. // the user has clicked on an already sorted column
  1565. if ( ts.isValueInArray( col, c.sortList ) >= 0 ) {
  1566. // reverse the sorting direction
  1567. for ( indx = 0; indx < c.sortList.length; indx++ ) {
  1568. tmp = c.sortList[ indx ];
  1569. if ( tmp[ 0 ] === col ) {
  1570. // order.count seems to be incorrect when compared to cell.count
  1571. tmp[ 1 ] = order[ c.sortVars[ col ].count ];
  1572. if ( tmp[1] === 2 ) {
  1573. c.sortList.splice( indx, 1 );
  1574. c.sortVars[ col ].count = -1;
  1575. }
  1576. }
  1577. }
  1578. } else {
  1579. // add column to sort list array
  1580. dir = order[ c.sortVars[ col ].count ];
  1581. if ( dir < 2 ) {
  1582. c.sortList[ c.sortList.length ] = [ col, dir ];
  1583. // add other columns if header spans across multiple
  1584. if ( cell.colSpan > 1 ) {
  1585. for ( indx = 1; indx < cell.colSpan; indx++ ) {
  1586. c.sortList[ c.sortList.length ] = [ col + indx, dir ];
  1587. // update count on columns in colSpan
  1588. c.sortVars[ col + indx ].count = $.inArray( dir, order );
  1589. }
  1590. }
  1591. }
  1592. }
  1593. }
  1594. // save sort before applying sortAppend
  1595. c.last.sortList = $.extend( [], c.sortList );
  1596. if ( c.sortList.length && c.sortAppend ) {
  1597. arry = $.isArray( c.sortAppend ) ? c.sortAppend : c.sortAppend[ c.sortList[ 0 ][ 0 ] ];
  1598. if ( !ts.isEmptyObject( arry ) ) {
  1599. for ( indx = 0; indx < arry.length; indx++ ) {
  1600. if ( arry[ indx ][ 0 ] !== col && ts.isValueInArray( arry[ indx ][ 0 ], c.sortList ) < 0 ) {
  1601. dir = arry[ indx ][ 1 ];
  1602. temp = ( '' + dir ).match( /^(a|d|s|o|n)/ );
  1603. if ( temp ) {
  1604. tmp = c.sortList[ 0 ][ 1 ];
  1605. switch ( temp[ 0 ] ) {
  1606. case 'd' :
  1607. dir = 1;
  1608. break;
  1609. case 's' :
  1610. dir = tmp;
  1611. break;
  1612. case 'o' :
  1613. dir = tmp === 0 ? 1 : 0;
  1614. break;
  1615. case 'n' :
  1616. dir = ( tmp + 1 ) % order.length;
  1617. break;
  1618. default:
  1619. dir = 0;
  1620. break;
  1621. }
  1622. }
  1623. c.sortList[ c.sortList.length ] = [ arry[ indx ][ 0 ], dir ];
  1624. }
  1625. }
  1626. }
  1627. }
  1628. // sortBegin event triggered immediately before the sort
  1629. c.$table.triggerHandler( 'sortBegin', table );
  1630. // setTimeout needed so the processing icon shows up
  1631. setTimeout( function() {
  1632. // set css for headers
  1633. ts.setHeadersCss( c );
  1634. ts.multisort( c );
  1635. ts.appendCache( c );
  1636. c.$table.triggerHandler( 'sortBeforeEnd', table );
  1637. c.$table.triggerHandler( 'sortEnd', table );
  1638. }, 1 );
  1639. },
  1640.  
  1641. // sort multiple columns
  1642. multisort : function( c ) { /*jshint loopfunc:true */
  1643. var tbodyIndex, sortTime, colMax, rows, tmp,
  1644. table = c.table,
  1645. sorter = [],
  1646. dir = 0,
  1647. textSorter = c.textSorter || '',
  1648. sortList = c.sortList,
  1649. sortLen = sortList.length,
  1650. len = c.$tbodies.length;
  1651. if ( c.serverSideSorting || ts.isEmptyObject( c.cache ) ) {
  1652. // empty table - fixes #206/#346
  1653. return;
  1654. }
  1655. if ( c.debug ) { sortTime = new Date(); }
  1656. // cache textSorter to optimize speed
  1657. if ( typeof textSorter === 'object' ) {
  1658. colMax = c.columns;
  1659. while ( colMax-- ) {
  1660. tmp = ts.getColumnData( table, textSorter, colMax );
  1661. if ( typeof tmp === 'function' ) {
  1662. sorter[ colMax ] = tmp;
  1663. }
  1664. }
  1665. }
  1666. for ( tbodyIndex = 0; tbodyIndex < len; tbodyIndex++ ) {
  1667. colMax = c.cache[ tbodyIndex ].colMax;
  1668. rows = c.cache[ tbodyIndex ].normalized;
  1669.  
  1670. rows.sort( function( a, b ) {
  1671. var sortIndex, num, col, order, sort, x, y;
  1672. // rows is undefined here in IE, so don't use it!
  1673. for ( sortIndex = 0; sortIndex < sortLen; sortIndex++ ) {
  1674. col = sortList[ sortIndex ][ 0 ];
  1675. order = sortList[ sortIndex ][ 1 ];
  1676. // sort direction, true = asc, false = desc
  1677. dir = order === 0;
  1678.  
  1679. if ( c.sortStable && a[ col ] === b[ col ] && sortLen === 1 ) {
  1680. return a[ c.columns ].order - b[ c.columns ].order;
  1681. }
  1682.  
  1683. // fallback to natural sort since it is more robust
  1684. num = /n/i.test( ts.getSortType( c.parsers, col ) );
  1685. if ( num && c.strings[ col ] ) {
  1686. // sort strings in numerical columns
  1687. if ( typeof ( ts.string[ c.strings[ col ] ] ) === 'boolean' ) {
  1688. num = ( dir ? 1 : -1 ) * ( ts.string[ c.strings[ col ] ] ? -1 : 1 );
  1689. } else {
  1690. num = ( c.strings[ col ] ) ? ts.string[ c.strings[ col ] ] || 0 : 0;
  1691. }
  1692. // fall back to built-in numeric sort
  1693. // var sort = $.tablesorter['sort' + s]( a[col], b[col], dir, colMax[col], table );
  1694. sort = c.numberSorter ? c.numberSorter( a[ col ], b[ col ], dir, colMax[ col ], table ) :
  1695. ts[ 'sortNumeric' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], num, colMax[ col ], col, c );
  1696. } else {
  1697. // set a & b depending on sort direction
  1698. x = dir ? a : b;
  1699. y = dir ? b : a;
  1700. // text sort function
  1701. if ( typeof textSorter === 'function' ) {
  1702. // custom OVERALL text sorter
  1703. sort = textSorter( x[ col ], y[ col ], dir, col, table );
  1704. } else if ( typeof sorter[ col ] === 'function' ) {
  1705. // custom text sorter for a SPECIFIC COLUMN
  1706. sort = sorter[ col ]( x[ col ], y[ col ], dir, col, table );
  1707. } else {
  1708. // fall back to natural sort
  1709. sort = ts[ 'sortNatural' + ( dir ? 'Asc' : 'Desc' ) ]( a[ col ], b[ col ], col, c );
  1710. }
  1711. }
  1712. if ( sort ) { return sort; }
  1713. }
  1714. return a[ c.columns ].order - b[ c.columns ].order;
  1715. });
  1716. }
  1717. if ( c.debug ) {
  1718. console.log( 'Applying sort ' + sortList.toString() + ts.benchmark( sortTime ) );
  1719. }
  1720. },
  1721.  
  1722. resortComplete : function( c, callback ) {
  1723. if ( c.table.isUpdating ) {
  1724. c.$table.triggerHandler( 'updateComplete', c.table );
  1725. }
  1726. if ( $.isFunction( callback ) ) {
  1727. callback( c.table );
  1728. }
  1729. },
  1730.  
  1731. checkResort : function( c, resort, callback ) {
  1732. var sortList = $.isArray( resort ) ? resort : c.sortList,
  1733. // if no resort parameter is passed, fallback to config.resort (true by default)
  1734. resrt = typeof resort === 'undefined' ? c.resort : resort;
  1735. // don't try to resort if the table is still processing
  1736. // this will catch spamming of the updateCell method
  1737. if ( resrt !== false && !c.serverSideSorting && !c.table.isProcessing ) {
  1738. if ( sortList.length ) {
  1739. ts.sortOn( c, sortList, function() {
  1740. ts.resortComplete( c, callback );
  1741. }, true );
  1742. } else {
  1743. ts.sortReset( c, function() {
  1744. ts.resortComplete( c, callback );
  1745. ts.applyWidget( c.table, false );
  1746. } );
  1747. }
  1748. } else {
  1749. ts.resortComplete( c, callback );
  1750. ts.applyWidget( c.table, false );
  1751. }
  1752. },
  1753.  
  1754. sortOn : function( c, list, callback, init ) {
  1755. var table = c.table;
  1756. c.$table.triggerHandler( 'sortStart', table );
  1757. // update header count index
  1758. ts.updateHeaderSortCount( c, list );
  1759. // set css for headers
  1760. ts.setHeadersCss( c );
  1761. // fixes #346
  1762. if ( c.delayInit && ts.isEmptyObject( c.cache ) ) {
  1763. ts.buildCache( c );
  1764. }
  1765. c.$table.triggerHandler( 'sortBegin', table );
  1766. // sort the table and append it to the dom
  1767. ts.multisort( c );
  1768. ts.appendCache( c, init );
  1769. c.$table.triggerHandler( 'sortBeforeEnd', table );
  1770. c.$table.triggerHandler( 'sortEnd', table );
  1771. ts.applyWidget( table );
  1772. if ( $.isFunction( callback ) ) {
  1773. callback( table );
  1774. }
  1775. },
  1776.  
  1777. sortReset : function( c, callback ) {
  1778. c.sortList = [];
  1779. ts.setHeadersCss( c );
  1780. ts.multisort( c );
  1781. ts.appendCache( c );
  1782. var indx;
  1783. for (indx = 0; indx < c.columns; indx++) {
  1784. c.sortVars[ indx ].count = -1;
  1785. }
  1786. if ( $.isFunction( callback ) ) {
  1787. callback( c.table );
  1788. }
  1789. },
  1790.  
  1791. getSortType : function( parsers, column ) {
  1792. return ( parsers && parsers[ column ] ) ? parsers[ column ].type || '' : '';
  1793. },
  1794.  
  1795. getOrder : function( val ) {
  1796. // look for 'd' in 'desc' order; return true
  1797. return ( /^d/i.test( val ) || val === 1 );
  1798. },
  1799.  
  1800. // Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed)
  1801. // this function will only accept strings, or you'll see 'TypeError: undefined is not a function'
  1802. // I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall
  1803. sortNatural : function( a, b ) {
  1804. if ( a === b ) { return 0; }
  1805. var aNum, bNum, aFloat, bFloat, indx, max,
  1806. regex = ts.regex;
  1807. // first try and sort Hex codes
  1808. if ( regex.hex.test( b ) ) {
  1809. aNum = parseInt( ( a || '' ).match( regex.hex ), 16 );
  1810. bNum = parseInt( ( b || '' ).match( regex.hex ), 16 );
  1811. if ( aNum < bNum ) { return -1; }
  1812. if ( aNum > bNum ) { return 1; }
  1813. }
  1814. // chunk/tokenize
  1815. aNum = ( a || '' ).replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
  1816. bNum = ( b || '' ).replace( regex.chunk, '\\0$1\\0' ).replace( regex.chunks, '' ).split( '\\0' );
  1817. max = Math.max( aNum.length, bNum.length );
  1818. // natural sorting through split numeric strings and default strings
  1819. for ( indx = 0; indx < max; indx++ ) {
  1820. // find floats not starting with '0', string or 0 if not defined
  1821. aFloat = isNaN( aNum[ indx ] ) ? aNum[ indx ] || 0 : parseFloat( aNum[ indx ] ) || 0;
  1822. bFloat = isNaN( bNum[ indx ] ) ? bNum[ indx ] || 0 : parseFloat( bNum[ indx ] ) || 0;
  1823. // handle numeric vs string comparison - number < string - (Kyle Adams)
  1824. if ( isNaN( aFloat ) !== isNaN( bFloat ) ) { return isNaN( aFloat ) ? 1 : -1; }
  1825. // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
  1826. if ( typeof aFloat !== typeof bFloat ) {
  1827. aFloat += '';
  1828. bFloat += '';
  1829. }
  1830. if ( aFloat < bFloat ) { return -1; }
  1831. if ( aFloat > bFloat ) { return 1; }
  1832. }
  1833. return 0;
  1834. },
  1835.  
  1836. sortNaturalAsc : function( a, b, col, c ) {
  1837. if ( a === b ) { return 0; }
  1838. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1839. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
  1840. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
  1841. return ts.sortNatural( a, b );
  1842. },
  1843.  
  1844. sortNaturalDesc : function( a, b, col, c ) {
  1845. if ( a === b ) { return 0; }
  1846. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1847. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
  1848. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
  1849. return ts.sortNatural( b, a );
  1850. },
  1851.  
  1852. // basic alphabetical sort
  1853. sortText : function( a, b ) {
  1854. return a > b ? 1 : ( a < b ? -1 : 0 );
  1855. },
  1856.  
  1857. // return text string value by adding up ascii value
  1858. // so the text is somewhat sorted when using a digital sort
  1859. // this is NOT an alphanumeric sort
  1860. getTextValue : function( val, num, max ) {
  1861. if ( max ) {
  1862. // make sure the text value is greater than the max numerical value (max)
  1863. var indx,
  1864. len = val ? val.length : 0,
  1865. n = max + num;
  1866. for ( indx = 0; indx < len; indx++ ) {
  1867. n += val.charCodeAt( indx );
  1868. }
  1869. return num * n;
  1870. }
  1871. return 0;
  1872. },
  1873.  
  1874. sortNumericAsc : function( a, b, num, max, col, c ) {
  1875. if ( a === b ) { return 0; }
  1876. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1877. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : -empty || -1; }
  1878. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : empty || 1; }
  1879. if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
  1880. if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
  1881. return a - b;
  1882. },
  1883.  
  1884. sortNumericDesc : function( a, b, num, max, col, c ) {
  1885. if ( a === b ) { return 0; }
  1886. var empty = ts.string[ ( c.empties[ col ] || c.emptyTo ) ];
  1887. if ( a === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? -1 : 1 ) : empty || 1; }
  1888. if ( b === '' && empty !== 0 ) { return typeof empty === 'boolean' ? ( empty ? 1 : -1 ) : -empty || -1; }
  1889. if ( isNaN( a ) ) { a = ts.getTextValue( a, num, max ); }
  1890. if ( isNaN( b ) ) { b = ts.getTextValue( b, num, max ); }
  1891. return b - a;
  1892. },
  1893.  
  1894. sortNumeric : function( a, b ) {
  1895. return a - b;
  1896. },
  1897.  
  1898. /*
  1899. ██ ██ ██ ██ █████▄ ▄████▄ ██████ ██████ ▄█████
  1900. ██ ██ ██ ██ ██ ██ ██ ▄▄▄ ██▄▄ ██ ▀█▄
  1901. ██ ██ ██ ██ ██ ██ ██ ▀██ ██▀▀ ██ ▀█▄
  1902. ███████▀ ██ █████▀ ▀████▀ ██████ ██ █████▀
  1903. */
  1904. addWidget : function( widget ) {
  1905. if ( widget.id && !ts.isEmptyObject( ts.getWidgetById( widget.id ) ) ) {
  1906. console.warn( '"' + widget.id + '" widget was loaded more than once!' );
  1907. }
  1908. ts.widgets[ ts.widgets.length ] = widget;
  1909. },
  1910.  
  1911. hasWidget : function( $table, name ) {
  1912. $table = $( $table );
  1913. return $table.length && $table[ 0 ].config && $table[ 0 ].config.widgetInit[ name ] || false;
  1914. },
  1915.  
  1916. getWidgetById : function( name ) {
  1917. var indx, widget,
  1918. len = ts.widgets.length;
  1919. for ( indx = 0; indx < len; indx++ ) {
  1920. widget = ts.widgets[ indx ];
  1921. if ( widget && widget.id && widget.id.toLowerCase() === name.toLowerCase() ) {
  1922. return widget;
  1923. }
  1924. }
  1925. },
  1926.  
  1927. applyWidgetOptions : function( table ) {
  1928. var indx, widget, wo,
  1929. c = table.config,
  1930. len = c.widgets.length;
  1931. if ( len ) {
  1932. for ( indx = 0; indx < len; indx++ ) {
  1933. widget = ts.getWidgetById( c.widgets[ indx ] );
  1934. if ( widget && widget.options ) {
  1935. wo = $.extend( {}, widget.options );
  1936. c.widgetOptions = $.extend( true, wo, c.widgetOptions );
  1937. // add widgetOptions to defaults for option validator
  1938. $.extend( true, ts.defaults.widgetOptions, widget.options );
  1939. }
  1940. }
  1941. }
  1942. },
  1943.  
  1944. addWidgetFromClass : function( table ) {
  1945. var len, indx,
  1946. c = table.config,
  1947. // look for widgets to apply from table class
  1948. // don't match from 'ui-widget-content'; use \S instead of \w to include widgets
  1949. // with dashes in the name, e.g. "widget-test-2" extracts out "test-2"
  1950. regex = '^' + c.widgetClass.replace( ts.regex.templateName, '(\\S+)+' ) + '$',
  1951. widgetClass = new RegExp( regex, 'g' ),
  1952. // split up table class (widget id's can include dashes) - stop using match
  1953. // otherwise only one widget gets extracted, see #1109
  1954. widgets = ( table.className || '' ).split( ts.regex.spaces );
  1955. if ( widgets.length ) {
  1956. len = widgets.length;
  1957. for ( indx = 0; indx < len; indx++ ) {
  1958. if ( widgets[ indx ].match( widgetClass ) ) {
  1959. c.widgets[ c.widgets.length ] = widgets[ indx ].replace( widgetClass, '$1' );
  1960. }
  1961. }
  1962. }
  1963. },
  1964.  
  1965. applyWidgetId : function( table, id, init ) {
  1966. table = $(table)[0];
  1967. var applied, time, name,
  1968. c = table.config,
  1969. wo = c.widgetOptions,
  1970. widget = ts.getWidgetById( id );
  1971. if ( widget ) {
  1972. name = widget.id;
  1973. applied = false;
  1974. // add widget name to option list so it gets reapplied after sorting, filtering, etc
  1975. if ( $.inArray( name, c.widgets ) < 0 ) {
  1976. c.widgets[ c.widgets.length ] = name;
  1977. }
  1978. if ( c.debug ) { time = new Date(); }
  1979.  
  1980. if ( init || !( c.widgetInit[ name ] ) ) {
  1981. // set init flag first to prevent calling init more than once (e.g. pager)
  1982. c.widgetInit[ name ] = true;
  1983. if ( table.hasInitialized ) {
  1984. // don't reapply widget options on tablesorter init
  1985. ts.applyWidgetOptions( table );
  1986. }
  1987. if ( typeof widget.init === 'function' ) {
  1988. applied = true;
  1989. if ( c.debug ) {
  1990. console[ console.group ? 'group' : 'log' ]( 'Initializing ' + name + ' widget' );
  1991. }
  1992. widget.init( table, widget, c, wo );
  1993. }
  1994. }
  1995. if ( !init && typeof widget.format === 'function' ) {
  1996. applied = true;
  1997. if ( c.debug ) {
  1998. console[ console.group ? 'group' : 'log' ]( 'Updating ' + name + ' widget' );
  1999. }
  2000. widget.format( table, c, wo, false );
  2001. }
  2002. if ( c.debug ) {
  2003. if ( applied ) {
  2004. console.log( 'Completed ' + ( init ? 'initializing ' : 'applying ' ) + name + ' widget' + ts.benchmark( time ) );
  2005. if ( console.groupEnd ) { console.groupEnd(); }
  2006. }
  2007. }
  2008. }
  2009. },
  2010.  
  2011. applyWidget : function( table, init, callback ) {
  2012. table = $( table )[ 0 ]; // in case this is called externally
  2013. var indx, len, names, widget, time,
  2014. c = table.config,
  2015. widgets = [];
  2016. // prevent numerous consecutive widget applications
  2017. if ( init !== false && table.hasInitialized && ( table.isApplyingWidgets || table.isUpdating ) ) {
  2018. return;
  2019. }
  2020. if ( c.debug ) { time = new Date(); }
  2021. ts.addWidgetFromClass( table );
  2022. // prevent "tablesorter-ready" from firing multiple times in a row
  2023. clearTimeout( c.timerReady );
  2024. if ( c.widgets.length ) {
  2025. table.isApplyingWidgets = true;
  2026. // ensure unique widget ids
  2027. c.widgets = $.grep( c.widgets, function( val, index ) {
  2028. return $.inArray( val, c.widgets ) === index;
  2029. });
  2030. names = c.widgets || [];
  2031. len = names.length;
  2032. // build widget array & add priority as needed
  2033. for ( indx = 0; indx < len; indx++ ) {
  2034. widget = ts.getWidgetById( names[ indx ] );
  2035. if ( widget && widget.id ) {
  2036. // set priority to 10 if not defined
  2037. if ( !widget.priority ) { widget.priority = 10; }
  2038. widgets[ indx ] = widget;
  2039. } else if ( c.debug ) {
  2040. console.warn( '"' + names[ indx ] + '" widget code does not exist!' );
  2041. }
  2042. }
  2043. // sort widgets by priority
  2044. widgets.sort( function( a, b ) {
  2045. return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1;
  2046. });
  2047. // add/update selected widgets
  2048. len = widgets.length;
  2049. if ( c.debug ) {
  2050. console[ console.group ? 'group' : 'log' ]( 'Start ' + ( init ? 'initializing' : 'applying' ) + ' widgets' );
  2051. }
  2052. for ( indx = 0; indx < len; indx++ ) {
  2053. widget = widgets[ indx ];
  2054. if ( widget && widget.id ) {
  2055. ts.applyWidgetId( table, widget.id, init );
  2056. }
  2057. }
  2058. if ( c.debug && console.groupEnd ) { console.groupEnd(); }
  2059. }
  2060. c.timerReady = setTimeout( function() {
  2061. table.isApplyingWidgets = false;
  2062. $.data( table, 'lastWidgetApplication', new Date() );
  2063. c.$table.triggerHandler( 'tablesorter-ready' );
  2064. // callback executed on init only
  2065. if ( !init && typeof callback === 'function' ) {
  2066. callback( table );
  2067. }
  2068. if ( c.debug ) {
  2069. widget = c.widgets.length;
  2070. console.log( 'Completed ' +
  2071. ( init === true ? 'initializing ' : 'applying ' ) + widget +
  2072. ' widget' + ( widget !== 1 ? 's' : '' ) + ts.benchmark( time ) );
  2073. }
  2074. }, 10 );
  2075. },
  2076.  
  2077. removeWidget : function( table, name, refreshing ) {
  2078. table = $( table )[ 0 ];
  2079. var index, widget, indx, len,
  2080. c = table.config;
  2081. // if name === true, add all widgets from $.tablesorter.widgets
  2082. if ( name === true ) {
  2083. name = [];
  2084. len = ts.widgets.length;
  2085. for ( indx = 0; indx < len; indx++ ) {
  2086. widget = ts.widgets[ indx ];
  2087. if ( widget && widget.id ) {
  2088. name[ name.length ] = widget.id;
  2089. }
  2090. }
  2091. } else {
  2092. // name can be either an array of widgets names,
  2093. // or a space/comma separated list of widget names
  2094. name = ( $.isArray( name ) ? name.join( ',' ) : name || '' ).toLowerCase().split( /[\s,]+/ );
  2095. }
  2096. len = name.length;
  2097. for ( index = 0; index < len; index++ ) {
  2098. widget = ts.getWidgetById( name[ index ] );
  2099. indx = $.inArray( name[ index ], c.widgets );
  2100. // don't remove the widget from config.widget if refreshing
  2101. if ( indx >= 0 && refreshing !== true ) {
  2102. c.widgets.splice( indx, 1 );
  2103. }
  2104. if ( widget && widget.remove ) {
  2105. if ( c.debug ) {
  2106. console.log( ( refreshing ? 'Refreshing' : 'Removing' ) + ' "' + name[ index ] + '" widget' );
  2107. }
  2108. widget.remove( table, c, c.widgetOptions, refreshing );
  2109. c.widgetInit[ name[ index ] ] = false;
  2110. }
  2111. }
  2112. },
  2113.  
  2114. refreshWidgets : function( table, doAll, dontapply ) {
  2115. table = $( table )[ 0 ]; // see issue #243
  2116. var indx, widget,
  2117. c = table.config,
  2118. curWidgets = c.widgets,
  2119. widgets = ts.widgets,
  2120. len = widgets.length,
  2121. list = [],
  2122. callback = function( table ) {
  2123. $( table ).triggerHandler( 'refreshComplete' );
  2124. };
  2125. // remove widgets not defined in config.widgets, unless doAll is true
  2126. for ( indx = 0; indx < len; indx++ ) {
  2127. widget = widgets[ indx ];
  2128. if ( widget && widget.id && ( doAll || $.inArray( widget.id, curWidgets ) < 0 ) ) {
  2129. list[ list.length ] = widget.id;
  2130. }
  2131. }
  2132. ts.removeWidget( table, list.join( ',' ), true );
  2133. if ( dontapply !== true ) {
  2134. // call widget init if
  2135. ts.applyWidget( table, doAll || false, callback );
  2136. if ( doAll ) {
  2137. // apply widget format
  2138. ts.applyWidget( table, false, callback );
  2139. }
  2140. } else {
  2141. callback( table );
  2142. }
  2143. },
  2144.  
  2145. /*
  2146. ██ ██ ██████ ██ ██ ██ ██████ ██ ██████ ▄█████
  2147. ██ ██ ██ ██ ██ ██ ██ ██ ██▄▄ ▀█▄
  2148. ██ ██ ██ ██ ██ ██ ██ ██ ██▀▀ ▀█▄
  2149. ▀████▀ ██ ██ ██████ ██ ██ ██ ██████ █████▀
  2150. */
  2151. benchmark : function( diff ) {
  2152. return ( ' (' + ( new Date().getTime() - diff.getTime() ) + ' ms)' );
  2153. },
  2154. // deprecated ts.log
  2155. log : function() {
  2156. console.log( arguments );
  2157. },
  2158.  
  2159. // $.isEmptyObject from jQuery v1.4
  2160. isEmptyObject : function( obj ) {
  2161. /*jshint forin: false */
  2162. for ( var name in obj ) {
  2163. return false;
  2164. }
  2165. return true;
  2166. },
  2167.  
  2168. isValueInArray : function( column, arry ) {
  2169. var indx,
  2170. len = arry && arry.length || 0;
  2171. for ( indx = 0; indx < len; indx++ ) {
  2172. if ( arry[ indx ][ 0 ] === column ) {
  2173. return indx;
  2174. }
  2175. }
  2176. return -1;
  2177. },
  2178.  
  2179. formatFloat : function( str, table ) {
  2180. if ( typeof str !== 'string' || str === '' ) { return str; }
  2181. // allow using formatFloat without a table; defaults to US number format
  2182. var num,
  2183. usFormat = table && table.config ? table.config.usNumberFormat !== false :
  2184. typeof table !== 'undefined' ? table : true;
  2185. if ( usFormat ) {
  2186. // US Format - 1,234,567.89 -> 1234567.89
  2187. str = str.replace( ts.regex.comma, '' );
  2188. } else {
  2189. // German Format = 1.234.567,89 -> 1234567.89
  2190. // French Format = 1 234 567,89 -> 1234567.89
  2191. str = str.replace( ts.regex.digitNonUS, '' ).replace( ts.regex.comma, '.' );
  2192. }
  2193. if ( ts.regex.digitNegativeTest.test( str ) ) {
  2194. // make (#) into a negative number -> (10) = -10
  2195. str = str.replace( ts.regex.digitNegativeReplace, '-$1' );
  2196. }
  2197. num = parseFloat( str );
  2198. // return the text instead of zero
  2199. return isNaN( num ) ? $.trim( str ) : num;
  2200. },
  2201.  
  2202. isDigit : function( str ) {
  2203. // replace all unwanted chars and match
  2204. return isNaN( str ) ?
  2205. ts.regex.digitTest.test( str.toString().replace( ts.regex.digitReplace, '' ) ) :
  2206. str !== '';
  2207. },
  2208.  
  2209. // computeTableHeaderCellIndexes from:
  2210. // http://www.javascripttoolbox.com/lib/table/examples.php
  2211. // http://www.javascripttoolbox.com/temp/table_cellindex.html
  2212. computeColumnIndex : function( $rows, c ) {
  2213. var i, j, k, l, cell, cells, rowIndex, rowSpan, colSpan, firstAvailCol,
  2214. // total columns has been calculated, use it to set the matrixrow
  2215. columns = c && c.columns || 0,
  2216. matrix = [],
  2217. matrixrow = new Array( columns );
  2218. for ( i = 0; i < $rows.length; i++ ) {
  2219. cells = $rows[ i ].cells;
  2220. for ( j = 0; j < cells.length; j++ ) {
  2221. cell = cells[ j ];
  2222. rowIndex = cell.parentNode.rowIndex;
  2223. rowSpan = cell.rowSpan || 1;
  2224. colSpan = cell.colSpan || 1;
  2225. if ( typeof matrix[ rowIndex ] === 'undefined' ) {
  2226. matrix[ rowIndex ] = [];
  2227. }
  2228. // Find first available column in the first row
  2229. for ( k = 0; k < matrix[ rowIndex ].length + 1; k++ ) {
  2230. if ( typeof matrix[ rowIndex ][ k ] === 'undefined' ) {
  2231. firstAvailCol = k;
  2232. break;
  2233. }
  2234. }
  2235. // jscs:disable disallowEmptyBlocks
  2236. if ( columns && cell.cellIndex === firstAvailCol ) {
  2237. // don't to anything
  2238. } else if ( cell.setAttribute ) {
  2239. // jscs:enable disallowEmptyBlocks
  2240. // add data-column (setAttribute = IE8+)
  2241. cell.setAttribute( 'data-column', firstAvailCol );
  2242. } else {
  2243. // remove once we drop support for IE7 - 1/12/2016
  2244. $( cell ).attr( 'data-column', firstAvailCol );
  2245. }
  2246. for ( k = rowIndex; k < rowIndex + rowSpan; k++ ) {
  2247. if ( typeof matrix[ k ] === 'undefined' ) {
  2248. matrix[ k ] = [];
  2249. }
  2250. matrixrow = matrix[ k ];
  2251. for ( l = firstAvailCol; l < firstAvailCol + colSpan; l++ ) {
  2252. matrixrow[ l ] = 'x';
  2253. }
  2254. }
  2255. }
  2256. }
  2257. return matrixrow.length;
  2258. },
  2259.  
  2260. // automatically add a colgroup with col elements set to a percentage width
  2261. fixColumnWidth : function( table ) {
  2262. table = $( table )[ 0 ];
  2263. var overallWidth, percent, $tbodies, len, index,
  2264. c = table.config,
  2265. $colgroup = c.$table.children( 'colgroup' );
  2266. // remove plugin-added colgroup, in case we need to refresh the widths
  2267. if ( $colgroup.length && $colgroup.hasClass( ts.css.colgroup ) ) {
  2268. $colgroup.remove();
  2269. }
  2270. if ( c.widthFixed && c.$table.children( 'colgroup' ).length === 0 ) {
  2271. $colgroup = $( '<colgroup class="' + ts.css.colgroup + '">' );
  2272. overallWidth = c.$table.width();
  2273. // only add col for visible columns - fixes #371
  2274. $tbodies = c.$tbodies.find( 'tr:first' ).children( ':visible' );
  2275. len = $tbodies.length;
  2276. for ( index = 0; index < len; index++ ) {
  2277. percent = parseInt( ( $tbodies.eq( index ).width() / overallWidth ) * 1000, 10 ) / 10 + '%';
  2278. $colgroup.append( $( '<col>' ).css( 'width', percent ) );
  2279. }
  2280. c.$table.prepend( $colgroup );
  2281. }
  2282. },
  2283.  
  2284. // get sorter, string, empty, etc options for each column from
  2285. // jQuery data, metadata, header option or header class name ('sorter-false')
  2286. // priority = jQuery data > meta > headers option > header class name
  2287. getData : function( header, configHeader, key ) {
  2288. var meta, cl4ss,
  2289. val = '',
  2290. $header = $( header );
  2291. if ( !$header.length ) { return ''; }
  2292. meta = $.metadata ? $header.metadata() : false;
  2293. cl4ss = ' ' + ( $header.attr( 'class' ) || '' );
  2294. if ( typeof $header.data( key ) !== 'undefined' ||
  2295. typeof $header.data( key.toLowerCase() ) !== 'undefined' ) {
  2296. // 'data-lockedOrder' is assigned to 'lockedorder'; but 'data-locked-order' is assigned to 'lockedOrder'
  2297. // 'data-sort-initial-order' is assigned to 'sortInitialOrder'
  2298. val += $header.data( key ) || $header.data( key.toLowerCase() );
  2299. } else if ( meta && typeof meta[ key ] !== 'undefined' ) {
  2300. val += meta[ key ];
  2301. } else if ( configHeader && typeof configHeader[ key ] !== 'undefined' ) {
  2302. val += configHeader[ key ];
  2303. } else if ( cl4ss !== ' ' && cl4ss.match( ' ' + key + '-' ) ) {
  2304. // include sorter class name 'sorter-text', etc; now works with 'sorter-my-custom-parser'
  2305. val = cl4ss.match( new RegExp( '\\s' + key + '-([\\w-]+)' ) )[ 1 ] || '';
  2306. }
  2307. return $.trim( val );
  2308. },
  2309.  
  2310. getColumnData : function( table, obj, indx, getCell, $headers ) {
  2311. if ( typeof obj !== 'object' || obj === null ) {
  2312. return obj;
  2313. }
  2314. table = $( table )[ 0 ];
  2315. var $header, key,
  2316. c = table.config,
  2317. $cells = ( $headers || c.$headers ),
  2318. // c.$headerIndexed is not defined initially
  2319. $cell = c.$headerIndexed && c.$headerIndexed[ indx ] ||
  2320. $cells.filter( '[data-column="' + indx + '"]:last' );
  2321. if ( typeof obj[ indx ] !== 'undefined' ) {
  2322. return getCell ? obj[ indx ] : obj[ $cells.index( $cell ) ];
  2323. }
  2324. for ( key in obj ) {
  2325. if ( typeof key === 'string' ) {
  2326. $header = $cell
  2327. // header cell with class/id
  2328. .filter( key )
  2329. // find elements within the header cell with cell/id
  2330. .add( $cell.find( key ) );
  2331. if ( $header.length ) {
  2332. return obj[ key ];
  2333. }
  2334. }
  2335. }
  2336. return;
  2337. },
  2338.  
  2339. // *** Process table ***
  2340. // add processing indicator
  2341. isProcessing : function( $table, toggle, $headers ) {
  2342. $table = $( $table );
  2343. var c = $table[ 0 ].config,
  2344. // default to all headers
  2345. $header = $headers || $table.find( '.' + ts.css.header );
  2346. if ( toggle ) {
  2347. // don't use sortList if custom $headers used
  2348. if ( typeof $headers !== 'undefined' && c.sortList.length > 0 ) {
  2349. // get headers from the sortList
  2350. $header = $header.filter( function() {
  2351. // get data-column from attr to keep compatibility with jQuery 1.2.6
  2352. return this.sortDisabled ?
  2353. false :
  2354. ts.isValueInArray( parseFloat( $( this ).attr( 'data-column' ) ), c.sortList ) >= 0;
  2355. });
  2356. }
  2357. $table.add( $header ).addClass( ts.css.processing + ' ' + c.cssProcessing );
  2358. } else {
  2359. $table.add( $header ).removeClass( ts.css.processing + ' ' + c.cssProcessing );
  2360. }
  2361. },
  2362.  
  2363. // detach tbody but save the position
  2364. // don't use tbody because there are portions that look for a tbody index (updateCell)
  2365. processTbody : function( table, $tb, getIt ) {
  2366. table = $( table )[ 0 ];
  2367. if ( getIt ) {
  2368. table.isProcessing = true;
  2369. $tb.before( '<colgroup class="tablesorter-savemyplace"/>' );
  2370. return $.fn.detach ? $tb.detach() : $tb.remove();
  2371. }
  2372. var holdr = $( table ).find( 'colgroup.tablesorter-savemyplace' );
  2373. $tb.insertAfter( holdr );
  2374. holdr.remove();
  2375. table.isProcessing = false;
  2376. },
  2377.  
  2378. clearTableBody : function( table ) {
  2379. $( table )[ 0 ].config.$tbodies.children().detach();
  2380. },
  2381.  
  2382. // used when replacing accented characters during sorting
  2383. characterEquivalents : {
  2384. 'a' : '\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5', // áàâãäąå
  2385. 'A' : '\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5', // ÁÀÂÃÄĄÅ
  2386. 'c' : '\u00e7\u0107\u010d', // çćč
  2387. 'C' : '\u00c7\u0106\u010c', // ÇĆČ
  2388. 'e' : '\u00e9\u00e8\u00ea\u00eb\u011b\u0119', // éèêëěę
  2389. 'E' : '\u00c9\u00c8\u00ca\u00cb\u011a\u0118', // ÉÈÊËĚĘ
  2390. 'i' : '\u00ed\u00ec\u0130\u00ee\u00ef\u0131', // íìİîïı
  2391. 'I' : '\u00cd\u00cc\u0130\u00ce\u00cf', // ÍÌİÎÏ
  2392. 'o' : '\u00f3\u00f2\u00f4\u00f5\u00f6\u014d', // óòôõöō
  2393. 'O' : '\u00d3\u00d2\u00d4\u00d5\u00d6\u014c', // ÓÒÔÕÖŌ
  2394. 'ss': '\u00df', // ß (s sharp)
  2395. 'SS': '\u1e9e', // ẞ (Capital sharp s)
  2396. 'u' : '\u00fa\u00f9\u00fb\u00fc\u016f', // úùûüů
  2397. 'U' : '\u00da\u00d9\u00db\u00dc\u016e' // ÚÙÛÜŮ
  2398. },
  2399.  
  2400. replaceAccents : function( str ) {
  2401. var chr,
  2402. acc = '[',
  2403. eq = ts.characterEquivalents;
  2404. if ( !ts.characterRegex ) {
  2405. ts.characterRegexArray = {};
  2406. for ( chr in eq ) {
  2407. if ( typeof chr === 'string' ) {
  2408. acc += eq[ chr ];
  2409. ts.characterRegexArray[ chr ] = new RegExp( '[' + eq[ chr ] + ']', 'g' );
  2410. }
  2411. }
  2412. ts.characterRegex = new RegExp( acc + ']' );
  2413. }
  2414. if ( ts.characterRegex.test( str ) ) {
  2415. for ( chr in eq ) {
  2416. if ( typeof chr === 'string' ) {
  2417. str = str.replace( ts.characterRegexArray[ chr ], chr );
  2418. }
  2419. }
  2420. }
  2421. return str;
  2422. },
  2423.  
  2424. validateOptions : function( c ) {
  2425. var setting, setting2, typ, timer,
  2426. // ignore options containing an array
  2427. ignore = 'headers sortForce sortList sortAppend widgets'.split( ' ' ),
  2428. orig = c.originalSettings;
  2429. if ( orig ) {
  2430. if ( c.debug ) {
  2431. timer = new Date();
  2432. }
  2433. for ( setting in orig ) {
  2434. typ = typeof ts.defaults[setting];
  2435. if ( typ === 'undefined' ) {
  2436. console.warn( 'Tablesorter Warning! "table.config.' + setting + '" option not recognized' );
  2437. } else if ( typ === 'object' ) {
  2438. for ( setting2 in orig[setting] ) {
  2439. typ = ts.defaults[setting] && typeof ts.defaults[setting][setting2];
  2440. if ( $.inArray( setting, ignore ) < 0 && typ === 'undefined' ) {
  2441. console.warn( 'Tablesorter Warning! "table.config.' + setting + '.' + setting2 + '" option not recognized' );
  2442. }
  2443. }
  2444. }
  2445. }
  2446. if ( c.debug ) {
  2447. console.log( 'validate options time:' + ts.benchmark( timer ) );
  2448. }
  2449. }
  2450. },
  2451.  
  2452. // restore headers
  2453. restoreHeaders : function( table ) {
  2454. var index, $cell,
  2455. c = $( table )[ 0 ].config,
  2456. $headers = c.$table.find( c.selectorHeaders ),
  2457. len = $headers.length;
  2458. // don't use c.$headers here in case header cells were swapped
  2459. for ( index = 0; index < len; index++ ) {
  2460. $cell = $headers.eq( index );
  2461. // only restore header cells if it is wrapped
  2462. // because this is also used by the updateAll method
  2463. if ( $cell.find( '.' + ts.css.headerIn ).length ) {
  2464. $cell.html( c.headerContent[ index ] );
  2465. }
  2466. }
  2467. },
  2468.  
  2469. destroy : function( table, removeClasses, callback ) {
  2470. table = $( table )[ 0 ];
  2471. if ( !table.hasInitialized ) { return; }
  2472. // remove all widgets
  2473. ts.removeWidget( table, true, false );
  2474. var events,
  2475. $t = $( table ),
  2476. c = table.config,
  2477. debug = c.debug,
  2478. $h = $t.find( 'thead:first' ),
  2479. $r = $h.find( 'tr.' + ts.css.headerRow ).removeClass( ts.css.headerRow + ' ' + c.cssHeaderRow ),
  2480. $f = $t.find( 'tfoot:first > tr' ).children( 'th, td' );
  2481. if ( removeClasses === false && $.inArray( 'uitheme', c.widgets ) >= 0 ) {
  2482. // reapply uitheme classes, in case we want to maintain appearance
  2483. $t.triggerHandler( 'applyWidgetId', [ 'uitheme' ] );
  2484. $t.triggerHandler( 'applyWidgetId', [ 'zebra' ] );
  2485. }
  2486. // remove widget added rows, just in case
  2487. $h.find( 'tr' ).not( $r ).remove();
  2488. // disable tablesorter - not using .unbind( namespace ) because namespacing was
  2489. // added in jQuery v1.4.3 - see http://api.jquery.com/event.namespace/
  2490. events = 'sortReset update updateRows updateAll updateHeaders updateCell addRows updateComplete sorton ' +
  2491. 'appendCache updateCache applyWidgetId applyWidgets refreshWidgets removeWidget destroy mouseup mouseleave ' +
  2492. 'keypress sortBegin sortEnd resetToLoadState '.split( ' ' )
  2493. .join( c.namespace + ' ' );
  2494. $t
  2495. .removeData( 'tablesorter' )
  2496. .unbind( events.replace( ts.regex.spaces, ' ' ) );
  2497. c.$headers
  2498. .add( $f )
  2499. .removeClass( [ ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone ].join( ' ' ) )
  2500. .removeAttr( 'data-column' )
  2501. .removeAttr( 'aria-label' )
  2502. .attr( 'aria-disabled', 'true' );
  2503. $r
  2504. .find( c.selectorSort )
  2505. .unbind( ( 'mousedown mouseup keypress '.split( ' ' ).join( c.namespace + ' ' ) ).replace( ts.regex.spaces, ' ' ) );
  2506. ts.restoreHeaders( table );
  2507. $t.toggleClass( ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false );
  2508. // clear flag in case the plugin is initialized again
  2509. table.hasInitialized = false;
  2510. delete table.config.cache;
  2511. if ( typeof callback === 'function' ) {
  2512. callback( table );
  2513. }
  2514. if ( debug ) {
  2515. console.log( 'tablesorter has been removed' );
  2516. }
  2517. }
  2518.  
  2519. };
  2520.  
  2521. $.fn.tablesorter = function( settings ) {
  2522. return this.each( function() {
  2523. var table = this,
  2524. // merge & extend config options
  2525. c = $.extend( true, {}, ts.defaults, settings, ts.instanceMethods );
  2526. // save initial settings
  2527. c.originalSettings = settings;
  2528. // create a table from data (build table widget)
  2529. if ( !table.hasInitialized && ts.buildTable && this.nodeName !== 'TABLE' ) {
  2530. // return the table (in case the original target is the table's container)
  2531. ts.buildTable( table, c );
  2532. } else {
  2533. ts.setup( table, c );
  2534. }
  2535. });
  2536. };
  2537.  
  2538. // set up debug logs
  2539. if ( !( window.console && window.console.log ) ) {
  2540. // access $.tablesorter.logs for browsers that don't have a console...
  2541. ts.logs = [];
  2542. /*jshint -W020 */
  2543. console = {};
  2544. console.log = console.warn = console.error = console.table = function() {
  2545. var arg = arguments.length > 1 ? arguments : arguments[0];
  2546. ts.logs[ ts.logs.length ] = { date: Date.now(), log: arg };
  2547. };
  2548. }
  2549.  
  2550. // add default parsers
  2551. ts.addParser({
  2552. id : 'no-parser',
  2553. is : function() {
  2554. return false;
  2555. },
  2556. format : function() {
  2557. return '';
  2558. },
  2559. type : 'text'
  2560. });
  2561.  
  2562. ts.addParser({
  2563. id : 'text',
  2564. is : function() {
  2565. return true;
  2566. },
  2567. format : function( str, table ) {
  2568. var c = table.config;
  2569. if ( str ) {
  2570. str = $.trim( c.ignoreCase ? str.toLocaleLowerCase() : str );
  2571. str = c.sortLocaleCompare ? ts.replaceAccents( str ) : str;
  2572. }
  2573. return str;
  2574. },
  2575. type : 'text'
  2576. });
  2577.  
  2578. ts.regex.nondigit = /[^\w,. \-()]/g;
  2579. ts.addParser({
  2580. id : 'digit',
  2581. is : function( str ) {
  2582. return ts.isDigit( str );
  2583. },
  2584. format : function( str, table ) {
  2585. var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
  2586. return str && typeof num === 'number' ? num :
  2587. str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
  2588. },
  2589. type : 'numeric'
  2590. });
  2591.  
  2592. ts.regex.currencyReplace = /[+\-,. ]/g;
  2593. ts.regex.currencyTest = /^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/;
  2594. ts.addParser({
  2595. id : 'currency',
  2596. is : function( str ) {
  2597. str = ( str || '' ).replace( ts.regex.currencyReplace, '' );
  2598. // test for £$€¤¥¢
  2599. return ts.regex.currencyTest.test( str );
  2600. },
  2601. format : function( str, table ) {
  2602. var num = ts.formatFloat( ( str || '' ).replace( ts.regex.nondigit, '' ), table );
  2603. return str && typeof num === 'number' ? num :
  2604. str ? $.trim( str && table.config.ignoreCase ? str.toLocaleLowerCase() : str ) : str;
  2605. },
  2606. type : 'numeric'
  2607. });
  2608.  
  2609. // too many protocols to add them all https://en.wikipedia.org/wiki/URI_scheme
  2610. // now, this regex can be updated before initialization
  2611. ts.regex.urlProtocolTest = /^(https?|ftp|file):\/\//;
  2612. ts.regex.urlProtocolReplace = /(https?|ftp|file):\/\/(www\.)?/;
  2613. ts.addParser({
  2614. id : 'url',
  2615. is : function( str ) {
  2616. return ts.regex.urlProtocolTest.test( str );
  2617. },
  2618. format : function( str ) {
  2619. return str ? $.trim( str.replace( ts.regex.urlProtocolReplace, '' ) ) : str;
  2620. },
  2621. type : 'text'
  2622. });
  2623.  
  2624. ts.regex.dash = /-/g;
  2625. ts.regex.isoDate = /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/;
  2626. ts.addParser({
  2627. id : 'isoDate',
  2628. is : function( str ) {
  2629. return ts.regex.isoDate.test( str );
  2630. },
  2631. format : function( str, table ) {
  2632. var date = str ? new Date( str.replace( ts.regex.dash, '/' ) ) : str;
  2633. return date instanceof Date && isFinite( date ) ? date.getTime() : str;
  2634. },
  2635. type : 'numeric'
  2636. });
  2637.  
  2638. ts.regex.percent = /%/g;
  2639. ts.regex.percentTest = /(\d\s*?%|%\s*?\d)/;
  2640. ts.addParser({
  2641. id : 'percent',
  2642. is : function( str ) {
  2643. return ts.regex.percentTest.test( str ) && str.length < 15;
  2644. },
  2645. format : function( str, table ) {
  2646. return str ? ts.formatFloat( str.replace( ts.regex.percent, '' ), table ) : str;
  2647. },
  2648. type : 'numeric'
  2649. });
  2650.  
  2651. // added image parser to core v2.17.9
  2652. ts.addParser({
  2653. id : 'image',
  2654. is : function( str, table, node, $node ) {
  2655. return $node.find( 'img' ).length > 0;
  2656. },
  2657. format : function( str, table, cell ) {
  2658. return $( cell ).find( 'img' ).attr( table.config.imgAttr || 'alt' ) || str;
  2659. },
  2660. parsed : true, // filter widget flag
  2661. type : 'text'
  2662. });
  2663.  
  2664. ts.regex.dateReplace = /(\S)([AP]M)$/i; // used by usLongDate & time parser
  2665. 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;
  2666. ts.regex.usLongDateTest2 = /^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i;
  2667. ts.addParser({
  2668. id : 'usLongDate',
  2669. is : function( str ) {
  2670. // two digit years are not allowed cross-browser
  2671. // Jan 01, 2013 12:34:56 PM or 01 Jan 2013
  2672. return ts.regex.usLongDateTest1.test( str ) || ts.regex.usLongDateTest2.test( str );
  2673. },
  2674. format : function( str, table ) {
  2675. var date = str ? new Date( str.replace( ts.regex.dateReplace, '$1 $2' ) ) : str;
  2676. return date instanceof Date && isFinite( date ) ? date.getTime() : str;
  2677. },
  2678. type : 'numeric'
  2679. });
  2680.  
  2681. // testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included
  2682. ts.regex.shortDateTest = /(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/;
  2683. // escaped "-" because JSHint in Firefox was showing it as an error
  2684. ts.regex.shortDateReplace = /[\-.,]/g;
  2685. // XXY covers MDY & DMY formats
  2686. ts.regex.shortDateXXY = /(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/;
  2687. ts.regex.shortDateYMD = /(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/;
  2688. ts.convertFormat = function( dateString, format ) {
  2689. dateString = ( dateString || '' )
  2690. .replace( ts.regex.spaces, ' ' )
  2691. .replace( ts.regex.shortDateReplace, '/' );
  2692. if ( format === 'mmddyyyy' ) {
  2693. dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$1/$2' );
  2694. } else if ( format === 'ddmmyyyy' ) {
  2695. dateString = dateString.replace( ts.regex.shortDateXXY, '$3/$2/$1' );
  2696. } else if ( format === 'yyyymmdd' ) {
  2697. dateString = dateString.replace( ts.regex.shortDateYMD, '$1/$2/$3' );
  2698. }
  2699. var date = new Date( dateString );
  2700. return date instanceof Date && isFinite( date ) ? date.getTime() : '';
  2701. };
  2702.  
  2703. ts.addParser({
  2704. id : 'shortDate', // 'mmddyyyy', 'ddmmyyyy' or 'yyyymmdd'
  2705. is : function( str ) {
  2706. str = ( str || '' ).replace( ts.regex.spaces, ' ' ).replace( ts.regex.shortDateReplace, '/' );
  2707. return ts.regex.shortDateTest.test( str );
  2708. },
  2709. format : function( str, table, cell, cellIndex ) {
  2710. if ( str ) {
  2711. var c = table.config,
  2712. $header = c.$headerIndexed[ cellIndex ],
  2713. format = $header.length && $header.data( 'dateFormat' ) ||
  2714. ts.getData( $header, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat' ) ||
  2715. c.dateFormat;
  2716. // save format because getData can be slow...
  2717. if ( $header.length ) {
  2718. $header.data( 'dateFormat', format );
  2719. }
  2720. return ts.convertFormat( str, format ) || str;
  2721. }
  2722. return str;
  2723. },
  2724. type : 'numeric'
  2725. });
  2726.  
  2727. // match 24 hour time & 12 hours time + am/pm - see http://regexr.com/3c3tk
  2728. ts.regex.timeTest = /^(0?[1-9]|1[0-2]):([0-5]\d)(\s[AP]M)$|^((?:[01]\d|[2][0-4]):[0-5]\d)$/i;
  2729. ts.regex.timeMatch = /(0?[1-9]|1[0-2]):([0-5]\d)(\s[AP]M)|((?:[01]\d|[2][0-4]):[0-5]\d)/i;
  2730. ts.addParser({
  2731. id : 'time',
  2732. is : function( str ) {
  2733. return ts.regex.timeTest.test( str );
  2734. },
  2735. format : function( str, table ) {
  2736. // isolate time... ignore month, day and year
  2737. var temp,
  2738. timePart = ( str || '' ).match( ts.regex.timeMatch ),
  2739. orig = new Date( str ),
  2740. // no time component? default to 00:00 by leaving it out, but only if str is defined
  2741. time = str && ( timePart !== null ? timePart[ 0 ] : '00:00 AM' ),
  2742. date = time ? new Date( '2000/01/01 ' + time.replace( ts.regex.dateReplace, '$1 $2' ) ) : time;
  2743. if ( date instanceof Date && isFinite( date ) ) {
  2744. temp = orig instanceof Date && isFinite( orig ) ? orig.getTime() : 0;
  2745. // if original string was a valid date, add it to the decimal so the column sorts in some kind of order
  2746. // luckily new Date() ignores the decimals
  2747. return temp ? parseFloat( date.getTime() + '.' + orig.getTime() ) : date.getTime();
  2748. }
  2749. return str;
  2750. },
  2751. type : 'numeric'
  2752. });
  2753.  
  2754. ts.addParser({
  2755. id : 'metadata',
  2756. is : function() {
  2757. return false;
  2758. },
  2759. format : function( str, table, cell ) {
  2760. var c = table.config,
  2761. p = ( !c.parserMetadataName ) ? 'sortValue' : c.parserMetadataName;
  2762. return $( cell ).metadata()[ p ];
  2763. },
  2764. type : 'numeric'
  2765. });
  2766.  
  2767. /*
  2768. ██████ ██████ █████▄ █████▄ ▄████▄
  2769. ▄█▀ ██▄▄ ██▄▄██ ██▄▄██ ██▄▄██
  2770. ▄█▀ ██▀▀ ██▀▀██ ██▀▀█ ██▀▀██
  2771. ██████ ██████ █████▀ ██ ██ ██ ██
  2772. */
  2773. // add default widgets
  2774. ts.addWidget({
  2775. id : 'zebra',
  2776. priority : 90,
  2777. format : function( table, c, wo ) {
  2778. var $visibleRows, $row, count, isEven, tbodyIndex, rowIndex, len,
  2779. child = new RegExp( c.cssChildRow, 'i' ),
  2780. $tbodies = c.$tbodies.add( $( c.namespace + '_extra_table' ).children( 'tbody:not(.' + c.cssInfoBlock + ')' ) );
  2781. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
  2782. // loop through the visible rows
  2783. count = 0;
  2784. $visibleRows = $tbodies.eq( tbodyIndex ).children( 'tr:visible' ).not( c.selectorRemove );
  2785. len = $visibleRows.length;
  2786. for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
  2787. $row = $visibleRows.eq( rowIndex );
  2788. // style child rows the same way the parent row was styled
  2789. if ( !child.test( $row[ 0 ].className ) ) { count++; }
  2790. isEven = ( count % 2 === 0 );
  2791. $row
  2792. .removeClass( wo.zebra[ isEven ? 1 : 0 ] )
  2793. .addClass( wo.zebra[ isEven ? 0 : 1 ] );
  2794. }
  2795. }
  2796. },
  2797. remove : function( table, c, wo, refreshing ) {
  2798. if ( refreshing ) { return; }
  2799. var tbodyIndex, $tbody,
  2800. $tbodies = c.$tbodies,
  2801. toRemove = ( wo.zebra || [ 'even', 'odd' ] ).join( ' ' );
  2802. for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ){
  2803. $tbody = ts.processTbody( table, $tbodies.eq( tbodyIndex ), true ); // remove tbody
  2804. $tbody.children().removeClass( toRemove );
  2805. ts.processTbody( table, $tbody, false ); // restore tbody
  2806. }
  2807. }
  2808. });
  2809.  
  2810. })( jQuery );

QingJ © 2025

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