TableSorter

Client-side table sorting with ease

当前为 2015-10-15 提交的版本,查看 最新版本

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

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

QingJ © 2025

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