tablesaw.js 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777
  1. /*! Tablesaw - v3.0.9 - 2018-02-14
  2. * https://github.com/filamentgroup/tablesaw
  3. * Copyright (c) 2018 Filament Group; Licensed MIT */
  4. /*! Shoestring - v2.0.0 - 2017-02-14
  5. * http://github.com/filamentgroup/shoestring/
  6. * Copyright (c) 2017 Scott Jehl, Filament Group, Inc; Licensed MIT & GPLv2 */
  7. (function( factory ) {
  8. if( typeof define === 'function' && define.amd ) {
  9. // AMD. Register as an anonymous module.
  10. define( [ 'shoestring' ], factory );
  11. } else if (typeof module === 'object' && module.exports) {
  12. // Node/CommonJS
  13. module.exports = factory();
  14. } else {
  15. // Browser globals
  16. factory();
  17. }
  18. }(function () {
  19. var win = typeof window !== "undefined" ? window : this;
  20. var doc = win.document;
  21. /**
  22. * The shoestring object constructor.
  23. *
  24. * @param {string,object} prim The selector to find or element to wrap.
  25. * @param {object} sec The context in which to match the `prim` selector.
  26. * @returns shoestring
  27. * @this window
  28. */
  29. function shoestring( prim, sec ){
  30. var pType = typeof( prim ),
  31. ret = [],
  32. sel;
  33. // return an empty shoestring object
  34. if( !prim ){
  35. return new Shoestring( ret );
  36. }
  37. // ready calls
  38. if( prim.call ){
  39. return shoestring.ready( prim );
  40. }
  41. // handle re-wrapping shoestring objects
  42. if( prim.constructor === Shoestring && !sec ){
  43. return prim;
  44. }
  45. // if string starting with <, make html
  46. if( pType === "string" && prim.indexOf( "<" ) === 0 ){
  47. var dfrag = doc.createElement( "div" );
  48. dfrag.innerHTML = prim;
  49. // TODO depends on children (circular)
  50. return shoestring( dfrag ).children().each(function(){
  51. dfrag.removeChild( this );
  52. });
  53. }
  54. // if string, it's a selector, use qsa
  55. if( pType === "string" ){
  56. if( sec ){
  57. return shoestring( sec ).find( prim );
  58. }
  59. sel = doc.querySelectorAll( prim );
  60. return new Shoestring( sel, prim );
  61. }
  62. // array like objects or node lists
  63. if( Object.prototype.toString.call( pType ) === '[object Array]' ||
  64. (win.NodeList && prim instanceof win.NodeList) ){
  65. return new Shoestring( prim, prim );
  66. }
  67. // if it's an array, use all the elements
  68. if( prim.constructor === Array ){
  69. return new Shoestring( prim, prim );
  70. }
  71. // otherwise assume it's an object the we want at an index
  72. return new Shoestring( [prim], prim );
  73. }
  74. var Shoestring = function( ret, prim ) {
  75. this.length = 0;
  76. this.selector = prim;
  77. shoestring.merge(this, ret);
  78. };
  79. // TODO only required for tests
  80. Shoestring.prototype.reverse = [].reverse;
  81. // For adding element set methods
  82. shoestring.fn = Shoestring.prototype;
  83. shoestring.Shoestring = Shoestring;
  84. // For extending objects
  85. // TODO move to separate module when we use prototypes
  86. shoestring.extend = function( first, second ){
  87. for( var i in second ){
  88. if( second.hasOwnProperty( i ) ){
  89. first[ i ] = second[ i ];
  90. }
  91. }
  92. return first;
  93. };
  94. // taken directly from jQuery
  95. shoestring.merge = function( first, second ) {
  96. var len, j, i;
  97. len = +second.length,
  98. j = 0,
  99. i = first.length;
  100. for ( ; j < len; j++ ) {
  101. first[ i++ ] = second[ j ];
  102. }
  103. first.length = i;
  104. return first;
  105. };
  106. // expose
  107. win.shoestring = shoestring;
  108. /**
  109. * Iterates over `shoestring` collections.
  110. *
  111. * @param {function} callback The callback to be invoked on each element and index
  112. * @return shoestring
  113. * @this shoestring
  114. */
  115. shoestring.fn.each = function( callback ){
  116. return shoestring.each( this, callback );
  117. };
  118. shoestring.each = function( collection, callback ) {
  119. var val;
  120. for( var i = 0, il = collection.length; i < il; i++ ){
  121. val = callback.call( collection[i], i, collection[i] );
  122. if( val === false ){
  123. break;
  124. }
  125. }
  126. return collection;
  127. };
  128. /**
  129. * Check for array membership.
  130. *
  131. * @param {object} needle The thing to find.
  132. * @param {object} haystack The thing to find the needle in.
  133. * @return {boolean}
  134. * @this window
  135. */
  136. shoestring.inArray = function( needle, haystack ){
  137. var isin = -1;
  138. for( var i = 0, il = haystack.length; i < il; i++ ){
  139. if( haystack.hasOwnProperty( i ) && haystack[ i ] === needle ){
  140. isin = i;
  141. }
  142. }
  143. return isin;
  144. };
  145. /**
  146. * Bind callbacks to be run when the DOM is "ready".
  147. *
  148. * @param {function} fn The callback to be run
  149. * @return shoestring
  150. * @this shoestring
  151. */
  152. shoestring.ready = function( fn ){
  153. if( ready && fn ){
  154. fn.call( doc );
  155. }
  156. else if( fn ){
  157. readyQueue.push( fn );
  158. }
  159. else {
  160. runReady();
  161. }
  162. return [doc];
  163. };
  164. // TODO necessary?
  165. shoestring.fn.ready = function( fn ){
  166. shoestring.ready( fn );
  167. return this;
  168. };
  169. // Empty and exec the ready queue
  170. var ready = false,
  171. readyQueue = [],
  172. runReady = function(){
  173. if( !ready ){
  174. while( readyQueue.length ){
  175. readyQueue.shift().call( doc );
  176. }
  177. ready = true;
  178. }
  179. };
  180. // If DOM is already ready at exec time, depends on the browser.
  181. // From: https://github.com/mobify/mobifyjs/blob/526841be5509e28fc949038021799e4223479f8d/src/capture.js#L128
  182. if (doc.attachEvent ? doc.readyState === "complete" : doc.readyState !== "loading") {
  183. runReady();
  184. } else {
  185. doc.addEventListener( "DOMContentLoaded", runReady, false );
  186. doc.addEventListener( "readystatechange", runReady, false );
  187. win.addEventListener( "load", runReady, false );
  188. }
  189. /**
  190. * Checks the current set of elements against the selector, if one matches return `true`.
  191. *
  192. * @param {string} selector The selector to check.
  193. * @return {boolean}
  194. * @this {shoestring}
  195. */
  196. shoestring.fn.is = function( selector ){
  197. var ret = false, self = this, parents, check;
  198. // assume a dom element
  199. if( typeof selector !== "string" ){
  200. // array-like, ie shoestring objects or element arrays
  201. if( selector.length && selector[0] ){
  202. check = selector;
  203. } else {
  204. check = [selector];
  205. }
  206. return _checkElements(this, check);
  207. }
  208. parents = this.parent();
  209. if( !parents.length ){
  210. parents = shoestring( doc );
  211. }
  212. parents.each(function( i, e ) {
  213. var children;
  214. children = e.querySelectorAll( selector );
  215. ret = _checkElements( self, children );
  216. });
  217. return ret;
  218. };
  219. function _checkElements(needles, haystack){
  220. var ret = false;
  221. needles.each(function() {
  222. var j = 0;
  223. while( j < haystack.length ){
  224. if( this === haystack[j] ){
  225. ret = true;
  226. }
  227. j++;
  228. }
  229. });
  230. return ret;
  231. }
  232. /**
  233. * Get data attached to the first element or set data values on all elements in the current set.
  234. *
  235. * @param {string} name The data attribute name.
  236. * @param {any} value The value assigned to the data attribute.
  237. * @return {any|shoestring}
  238. * @this shoestring
  239. */
  240. shoestring.fn.data = function( name, value ){
  241. if( name !== undefined ){
  242. if( value !== undefined ){
  243. return this.each(function(){
  244. if( !this.shoestringData ){
  245. this.shoestringData = {};
  246. }
  247. this.shoestringData[ name ] = value;
  248. });
  249. }
  250. else {
  251. if( this[ 0 ] ) {
  252. if( this[ 0 ].shoestringData ) {
  253. return this[ 0 ].shoestringData[ name ];
  254. }
  255. }
  256. }
  257. }
  258. else {
  259. return this[ 0 ] ? this[ 0 ].shoestringData || {} : undefined;
  260. }
  261. };
  262. /**
  263. * Remove data associated with `name` or all the data, for each element in the current set.
  264. *
  265. * @param {string} name The data attribute name.
  266. * @return shoestring
  267. * @this shoestring
  268. */
  269. shoestring.fn.removeData = function( name ){
  270. return this.each(function(){
  271. if( name !== undefined && this.shoestringData ){
  272. this.shoestringData[ name ] = undefined;
  273. delete this.shoestringData[ name ];
  274. } else {
  275. this[ 0 ].shoestringData = {};
  276. }
  277. });
  278. };
  279. /**
  280. * An alias for the `shoestring` constructor.
  281. */
  282. win.$ = shoestring;
  283. /**
  284. * Add a class to each DOM element in the set of elements.
  285. *
  286. * @param {string} className The name of the class to be added.
  287. * @return shoestring
  288. * @this shoestring
  289. */
  290. shoestring.fn.addClass = function( className ){
  291. var classes = className.replace(/^\s+|\s+$/g, '').split( " " );
  292. return this.each(function(){
  293. for( var i = 0, il = classes.length; i < il; i++ ){
  294. if( this.className !== undefined &&
  295. (this.className === "" ||
  296. !this.className.match( new RegExp( "(^|\\s)" + classes[ i ] + "($|\\s)"))) ){
  297. this.className += " " + classes[ i ];
  298. }
  299. }
  300. });
  301. };
  302. /**
  303. * Add elements matching the selector to the current set.
  304. *
  305. * @param {string} selector The selector for the elements to add from the DOM
  306. * @return shoestring
  307. * @this shoestring
  308. */
  309. shoestring.fn.add = function( selector ){
  310. var ret = [];
  311. this.each(function(){
  312. ret.push( this );
  313. });
  314. shoestring( selector ).each(function(){
  315. ret.push( this );
  316. });
  317. return shoestring( ret );
  318. };
  319. /**
  320. * Insert an element or HTML string as the last child of each element in the set.
  321. *
  322. * @param {string|HTMLElement} fragment The HTML or HTMLElement to insert.
  323. * @return shoestring
  324. * @this shoestring
  325. */
  326. shoestring.fn.append = function( fragment ){
  327. if( typeof( fragment ) === "string" || fragment.nodeType !== undefined ){
  328. fragment = shoestring( fragment );
  329. }
  330. return this.each(function( i ){
  331. for( var j = 0, jl = fragment.length; j < jl; j++ ){
  332. this.appendChild( i > 0 ? fragment[ j ].cloneNode( true ) : fragment[ j ] );
  333. }
  334. });
  335. };
  336. /**
  337. * Insert the current set as the last child of the elements matching the selector.
  338. *
  339. * @param {string} selector The selector after which to append the current set.
  340. * @return shoestring
  341. * @this shoestring
  342. */
  343. shoestring.fn.appendTo = function( selector ){
  344. return this.each(function(){
  345. shoestring( selector ).append( this );
  346. });
  347. };
  348. /**
  349. * Get the value of the first element of the set or set the value of all the elements in the set.
  350. *
  351. * @param {string} name The attribute name.
  352. * @param {string} value The new value for the attribute.
  353. * @return {shoestring|string|undefined}
  354. * @this {shoestring}
  355. */
  356. shoestring.fn.attr = function( name, value ){
  357. var nameStr = typeof( name ) === "string";
  358. if( value !== undefined || !nameStr ){
  359. return this.each(function(){
  360. if( nameStr ){
  361. this.setAttribute( name, value );
  362. } else {
  363. for( var i in name ){
  364. if( name.hasOwnProperty( i ) ){
  365. this.setAttribute( i, name[ i ] );
  366. }
  367. }
  368. }
  369. });
  370. } else {
  371. return this[ 0 ] ? this[ 0 ].getAttribute( name ) : undefined;
  372. }
  373. };
  374. /**
  375. * Insert an element or HTML string before each element in the current set.
  376. *
  377. * @param {string|HTMLElement} fragment The HTML or HTMLElement to insert.
  378. * @return shoestring
  379. * @this shoestring
  380. */
  381. shoestring.fn.before = function( fragment ){
  382. if( typeof( fragment ) === "string" || fragment.nodeType !== undefined ){
  383. fragment = shoestring( fragment );
  384. }
  385. return this.each(function( i ){
  386. for( var j = 0, jl = fragment.length; j < jl; j++ ){
  387. this.parentNode.insertBefore( i > 0 ? fragment[ j ].cloneNode( true ) : fragment[ j ], this );
  388. }
  389. });
  390. };
  391. /**
  392. * Get the children of the current collection.
  393. * @return shoestring
  394. * @this shoestring
  395. */
  396. shoestring.fn.children = function(){
  397. var ret = [],
  398. childs,
  399. j;
  400. this.each(function(){
  401. childs = this.children;
  402. j = -1;
  403. while( j++ < childs.length-1 ){
  404. if( shoestring.inArray( childs[ j ], ret ) === -1 ){
  405. ret.push( childs[ j ] );
  406. }
  407. }
  408. });
  409. return shoestring(ret);
  410. };
  411. /**
  412. * Find an element matching the selector in the set of the current element and its parents.
  413. *
  414. * @param {string} selector The selector used to identify the target element.
  415. * @return shoestring
  416. * @this shoestring
  417. */
  418. shoestring.fn.closest = function( selector ){
  419. var ret = [];
  420. if( !selector ){
  421. return shoestring( ret );
  422. }
  423. this.each(function(){
  424. var element, $self = shoestring( element = this );
  425. if( $self.is(selector) ){
  426. ret.push( this );
  427. return;
  428. }
  429. while( element.parentElement ) {
  430. if( shoestring(element.parentElement).is(selector) ){
  431. ret.push( element.parentElement );
  432. break;
  433. }
  434. element = element.parentElement;
  435. }
  436. });
  437. return shoestring( ret );
  438. };
  439. shoestring.cssExceptions = {
  440. 'float': [ 'cssFloat' ]
  441. };
  442. (function() {
  443. var cssExceptions = shoestring.cssExceptions;
  444. // IE8 uses marginRight instead of margin-right
  445. function convertPropertyName( str ) {
  446. return str.replace( /\-([A-Za-z])/g, function ( match, character ) {
  447. return character.toUpperCase();
  448. });
  449. }
  450. function _getStyle( element, property ) {
  451. return win.getComputedStyle( element, null ).getPropertyValue( property );
  452. }
  453. var vendorPrefixes = [ '', '-webkit-', '-ms-', '-moz-', '-o-', '-khtml-' ];
  454. /**
  455. * Private function for getting the computed style of an element.
  456. *
  457. * **NOTE** Please use the [css](../css.js.html) method instead.
  458. *
  459. * @method _getStyle
  460. * @param {HTMLElement} element The element we want the style property for.
  461. * @param {string} property The css property we want the style for.
  462. */
  463. shoestring._getStyle = function( element, property ) {
  464. var convert, value, j, k;
  465. if( cssExceptions[ property ] ) {
  466. for( j = 0, k = cssExceptions[ property ].length; j < k; j++ ) {
  467. value = _getStyle( element, cssExceptions[ property ][ j ] );
  468. if( value ) {
  469. return value;
  470. }
  471. }
  472. }
  473. for( j = 0, k = vendorPrefixes.length; j < k; j++ ) {
  474. convert = convertPropertyName( vendorPrefixes[ j ] + property );
  475. // VendorprefixKeyName || key-name
  476. value = _getStyle( element, convert );
  477. if( convert !== property ) {
  478. value = value || _getStyle( element, property );
  479. }
  480. if( vendorPrefixes[ j ] ) {
  481. // -vendorprefix-key-name
  482. value = value || _getStyle( element, vendorPrefixes[ j ] + property );
  483. }
  484. if( value ) {
  485. return value;
  486. }
  487. }
  488. return undefined;
  489. };
  490. })();
  491. (function() {
  492. var cssExceptions = shoestring.cssExceptions;
  493. // IE8 uses marginRight instead of margin-right
  494. function convertPropertyName( str ) {
  495. return str.replace( /\-([A-Za-z])/g, function ( match, character ) {
  496. return character.toUpperCase();
  497. });
  498. }
  499. /**
  500. * Private function for setting the style of an element.
  501. *
  502. * **NOTE** Please use the [css](../css.js.html) method instead.
  503. *
  504. * @method _setStyle
  505. * @param {HTMLElement} element The element we want to style.
  506. * @param {string} property The property being used to style the element.
  507. * @param {string} value The css value for the style property.
  508. */
  509. shoestring._setStyle = function( element, property, value ) {
  510. var convertedProperty = convertPropertyName(property);
  511. element.style[ property ] = value;
  512. if( convertedProperty !== property ) {
  513. element.style[ convertedProperty ] = value;
  514. }
  515. if( cssExceptions[ property ] ) {
  516. for( var j = 0, k = cssExceptions[ property ].length; j<k; j++ ) {
  517. element.style[ cssExceptions[ property ][ j ] ] = value;
  518. }
  519. }
  520. };
  521. })();
  522. /**
  523. * Get the compute style property of the first element or set the value of a style property
  524. * on all elements in the set.
  525. *
  526. * @method _setStyle
  527. * @param {string} property The property being used to style the element.
  528. * @param {string|undefined} value The css value for the style property.
  529. * @return {string|shoestring}
  530. * @this shoestring
  531. */
  532. shoestring.fn.css = function( property, value ){
  533. if( !this[0] ){
  534. return;
  535. }
  536. if( typeof property === "object" ) {
  537. return this.each(function() {
  538. for( var key in property ) {
  539. if( property.hasOwnProperty( key ) ) {
  540. shoestring._setStyle( this, key, property[key] );
  541. }
  542. }
  543. });
  544. } else {
  545. // assignment else retrieve first
  546. if( value !== undefined ){
  547. return this.each(function(){
  548. shoestring._setStyle( this, property, value );
  549. });
  550. }
  551. return shoestring._getStyle( this[0], property );
  552. }
  553. };
  554. /**
  555. * Returns the indexed element wrapped in a new `shoestring` object.
  556. *
  557. * @param {integer} index The index of the element to wrap and return.
  558. * @return shoestring
  559. * @this shoestring
  560. */
  561. shoestring.fn.eq = function( index ){
  562. if( this[index] ){
  563. return shoestring( this[index] );
  564. }
  565. return shoestring([]);
  566. };
  567. /**
  568. * Filter out the current set if they do *not* match the passed selector or
  569. * the supplied callback returns false
  570. *
  571. * @param {string,function} selector The selector or boolean return value callback used to filter the elements.
  572. * @return shoestring
  573. * @this shoestring
  574. */
  575. shoestring.fn.filter = function( selector ){
  576. var ret = [];
  577. this.each(function( index ){
  578. var wsel;
  579. if( typeof selector === 'function' ) {
  580. if( selector.call( this, index ) !== false ) {
  581. ret.push( this );
  582. }
  583. } else {
  584. if( !this.parentNode ){
  585. var context = shoestring( doc.createDocumentFragment() );
  586. context[ 0 ].appendChild( this );
  587. wsel = shoestring( selector, context );
  588. } else {
  589. wsel = shoestring( selector, this.parentNode );
  590. }
  591. if( shoestring.inArray( this, wsel ) > -1 ){
  592. ret.push( this );
  593. }
  594. }
  595. });
  596. return shoestring( ret );
  597. };
  598. /**
  599. * Find descendant elements of the current collection.
  600. *
  601. * @param {string} selector The selector used to find the children
  602. * @return shoestring
  603. * @this shoestring
  604. */
  605. shoestring.fn.find = function( selector ){
  606. var ret = [],
  607. finds;
  608. this.each(function(){
  609. finds = this.querySelectorAll( selector );
  610. for( var i = 0, il = finds.length; i < il; i++ ){
  611. ret = ret.concat( finds[i] );
  612. }
  613. });
  614. return shoestring( ret );
  615. };
  616. /**
  617. * Returns the first element of the set wrapped in a new `shoestring` object.
  618. *
  619. * @return shoestring
  620. * @this shoestring
  621. */
  622. shoestring.fn.first = function(){
  623. return this.eq( 0 );
  624. };
  625. /**
  626. * Returns the raw DOM node at the passed index.
  627. *
  628. * @param {integer} index The index of the element to wrap and return.
  629. * @return {HTMLElement|undefined|array}
  630. * @this shoestring
  631. */
  632. shoestring.fn.get = function( index ){
  633. // return an array of elements if index is undefined
  634. if( index === undefined ){
  635. var elements = [];
  636. for( var i = 0; i < this.length; i++ ){
  637. elements.push( this[ i ] );
  638. }
  639. return elements;
  640. } else {
  641. return this[ index ];
  642. }
  643. };
  644. var set = function( html ){
  645. if( typeof html === "string" || typeof html === "number" ){
  646. return this.each(function(){
  647. this.innerHTML = "" + html;
  648. });
  649. } else {
  650. var h = "";
  651. if( typeof html.length !== "undefined" ){
  652. for( var i = 0, l = html.length; i < l; i++ ){
  653. h += html[i].outerHTML;
  654. }
  655. } else {
  656. h = html.outerHTML;
  657. }
  658. return this.each(function(){
  659. this.innerHTML = h;
  660. });
  661. }
  662. };
  663. /**
  664. * Gets or sets the `innerHTML` from all the elements in the set.
  665. *
  666. * @param {string|undefined} html The html to assign
  667. * @return {string|shoestring}
  668. * @this shoestring
  669. */
  670. shoestring.fn.html = function( html ){
  671. if( typeof html !== "undefined" ){
  672. return set.call( this, html );
  673. } else { // get
  674. var pile = "";
  675. this.each(function(){
  676. pile += this.innerHTML;
  677. });
  678. return pile;
  679. }
  680. };
  681. (function() {
  682. function _getIndex( set, test ) {
  683. var i, result, element;
  684. for( i = result = 0; i < set.length; i++ ) {
  685. element = set.item ? set.item(i) : set[i];
  686. if( test(element) ){
  687. return result;
  688. }
  689. // ignore text nodes, etc
  690. // NOTE may need to be more permissive
  691. if( element.nodeType === 1 ){
  692. result++;
  693. }
  694. }
  695. return -1;
  696. }
  697. /**
  698. * Find the index in the current set for the passed selector.
  699. * Without a selector it returns the index of the first node within the array of its siblings.
  700. *
  701. * @param {string|undefined} selector The selector used to search for the index.
  702. * @return {integer}
  703. * @this {shoestring}
  704. */
  705. shoestring.fn.index = function( selector ){
  706. var self, children;
  707. self = this;
  708. // no arg? check the children, otherwise check each element that matches
  709. if( selector === undefined ){
  710. children = ( ( this[ 0 ] && this[0].parentNode ) || doc.documentElement).childNodes;
  711. // check if the element matches the first of the set
  712. return _getIndex(children, function( element ) {
  713. return self[0] === element;
  714. });
  715. } else {
  716. // check if the element matches the first selected node from the parent
  717. return _getIndex(self, function( element ) {
  718. return element === (shoestring( selector, element.parentNode )[ 0 ]);
  719. });
  720. }
  721. };
  722. })();
  723. /**
  724. * Insert the current set before the elements matching the selector.
  725. *
  726. * @param {string} selector The selector before which to insert the current set.
  727. * @return shoestring
  728. * @this shoestring
  729. */
  730. shoestring.fn.insertBefore = function( selector ){
  731. return this.each(function(){
  732. shoestring( selector ).before( this );
  733. });
  734. };
  735. /**
  736. * Returns the last element of the set wrapped in a new `shoestring` object.
  737. *
  738. * @return shoestring
  739. * @this shoestring
  740. */
  741. shoestring.fn.last = function(){
  742. return this.eq( this.length - 1 );
  743. };
  744. /**
  745. * Returns a `shoestring` object with the set of siblings of each element in the original set.
  746. *
  747. * @return shoestring
  748. * @this shoestring
  749. */
  750. shoestring.fn.next = function(){
  751. var result = [];
  752. // TODO need to implement map
  753. this.each(function() {
  754. var children, item, found;
  755. // get the child nodes for this member of the set
  756. children = shoestring( this.parentNode )[0].childNodes;
  757. for( var i = 0; i < children.length; i++ ){
  758. item = children.item( i );
  759. // found the item we needed (found) which means current item value is
  760. // the next node in the list, as long as it's viable grab it
  761. // NOTE may need to be more permissive
  762. if( found && item.nodeType === 1 ){
  763. result.push( item );
  764. break;
  765. }
  766. // find the current item and mark it as found
  767. if( item === this ){
  768. found = true;
  769. }
  770. }
  771. });
  772. return shoestring( result );
  773. };
  774. /**
  775. * Removes elements from the current set.
  776. *
  777. * @param {string} selector The selector to use when removing the elements.
  778. * @return shoestring
  779. * @this shoestring
  780. */
  781. shoestring.fn.not = function( selector ){
  782. var ret = [];
  783. this.each(function(){
  784. var found = shoestring( selector, this.parentNode );
  785. if( shoestring.inArray(this, found) === -1 ){
  786. ret.push( this );
  787. }
  788. });
  789. return shoestring( ret );
  790. };
  791. /**
  792. * Returns the set of first parents for each element in the current set.
  793. *
  794. * @return shoestring
  795. * @this shoestring
  796. */
  797. shoestring.fn.parent = function(){
  798. var ret = [],
  799. parent;
  800. this.each(function(){
  801. // no parent node, assume top level
  802. // jQuery parent: return the document object for <html> or the parent node if it exists
  803. parent = (this === doc.documentElement ? doc : this.parentNode);
  804. // if there is a parent and it's not a document fragment
  805. if( parent && parent.nodeType !== 11 ){
  806. ret.push( parent );
  807. }
  808. });
  809. return shoestring(ret);
  810. };
  811. /**
  812. * Add an HTML string or element before the children of each element in the current set.
  813. *
  814. * @param {string|HTMLElement} fragment The HTML string or element to add.
  815. * @return shoestring
  816. * @this shoestring
  817. */
  818. shoestring.fn.prepend = function( fragment ){
  819. if( typeof( fragment ) === "string" || fragment.nodeType !== undefined ){
  820. fragment = shoestring( fragment );
  821. }
  822. return this.each(function( i ){
  823. for( var j = 0, jl = fragment.length; j < jl; j++ ){
  824. var insertEl = i > 0 ? fragment[ j ].cloneNode( true ) : fragment[ j ];
  825. if ( this.firstChild ){
  826. this.insertBefore( insertEl, this.firstChild );
  827. } else {
  828. this.appendChild( insertEl );
  829. }
  830. }
  831. });
  832. };
  833. /**
  834. * Returns a `shoestring` object with the set of *one* siblingx before each element in the original set.
  835. *
  836. * @return shoestring
  837. * @this shoestring
  838. */
  839. shoestring.fn.prev = function(){
  840. var result = [];
  841. // TODO need to implement map
  842. this.each(function() {
  843. var children, item, found;
  844. // get the child nodes for this member of the set
  845. children = shoestring( this.parentNode )[0].childNodes;
  846. for( var i = children.length -1; i >= 0; i-- ){
  847. item = children.item( i );
  848. // found the item we needed (found) which means current item value is
  849. // the next node in the list, as long as it's viable grab it
  850. // NOTE may need to be more permissive
  851. if( found && item.nodeType === 1 ){
  852. result.push( item );
  853. break;
  854. }
  855. // find the current item and mark it as found
  856. if( item === this ){
  857. found = true;
  858. }
  859. }
  860. });
  861. return shoestring( result );
  862. };
  863. /**
  864. * Returns a `shoestring` object with the set of *all* siblings before each element in the original set.
  865. *
  866. * @return shoestring
  867. * @this shoestring
  868. */
  869. shoestring.fn.prevAll = function(){
  870. var result = [];
  871. this.each(function() {
  872. var $previous = shoestring( this ).prev();
  873. while( $previous.length ){
  874. result.push( $previous[0] );
  875. $previous = $previous.prev();
  876. }
  877. });
  878. return shoestring( result );
  879. };
  880. /**
  881. * Remove an attribute from each element in the current set.
  882. *
  883. * @param {string} name The name of the attribute.
  884. * @return shoestring
  885. * @this shoestring
  886. */
  887. shoestring.fn.removeAttr = function( name ){
  888. return this.each(function(){
  889. this.removeAttribute( name );
  890. });
  891. };
  892. /**
  893. * Remove a class from each DOM element in the set of elements.
  894. *
  895. * @param {string} className The name of the class to be removed.
  896. * @return shoestring
  897. * @this shoestring
  898. */
  899. shoestring.fn.removeClass = function( cname ){
  900. var classes = cname.replace(/^\s+|\s+$/g, '').split( " " );
  901. return this.each(function(){
  902. var newClassName, regex;
  903. for( var i = 0, il = classes.length; i < il; i++ ){
  904. if( this.className !== undefined ){
  905. regex = new RegExp( "(^|\\s)" + classes[ i ] + "($|\\s)", "gmi" );
  906. newClassName = this.className.replace( regex, " " );
  907. this.className = newClassName.replace(/^\s+|\s+$/g, '');
  908. }
  909. }
  910. });
  911. };
  912. /**
  913. * Remove the current set of elements from the DOM.
  914. *
  915. * @return shoestring
  916. * @this shoestring
  917. */
  918. shoestring.fn.remove = function(){
  919. return this.each(function(){
  920. if( this.parentNode ) {
  921. this.parentNode.removeChild( this );
  922. }
  923. });
  924. };
  925. /**
  926. * Replace each element in the current set with that argument HTML string or HTMLElement.
  927. *
  928. * @param {string|HTMLElement} fragment The value to assign.
  929. * @return shoestring
  930. * @this shoestring
  931. */
  932. shoestring.fn.replaceWith = function( fragment ){
  933. if( typeof( fragment ) === "string" ){
  934. fragment = shoestring( fragment );
  935. }
  936. var ret = [];
  937. if( fragment.length > 1 ){
  938. fragment = fragment.reverse();
  939. }
  940. this.each(function( i ){
  941. var clone = this.cloneNode( true ),
  942. insertEl;
  943. ret.push( clone );
  944. // If there is no parentNode, this is pointless, drop it.
  945. if( !this.parentNode ){ return; }
  946. if( fragment.length === 1 ){
  947. insertEl = i > 0 ? fragment[ 0 ].cloneNode( true ) : fragment[ 0 ];
  948. this.parentNode.replaceChild( insertEl, this );
  949. } else {
  950. for( var j = 0, jl = fragment.length; j < jl; j++ ){
  951. insertEl = i > 0 ? fragment[ j ].cloneNode( true ) : fragment[ j ];
  952. this.parentNode.insertBefore( insertEl, this.nextSibling );
  953. }
  954. this.parentNode.removeChild( this );
  955. }
  956. });
  957. return shoestring( ret );
  958. };
  959. /**
  960. * Get all of the sibling elements for each element in the current set.
  961. *
  962. * @return shoestring
  963. * @this shoestring
  964. */
  965. shoestring.fn.siblings = function(){
  966. if( !this.length ) {
  967. return shoestring( [] );
  968. }
  969. var sibs = [], el = this[ 0 ].parentNode.firstChild;
  970. do {
  971. if( el.nodeType === 1 && el !== this[ 0 ] ) {
  972. sibs.push( el );
  973. }
  974. el = el.nextSibling;
  975. } while( el );
  976. return shoestring( sibs );
  977. };
  978. var getText = function( elem ){
  979. var node,
  980. ret = "",
  981. i = 0,
  982. nodeType = elem.nodeType;
  983. if ( !nodeType ) {
  984. // If no nodeType, this is expected to be an array
  985. while ( (node = elem[i++]) ) {
  986. // Do not traverse comment nodes
  987. ret += getText( node );
  988. }
  989. } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
  990. // Use textContent for elements
  991. // innerText usage removed for consistency of new lines (jQuery #11153)
  992. if ( typeof elem.textContent === "string" ) {
  993. return elem.textContent;
  994. } else {
  995. // Traverse its children
  996. for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
  997. ret += getText( elem );
  998. }
  999. }
  1000. } else if ( nodeType === 3 || nodeType === 4 ) {
  1001. return elem.nodeValue;
  1002. }
  1003. // Do not include comment or processing instruction nodes
  1004. return ret;
  1005. };
  1006. /**
  1007. * Recursively retrieve the text content of the each element in the current set.
  1008. *
  1009. * @return shoestring
  1010. * @this shoestring
  1011. */
  1012. shoestring.fn.text = function() {
  1013. return getText( this );
  1014. };
  1015. /**
  1016. * Get the value of the first element or set the value of all elements in the current set.
  1017. *
  1018. * @param {string} value The value to set.
  1019. * @return shoestring
  1020. * @this shoestring
  1021. */
  1022. shoestring.fn.val = function( value ){
  1023. var el;
  1024. if( value !== undefined ){
  1025. return this.each(function(){
  1026. if( this.tagName === "SELECT" ){
  1027. var optionSet, option,
  1028. options = this.options,
  1029. values = [],
  1030. i = options.length,
  1031. newIndex;
  1032. values[0] = value;
  1033. while ( i-- ) {
  1034. option = options[ i ];
  1035. if ( (option.selected = shoestring.inArray( option.value, values ) >= 0) ) {
  1036. optionSet = true;
  1037. newIndex = i;
  1038. }
  1039. }
  1040. // force browsers to behave consistently when non-matching value is set
  1041. if ( !optionSet ) {
  1042. this.selectedIndex = -1;
  1043. } else {
  1044. this.selectedIndex = newIndex;
  1045. }
  1046. } else {
  1047. this.value = value;
  1048. }
  1049. });
  1050. } else {
  1051. el = this[0];
  1052. if( el.tagName === "SELECT" ){
  1053. if( el.selectedIndex < 0 ){ return ""; }
  1054. return el.options[ el.selectedIndex ].value;
  1055. } else {
  1056. return el.value;
  1057. }
  1058. }
  1059. };
  1060. /**
  1061. * Private function for setting/getting the offset property for height/width.
  1062. *
  1063. * **NOTE** Please use the [width](width.js.html) or [height](height.js.html) methods instead.
  1064. *
  1065. * @param {shoestring} set The set of elements.
  1066. * @param {string} name The string "height" or "width".
  1067. * @param {float|undefined} value The value to assign.
  1068. * @return shoestring
  1069. * @this window
  1070. */
  1071. shoestring._dimension = function( set, name, value ){
  1072. var offsetName;
  1073. if( value === undefined ){
  1074. offsetName = name.replace(/^[a-z]/, function( letter ) {
  1075. return letter.toUpperCase();
  1076. });
  1077. return set[ 0 ][ "offset" + offsetName ];
  1078. } else {
  1079. // support integer values as pixels
  1080. value = typeof value === "string" ? value : value + "px";
  1081. return set.each(function(){
  1082. this.style[ name ] = value;
  1083. });
  1084. }
  1085. };
  1086. /**
  1087. * Gets the width value of the first element or sets the width for the whole set.
  1088. *
  1089. * @param {float|undefined} value The value to assign.
  1090. * @return shoestring
  1091. * @this shoestring
  1092. */
  1093. shoestring.fn.width = function( value ){
  1094. return shoestring._dimension( this, "width", value );
  1095. };
  1096. /**
  1097. * Wraps the child elements in the provided HTML.
  1098. *
  1099. * @param {string} html The wrapping HTML.
  1100. * @return shoestring
  1101. * @this shoestring
  1102. */
  1103. shoestring.fn.wrapInner = function( html ){
  1104. return this.each(function(){
  1105. var inH = this.innerHTML;
  1106. this.innerHTML = "";
  1107. shoestring( this ).append( shoestring( html ).html( inH ) );
  1108. });
  1109. };
  1110. function initEventCache( el, evt ) {
  1111. if ( !el.shoestringData ) {
  1112. el.shoestringData = {};
  1113. }
  1114. if ( !el.shoestringData.events ) {
  1115. el.shoestringData.events = {};
  1116. }
  1117. if ( !el.shoestringData.loop ) {
  1118. el.shoestringData.loop = {};
  1119. }
  1120. if ( !el.shoestringData.events[ evt ] ) {
  1121. el.shoestringData.events[ evt ] = [];
  1122. }
  1123. }
  1124. function addToEventCache( el, evt, eventInfo ) {
  1125. var obj = {};
  1126. obj.isCustomEvent = eventInfo.isCustomEvent;
  1127. obj.callback = eventInfo.callfunc;
  1128. obj.originalCallback = eventInfo.originalCallback;
  1129. obj.namespace = eventInfo.namespace;
  1130. el.shoestringData.events[ evt ].push( obj );
  1131. if( eventInfo.customEventLoop ) {
  1132. el.shoestringData.loop[ evt ] = eventInfo.customEventLoop;
  1133. }
  1134. }
  1135. /**
  1136. * Bind a callback to an event for the currrent set of elements.
  1137. *
  1138. * @param {string} evt The event(s) to watch for.
  1139. * @param {object,function} data Data to be included with each event or the callback.
  1140. * @param {function} originalCallback Callback to be invoked when data is define.d.
  1141. * @return shoestring
  1142. * @this shoestring
  1143. */
  1144. shoestring.fn.bind = function( evt, data, originalCallback ){
  1145. if( typeof data === "function" ){
  1146. originalCallback = data;
  1147. data = null;
  1148. }
  1149. var evts = evt.split( " " );
  1150. // NOTE the `triggeredElement` is purely for custom events from IE
  1151. function encasedCallback( e, namespace, triggeredElement ){
  1152. var result;
  1153. if( e._namespace && e._namespace !== namespace ) {
  1154. return;
  1155. }
  1156. e.data = data;
  1157. e.namespace = e._namespace;
  1158. var returnTrue = function(){
  1159. return true;
  1160. };
  1161. e.isDefaultPrevented = function(){
  1162. return false;
  1163. };
  1164. var originalPreventDefault = e.preventDefault;
  1165. var preventDefaultConstructor = function(){
  1166. if( originalPreventDefault ) {
  1167. return function(){
  1168. e.isDefaultPrevented = returnTrue;
  1169. originalPreventDefault.call(e);
  1170. };
  1171. } else {
  1172. return function(){
  1173. e.isDefaultPrevented = returnTrue;
  1174. e.returnValue = false;
  1175. };
  1176. }
  1177. };
  1178. // thanks https://github.com/jonathantneal/EventListener
  1179. e.target = triggeredElement || e.target || e.srcElement;
  1180. e.preventDefault = preventDefaultConstructor();
  1181. e.stopPropagation = e.stopPropagation || function () {
  1182. e.cancelBubble = true;
  1183. };
  1184. result = originalCallback.apply(this, [ e ].concat( e._args ) );
  1185. if( result === false ){
  1186. e.preventDefault();
  1187. e.stopPropagation();
  1188. }
  1189. return result;
  1190. }
  1191. return this.each(function(){
  1192. var domEventCallback,
  1193. customEventCallback,
  1194. customEventLoop,
  1195. oEl = this;
  1196. for( var i = 0, il = evts.length; i < il; i++ ){
  1197. var split = evts[ i ].split( "." ),
  1198. evt = split[ 0 ],
  1199. namespace = split.length > 0 ? split[ 1 ] : null;
  1200. domEventCallback = function( originalEvent ) {
  1201. if( oEl.ssEventTrigger ) {
  1202. originalEvent._namespace = oEl.ssEventTrigger._namespace;
  1203. originalEvent._args = oEl.ssEventTrigger._args;
  1204. oEl.ssEventTrigger = null;
  1205. }
  1206. return encasedCallback.call( oEl, originalEvent, namespace );
  1207. };
  1208. customEventCallback = null;
  1209. customEventLoop = null;
  1210. initEventCache( this, evt );
  1211. this.addEventListener( evt, domEventCallback, false );
  1212. addToEventCache( this, evt, {
  1213. callfunc: customEventCallback || domEventCallback,
  1214. isCustomEvent: !!customEventCallback,
  1215. customEventLoop: customEventLoop,
  1216. originalCallback: originalCallback,
  1217. namespace: namespace
  1218. });
  1219. }
  1220. });
  1221. };
  1222. shoestring.fn.on = shoestring.fn.bind;
  1223. /**
  1224. * Unbind a previous bound callback for an event.
  1225. *
  1226. * @param {string} event The event(s) the callback was bound to..
  1227. * @param {function} callback Callback to unbind.
  1228. * @return shoestring
  1229. * @this shoestring
  1230. */
  1231. shoestring.fn.unbind = function( event, callback ){
  1232. var evts = event ? event.split( " " ) : [];
  1233. return this.each(function(){
  1234. if( !this.shoestringData || !this.shoestringData.events ) {
  1235. return;
  1236. }
  1237. if( !evts.length ) {
  1238. unbindAll.call( this );
  1239. } else {
  1240. var split, evt, namespace;
  1241. for( var i = 0, il = evts.length; i < il; i++ ){
  1242. split = evts[ i ].split( "." ),
  1243. evt = split[ 0 ],
  1244. namespace = split.length > 0 ? split[ 1 ] : null;
  1245. if( evt ) {
  1246. unbind.call( this, evt, namespace, callback );
  1247. } else {
  1248. unbindAll.call( this, namespace, callback );
  1249. }
  1250. }
  1251. }
  1252. });
  1253. };
  1254. function unbind( evt, namespace, callback ) {
  1255. var bound = this.shoestringData.events[ evt ];
  1256. if( !(bound && bound.length) ) {
  1257. return;
  1258. }
  1259. var matched = [], j, jl;
  1260. for( j = 0, jl = bound.length; j < jl; j++ ) {
  1261. if( !namespace || namespace === bound[ j ].namespace ) {
  1262. if( callback === undefined || callback === bound[ j ].originalCallback ) {
  1263. this.removeEventListener( evt, bound[ j ].callback, false );
  1264. matched.push( j );
  1265. }
  1266. }
  1267. }
  1268. for( j = 0, jl = matched.length; j < jl; j++ ) {
  1269. this.shoestringData.events[ evt ].splice( j, 1 );
  1270. }
  1271. }
  1272. function unbindAll( namespace, callback ) {
  1273. for( var evtKey in this.shoestringData.events ) {
  1274. unbind.call( this, evtKey, namespace, callback );
  1275. }
  1276. }
  1277. shoestring.fn.off = shoestring.fn.unbind;
  1278. /**
  1279. * Bind a callback to an event for the currrent set of elements, unbind after one occurence.
  1280. *
  1281. * @param {string} event The event(s) to watch for.
  1282. * @param {function} callback Callback to invoke on the event.
  1283. * @return shoestring
  1284. * @this shoestring
  1285. */
  1286. shoestring.fn.one = function( event, callback ){
  1287. var evts = event.split( " " );
  1288. return this.each(function(){
  1289. var thisevt, cbs = {}, $t = shoestring( this );
  1290. for( var i = 0, il = evts.length; i < il; i++ ){
  1291. thisevt = evts[ i ];
  1292. cbs[ thisevt ] = function( e ){
  1293. var $t = shoestring( this );
  1294. for( var j in cbs ) {
  1295. $t.unbind( j, cbs[ j ] );
  1296. }
  1297. return callback.apply( this, [ e ].concat( e._args ) );
  1298. };
  1299. $t.bind( thisevt, cbs[ thisevt ] );
  1300. }
  1301. });
  1302. };
  1303. /**
  1304. * Trigger an event on the first element in the set, no bubbling, no defaults.
  1305. *
  1306. * @param {string} event The event(s) to trigger.
  1307. * @param {object} args Arguments to append to callback invocations.
  1308. * @return shoestring
  1309. * @this shoestring
  1310. */
  1311. shoestring.fn.triggerHandler = function( event, args ){
  1312. var e = event.split( " " )[ 0 ],
  1313. el = this[ 0 ],
  1314. ret;
  1315. // See this.fireEvent( 'on' + evts[ i ], document.createEventObject() ); instead of click() etc in trigger.
  1316. if( doc.createEvent && el.shoestringData && el.shoestringData.events && el.shoestringData.events[ e ] ){
  1317. var bindings = el.shoestringData.events[ e ];
  1318. for (var i in bindings ){
  1319. if( bindings.hasOwnProperty( i ) ){
  1320. event = doc.createEvent( "Event" );
  1321. event.initEvent( e, true, true );
  1322. event._args = args;
  1323. args.unshift( event );
  1324. ret = bindings[ i ].originalCallback.apply( event.target, args );
  1325. }
  1326. }
  1327. }
  1328. return ret;
  1329. };
  1330. /**
  1331. * Trigger an event on each of the DOM elements in the current set.
  1332. *
  1333. * @param {string} event The event(s) to trigger.
  1334. * @param {object} args Arguments to append to callback invocations.
  1335. * @return shoestring
  1336. * @this shoestring
  1337. */
  1338. shoestring.fn.trigger = function( event, args ){
  1339. var evts = event.split( " " );
  1340. return this.each(function(){
  1341. var split, evt, namespace;
  1342. for( var i = 0, il = evts.length; i < il; i++ ){
  1343. split = evts[ i ].split( "." ),
  1344. evt = split[ 0 ],
  1345. namespace = split.length > 0 ? split[ 1 ] : null;
  1346. if( evt === "click" ){
  1347. if( this.tagName === "INPUT" && this.type === "checkbox" && this.click ){
  1348. this.click();
  1349. return false;
  1350. }
  1351. }
  1352. if( doc.createEvent ){
  1353. var event = doc.createEvent( "Event" );
  1354. event.initEvent( evt, true, true );
  1355. event._args = args;
  1356. event._namespace = namespace;
  1357. this.dispatchEvent( event );
  1358. }
  1359. }
  1360. });
  1361. };
  1362. return shoestring;
  1363. }));
  1364. (function (root, factory) {
  1365. if (typeof define === 'function' && define.amd) {
  1366. define(["shoestring"], function (shoestring) {
  1367. return (root.Tablesaw = factory(shoestring, root));
  1368. });
  1369. } else if (typeof exports === 'object') {
  1370. module.exports = factory(require('shoestring'), root);
  1371. } else {
  1372. root.Tablesaw = factory(shoestring, root);
  1373. }
  1374. }(typeof window !== "undefined" ? window : this, function ($, window) {
  1375. "use strict";
  1376. var document = window.document;
  1377. var domContentLoadedTriggered = false;
  1378. document.addEventListener("DOMContentLoaded", function() {
  1379. domContentLoadedTriggered = true;
  1380. });
  1381. var Tablesaw = {
  1382. i18n: {
  1383. modeStack: "Stack",
  1384. modeSwipe: "Swipe",
  1385. modeToggle: "Toggle",
  1386. modeSwitchColumnsAbbreviated: "Cols",
  1387. modeSwitchColumns: "Columns",
  1388. columnToggleButton: "Columns",
  1389. columnToggleError: "No eligible columns.",
  1390. sort: "Sort",
  1391. swipePreviousColumn: "Previous column",
  1392. swipeNextColumn: "Next column"
  1393. },
  1394. // cut the mustard
  1395. mustard:
  1396. "head" in document && // IE9+, Firefox 4+, Safari 5.1+, Mobile Safari 4.1+, Opera 11.5+, Android 2.3+
  1397. (!window.blackberry || window.WebKitPoint) && // only WebKit Blackberry (OS 6+)
  1398. !window.operamini,
  1399. $: $,
  1400. _init: function(element) {
  1401. Tablesaw.$(element || document).trigger("enhance.tablesaw");
  1402. },
  1403. init: function(element) {
  1404. if (!domContentLoadedTriggered) {
  1405. if ("addEventListener" in document) {
  1406. // Use raw DOMContentLoaded instead of shoestring (may have issues in Android 2.3, exhibited by stack table)
  1407. document.addEventListener("DOMContentLoaded", function() {
  1408. Tablesaw._init(element);
  1409. });
  1410. }
  1411. } else {
  1412. Tablesaw._init(element);
  1413. }
  1414. }
  1415. };
  1416. $(document).on("enhance.tablesaw", function() {
  1417. // Extend i18n config, if one exists.
  1418. if (typeof TablesawConfig !== "undefined" && TablesawConfig.i18n) {
  1419. Tablesaw.i18n = $.extend(Tablesaw.i18n, TablesawConfig.i18n || {});
  1420. }
  1421. Tablesaw.i18n.modes = [
  1422. Tablesaw.i18n.modeStack,
  1423. Tablesaw.i18n.modeSwipe,
  1424. Tablesaw.i18n.modeToggle
  1425. ];
  1426. });
  1427. if (Tablesaw.mustard) {
  1428. $(document.documentElement).addClass("tablesaw-enhanced");
  1429. }
  1430. (function() {
  1431. var pluginName = "tablesaw";
  1432. var classes = {
  1433. toolbar: "tablesaw-bar"
  1434. };
  1435. var events = {
  1436. create: "tablesawcreate",
  1437. destroy: "tablesawdestroy",
  1438. refresh: "tablesawrefresh",
  1439. resize: "tablesawresize"
  1440. };
  1441. var defaultMode = "stack";
  1442. var initSelector = "table";
  1443. var initFilterSelector = "[data-tablesaw],[data-tablesaw-mode],[data-tablesaw-sortable]";
  1444. var defaultConfig = {};
  1445. Tablesaw.events = events;
  1446. var Table = function(element) {
  1447. if (!element) {
  1448. throw new Error("Tablesaw requires an element.");
  1449. }
  1450. this.table = element;
  1451. this.$table = $(element);
  1452. // only one <thead> and <tfoot> are allowed, per the specification
  1453. this.$thead = this.$table
  1454. .children()
  1455. .filter("thead")
  1456. .eq(0);
  1457. // multiple <tbody> are allowed, per the specification
  1458. this.$tbody = this.$table.children().filter("tbody");
  1459. this.mode = this.$table.attr("data-tablesaw-mode") || defaultMode;
  1460. this.$toolbar = null;
  1461. this.attributes = {
  1462. subrow: "data-tablesaw-subrow",
  1463. ignorerow: "data-tablesaw-ignorerow"
  1464. };
  1465. this.init();
  1466. };
  1467. Table.prototype.init = function() {
  1468. if (!this.$thead.length) {
  1469. throw new Error("tablesaw: a <thead> is required, but none was found.");
  1470. }
  1471. if (!this.$thead.find("th").length) {
  1472. throw new Error("tablesaw: no header cells found. Are you using <th> inside of <thead>?");
  1473. }
  1474. // assign an id if there is none
  1475. if (!this.$table.attr("id")) {
  1476. this.$table.attr("id", pluginName + "-" + Math.round(Math.random() * 10000));
  1477. }
  1478. this.createToolbar();
  1479. this._initCells();
  1480. this.$table.data(pluginName, this);
  1481. this.$table.trigger(events.create, [this]);
  1482. };
  1483. Table.prototype.getConfig = function(pluginSpecificConfig) {
  1484. // shoestring extend doesn’t support arbitrary args
  1485. var configs = $.extend(defaultConfig, pluginSpecificConfig || {});
  1486. return $.extend(configs, typeof TablesawConfig !== "undefined" ? TablesawConfig : {});
  1487. };
  1488. Table.prototype._getPrimaryHeaderRow = function() {
  1489. return this._getHeaderRows().eq(0);
  1490. };
  1491. Table.prototype._getHeaderRows = function() {
  1492. return this.$thead
  1493. .children()
  1494. .filter("tr")
  1495. .filter(function() {
  1496. return !$(this).is("[data-tablesaw-ignorerow]");
  1497. });
  1498. };
  1499. Table.prototype._getRowIndex = function($row) {
  1500. return $row.prevAll().length;
  1501. };
  1502. Table.prototype._getHeaderRowIndeces = function() {
  1503. var self = this;
  1504. var indeces = [];
  1505. this._getHeaderRows().each(function() {
  1506. indeces.push(self._getRowIndex($(this)));
  1507. });
  1508. return indeces;
  1509. };
  1510. Table.prototype._getPrimaryHeaderCells = function($row) {
  1511. return ($row || this._getPrimaryHeaderRow()).find("th");
  1512. };
  1513. Table.prototype._$getCells = function(th) {
  1514. var self = this;
  1515. return $(th)
  1516. .add(th.cells)
  1517. .filter(function() {
  1518. var $t = $(this);
  1519. var $row = $t.parent();
  1520. var hasColspan = $t.is("[colspan]");
  1521. // no subrows or ignored rows (keep cells in ignored rows that do not have a colspan)
  1522. return (
  1523. !$row.is("[" + self.attributes.subrow + "]") &&
  1524. (!$row.is("[" + self.attributes.ignorerow + "]") || !hasColspan)
  1525. );
  1526. });
  1527. };
  1528. Table.prototype._getVisibleColspan = function() {
  1529. var colspan = 0;
  1530. this._getPrimaryHeaderCells().each(function() {
  1531. var $t = $(this);
  1532. if ($t.css("display") !== "none") {
  1533. colspan += parseInt($t.attr("colspan"), 10) || 1;
  1534. }
  1535. });
  1536. return colspan;
  1537. };
  1538. Table.prototype.getColspanForCell = function($cell) {
  1539. var visibleColspan = this._getVisibleColspan();
  1540. var visibleSiblingColumns = 0;
  1541. if ($cell.closest("tr").data("tablesaw-rowspanned")) {
  1542. visibleSiblingColumns++;
  1543. }
  1544. $cell.siblings().each(function() {
  1545. var $t = $(this);
  1546. var colColspan = parseInt($t.attr("colspan"), 10) || 1;
  1547. if ($t.css("display") !== "none") {
  1548. visibleSiblingColumns += colColspan;
  1549. }
  1550. });
  1551. // console.log( $cell[ 0 ], visibleColspan, visibleSiblingColumns );
  1552. return visibleColspan - visibleSiblingColumns;
  1553. };
  1554. Table.prototype.isCellInColumn = function(header, cell) {
  1555. return $(header)
  1556. .add(header.cells)
  1557. .filter(function() {
  1558. return this === cell;
  1559. }).length;
  1560. };
  1561. Table.prototype.updateColspanCells = function(cls, header, userAction) {
  1562. var self = this;
  1563. var primaryHeaderRow = self._getPrimaryHeaderRow();
  1564. // find persistent column rowspans
  1565. this.$table.find("[rowspan][data-tablesaw-priority]").each(function() {
  1566. var $t = $(this);
  1567. if ($t.attr("data-tablesaw-priority") !== "persist") {
  1568. return;
  1569. }
  1570. var $row = $t.closest("tr");
  1571. var rowspan = parseInt($t.attr("rowspan"), 10);
  1572. if (rowspan > 1) {
  1573. $row = $row.next();
  1574. $row.data("tablesaw-rowspanned", true);
  1575. rowspan--;
  1576. }
  1577. });
  1578. this.$table
  1579. .find("[colspan],[data-tablesaw-maxcolspan]")
  1580. .filter(function() {
  1581. // is not in primary header row
  1582. return $(this).closest("tr")[0] !== primaryHeaderRow[0];
  1583. })
  1584. .each(function() {
  1585. var $cell = $(this);
  1586. if (userAction === undefined || self.isCellInColumn(header, this)) {
  1587. } else {
  1588. // if is not a user action AND the cell is not in the updating column, kill it
  1589. return;
  1590. }
  1591. var colspan = self.getColspanForCell($cell);
  1592. if (cls && userAction !== undefined) {
  1593. // console.log( colspan === 0 ? "addClass" : "removeClass", $cell );
  1594. $cell[colspan === 0 ? "addClass" : "removeClass"](cls);
  1595. }
  1596. // cache original colspan
  1597. var maxColspan = parseInt($cell.attr("data-tablesaw-maxcolspan"), 10);
  1598. if (!maxColspan) {
  1599. $cell.attr("data-tablesaw-maxcolspan", $cell.attr("colspan"));
  1600. } else if (colspan > maxColspan) {
  1601. colspan = maxColspan;
  1602. }
  1603. // console.log( this, "setting colspan to ", colspan );
  1604. $cell.attr("colspan", colspan);
  1605. });
  1606. };
  1607. Table.prototype._findPrimaryHeadersForCell = function(cell) {
  1608. var $headerRow = this._getPrimaryHeaderRow();
  1609. var $headers = this._getPrimaryHeaderCells($headerRow);
  1610. var headerRowIndex = this._getRowIndex($headerRow);
  1611. var results = [];
  1612. for (var rowNumber = 0; rowNumber < this.headerMapping.length; rowNumber++) {
  1613. if (rowNumber === headerRowIndex) {
  1614. continue;
  1615. }
  1616. for (var colNumber = 0; colNumber < this.headerMapping[rowNumber].length; colNumber++) {
  1617. if (this.headerMapping[rowNumber][colNumber] === cell) {
  1618. results.push($headers[colNumber]);
  1619. }
  1620. }
  1621. }
  1622. return results;
  1623. };
  1624. // used by init cells
  1625. Table.prototype.getRows = function() {
  1626. var self = this;
  1627. return this.$table.find("tr").filter(function() {
  1628. return $(this)
  1629. .closest("table")
  1630. .is(self.$table);
  1631. });
  1632. };
  1633. // used by sortable
  1634. Table.prototype.getBodyRows = function(tbody) {
  1635. return (tbody ? $(tbody) : this.$tbody).children().filter("tr");
  1636. };
  1637. Table.prototype.getHeaderCellIndex = function(cell) {
  1638. var lookup = this.headerMapping[0];
  1639. for (var colIndex = 0; colIndex < lookup.length; colIndex++) {
  1640. if (lookup[colIndex] === cell) {
  1641. return colIndex;
  1642. }
  1643. }
  1644. return -1;
  1645. };
  1646. Table.prototype._initCells = function() {
  1647. // re-establish original colspans
  1648. this.$table.find("[data-tablesaw-maxcolspan]").each(function() {
  1649. var $t = $(this);
  1650. $t.attr("colspan", $t.attr("data-tablesaw-maxcolspan"));
  1651. });
  1652. var $rows = this.getRows();
  1653. var columnLookup = [];
  1654. $rows.each(function(rowNumber) {
  1655. columnLookup[rowNumber] = [];
  1656. });
  1657. $rows.each(function(rowNumber) {
  1658. var coltally = 0;
  1659. var $t = $(this);
  1660. var children = $t.children();
  1661. children.each(function() {
  1662. var colspan = parseInt(
  1663. this.getAttribute("data-tablesaw-maxcolspan") || this.getAttribute("colspan"),
  1664. 10
  1665. );
  1666. var rowspan = parseInt(this.getAttribute("rowspan"), 10);
  1667. // set in a previous rowspan
  1668. while (columnLookup[rowNumber][coltally]) {
  1669. coltally++;
  1670. }
  1671. columnLookup[rowNumber][coltally] = this;
  1672. // TODO? both colspan and rowspan
  1673. if (colspan) {
  1674. for (var k = 0; k < colspan - 1; k++) {
  1675. coltally++;
  1676. columnLookup[rowNumber][coltally] = this;
  1677. }
  1678. }
  1679. if (rowspan) {
  1680. for (var j = 1; j < rowspan; j++) {
  1681. columnLookup[rowNumber + j][coltally] = this;
  1682. }
  1683. }
  1684. coltally++;
  1685. });
  1686. });
  1687. var headerRowIndeces = this._getHeaderRowIndeces();
  1688. for (var colNumber = 0; colNumber < columnLookup[0].length; colNumber++) {
  1689. for (var headerIndex = 0, k = headerRowIndeces.length; headerIndex < k; headerIndex++) {
  1690. var headerCol = columnLookup[headerRowIndeces[headerIndex]][colNumber];
  1691. var rowNumber = headerRowIndeces[headerIndex];
  1692. var rowCell;
  1693. if (!headerCol.cells) {
  1694. headerCol.cells = [];
  1695. }
  1696. while (rowNumber < columnLookup.length) {
  1697. rowCell = columnLookup[rowNumber][colNumber];
  1698. if (headerCol !== rowCell) {
  1699. headerCol.cells.push(rowCell);
  1700. }
  1701. rowNumber++;
  1702. }
  1703. }
  1704. }
  1705. this.headerMapping = columnLookup;
  1706. };
  1707. Table.prototype.refresh = function() {
  1708. this._initCells();
  1709. this.$table.trigger(events.refresh, [this]);
  1710. };
  1711. Table.prototype._getToolbarAnchor = function() {
  1712. var $parent = this.$table.parent();
  1713. if ($parent.is(".tablesaw-overflow")) {
  1714. return $parent;
  1715. }
  1716. return this.$table;
  1717. };
  1718. Table.prototype._getToolbar = function($anchor) {
  1719. if (!$anchor) {
  1720. $anchor = this._getToolbarAnchor();
  1721. }
  1722. return $anchor.prev().filter("." + classes.toolbar);
  1723. };
  1724. Table.prototype.createToolbar = function() {
  1725. // Insert the toolbar
  1726. // TODO move this into a separate component
  1727. var $anchor = this._getToolbarAnchor();
  1728. var $toolbar = this._getToolbar($anchor);
  1729. if (!$toolbar.length) {
  1730. $toolbar = $("<div>")
  1731. .addClass(classes.toolbar)
  1732. .insertBefore($anchor);
  1733. }
  1734. this.$toolbar = $toolbar;
  1735. if (this.mode) {
  1736. this.$toolbar.addClass("tablesaw-mode-" + this.mode);
  1737. }
  1738. };
  1739. Table.prototype.destroy = function() {
  1740. // Don’t remove the toolbar, just erase the classes on it.
  1741. // Some of the table features are not yet destroy-friendly.
  1742. this._getToolbar().each(function() {
  1743. this.className = this.className.replace(/\btablesaw-mode\-\w*\b/gi, "");
  1744. });
  1745. var tableId = this.$table.attr("id");
  1746. $(document).off("." + tableId);
  1747. $(window).off("." + tableId);
  1748. // other plugins
  1749. this.$table.trigger(events.destroy, [this]);
  1750. this.$table.removeData(pluginName);
  1751. };
  1752. // Collection method.
  1753. $.fn[pluginName] = function() {
  1754. return this.each(function() {
  1755. var $t = $(this);
  1756. if ($t.data(pluginName)) {
  1757. return;
  1758. }
  1759. new Table(this);
  1760. });
  1761. };
  1762. var $doc = $(document);
  1763. $doc.on("enhance.tablesaw", function(e) {
  1764. // Cut the mustard
  1765. if (Tablesaw.mustard) {
  1766. $(e.target)
  1767. .find(initSelector)
  1768. .filter(initFilterSelector)
  1769. [pluginName]();
  1770. }
  1771. });
  1772. // Avoid a resize during scroll:
  1773. // Some Mobile devices trigger a resize during scroll (sometimes when
  1774. // doing elastic stretch at the end of the document or from the
  1775. // location bar hide)
  1776. var isScrolling = false;
  1777. var scrollTimeout;
  1778. $doc.on("scroll.tablesaw", function() {
  1779. isScrolling = true;
  1780. window.clearTimeout(scrollTimeout);
  1781. scrollTimeout = window.setTimeout(function() {
  1782. isScrolling = false;
  1783. }, 300); // must be greater than the resize timeout below
  1784. });
  1785. var resizeTimeout;
  1786. $(window).on("resize", function() {
  1787. if (!isScrolling) {
  1788. window.clearTimeout(resizeTimeout);
  1789. resizeTimeout = window.setTimeout(function() {
  1790. $doc.trigger(events.resize);
  1791. }, 150); // must be less than the scrolling timeout above.
  1792. }
  1793. });
  1794. Tablesaw.Table = Table;
  1795. })();
  1796. (function() {
  1797. var classes = {
  1798. stackTable: "tablesaw-stack",
  1799. cellLabels: "tablesaw-cell-label",
  1800. cellContentLabels: "tablesaw-cell-content"
  1801. };
  1802. var data = {
  1803. key: "tablesaw-stack"
  1804. };
  1805. var attrs = {
  1806. labelless: "data-tablesaw-no-labels",
  1807. hideempty: "data-tablesaw-hide-empty"
  1808. };
  1809. var Stack = function(element, tablesaw) {
  1810. this.tablesaw = tablesaw;
  1811. this.$table = $(element);
  1812. this.labelless = this.$table.is("[" + attrs.labelless + "]");
  1813. this.hideempty = this.$table.is("[" + attrs.hideempty + "]");
  1814. this.$table.data(data.key, this);
  1815. };
  1816. Stack.prototype.init = function() {
  1817. this.$table.addClass(classes.stackTable);
  1818. if (this.labelless) {
  1819. return;
  1820. }
  1821. var self = this;
  1822. this.$table
  1823. .find("th, td")
  1824. .filter(function() {
  1825. return !$(this).closest("thead").length;
  1826. })
  1827. .filter(function() {
  1828. return (
  1829. !$(this)
  1830. .closest("tr")
  1831. .is("[" + attrs.labelless + "]") &&
  1832. (!self.hideempty || !!$(this).html())
  1833. );
  1834. })
  1835. .each(function() {
  1836. var $newHeader = $(document.createElement("b")).addClass(classes.cellLabels);
  1837. var $cell = $(this);
  1838. $(self.tablesaw._findPrimaryHeadersForCell(this)).each(function(index) {
  1839. var $header = $(this.cloneNode(true));
  1840. // TODO decouple from sortable better
  1841. // Changed from .text() in https://github.com/filamentgroup/tablesaw/commit/b9c12a8f893ec192830ec3ba2d75f062642f935b
  1842. // to preserve structural html in headers, like <a>
  1843. var $sortableButton = $header.find(".tablesaw-sortable-btn");
  1844. $header.find(".tablesaw-sortable-arrow").remove();
  1845. // TODO decouple from checkall better
  1846. var $checkall = $header.find("[data-tablesaw-checkall]");
  1847. $checkall.closest("label").remove();
  1848. if ($checkall.length) {
  1849. $newHeader = $([]);
  1850. return;
  1851. }
  1852. if (index > 0) {
  1853. $newHeader.append(document.createTextNode(", "));
  1854. }
  1855. var parentNode = $sortableButton.length ? $sortableButton[0] : $header[0];
  1856. var el;
  1857. while ((el = parentNode.firstChild)) {
  1858. $newHeader[0].appendChild(el);
  1859. }
  1860. });
  1861. if ($newHeader.length && !$cell.find("." + classes.cellContentLabels).length) {
  1862. $cell.wrapInner("<span class='" + classes.cellContentLabels + "'></span>");
  1863. }
  1864. // Update if already exists.
  1865. var $label = $cell.find("." + classes.cellLabels);
  1866. if (!$label.length) {
  1867. $cell.prepend($newHeader);
  1868. } else {
  1869. // only if changed
  1870. $label.replaceWith($newHeader);
  1871. }
  1872. });
  1873. };
  1874. Stack.prototype.destroy = function() {
  1875. this.$table.removeClass(classes.stackTable);
  1876. this.$table.find("." + classes.cellLabels).remove();
  1877. this.$table.find("." + classes.cellContentLabels).each(function() {
  1878. $(this).replaceWith(this.childNodes);
  1879. });
  1880. };
  1881. // on tablecreate, init
  1882. $(document)
  1883. .on(Tablesaw.events.create, function(e, tablesaw) {
  1884. if (tablesaw.mode === "stack") {
  1885. var table = new Stack(tablesaw.table, tablesaw);
  1886. table.init();
  1887. }
  1888. })
  1889. .on(Tablesaw.events.refresh, function(e, tablesaw) {
  1890. if (tablesaw.mode === "stack") {
  1891. $(tablesaw.table)
  1892. .data(data.key)
  1893. .init();
  1894. }
  1895. })
  1896. .on(Tablesaw.events.destroy, function(e, tablesaw) {
  1897. if (tablesaw.mode === "stack") {
  1898. $(tablesaw.table)
  1899. .data(data.key)
  1900. .destroy();
  1901. }
  1902. });
  1903. Tablesaw.Stack = Stack;
  1904. })();
  1905. (function() {
  1906. var pluginName = "tablesawbtn",
  1907. methods = {
  1908. _create: function() {
  1909. return $(this).each(function() {
  1910. $(this)
  1911. .trigger("beforecreate." + pluginName)
  1912. [pluginName]("_init")
  1913. .trigger("create." + pluginName);
  1914. });
  1915. },
  1916. _init: function() {
  1917. var oEl = $(this),
  1918. sel = this.getElementsByTagName("select")[0];
  1919. if (sel) {
  1920. // TODO next major version: remove .btn-select
  1921. $(this)
  1922. .addClass("btn-select tablesaw-btn-select")
  1923. [pluginName]("_select", sel);
  1924. }
  1925. return oEl;
  1926. },
  1927. _select: function(sel) {
  1928. var update = function(oEl, sel) {
  1929. var opts = $(sel).find("option");
  1930. var label = document.createElement("span");
  1931. var el;
  1932. var children;
  1933. var found = false;
  1934. label.setAttribute("aria-hidden", "true");
  1935. label.innerHTML = "&#160;";
  1936. opts.each(function() {
  1937. var opt = this;
  1938. if (opt.selected) {
  1939. label.innerHTML = opt.text;
  1940. }
  1941. });
  1942. children = oEl.childNodes;
  1943. if (opts.length > 0) {
  1944. for (var i = 0, l = children.length; i < l; i++) {
  1945. el = children[i];
  1946. if (el && el.nodeName.toUpperCase() === "SPAN") {
  1947. oEl.replaceChild(label, el);
  1948. found = true;
  1949. }
  1950. }
  1951. if (!found) {
  1952. oEl.insertBefore(label, oEl.firstChild);
  1953. }
  1954. }
  1955. };
  1956. update(this, sel);
  1957. // todo should this be tablesawrefresh?
  1958. $(this).on("change refresh", function() {
  1959. update(this, sel);
  1960. });
  1961. }
  1962. };
  1963. // Collection method.
  1964. $.fn[pluginName] = function(arrg, a, b, c) {
  1965. return this.each(function() {
  1966. // if it's a method
  1967. if (arrg && typeof arrg === "string") {
  1968. return $.fn[pluginName].prototype[arrg].call(this, a, b, c);
  1969. }
  1970. // don't re-init
  1971. if ($(this).data(pluginName + "active")) {
  1972. return $(this);
  1973. }
  1974. $(this).data(pluginName + "active", true);
  1975. $.fn[pluginName].prototype._create.call(this);
  1976. });
  1977. };
  1978. // add methods
  1979. $.extend($.fn[pluginName].prototype, methods);
  1980. // TODO OOP this and add to Tablesaw object
  1981. })();
  1982. (function() {
  1983. var data = {
  1984. key: "tablesaw-coltoggle"
  1985. };
  1986. var ColumnToggle = function(element) {
  1987. this.$table = $(element);
  1988. if (!this.$table.length) {
  1989. return;
  1990. }
  1991. this.tablesaw = this.$table.data("tablesaw");
  1992. this.attributes = {
  1993. btnTarget: "data-tablesaw-columntoggle-btn-target",
  1994. set: "data-tablesaw-columntoggle-set"
  1995. };
  1996. this.classes = {
  1997. columnToggleTable: "tablesaw-columntoggle",
  1998. columnBtnContain: "tablesaw-columntoggle-btnwrap tablesaw-advance",
  1999. columnBtn: "tablesaw-columntoggle-btn tablesaw-nav-btn down",
  2000. popup: "tablesaw-columntoggle-popup",
  2001. priorityPrefix: "tablesaw-priority-"
  2002. };
  2003. this.set = [];
  2004. this.$headers = this.tablesaw._getPrimaryHeaderCells();
  2005. this.$table.data(data.key, this);
  2006. };
  2007. // Column Toggle Sets (one column chooser can control multiple tables)
  2008. ColumnToggle.prototype.initSet = function() {
  2009. var set = this.$table.attr(this.attributes.set);
  2010. if (set) {
  2011. // Should not include the current table
  2012. var table = this.$table[0];
  2013. this.set = $("table[" + this.attributes.set + "='" + set + "']")
  2014. .filter(function() {
  2015. return this !== table;
  2016. })
  2017. .get();
  2018. }
  2019. };
  2020. ColumnToggle.prototype.init = function() {
  2021. if (!this.$table.length) {
  2022. return;
  2023. }
  2024. var tableId,
  2025. id,
  2026. $menuButton,
  2027. $popup,
  2028. $menu,
  2029. $btnContain,
  2030. self = this;
  2031. var cfg = this.tablesaw.getConfig({
  2032. getColumnToggleLabelTemplate: function(text) {
  2033. return "<label><input type='checkbox' checked>" + text + "</label>";
  2034. }
  2035. });
  2036. this.$table.addClass(this.classes.columnToggleTable);
  2037. tableId = this.$table.attr("id");
  2038. id = tableId + "-popup";
  2039. $btnContain = $("<div class='" + this.classes.columnBtnContain + "'></div>");
  2040. // TODO next major version: remove .btn
  2041. $menuButton = $(
  2042. "<a href='#" +
  2043. id +
  2044. "' class='btn tablesaw-btn btn-micro " +
  2045. this.classes.columnBtn +
  2046. "' data-popup-link>" +
  2047. "<span>" +
  2048. Tablesaw.i18n.columnToggleButton +
  2049. "</span></a>"
  2050. );
  2051. $popup = $("<div class='" + this.classes.popup + "' id='" + id + "'></div>");
  2052. $menu = $("<div class='btn-group'></div>");
  2053. this.$popup = $popup;
  2054. var hasNonPersistentHeaders = false;
  2055. this.$headers.each(function() {
  2056. var $this = $(this),
  2057. priority = $this.attr("data-tablesaw-priority"),
  2058. $cells = self.tablesaw._$getCells(this);
  2059. if (priority && priority !== "persist") {
  2060. $cells.addClass(self.classes.priorityPrefix + priority);
  2061. $(cfg.getColumnToggleLabelTemplate($this.text()))
  2062. .appendTo($menu)
  2063. .find('input[type="checkbox"]')
  2064. .data("tablesaw-header", this);
  2065. hasNonPersistentHeaders = true;
  2066. }
  2067. });
  2068. if (!hasNonPersistentHeaders) {
  2069. $menu.append("<label>" + Tablesaw.i18n.columnToggleError + "</label>");
  2070. }
  2071. $menu.appendTo($popup);
  2072. function onToggleCheckboxChange(checkbox) {
  2073. var checked = checkbox.checked;
  2074. var header = self.getHeaderFromCheckbox(checkbox);
  2075. var $cells = self.tablesaw._$getCells(header);
  2076. $cells[!checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellhidden");
  2077. $cells[checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellvisible");
  2078. self.updateColspanCells(header, checked);
  2079. self.$table.trigger("tablesawcolumns");
  2080. }
  2081. // bind change event listeners to inputs - TODO: move to a private method?
  2082. $menu.find('input[type="checkbox"]').on("change", function(e) {
  2083. onToggleCheckboxChange(e.target);
  2084. if (self.set.length) {
  2085. var index;
  2086. $(self.$popup)
  2087. .find("input[type='checkbox']")
  2088. .each(function(j) {
  2089. if (this === e.target) {
  2090. index = j;
  2091. return false;
  2092. }
  2093. });
  2094. $(self.set).each(function() {
  2095. var checkbox = $(this)
  2096. .data(data.key)
  2097. .$popup.find("input[type='checkbox']")
  2098. .get(index);
  2099. if (checkbox) {
  2100. checkbox.checked = e.target.checked;
  2101. onToggleCheckboxChange(checkbox);
  2102. }
  2103. });
  2104. }
  2105. });
  2106. $menuButton.appendTo($btnContain);
  2107. // Use a different target than the toolbar
  2108. var $btnTarget = $(this.$table.attr(this.attributes.btnTarget));
  2109. $btnContain.appendTo($btnTarget.length ? $btnTarget : this.tablesaw.$toolbar);
  2110. function closePopup(event) {
  2111. // Click came from inside the popup, ignore.
  2112. if (event && $(event.target).closest("." + self.classes.popup).length) {
  2113. return;
  2114. }
  2115. $(document).off("click." + tableId);
  2116. $menuButton.removeClass("up").addClass("down");
  2117. $btnContain.removeClass("visible");
  2118. }
  2119. var closeTimeout;
  2120. function openPopup() {
  2121. $btnContain.addClass("visible");
  2122. $menuButton.removeClass("down").addClass("up");
  2123. $(document).off("click." + tableId, closePopup);
  2124. window.clearTimeout(closeTimeout);
  2125. closeTimeout = window.setTimeout(function() {
  2126. $(document).on("click." + tableId, closePopup);
  2127. }, 15);
  2128. }
  2129. $menuButton.on("click.tablesaw", function(event) {
  2130. event.preventDefault();
  2131. if (!$btnContain.is(".visible")) {
  2132. openPopup();
  2133. } else {
  2134. closePopup();
  2135. }
  2136. });
  2137. $popup.appendTo($btnContain);
  2138. this.$menu = $menu;
  2139. // Fix for iOS not rendering shadows correctly when using `-webkit-overflow-scrolling`
  2140. var $overflow = this.$table.closest(".tablesaw-overflow");
  2141. if ($overflow.css("-webkit-overflow-scrolling")) {
  2142. var timeout;
  2143. $overflow.on("scroll", function() {
  2144. var $div = $(this);
  2145. window.clearTimeout(timeout);
  2146. timeout = window.setTimeout(function() {
  2147. $div.css("-webkit-overflow-scrolling", "auto");
  2148. window.setTimeout(function() {
  2149. $div.css("-webkit-overflow-scrolling", "touch");
  2150. }, 0);
  2151. }, 100);
  2152. });
  2153. }
  2154. $(window).on(Tablesaw.events.resize + "." + tableId, function() {
  2155. self.refreshToggle();
  2156. });
  2157. this.initSet();
  2158. this.refreshToggle();
  2159. };
  2160. ColumnToggle.prototype.getHeaderFromCheckbox = function(checkbox) {
  2161. return $(checkbox).data("tablesaw-header");
  2162. };
  2163. ColumnToggle.prototype.refreshToggle = function() {
  2164. var self = this;
  2165. var invisibleColumns = 0;
  2166. this.$menu.find("input").each(function() {
  2167. var header = self.getHeaderFromCheckbox(this);
  2168. this.checked =
  2169. self.tablesaw
  2170. ._$getCells(header)
  2171. .eq(0)
  2172. .css("display") === "table-cell";
  2173. });
  2174. this.updateColspanCells();
  2175. };
  2176. ColumnToggle.prototype.updateColspanCells = function(header, userAction) {
  2177. this.tablesaw.updateColspanCells("tablesaw-toggle-cellhidden", header, userAction);
  2178. };
  2179. ColumnToggle.prototype.destroy = function() {
  2180. this.$table.removeClass(this.classes.columnToggleTable);
  2181. this.$table.find("th, td").each(function() {
  2182. var $cell = $(this);
  2183. $cell.removeClass("tablesaw-toggle-cellhidden").removeClass("tablesaw-toggle-cellvisible");
  2184. this.className = this.className.replace(/\bui\-table\-priority\-\d\b/g, "");
  2185. });
  2186. };
  2187. // on tablecreate, init
  2188. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2189. if (tablesaw.mode === "columntoggle") {
  2190. var table = new ColumnToggle(tablesaw.table);
  2191. table.init();
  2192. }
  2193. });
  2194. $(document).on(Tablesaw.events.destroy, function(e, tablesaw) {
  2195. if (tablesaw.mode === "columntoggle") {
  2196. $(tablesaw.table)
  2197. .data(data.key)
  2198. .destroy();
  2199. }
  2200. });
  2201. $(document).on(Tablesaw.events.refresh, function(e, tablesaw) {
  2202. if (tablesaw.mode === "columntoggle") {
  2203. $(tablesaw.table)
  2204. .data(data.key)
  2205. .refreshPriority();
  2206. }
  2207. });
  2208. Tablesaw.ColumnToggle = ColumnToggle;
  2209. })();
  2210. (function() {
  2211. function getSortValue(cell) {
  2212. var text = [];
  2213. $(cell.childNodes).each(function() {
  2214. var $el = $(this);
  2215. if ($el.is("input, select")) {
  2216. text.push($el.val());
  2217. } else if ($el.is(".tablesaw-cell-label")) {
  2218. } else {
  2219. text.push(($el.text() || "").replace(/^\s+|\s+$/g, ""));
  2220. }
  2221. });
  2222. return text.join("");
  2223. }
  2224. var pluginName = "tablesaw-sortable",
  2225. initSelector = "table[data-" + pluginName + "]",
  2226. sortableSwitchSelector = "[data-" + pluginName + "-switch]",
  2227. attrs = {
  2228. sortCol: "data-tablesaw-sortable-col",
  2229. defaultCol: "data-tablesaw-sortable-default-col",
  2230. numericCol: "data-tablesaw-sortable-numeric",
  2231. subRow: "data-tablesaw-subrow",
  2232. ignoreRow: "data-tablesaw-ignorerow"
  2233. },
  2234. classes = {
  2235. head: pluginName + "-head",
  2236. ascend: pluginName + "-ascending",
  2237. descend: pluginName + "-descending",
  2238. switcher: pluginName + "-switch",
  2239. tableToolbar: "tablesaw-bar-section",
  2240. sortButton: pluginName + "-btn"
  2241. },
  2242. methods = {
  2243. _create: function(o) {
  2244. return $(this).each(function() {
  2245. var init = $(this).data(pluginName + "-init");
  2246. if (init) {
  2247. return false;
  2248. }
  2249. $(this)
  2250. .data(pluginName + "-init", true)
  2251. .trigger("beforecreate." + pluginName)
  2252. [pluginName]("_init", o)
  2253. .trigger("create." + pluginName);
  2254. });
  2255. },
  2256. _init: function() {
  2257. var el = $(this);
  2258. var tblsaw = el.data("tablesaw");
  2259. var heads;
  2260. var $switcher;
  2261. function addClassToHeads(h) {
  2262. $.each(h, function(i, v) {
  2263. $(v).addClass(classes.head);
  2264. });
  2265. }
  2266. function makeHeadsActionable(h, fn) {
  2267. $.each(h, function(i, col) {
  2268. var b = $("<button class='" + classes.sortButton + "'/>");
  2269. b.on("click", { col: col }, fn);
  2270. $(col)
  2271. .wrapInner(b)
  2272. .find("button")
  2273. .append("<span class='tablesaw-sortable-arrow'>");
  2274. });
  2275. }
  2276. function clearOthers(headcells) {
  2277. $.each(headcells, function(i, v) {
  2278. var col = $(v);
  2279. col.removeAttr(attrs.defaultCol);
  2280. col.removeClass(classes.ascend);
  2281. col.removeClass(classes.descend);
  2282. });
  2283. }
  2284. function headsOnAction(e) {
  2285. if ($(e.target).is("a[href]")) {
  2286. return;
  2287. }
  2288. e.stopPropagation();
  2289. var headCell = $(e.target).closest("[" + attrs.sortCol + "]"),
  2290. v = e.data.col,
  2291. newSortValue = heads.index(headCell[0]);
  2292. clearOthers(
  2293. headCell
  2294. .closest("thead")
  2295. .find("th")
  2296. .filter(function() {
  2297. return this !== headCell[0];
  2298. })
  2299. );
  2300. if (headCell.is("." + classes.descend) || !headCell.is("." + classes.ascend)) {
  2301. el[pluginName]("sortBy", v, true);
  2302. newSortValue += "_asc";
  2303. } else {
  2304. el[pluginName]("sortBy", v);
  2305. newSortValue += "_desc";
  2306. }
  2307. if ($switcher) {
  2308. $switcher
  2309. .find("select")
  2310. .val(newSortValue)
  2311. .trigger("refresh");
  2312. }
  2313. e.preventDefault();
  2314. }
  2315. function handleDefault(heads) {
  2316. $.each(heads, function(idx, el) {
  2317. var $el = $(el);
  2318. if ($el.is("[" + attrs.defaultCol + "]")) {
  2319. if (!$el.is("." + classes.descend)) {
  2320. $el.addClass(classes.ascend);
  2321. }
  2322. }
  2323. });
  2324. }
  2325. function addSwitcher(heads) {
  2326. $switcher = $("<div>")
  2327. .addClass(classes.switcher)
  2328. .addClass(classes.tableToolbar);
  2329. var html = ["<label>" + Tablesaw.i18n.sort + ":"];
  2330. // TODO next major version: remove .btn
  2331. html.push('<span class="btn tablesaw-btn"><select>');
  2332. heads.each(function(j) {
  2333. var $t = $(this);
  2334. var isDefaultCol = $t.is("[" + attrs.defaultCol + "]");
  2335. var isDescending = $t.is("." + classes.descend);
  2336. var hasNumericAttribute = $t.is("[" + attrs.numericCol + "]");
  2337. var numericCount = 0;
  2338. // Check only the first four rows to see if the column is numbers.
  2339. var numericCountMax = 5;
  2340. $(this.cells.slice(0, numericCountMax)).each(function() {
  2341. if (!isNaN(parseInt(getSortValue(this), 10))) {
  2342. numericCount++;
  2343. }
  2344. });
  2345. var isNumeric = numericCount === numericCountMax;
  2346. if (!hasNumericAttribute) {
  2347. $t.attr(attrs.numericCol, isNumeric ? "" : "false");
  2348. }
  2349. html.push(
  2350. "<option" +
  2351. (isDefaultCol && !isDescending ? " selected" : "") +
  2352. ' value="' +
  2353. j +
  2354. '_asc">' +
  2355. $t.text() +
  2356. " " +
  2357. (isNumeric ? "&#x2191;" : "(A-Z)") +
  2358. "</option>"
  2359. );
  2360. html.push(
  2361. "<option" +
  2362. (isDefaultCol && isDescending ? " selected" : "") +
  2363. ' value="' +
  2364. j +
  2365. '_desc">' +
  2366. $t.text() +
  2367. " " +
  2368. (isNumeric ? "&#x2193;" : "(Z-A)") +
  2369. "</option>"
  2370. );
  2371. });
  2372. html.push("</select></span></label>");
  2373. $switcher.html(html.join(""));
  2374. var $firstChild = tblsaw.$toolbar.children().eq(0);
  2375. if ($firstChild.length) {
  2376. $switcher.insertBefore($firstChild);
  2377. } else {
  2378. $switcher.appendTo(tblsaw.$toolbar);
  2379. }
  2380. $switcher.find(".tablesaw-btn").tablesawbtn();
  2381. $switcher.find("select").on("change", function() {
  2382. var val = $(this)
  2383. .val()
  2384. .split("_"),
  2385. head = heads.eq(val[0]);
  2386. clearOthers(head.siblings());
  2387. el[pluginName]("sortBy", head.get(0), val[1] === "asc");
  2388. });
  2389. }
  2390. el.addClass(pluginName);
  2391. heads = el
  2392. .children()
  2393. .filter("thead")
  2394. .find("th[" + attrs.sortCol + "]");
  2395. addClassToHeads(heads);
  2396. makeHeadsActionable(heads, headsOnAction);
  2397. handleDefault(heads);
  2398. if (el.is(sortableSwitchSelector)) {
  2399. addSwitcher(heads);
  2400. }
  2401. },
  2402. sortRows: function(rows, colNum, ascending, col, tbody) {
  2403. function convertCells(cellArr, belongingToTbody) {
  2404. var cells = [];
  2405. $.each(cellArr, function(i, cell) {
  2406. var row = cell.parentNode;
  2407. var $row = $(row);
  2408. // next row is a subrow
  2409. var subrows = [];
  2410. var $next = $row.next();
  2411. while ($next.is("[" + attrs.subRow + "]")) {
  2412. subrows.push($next[0]);
  2413. $next = $next.next();
  2414. }
  2415. var tbody = row.parentNode;
  2416. // current row is a subrow
  2417. if ($row.is("[" + attrs.subRow + "]")) {
  2418. } else if (tbody === belongingToTbody) {
  2419. cells.push({
  2420. element: cell,
  2421. cell: getSortValue(cell),
  2422. row: row,
  2423. subrows: subrows.length ? subrows : null,
  2424. ignored: $row.is("[" + attrs.ignoreRow + "]")
  2425. });
  2426. }
  2427. });
  2428. return cells;
  2429. }
  2430. function getSortFxn(ascending, forceNumeric) {
  2431. var fn,
  2432. regex = /[^\-\+\d\.]/g;
  2433. if (ascending) {
  2434. fn = function(a, b) {
  2435. if (a.ignored || b.ignored) {
  2436. return 0;
  2437. }
  2438. if (forceNumeric) {
  2439. return (
  2440. parseFloat(a.cell.replace(regex, "")) - parseFloat(b.cell.replace(regex, ""))
  2441. );
  2442. } else {
  2443. return a.cell.toLowerCase() > b.cell.toLowerCase() ? 1 : -1;
  2444. }
  2445. };
  2446. } else {
  2447. fn = function(a, b) {
  2448. if (a.ignored || b.ignored) {
  2449. return 0;
  2450. }
  2451. if (forceNumeric) {
  2452. return (
  2453. parseFloat(b.cell.replace(regex, "")) - parseFloat(a.cell.replace(regex, ""))
  2454. );
  2455. } else {
  2456. return a.cell.toLowerCase() < b.cell.toLowerCase() ? 1 : -1;
  2457. }
  2458. };
  2459. }
  2460. return fn;
  2461. }
  2462. function convertToRows(sorted) {
  2463. var newRows = [],
  2464. i,
  2465. l;
  2466. for (i = 0, l = sorted.length; i < l; i++) {
  2467. newRows.push(sorted[i].row);
  2468. if (sorted[i].subrows) {
  2469. newRows.push(sorted[i].subrows);
  2470. }
  2471. }
  2472. return newRows;
  2473. }
  2474. var fn;
  2475. var sorted;
  2476. var cells = convertCells(col.cells, tbody);
  2477. var customFn = $(col).data("tablesaw-sort");
  2478. fn =
  2479. (customFn && typeof customFn === "function" ? customFn(ascending) : false) ||
  2480. getSortFxn(
  2481. ascending,
  2482. $(col).is("[" + attrs.numericCol + "]") &&
  2483. !$(col).is("[" + attrs.numericCol + '="false"]')
  2484. );
  2485. sorted = cells.sort(fn);
  2486. rows = convertToRows(sorted);
  2487. return rows;
  2488. },
  2489. makeColDefault: function(col, a) {
  2490. var c = $(col);
  2491. c.attr(attrs.defaultCol, "true");
  2492. if (a) {
  2493. c.removeClass(classes.descend);
  2494. c.addClass(classes.ascend);
  2495. } else {
  2496. c.removeClass(classes.ascend);
  2497. c.addClass(classes.descend);
  2498. }
  2499. },
  2500. sortBy: function(col, ascending) {
  2501. var el = $(this);
  2502. var colNum;
  2503. var tbl = el.data("tablesaw");
  2504. tbl.$tbody.each(function() {
  2505. var tbody = this;
  2506. var $tbody = $(this);
  2507. var rows = tbl.getBodyRows(tbody);
  2508. var sortedRows;
  2509. var map = tbl.headerMapping[0];
  2510. var j, k;
  2511. // find the column number that we’re sorting
  2512. for (j = 0, k = map.length; j < k; j++) {
  2513. if (map[j] === col) {
  2514. colNum = j;
  2515. break;
  2516. }
  2517. }
  2518. sortedRows = el[pluginName]("sortRows", rows, colNum, ascending, col, tbody);
  2519. // replace Table rows
  2520. for (j = 0, k = sortedRows.length; j < k; j++) {
  2521. $tbody.append(sortedRows[j]);
  2522. }
  2523. });
  2524. el[pluginName]("makeColDefault", col, ascending);
  2525. el.trigger("tablesaw-sorted");
  2526. }
  2527. };
  2528. // Collection method.
  2529. $.fn[pluginName] = function(arrg) {
  2530. var args = Array.prototype.slice.call(arguments, 1),
  2531. returnVal;
  2532. // if it's a method
  2533. if (arrg && typeof arrg === "string") {
  2534. returnVal = $.fn[pluginName].prototype[arrg].apply(this[0], args);
  2535. return typeof returnVal !== "undefined" ? returnVal : $(this);
  2536. }
  2537. // check init
  2538. if (!$(this).data(pluginName + "-active")) {
  2539. $(this).data(pluginName + "-active", true);
  2540. $.fn[pluginName].prototype._create.call(this, arrg);
  2541. }
  2542. return $(this);
  2543. };
  2544. // add methods
  2545. $.extend($.fn[pluginName].prototype, methods);
  2546. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  2547. if (Tablesaw.$table.is(initSelector)) {
  2548. Tablesaw.$table[pluginName]();
  2549. }
  2550. });
  2551. // TODO OOP this and add to Tablesaw object
  2552. })();
  2553. (function() {
  2554. var classes = {
  2555. hideBtn: "disabled",
  2556. persistWidths: "tablesaw-fix-persist",
  2557. hiddenCol: "tablesaw-swipe-cellhidden",
  2558. persistCol: "tablesaw-swipe-cellpersist",
  2559. allColumnsVisible: "tablesaw-all-cols-visible"
  2560. };
  2561. var attrs = {
  2562. disableTouchEvents: "data-tablesaw-no-touch",
  2563. ignorerow: "data-tablesaw-ignorerow",
  2564. subrow: "data-tablesaw-subrow"
  2565. };
  2566. function createSwipeTable(tbl, $table) {
  2567. var tblsaw = $table.data("tablesaw");
  2568. var $btns = $("<div class='tablesaw-advance'></div>");
  2569. // TODO next major version: remove .btn
  2570. var $prevBtn = $(
  2571. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro left'>" +
  2572. Tablesaw.i18n.swipePreviousColumn +
  2573. "</a>"
  2574. ).appendTo($btns);
  2575. // TODO next major version: remove .btn
  2576. var $nextBtn = $(
  2577. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro right'>" +
  2578. Tablesaw.i18n.swipeNextColumn +
  2579. "</a>"
  2580. ).appendTo($btns);
  2581. var $headerCells = tbl._getPrimaryHeaderCells();
  2582. var $headerCellsNoPersist = $headerCells.not('[data-tablesaw-priority="persist"]');
  2583. var headerWidths = [];
  2584. var $head = $(document.head || "head");
  2585. var tableId = $table.attr("id");
  2586. if (!$headerCells.length) {
  2587. throw new Error("tablesaw swipe: no header cells found.");
  2588. }
  2589. $table.addClass("tablesaw-swipe");
  2590. function initMinHeaderWidths() {
  2591. $table.css({
  2592. width: "1px"
  2593. });
  2594. // remove any hidden columns
  2595. $table.find("." + classes.hiddenCol).removeClass(classes.hiddenCol);
  2596. headerWidths = [];
  2597. // Calculate initial widths
  2598. $headerCells.each(function() {
  2599. headerWidths.push(this.offsetWidth);
  2600. });
  2601. // reset props
  2602. $table.css({
  2603. width: ""
  2604. });
  2605. }
  2606. initMinHeaderWidths();
  2607. $btns.appendTo(tblsaw.$toolbar);
  2608. if (!tableId) {
  2609. tableId = "tableswipe-" + Math.round(Math.random() * 10000);
  2610. $table.attr("id", tableId);
  2611. }
  2612. function showColumn(headerCell) {
  2613. tblsaw._$getCells(headerCell).removeClass(classes.hiddenCol);
  2614. }
  2615. function hideColumn(headerCell) {
  2616. tblsaw._$getCells(headerCell).addClass(classes.hiddenCol);
  2617. }
  2618. function persistColumn(headerCell) {
  2619. tblsaw._$getCells(headerCell).addClass(classes.persistCol);
  2620. }
  2621. function isPersistent(headerCell) {
  2622. return $(headerCell).is('[data-tablesaw-priority="persist"]');
  2623. }
  2624. function unmaintainWidths() {
  2625. $table.removeClass(classes.persistWidths);
  2626. $("#" + tableId + "-persist").remove();
  2627. }
  2628. function maintainWidths() {
  2629. var prefix = "#" + tableId + ".tablesaw-swipe ",
  2630. styles = [],
  2631. tableWidth = $table.width(),
  2632. hash = [],
  2633. newHash;
  2634. // save persistent column widths (as long as they take up less than 75% of table width)
  2635. $headerCells.each(function(index) {
  2636. var width;
  2637. if (isPersistent(this)) {
  2638. width = this.offsetWidth;
  2639. if (width < tableWidth * 0.75) {
  2640. hash.push(index + "-" + width);
  2641. styles.push(
  2642. prefix +
  2643. " ." +
  2644. classes.persistCol +
  2645. ":nth-child(" +
  2646. (index + 1) +
  2647. ") { width: " +
  2648. width +
  2649. "px; }"
  2650. );
  2651. }
  2652. }
  2653. });
  2654. newHash = hash.join("_");
  2655. if (styles.length) {
  2656. $table.addClass(classes.persistWidths);
  2657. var $style = $("#" + tableId + "-persist");
  2658. // If style element not yet added OR if the widths have changed
  2659. if (!$style.length || $style.data("tablesaw-hash") !== newHash) {
  2660. // Remove existing
  2661. $style.remove();
  2662. $("<style>" + styles.join("\n") + "</style>")
  2663. .attr("id", tableId + "-persist")
  2664. .data("tablesaw-hash", newHash)
  2665. .appendTo($head);
  2666. }
  2667. }
  2668. }
  2669. function getNext() {
  2670. var next = [],
  2671. checkFound;
  2672. $headerCellsNoPersist.each(function(i) {
  2673. var $t = $(this),
  2674. isHidden = $t.css("display") === "none" || $t.is("." + classes.hiddenCol);
  2675. if (!isHidden && !checkFound) {
  2676. checkFound = true;
  2677. next[0] = i;
  2678. } else if (isHidden && checkFound) {
  2679. next[1] = i;
  2680. return false;
  2681. }
  2682. });
  2683. return next;
  2684. }
  2685. function getPrev() {
  2686. var next = getNext();
  2687. return [next[1] - 1, next[0] - 1];
  2688. }
  2689. function nextpair(fwd) {
  2690. return fwd ? getNext() : getPrev();
  2691. }
  2692. function canAdvance(pair) {
  2693. return pair[1] > -1 && pair[1] < $headerCellsNoPersist.length;
  2694. }
  2695. function matchesMedia() {
  2696. var matchMedia = $table.attr("data-tablesaw-swipe-media");
  2697. return !matchMedia || ("matchMedia" in window && window.matchMedia(matchMedia).matches);
  2698. }
  2699. function fakeBreakpoints() {
  2700. if (!matchesMedia()) {
  2701. return;
  2702. }
  2703. var containerWidth = $table.parent().width(),
  2704. persist = [],
  2705. sum = 0,
  2706. sums = [],
  2707. visibleNonPersistantCount = $headerCells.length;
  2708. $headerCells.each(function(index) {
  2709. var $t = $(this),
  2710. isPersist = $t.is('[data-tablesaw-priority="persist"]');
  2711. persist.push(isPersist);
  2712. sum += headerWidths[index];
  2713. sums.push(sum);
  2714. // is persistent or is hidden
  2715. if (isPersist || sum > containerWidth) {
  2716. visibleNonPersistantCount--;
  2717. }
  2718. });
  2719. // We need at least one column to swipe.
  2720. var needsNonPersistentColumn = visibleNonPersistantCount === 0;
  2721. $headerCells.each(function(index) {
  2722. if (sums[index] > containerWidth) {
  2723. hideColumn(this);
  2724. }
  2725. });
  2726. $headerCells.each(function(index) {
  2727. if (persist[index]) {
  2728. // for visual box-shadow
  2729. persistColumn(this);
  2730. return;
  2731. }
  2732. if (sums[index] <= containerWidth || needsNonPersistentColumn) {
  2733. needsNonPersistentColumn = false;
  2734. showColumn(this);
  2735. tblsaw.updateColspanCells(classes.hiddenCol, this, true);
  2736. }
  2737. });
  2738. unmaintainWidths();
  2739. $table.trigger("tablesawcolumns");
  2740. }
  2741. function advance(fwd) {
  2742. var pair = nextpair(fwd);
  2743. if (canAdvance(pair)) {
  2744. if (isNaN(pair[0])) {
  2745. if (fwd) {
  2746. pair[0] = 0;
  2747. } else {
  2748. pair[0] = $headerCellsNoPersist.length - 1;
  2749. }
  2750. }
  2751. // TODO just blindly hiding the previous column and showing the next column can result in
  2752. // column content overflow
  2753. maintainWidths();
  2754. hideColumn($headerCellsNoPersist.get(pair[0]));
  2755. tblsaw.updateColspanCells(classes.hiddenCol, $headerCellsNoPersist.get(pair[0]), false);
  2756. showColumn($headerCellsNoPersist.get(pair[1]));
  2757. tblsaw.updateColspanCells(classes.hiddenCol, $headerCellsNoPersist.get(pair[1]), true);
  2758. $table.trigger("tablesawcolumns");
  2759. }
  2760. }
  2761. $prevBtn.add($nextBtn).on("click", function(e) {
  2762. advance(!!$(e.target).closest($nextBtn).length);
  2763. e.preventDefault();
  2764. });
  2765. function getCoord(event, key) {
  2766. return (event.touches || event.originalEvent.touches)[0][key];
  2767. }
  2768. if (!$table.is("[" + attrs.disableTouchEvents + "]")) {
  2769. $table.on("touchstart.swipetoggle", function(e) {
  2770. var originX = getCoord(e, "pageX");
  2771. var originY = getCoord(e, "pageY");
  2772. var x;
  2773. var y;
  2774. var scrollTop = window.pageYOffset;
  2775. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  2776. $(this)
  2777. .on("touchmove.swipetoggle", function(e) {
  2778. x = getCoord(e, "pageX");
  2779. y = getCoord(e, "pageY");
  2780. })
  2781. .on("touchend.swipetoggle", function() {
  2782. var cfg = tbl.getConfig({
  2783. swipeHorizontalThreshold: 30,
  2784. swipeVerticalThreshold: 30
  2785. });
  2786. // This config code is a little awkward because shoestring doesn’t support deep $.extend
  2787. // Trying to work around when devs only override one of (not both) horizontalThreshold or
  2788. // verticalThreshold in their TablesawConfig.
  2789. // @TODO major version bump: remove cfg.swipe, move to just use the swipePrefix keys
  2790. var verticalThreshold = cfg.swipe
  2791. ? cfg.swipe.verticalThreshold
  2792. : cfg.swipeVerticalThreshold;
  2793. var horizontalThreshold = cfg.swipe
  2794. ? cfg.swipe.horizontalThreshold
  2795. : cfg.swipeHorizontalThreshold;
  2796. var isPageScrolled = Math.abs(window.pageYOffset - scrollTop) >= verticalThreshold;
  2797. var isVerticalSwipe = Math.abs(y - originY) >= verticalThreshold;
  2798. if (!isVerticalSwipe && !isPageScrolled) {
  2799. if (x - originX < -1 * horizontalThreshold) {
  2800. advance(true);
  2801. }
  2802. if (x - originX > horizontalThreshold) {
  2803. advance(false);
  2804. }
  2805. }
  2806. window.setTimeout(function() {
  2807. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  2808. }, 300);
  2809. $(this).off("touchmove.swipetoggle touchend.swipetoggle");
  2810. });
  2811. });
  2812. }
  2813. $table
  2814. .on("tablesawcolumns.swipetoggle", function() {
  2815. var canGoPrev = canAdvance(getPrev());
  2816. var canGoNext = canAdvance(getNext());
  2817. $prevBtn[canGoPrev ? "removeClass" : "addClass"](classes.hideBtn);
  2818. $nextBtn[canGoNext ? "removeClass" : "addClass"](classes.hideBtn);
  2819. tblsaw.$toolbar[!canGoPrev && !canGoNext ? "addClass" : "removeClass"](
  2820. classes.allColumnsVisible
  2821. );
  2822. })
  2823. .on("tablesawnext.swipetoggle", function() {
  2824. advance(true);
  2825. })
  2826. .on("tablesawprev.swipetoggle", function() {
  2827. advance(false);
  2828. })
  2829. .on(Tablesaw.events.destroy + ".swipetoggle", function() {
  2830. var $t = $(this);
  2831. $t.removeClass("tablesaw-swipe");
  2832. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  2833. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  2834. $t.off(".swipetoggle");
  2835. })
  2836. .on(Tablesaw.events.refresh, function() {
  2837. unmaintainWidths();
  2838. initMinHeaderWidths();
  2839. fakeBreakpoints();
  2840. });
  2841. fakeBreakpoints();
  2842. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  2843. }
  2844. // on tablecreate, init
  2845. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2846. if (tablesaw.mode === "swipe") {
  2847. createSwipeTable(tablesaw, tablesaw.$table);
  2848. }
  2849. });
  2850. // TODO OOP this and add to Tablesaw object
  2851. })();
  2852. (function() {
  2853. var MiniMap = {
  2854. attr: {
  2855. init: "data-tablesaw-minimap"
  2856. },
  2857. show: function(table) {
  2858. var mq = table.getAttribute(MiniMap.attr.init);
  2859. if (mq === "") {
  2860. // value-less but exists
  2861. return true;
  2862. } else if (mq && "matchMedia" in window) {
  2863. // has a mq value
  2864. return window.matchMedia(mq).matches;
  2865. }
  2866. return false;
  2867. }
  2868. };
  2869. function createMiniMap($table) {
  2870. var tblsaw = $table.data("tablesaw");
  2871. var $btns = $('<div class="tablesaw-advance minimap">');
  2872. var $dotNav = $('<ul class="tablesaw-advance-dots">').appendTo($btns);
  2873. var hideDot = "tablesaw-advance-dots-hide";
  2874. var $headerCells = $table.data("tablesaw")._getPrimaryHeaderCells();
  2875. // populate dots
  2876. $headerCells.each(function() {
  2877. $dotNav.append("<li><i></i></li>");
  2878. });
  2879. $btns.appendTo(tblsaw.$toolbar);
  2880. function showHideNav() {
  2881. if (!MiniMap.show($table[0])) {
  2882. $btns.css("display", "none");
  2883. return;
  2884. }
  2885. $btns.css("display", "block");
  2886. // show/hide dots
  2887. var dots = $dotNav.find("li").removeClass(hideDot);
  2888. $table.find("thead th").each(function(i) {
  2889. if ($(this).css("display") === "none") {
  2890. dots.eq(i).addClass(hideDot);
  2891. }
  2892. });
  2893. }
  2894. // run on init and resize
  2895. showHideNav();
  2896. $(window).on(Tablesaw.events.resize, showHideNav);
  2897. $table
  2898. .on("tablesawcolumns.minimap", function() {
  2899. showHideNav();
  2900. })
  2901. .on(Tablesaw.events.destroy + ".minimap", function() {
  2902. var $t = $(this);
  2903. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  2904. $(window).off(Tablesaw.events.resize, showHideNav);
  2905. $t.off(".minimap");
  2906. });
  2907. }
  2908. // on tablecreate, init
  2909. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2910. if (
  2911. (tablesaw.mode === "swipe" || tablesaw.mode === "columntoggle") &&
  2912. tablesaw.$table.is("[ " + MiniMap.attr.init + "]")
  2913. ) {
  2914. createMiniMap(tablesaw.$table);
  2915. }
  2916. });
  2917. // TODO OOP this better
  2918. Tablesaw.MiniMap = MiniMap;
  2919. })();
  2920. (function() {
  2921. var S = {
  2922. selectors: {
  2923. init: "table[data-tablesaw-mode-switch]"
  2924. },
  2925. attributes: {
  2926. excludeMode: "data-tablesaw-mode-exclude"
  2927. },
  2928. classes: {
  2929. main: "tablesaw-modeswitch",
  2930. toolbar: "tablesaw-bar-section"
  2931. },
  2932. modes: ["stack", "swipe", "columntoggle"],
  2933. init: function(table) {
  2934. var $table = $(table);
  2935. var tblsaw = $table.data("tablesaw");
  2936. var ignoreMode = $table.attr(S.attributes.excludeMode);
  2937. var $toolbar = tblsaw.$toolbar;
  2938. var $switcher = $("<div>").addClass(S.classes.main + " " + S.classes.toolbar);
  2939. var html = [
  2940. '<label><span class="abbreviated">' +
  2941. Tablesaw.i18n.modeSwitchColumnsAbbreviated +
  2942. '</span><span class="longform">' +
  2943. Tablesaw.i18n.modeSwitchColumns +
  2944. "</span>:"
  2945. ],
  2946. dataMode = $table.attr("data-tablesaw-mode"),
  2947. isSelected;
  2948. // TODO next major version: remove .btn
  2949. html.push('<span class="btn tablesaw-btn"><select>');
  2950. for (var j = 0, k = S.modes.length; j < k; j++) {
  2951. if (ignoreMode && ignoreMode.toLowerCase() === S.modes[j]) {
  2952. continue;
  2953. }
  2954. isSelected = dataMode === S.modes[j];
  2955. html.push(
  2956. "<option" +
  2957. (isSelected ? " selected" : "") +
  2958. ' value="' +
  2959. S.modes[j] +
  2960. '">' +
  2961. Tablesaw.i18n.modes[j] +
  2962. "</option>"
  2963. );
  2964. }
  2965. html.push("</select></span></label>");
  2966. $switcher.html(html.join(""));
  2967. var $otherToolbarItems = $toolbar.find(".tablesaw-advance").eq(0);
  2968. if ($otherToolbarItems.length) {
  2969. $switcher.insertBefore($otherToolbarItems);
  2970. } else {
  2971. $switcher.appendTo($toolbar);
  2972. }
  2973. $switcher.find(".tablesaw-btn").tablesawbtn();
  2974. $switcher.find("select").on("change", function(event) {
  2975. return S.onModeChange.call(table, event, $(this).val());
  2976. });
  2977. },
  2978. onModeChange: function(event, val) {
  2979. var $table = $(this);
  2980. var tblsaw = $table.data("tablesaw");
  2981. var $switcher = tblsaw.$toolbar.find("." + S.classes.main);
  2982. $switcher.remove();
  2983. tblsaw.destroy();
  2984. $table.attr("data-tablesaw-mode", val);
  2985. $table.tablesaw();
  2986. }
  2987. };
  2988. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  2989. if (Tablesaw.$table.is(S.selectors.init)) {
  2990. S.init(Tablesaw.table);
  2991. }
  2992. });
  2993. // TODO OOP this and add to Tablesaw object
  2994. })();
  2995. (function() {
  2996. var pluginName = "tablesawCheckAll";
  2997. function CheckAll(tablesaw) {
  2998. this.tablesaw = tablesaw;
  2999. this.$table = tablesaw.$table;
  3000. this.attr = "data-tablesaw-checkall";
  3001. this.checkAllSelector = "[" + this.attr + "]";
  3002. this.forceCheckedSelector = "[" + this.attr + "-checked]";
  3003. this.forceUncheckedSelector = "[" + this.attr + "-unchecked]";
  3004. this.checkboxSelector = 'input[type="checkbox"]';
  3005. this.$triggers = null;
  3006. this.$checkboxes = null;
  3007. if (this.$table.data(pluginName)) {
  3008. return;
  3009. }
  3010. this.$table.data(pluginName, this);
  3011. this.init();
  3012. }
  3013. CheckAll.prototype._filterCells = function($checkboxes) {
  3014. return $checkboxes
  3015. .filter(function() {
  3016. return !$(this)
  3017. .closest("tr")
  3018. .is("[data-tablesaw-subrow],[data-tablesaw-ignorerow]");
  3019. })
  3020. .find(this.checkboxSelector)
  3021. .not(this.checkAllSelector);
  3022. };
  3023. // With buttons you can use a scoping selector like: data-tablesaw-checkall="#my-scoped-id input[type='checkbox']"
  3024. CheckAll.prototype.getCheckboxesForButton = function(button) {
  3025. return this._filterCells($($(button).attr(this.attr)));
  3026. };
  3027. CheckAll.prototype.getCheckboxesForCheckbox = function(checkbox) {
  3028. return this._filterCells($($(checkbox).closest("th")[0].cells));
  3029. };
  3030. CheckAll.prototype.init = function() {
  3031. var self = this;
  3032. this.$table.find(this.checkAllSelector).each(function() {
  3033. var $trigger = $(this);
  3034. if ($trigger.is(self.checkboxSelector)) {
  3035. self.addCheckboxEvents(this);
  3036. } else {
  3037. self.addButtonEvents(this);
  3038. }
  3039. });
  3040. };
  3041. CheckAll.prototype.addButtonEvents = function(trigger) {
  3042. var self = this;
  3043. // Update body checkboxes when header checkbox is changed
  3044. $(trigger).on("click", function(event) {
  3045. event.preventDefault();
  3046. var $checkboxes = self.getCheckboxesForButton(this);
  3047. var allChecked = true;
  3048. $checkboxes.each(function() {
  3049. if (!this.checked) {
  3050. allChecked = false;
  3051. }
  3052. });
  3053. var setChecked;
  3054. if ($(this).is(self.forceCheckedSelector)) {
  3055. setChecked = true;
  3056. } else if ($(this).is(self.forceUncheckedSelector)) {
  3057. setChecked = false;
  3058. } else {
  3059. setChecked = allChecked ? false : true;
  3060. }
  3061. $checkboxes.each(function() {
  3062. this.checked = setChecked;
  3063. $(this).trigger("change." + pluginName);
  3064. });
  3065. });
  3066. };
  3067. CheckAll.prototype.addCheckboxEvents = function(trigger) {
  3068. var self = this;
  3069. // Update body checkboxes when header checkbox is changed
  3070. $(trigger).on("change", function() {
  3071. var setChecked = this.checked;
  3072. self.getCheckboxesForCheckbox(this).each(function() {
  3073. this.checked = setChecked;
  3074. });
  3075. });
  3076. var $checkboxes = self.getCheckboxesForCheckbox(trigger);
  3077. // Update header checkbox when body checkboxes are changed
  3078. $checkboxes.on("change." + pluginName, function() {
  3079. var checkedCount = 0;
  3080. $checkboxes.each(function() {
  3081. if (this.checked) {
  3082. checkedCount++;
  3083. }
  3084. });
  3085. var allSelected = checkedCount === $checkboxes.length;
  3086. trigger.checked = allSelected;
  3087. // only indeterminate if some are selected (not all and not none)
  3088. trigger.indeterminate = checkedCount !== 0 && !allSelected;
  3089. });
  3090. };
  3091. // on tablecreate, init
  3092. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  3093. new CheckAll(tablesaw);
  3094. });
  3095. Tablesaw.CheckAll = CheckAll;
  3096. })();
  3097. return Tablesaw;
  3098. }));