jquery.tablesorter.js 106 KB

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