TableSorter

Client-side table sorting with ease

当前为 2015-09-02 提交的版本,查看 最新版本

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

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

QingJ © 2025

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