TableSorter

Client-side table sorting with ease

当前为 2017-05-17 提交的版本,查看 最新版本

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

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

QingJ © 2025

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