TableSorter

Client-side table sorting with ease

当前为 2017-08-27 提交的版本,查看 最新版本

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

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

QingJ © 2025

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