TableSorter

Client-side table sorting with ease

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

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

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

QingJ © 2025

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