tablesaw.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857
  1. /*! Tablesaw - v3.1.2 - 2019-03-19
  2. * https://github.com/filamentgroup/tablesaw
  3. * Copyright (c) 2019 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. // Account for Tablesaw being loaded either before or after the DOMContentLoaded event is fired.
  1378. var domContentLoadedTriggered = /complete|loaded/.test(document.readyState);
  1379. document.addEventListener("DOMContentLoaded", function() {
  1380. domContentLoadedTriggered = true;
  1381. });
  1382. var Tablesaw = {
  1383. i18n: {
  1384. modeStack: "Stack",
  1385. modeSwipe: "Swipe",
  1386. modeToggle: "Toggle",
  1387. modeSwitchColumnsAbbreviated: "Cols",
  1388. modeSwitchColumns: "Columns",
  1389. columnToggleButton: "Columns",
  1390. columnToggleError: "No eligible columns.",
  1391. sort: "Sort",
  1392. swipePreviousColumn: "Previous column",
  1393. swipeNextColumn: "Next column"
  1394. },
  1395. // cut the mustard
  1396. mustard:
  1397. "head" in document && // IE9+, Firefox 4+, Safari 5.1+, Mobile Safari 4.1+, Opera 11.5+, Android 2.3+
  1398. (!window.blackberry || window.WebKitPoint) && // only WebKit Blackberry (OS 6+)
  1399. !window.operamini,
  1400. $: $,
  1401. _init: function(element) {
  1402. Tablesaw.$(element || document).trigger("enhance.tablesaw");
  1403. },
  1404. init: function(element) {
  1405. // Account for Tablesaw being loaded either before or after the DOMContentLoaded event is fired.
  1406. domContentLoadedTriggered =
  1407. domContentLoadedTriggered || /complete|loaded/.test(document.readyState);
  1408. if (!domContentLoadedTriggered) {
  1409. if ("addEventListener" in document) {
  1410. // Use raw DOMContentLoaded instead of shoestring (may have issues in Android 2.3, exhibited by stack table)
  1411. document.addEventListener("DOMContentLoaded", function() {
  1412. Tablesaw._init(element);
  1413. });
  1414. }
  1415. } else {
  1416. Tablesaw._init(element);
  1417. }
  1418. }
  1419. };
  1420. $(document).on("enhance.tablesaw", function() {
  1421. // Extend i18n config, if one exists.
  1422. if (typeof TablesawConfig !== "undefined" && TablesawConfig.i18n) {
  1423. Tablesaw.i18n = $.extend(Tablesaw.i18n, TablesawConfig.i18n || {});
  1424. }
  1425. Tablesaw.i18n.modes = [
  1426. Tablesaw.i18n.modeStack,
  1427. Tablesaw.i18n.modeSwipe,
  1428. Tablesaw.i18n.modeToggle
  1429. ];
  1430. });
  1431. if (Tablesaw.mustard) {
  1432. $(document.documentElement).addClass("tablesaw-enhanced");
  1433. }
  1434. (function() {
  1435. var pluginName = "tablesaw";
  1436. var classes = {
  1437. toolbar: "tablesaw-bar"
  1438. };
  1439. var events = {
  1440. create: "tablesawcreate",
  1441. destroy: "tablesawdestroy",
  1442. refresh: "tablesawrefresh",
  1443. resize: "tablesawresize"
  1444. };
  1445. var defaultMode = "stack";
  1446. var initSelector = "table";
  1447. var initFilterSelector = "[data-tablesaw],[data-tablesaw-mode],[data-tablesaw-sortable]";
  1448. var defaultConfig = {};
  1449. Tablesaw.events = events;
  1450. var Table = function(element) {
  1451. if (!element) {
  1452. throw new Error("Tablesaw requires an element.");
  1453. }
  1454. this.table = element;
  1455. this.$table = $(element);
  1456. // only one <thead> and <tfoot> are allowed, per the specification
  1457. this.$thead = this.$table
  1458. .children()
  1459. .filter("thead")
  1460. .eq(0);
  1461. // multiple <tbody> are allowed, per the specification
  1462. this.$tbody = this.$table.children().filter("tbody");
  1463. this.mode = this.$table.attr("data-tablesaw-mode") || defaultMode;
  1464. this.$toolbar = null;
  1465. this.attributes = {
  1466. subrow: "data-tablesaw-subrow",
  1467. ignorerow: "data-tablesaw-ignorerow"
  1468. };
  1469. this.init();
  1470. };
  1471. Table.prototype.init = function() {
  1472. if (!this.$thead.length) {
  1473. throw new Error("tablesaw: a <thead> is required, but none was found.");
  1474. }
  1475. if (!this.$thead.find("th").length) {
  1476. throw new Error("tablesaw: no header cells found. Are you using <th> inside of <thead>?");
  1477. }
  1478. // assign an id if there is none
  1479. if (!this.$table.attr("id")) {
  1480. this.$table.attr("id", pluginName + "-" + Math.round(Math.random() * 10000));
  1481. }
  1482. this.createToolbar();
  1483. this._initCells();
  1484. this.$table.data(pluginName, this);
  1485. this.$table.trigger(events.create, [this]);
  1486. };
  1487. Table.prototype.getConfig = function(pluginSpecificConfig) {
  1488. // shoestring extend doesn’t support arbitrary args
  1489. var configs = $.extend(defaultConfig, pluginSpecificConfig || {});
  1490. return $.extend(configs, typeof TablesawConfig !== "undefined" ? TablesawConfig : {});
  1491. };
  1492. Table.prototype._getPrimaryHeaderRow = function() {
  1493. return this._getHeaderRows().eq(0);
  1494. };
  1495. Table.prototype._getHeaderRows = function() {
  1496. return this.$thead
  1497. .children()
  1498. .filter("tr")
  1499. .filter(function() {
  1500. return !$(this).is("[data-tablesaw-ignorerow]");
  1501. });
  1502. };
  1503. Table.prototype._getRowIndex = function($row) {
  1504. return $row.prevAll().length;
  1505. };
  1506. Table.prototype._getHeaderRowIndeces = function() {
  1507. var self = this;
  1508. var indeces = [];
  1509. this._getHeaderRows().each(function() {
  1510. indeces.push(self._getRowIndex($(this)));
  1511. });
  1512. return indeces;
  1513. };
  1514. Table.prototype._getPrimaryHeaderCells = function($row) {
  1515. return ($row || this._getPrimaryHeaderRow()).find("th");
  1516. };
  1517. Table.prototype._$getCells = function(th) {
  1518. var self = this;
  1519. return $(th)
  1520. .add(th.cells)
  1521. .filter(function() {
  1522. var $t = $(this);
  1523. var $row = $t.parent();
  1524. var hasColspan = $t.is("[colspan]");
  1525. // no subrows or ignored rows (keep cells in ignored rows that do not have a colspan)
  1526. return (
  1527. !$row.is("[" + self.attributes.subrow + "]") &&
  1528. (!$row.is("[" + self.attributes.ignorerow + "]") || !hasColspan)
  1529. );
  1530. });
  1531. };
  1532. Table.prototype._getVisibleColspan = function() {
  1533. var colspan = 0;
  1534. this._getPrimaryHeaderCells().each(function() {
  1535. var $t = $(this);
  1536. if ($t.css("display") !== "none") {
  1537. colspan += parseInt($t.attr("colspan"), 10) || 1;
  1538. }
  1539. });
  1540. return colspan;
  1541. };
  1542. Table.prototype.getColspanForCell = function($cell) {
  1543. var visibleColspan = this._getVisibleColspan();
  1544. var visibleSiblingColumns = 0;
  1545. if ($cell.closest("tr").data("tablesaw-rowspanned")) {
  1546. visibleSiblingColumns++;
  1547. }
  1548. $cell.siblings().each(function() {
  1549. var $t = $(this);
  1550. var colColspan = parseInt($t.attr("colspan"), 10) || 1;
  1551. if ($t.css("display") !== "none") {
  1552. visibleSiblingColumns += colColspan;
  1553. }
  1554. });
  1555. // console.log( $cell[ 0 ], visibleColspan, visibleSiblingColumns );
  1556. return visibleColspan - visibleSiblingColumns;
  1557. };
  1558. Table.prototype.isCellInColumn = function(header, cell) {
  1559. return $(header)
  1560. .add(header.cells)
  1561. .filter(function() {
  1562. return this === cell;
  1563. }).length;
  1564. };
  1565. Table.prototype.updateColspanCells = function(cls, header, userAction) {
  1566. var self = this;
  1567. var primaryHeaderRow = self._getPrimaryHeaderRow();
  1568. // find persistent column rowspans
  1569. this.$table.find("[rowspan][data-tablesaw-priority]").each(function() {
  1570. var $t = $(this);
  1571. if ($t.attr("data-tablesaw-priority") !== "persist") {
  1572. return;
  1573. }
  1574. var $row = $t.closest("tr");
  1575. var rowspan = parseInt($t.attr("rowspan"), 10);
  1576. if (rowspan > 1) {
  1577. $row = $row.next();
  1578. $row.data("tablesaw-rowspanned", true);
  1579. rowspan--;
  1580. }
  1581. });
  1582. this.$table
  1583. .find("[colspan],[data-tablesaw-maxcolspan]")
  1584. .filter(function() {
  1585. // is not in primary header row
  1586. return $(this).closest("tr")[0] !== primaryHeaderRow[0];
  1587. })
  1588. .each(function() {
  1589. var $cell = $(this);
  1590. if (userAction === undefined || self.isCellInColumn(header, this)) {
  1591. } else {
  1592. // if is not a user action AND the cell is not in the updating column, kill it
  1593. return;
  1594. }
  1595. var colspan = self.getColspanForCell($cell);
  1596. if (cls && userAction !== undefined) {
  1597. // console.log( colspan === 0 ? "addClass" : "removeClass", $cell );
  1598. $cell[colspan === 0 ? "addClass" : "removeClass"](cls);
  1599. }
  1600. // cache original colspan
  1601. var maxColspan = parseInt($cell.attr("data-tablesaw-maxcolspan"), 10);
  1602. if (!maxColspan) {
  1603. $cell.attr("data-tablesaw-maxcolspan", $cell.attr("colspan"));
  1604. } else if (colspan > maxColspan) {
  1605. colspan = maxColspan;
  1606. }
  1607. // console.log( this, "setting colspan to ", colspan );
  1608. $cell.attr("colspan", colspan);
  1609. });
  1610. };
  1611. Table.prototype._findPrimaryHeadersForCell = function(cell) {
  1612. var $headerRow = this._getPrimaryHeaderRow();
  1613. var headerRowIndex = this._getRowIndex($headerRow);
  1614. var results = [];
  1615. for (var rowNumber = 0; rowNumber < this.headerMapping.length; rowNumber++) {
  1616. if (rowNumber === headerRowIndex) {
  1617. continue;
  1618. }
  1619. for (var colNumber = 0; colNumber < this.headerMapping[rowNumber].length; colNumber++) {
  1620. if (this.headerMapping[rowNumber][colNumber] === cell) {
  1621. results.push(this.headerMapping[headerRowIndex][colNumber]);
  1622. }
  1623. }
  1624. }
  1625. return results;
  1626. };
  1627. // used by init cells
  1628. Table.prototype.getRows = function() {
  1629. var self = this;
  1630. return this.$table.find("tr").filter(function() {
  1631. return $(this)
  1632. .closest("table")
  1633. .is(self.$table);
  1634. });
  1635. };
  1636. // used by sortable
  1637. Table.prototype.getBodyRows = function(tbody) {
  1638. return (tbody ? $(tbody) : this.$tbody).children().filter("tr");
  1639. };
  1640. Table.prototype.getHeaderCellIndex = function(cell) {
  1641. var lookup = this.headerMapping[0];
  1642. for (var colIndex = 0; colIndex < lookup.length; colIndex++) {
  1643. if (lookup[colIndex] === cell) {
  1644. return colIndex;
  1645. }
  1646. }
  1647. return -1;
  1648. };
  1649. Table.prototype._initCells = function() {
  1650. // re-establish original colspans
  1651. this.$table.find("[data-tablesaw-maxcolspan]").each(function() {
  1652. var $t = $(this);
  1653. $t.attr("colspan", $t.attr("data-tablesaw-maxcolspan"));
  1654. });
  1655. var $rows = this.getRows();
  1656. var columnLookup = [];
  1657. $rows.each(function(rowNumber) {
  1658. columnLookup[rowNumber] = [];
  1659. });
  1660. $rows.each(function(rowNumber) {
  1661. var coltally = 0;
  1662. var $t = $(this);
  1663. var children = $t.children();
  1664. children.each(function() {
  1665. var colspan = parseInt(
  1666. this.getAttribute("data-tablesaw-maxcolspan") || this.getAttribute("colspan"),
  1667. 10
  1668. );
  1669. var rowspan = parseInt(this.getAttribute("rowspan"), 10);
  1670. // set in a previous rowspan
  1671. while (columnLookup[rowNumber][coltally]) {
  1672. coltally++;
  1673. }
  1674. columnLookup[rowNumber][coltally] = this;
  1675. // TODO? both colspan and rowspan
  1676. if (colspan) {
  1677. for (var k = 0; k < colspan - 1; k++) {
  1678. coltally++;
  1679. columnLookup[rowNumber][coltally] = this;
  1680. }
  1681. }
  1682. if (rowspan) {
  1683. for (var j = 1; j < rowspan; j++) {
  1684. columnLookup[rowNumber + j][coltally] = this;
  1685. }
  1686. }
  1687. coltally++;
  1688. });
  1689. });
  1690. var headerRowIndeces = this._getHeaderRowIndeces();
  1691. for (var colNumber = 0; colNumber < columnLookup[0].length; colNumber++) {
  1692. for (var headerIndex = 0, k = headerRowIndeces.length; headerIndex < k; headerIndex++) {
  1693. var headerCol = columnLookup[headerRowIndeces[headerIndex]][colNumber];
  1694. var rowNumber = headerRowIndeces[headerIndex];
  1695. var rowCell;
  1696. if (!headerCol.cells) {
  1697. headerCol.cells = [];
  1698. }
  1699. while (rowNumber < columnLookup.length) {
  1700. rowCell = columnLookup[rowNumber][colNumber];
  1701. if (headerCol !== rowCell) {
  1702. headerCol.cells.push(rowCell);
  1703. }
  1704. rowNumber++;
  1705. }
  1706. }
  1707. }
  1708. this.headerMapping = columnLookup;
  1709. };
  1710. Table.prototype.refresh = function() {
  1711. this._initCells();
  1712. this.$table.trigger(events.refresh, [this]);
  1713. };
  1714. Table.prototype._getToolbarAnchor = function() {
  1715. var $parent = this.$table.parent();
  1716. if ($parent.is(".tablesaw-overflow")) {
  1717. return $parent;
  1718. }
  1719. return this.$table;
  1720. };
  1721. Table.prototype._getToolbar = function($anchor) {
  1722. if (!$anchor) {
  1723. $anchor = this._getToolbarAnchor();
  1724. }
  1725. return $anchor.prev().filter("." + classes.toolbar);
  1726. };
  1727. Table.prototype.createToolbar = function() {
  1728. // Insert the toolbar
  1729. // TODO move this into a separate component
  1730. var $anchor = this._getToolbarAnchor();
  1731. var $toolbar = this._getToolbar($anchor);
  1732. if (!$toolbar.length) {
  1733. $toolbar = $("<div>")
  1734. .addClass(classes.toolbar)
  1735. .insertBefore($anchor);
  1736. }
  1737. this.$toolbar = $toolbar;
  1738. if (this.mode) {
  1739. this.$toolbar.addClass("tablesaw-mode-" + this.mode);
  1740. }
  1741. };
  1742. Table.prototype.destroy = function() {
  1743. // Don’t remove the toolbar, just erase the classes on it.
  1744. // Some of the table features are not yet destroy-friendly.
  1745. this._getToolbar().each(function() {
  1746. this.className = this.className.replace(/\btablesaw-mode\-\w*\b/gi, "");
  1747. });
  1748. var tableId = this.$table.attr("id");
  1749. $(document).off("." + tableId);
  1750. $(window).off("." + tableId);
  1751. // other plugins
  1752. this.$table.trigger(events.destroy, [this]);
  1753. this.$table.removeData(pluginName);
  1754. };
  1755. // Collection method.
  1756. $.fn[pluginName] = function() {
  1757. return this.each(function() {
  1758. var $t = $(this);
  1759. if ($t.data(pluginName)) {
  1760. return;
  1761. }
  1762. new Table(this);
  1763. });
  1764. };
  1765. var $doc = $(document);
  1766. $doc.on("enhance.tablesaw", function(e) {
  1767. // Cut the mustard
  1768. if (Tablesaw.mustard) {
  1769. var $target = $(e.target);
  1770. if ($target.parent().length) {
  1771. $target = $target.parent();
  1772. }
  1773. $target
  1774. .find(initSelector)
  1775. .filter(initFilterSelector)
  1776. [pluginName]();
  1777. }
  1778. });
  1779. // Avoid a resize during scroll:
  1780. // Some Mobile devices trigger a resize during scroll (sometimes when
  1781. // doing elastic stretch at the end of the document or from the
  1782. // location bar hide)
  1783. var isScrolling = false;
  1784. var scrollTimeout;
  1785. $doc.on("scroll.tablesaw", function() {
  1786. isScrolling = true;
  1787. window.clearTimeout(scrollTimeout);
  1788. scrollTimeout = window.setTimeout(function() {
  1789. isScrolling = false;
  1790. }, 300); // must be greater than the resize timeout below
  1791. });
  1792. var resizeTimeout;
  1793. $(window).on("resize", function() {
  1794. if (!isScrolling) {
  1795. window.clearTimeout(resizeTimeout);
  1796. resizeTimeout = window.setTimeout(function() {
  1797. $doc.trigger(events.resize);
  1798. }, 150); // must be less than the scrolling timeout above.
  1799. }
  1800. });
  1801. Tablesaw.Table = Table;
  1802. })();
  1803. (function() {
  1804. var classes = {
  1805. stackTable: "tablesaw-stack",
  1806. cellLabels: "tablesaw-cell-label",
  1807. cellContentLabels: "tablesaw-cell-content"
  1808. };
  1809. var data = {
  1810. key: "tablesaw-stack"
  1811. };
  1812. var attrs = {
  1813. labelless: "data-tablesaw-no-labels",
  1814. hideempty: "data-tablesaw-hide-empty"
  1815. };
  1816. var Stack = function(element, tablesaw) {
  1817. this.tablesaw = tablesaw;
  1818. this.$table = $(element);
  1819. this.labelless = this.$table.is("[" + attrs.labelless + "]");
  1820. this.hideempty = this.$table.is("[" + attrs.hideempty + "]");
  1821. this.$table.data(data.key, this);
  1822. };
  1823. Stack.prototype.init = function() {
  1824. this.$table.addClass(classes.stackTable);
  1825. if (this.labelless) {
  1826. return;
  1827. }
  1828. var self = this;
  1829. this.$table
  1830. .find("th, td")
  1831. .filter(function() {
  1832. return !$(this).closest("thead").length;
  1833. })
  1834. .filter(function() {
  1835. return (
  1836. !$(this).is("[" + attrs.labelless + "]") &&
  1837. !$(this)
  1838. .closest("tr")
  1839. .is("[" + attrs.labelless + "]") &&
  1840. (!self.hideempty || !!$(this).html())
  1841. );
  1842. })
  1843. .each(function() {
  1844. var $newHeader = $(document.createElement("b")).addClass(classes.cellLabels);
  1845. var $cell = $(this);
  1846. $(self.tablesaw._findPrimaryHeadersForCell(this)).each(function(index) {
  1847. var $header = $(this.cloneNode(true));
  1848. // TODO decouple from sortable better
  1849. // Changed from .text() in https://github.com/filamentgroup/tablesaw/commit/b9c12a8f893ec192830ec3ba2d75f062642f935b
  1850. // to preserve structural html in headers, like <a>
  1851. var $sortableButton = $header.find(".tablesaw-sortable-btn");
  1852. $header.find(".tablesaw-sortable-arrow").remove();
  1853. // TODO decouple from checkall better
  1854. var $checkall = $header.find("[data-tablesaw-checkall]");
  1855. $checkall.closest("label").remove();
  1856. if ($checkall.length) {
  1857. $newHeader = $([]);
  1858. return;
  1859. }
  1860. if (index > 0) {
  1861. $newHeader.append(document.createTextNode(", "));
  1862. }
  1863. var parentNode = $sortableButton.length ? $sortableButton[0] : $header[0];
  1864. var el;
  1865. while ((el = parentNode.firstChild)) {
  1866. $newHeader[0].appendChild(el);
  1867. }
  1868. });
  1869. if ($newHeader.length && !$cell.find("." + classes.cellContentLabels).length) {
  1870. $cell.wrapInner("<span class='" + classes.cellContentLabels + "'></span>");
  1871. }
  1872. // Update if already exists.
  1873. var $label = $cell.find("." + classes.cellLabels);
  1874. if (!$label.length) {
  1875. $cell.prepend(document.createTextNode(" "));
  1876. $cell.prepend($newHeader);
  1877. } else {
  1878. // only if changed
  1879. $label.replaceWith($newHeader);
  1880. }
  1881. });
  1882. };
  1883. Stack.prototype.destroy = function() {
  1884. this.$table.removeClass(classes.stackTable);
  1885. this.$table.find("." + classes.cellLabels).remove();
  1886. this.$table.find("." + classes.cellContentLabels).each(function() {
  1887. $(this).replaceWith($(this.childNodes));
  1888. });
  1889. };
  1890. // on tablecreate, init
  1891. $(document)
  1892. .on(Tablesaw.events.create, function(e, tablesaw) {
  1893. if (tablesaw.mode === "stack") {
  1894. var table = new Stack(tablesaw.table, tablesaw);
  1895. table.init();
  1896. }
  1897. })
  1898. .on(Tablesaw.events.refresh, function(e, tablesaw) {
  1899. if (tablesaw.mode === "stack") {
  1900. $(tablesaw.table)
  1901. .data(data.key)
  1902. .init();
  1903. }
  1904. })
  1905. .on(Tablesaw.events.destroy, function(e, tablesaw) {
  1906. if (tablesaw.mode === "stack") {
  1907. $(tablesaw.table)
  1908. .data(data.key)
  1909. .destroy();
  1910. }
  1911. });
  1912. Tablesaw.Stack = Stack;
  1913. })();
  1914. (function() {
  1915. var pluginName = "tablesawbtn",
  1916. methods = {
  1917. _create: function() {
  1918. return $(this).each(function() {
  1919. $(this)
  1920. .trigger("beforecreate." + pluginName)
  1921. [pluginName]("_init")
  1922. .trigger("create." + pluginName);
  1923. });
  1924. },
  1925. _init: function() {
  1926. var oEl = $(this),
  1927. sel = this.getElementsByTagName("select")[0];
  1928. if (sel) {
  1929. // TODO next major version: remove .btn-select
  1930. $(this)
  1931. .addClass("btn-select tablesaw-btn-select")
  1932. [pluginName]("_select", sel);
  1933. }
  1934. return oEl;
  1935. },
  1936. _select: function(sel) {
  1937. var update = function(oEl, sel) {
  1938. var opts = $(sel).find("option");
  1939. var label = document.createElement("span");
  1940. var el;
  1941. var children;
  1942. var found = false;
  1943. label.setAttribute("aria-hidden", "true");
  1944. label.innerHTML = "&#160;";
  1945. opts.each(function() {
  1946. var opt = this;
  1947. if (opt.selected) {
  1948. label.innerHTML = opt.text;
  1949. }
  1950. });
  1951. children = oEl.childNodes;
  1952. if (opts.length > 0) {
  1953. for (var i = 0, l = children.length; i < l; i++) {
  1954. el = children[i];
  1955. if (el && el.nodeName.toUpperCase() === "SPAN") {
  1956. oEl.replaceChild(label, el);
  1957. found = true;
  1958. }
  1959. }
  1960. if (!found) {
  1961. oEl.insertBefore(label, oEl.firstChild);
  1962. }
  1963. }
  1964. };
  1965. update(this, sel);
  1966. // todo should this be tablesawrefresh?
  1967. $(this).on("change refresh", function() {
  1968. update(this, sel);
  1969. });
  1970. }
  1971. };
  1972. // Collection method.
  1973. $.fn[pluginName] = function(arrg, a, b, c) {
  1974. return this.each(function() {
  1975. // if it's a method
  1976. if (arrg && typeof arrg === "string") {
  1977. return $.fn[pluginName].prototype[arrg].call(this, a, b, c);
  1978. }
  1979. // don't re-init
  1980. if ($(this).data(pluginName + "active")) {
  1981. return $(this);
  1982. }
  1983. $(this).data(pluginName + "active", true);
  1984. $.fn[pluginName].prototype._create.call(this);
  1985. });
  1986. };
  1987. // add methods
  1988. $.extend($.fn[pluginName].prototype, methods);
  1989. // TODO OOP this and add to Tablesaw object
  1990. })();
  1991. (function() {
  1992. var data = {
  1993. key: "tablesaw-coltoggle"
  1994. };
  1995. var ColumnToggle = function(element) {
  1996. this.$table = $(element);
  1997. if (!this.$table.length) {
  1998. return;
  1999. }
  2000. this.tablesaw = this.$table.data("tablesaw");
  2001. this.attributes = {
  2002. btnTarget: "data-tablesaw-columntoggle-btn-target",
  2003. set: "data-tablesaw-columntoggle-set"
  2004. };
  2005. this.classes = {
  2006. columnToggleTable: "tablesaw-columntoggle",
  2007. columnBtnContain: "tablesaw-columntoggle-btnwrap tablesaw-advance",
  2008. columnBtn: "tablesaw-columntoggle-btn tablesaw-nav-btn down",
  2009. popup: "tablesaw-columntoggle-popup",
  2010. priorityPrefix: "tablesaw-priority-"
  2011. };
  2012. this.set = [];
  2013. this.$headers = this.tablesaw._getPrimaryHeaderCells();
  2014. this.$table.data(data.key, this);
  2015. };
  2016. // Column Toggle Sets (one column chooser can control multiple tables)
  2017. ColumnToggle.prototype.initSet = function() {
  2018. var set = this.$table.attr(this.attributes.set);
  2019. if (set) {
  2020. // Should not include the current table
  2021. var table = this.$table[0];
  2022. this.set = $("table[" + this.attributes.set + "='" + set + "']")
  2023. .filter(function() {
  2024. return this !== table;
  2025. })
  2026. .get();
  2027. }
  2028. };
  2029. ColumnToggle.prototype.init = function() {
  2030. if (!this.$table.length) {
  2031. return;
  2032. }
  2033. var tableId,
  2034. id,
  2035. $menuButton,
  2036. $popup,
  2037. $menu,
  2038. $btnContain,
  2039. self = this;
  2040. var cfg = this.tablesaw.getConfig({
  2041. getColumnToggleLabelTemplate: function(text) {
  2042. return "<label><input type='checkbox' checked>" + text + "</label>";
  2043. }
  2044. });
  2045. this.$table.addClass(this.classes.columnToggleTable);
  2046. tableId = this.$table.attr("id");
  2047. id = tableId + "-popup";
  2048. $btnContain = $("<div class='" + this.classes.columnBtnContain + "'></div>");
  2049. // TODO next major version: remove .btn
  2050. $menuButton = $(
  2051. "<a href='#" +
  2052. id +
  2053. "' class='btn tablesaw-btn btn-micro " +
  2054. this.classes.columnBtn +
  2055. "' data-popup-link>" +
  2056. "<span>" +
  2057. Tablesaw.i18n.columnToggleButton +
  2058. "</span></a>"
  2059. );
  2060. $popup = $("<div class='" + this.classes.popup + "' id='" + id + "'></div>");
  2061. $menu = $("<div class='tablesaw-btn-group'></div>");
  2062. this.$popup = $popup;
  2063. var hasNonPersistentHeaders = false;
  2064. this.$headers.each(function() {
  2065. var $this = $(this),
  2066. priority = $this.attr("data-tablesaw-priority"),
  2067. $cells = self.tablesaw._$getCells(this);
  2068. if (priority && priority !== "persist") {
  2069. $cells.addClass(self.classes.priorityPrefix + priority);
  2070. $(cfg.getColumnToggleLabelTemplate($this.text()))
  2071. .appendTo($menu)
  2072. .find('input[type="checkbox"]')
  2073. .data("tablesaw-header", this);
  2074. hasNonPersistentHeaders = true;
  2075. }
  2076. });
  2077. if (!hasNonPersistentHeaders) {
  2078. $menu.append("<label>" + Tablesaw.i18n.columnToggleError + "</label>");
  2079. }
  2080. $menu.appendTo($popup);
  2081. function onToggleCheckboxChange(checkbox) {
  2082. var checked = checkbox.checked;
  2083. var header = self.getHeaderFromCheckbox(checkbox);
  2084. var $cells = self.tablesaw._$getCells(header);
  2085. $cells[!checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellhidden");
  2086. $cells[checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellvisible");
  2087. self.updateColspanCells(header, checked);
  2088. self.$table.trigger("tablesawcolumns");
  2089. }
  2090. // bind change event listeners to inputs - TODO: move to a private method?
  2091. $menu.find('input[type="checkbox"]').on("change", function(e) {
  2092. onToggleCheckboxChange(e.target);
  2093. if (self.set.length) {
  2094. var index;
  2095. $(self.$popup)
  2096. .find("input[type='checkbox']")
  2097. .each(function(j) {
  2098. if (this === e.target) {
  2099. index = j;
  2100. return false;
  2101. }
  2102. });
  2103. $(self.set).each(function() {
  2104. var checkbox = $(this)
  2105. .data(data.key)
  2106. .$popup.find("input[type='checkbox']")
  2107. .get(index);
  2108. if (checkbox) {
  2109. checkbox.checked = e.target.checked;
  2110. onToggleCheckboxChange(checkbox);
  2111. }
  2112. });
  2113. }
  2114. });
  2115. $menuButton.appendTo($btnContain);
  2116. // Use a different target than the toolbar
  2117. var $btnTarget = $(this.$table.attr(this.attributes.btnTarget));
  2118. $btnContain.appendTo($btnTarget.length ? $btnTarget : this.tablesaw.$toolbar);
  2119. function closePopup(event) {
  2120. // Click came from inside the popup, ignore.
  2121. if (event && $(event.target).closest("." + self.classes.popup).length) {
  2122. return;
  2123. }
  2124. $(document).off("click." + tableId);
  2125. $menuButton.removeClass("up").addClass("down");
  2126. $btnContain.removeClass("visible");
  2127. }
  2128. var closeTimeout;
  2129. function openPopup() {
  2130. $btnContain.addClass("visible");
  2131. $menuButton.removeClass("down").addClass("up");
  2132. $(document).off("click." + tableId, closePopup);
  2133. window.clearTimeout(closeTimeout);
  2134. closeTimeout = window.setTimeout(function() {
  2135. $(document).on("click." + tableId, closePopup);
  2136. }, 15);
  2137. }
  2138. $menuButton.on("click.tablesaw", function(event) {
  2139. event.preventDefault();
  2140. if (!$btnContain.is(".visible")) {
  2141. openPopup();
  2142. } else {
  2143. closePopup();
  2144. }
  2145. });
  2146. $popup.appendTo($btnContain);
  2147. this.$menu = $menu;
  2148. // Fix for iOS not rendering shadows correctly when using `-webkit-overflow-scrolling`
  2149. var $overflow = this.$table.closest(".tablesaw-overflow");
  2150. if ($overflow.css("-webkit-overflow-scrolling")) {
  2151. var timeout;
  2152. $overflow.on("scroll", function() {
  2153. var $div = $(this);
  2154. window.clearTimeout(timeout);
  2155. timeout = window.setTimeout(function() {
  2156. $div.css("-webkit-overflow-scrolling", "auto");
  2157. window.setTimeout(function() {
  2158. $div.css("-webkit-overflow-scrolling", "touch");
  2159. }, 0);
  2160. }, 100);
  2161. });
  2162. }
  2163. $(window).on(Tablesaw.events.resize + "." + tableId, function() {
  2164. self.refreshToggle();
  2165. });
  2166. this.initSet();
  2167. this.refreshToggle();
  2168. };
  2169. ColumnToggle.prototype.getHeaderFromCheckbox = function(checkbox) {
  2170. return $(checkbox).data("tablesaw-header");
  2171. };
  2172. ColumnToggle.prototype.refreshToggle = function() {
  2173. var self = this;
  2174. var invisibleColumns = 0;
  2175. this.$menu.find("input").each(function() {
  2176. var header = self.getHeaderFromCheckbox(this);
  2177. this.checked =
  2178. self.tablesaw
  2179. ._$getCells(header)
  2180. .eq(0)
  2181. .css("display") === "table-cell";
  2182. });
  2183. this.updateColspanCells();
  2184. };
  2185. ColumnToggle.prototype.updateColspanCells = function(header, userAction) {
  2186. this.tablesaw.updateColspanCells("tablesaw-toggle-cellhidden", header, userAction);
  2187. };
  2188. ColumnToggle.prototype.destroy = function() {
  2189. this.$table.removeClass(this.classes.columnToggleTable);
  2190. this.$table.find("th, td").each(function() {
  2191. var $cell = $(this);
  2192. $cell.removeClass("tablesaw-toggle-cellhidden").removeClass("tablesaw-toggle-cellvisible");
  2193. this.className = this.className.replace(/\bui\-table\-priority\-\d\b/g, "");
  2194. });
  2195. };
  2196. // on tablecreate, init
  2197. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2198. if (tablesaw.mode === "columntoggle") {
  2199. var table = new ColumnToggle(tablesaw.table);
  2200. table.init();
  2201. }
  2202. });
  2203. $(document).on(Tablesaw.events.destroy, function(e, tablesaw) {
  2204. if (tablesaw.mode === "columntoggle") {
  2205. $(tablesaw.table)
  2206. .data(data.key)
  2207. .destroy();
  2208. }
  2209. });
  2210. $(document).on(Tablesaw.events.refresh, function(e, tablesaw) {
  2211. if (tablesaw.mode === "columntoggle") {
  2212. $(tablesaw.table)
  2213. .data(data.key)
  2214. .refreshToggle();
  2215. }
  2216. });
  2217. Tablesaw.ColumnToggle = ColumnToggle;
  2218. })();
  2219. (function() {
  2220. function getSortValue(cell) {
  2221. var text = [];
  2222. $(cell.childNodes).each(function() {
  2223. var $el = $(this);
  2224. if ($el.is("input, select")) {
  2225. text.push($el.val());
  2226. } else if ($el.is(".tablesaw-cell-label")) {
  2227. } else {
  2228. text.push(($el.text() || "").replace(/^\s+|\s+$/g, ""));
  2229. }
  2230. });
  2231. return text.join("");
  2232. }
  2233. var pluginName = "tablesaw-sortable",
  2234. initSelector = "table[data-" + pluginName + "]",
  2235. sortableSwitchSelector = "[data-" + pluginName + "-switch]",
  2236. attrs = {
  2237. sortCol: "data-tablesaw-sortable-col",
  2238. defaultCol: "data-tablesaw-sortable-default-col",
  2239. numericCol: "data-tablesaw-sortable-numeric",
  2240. subRow: "data-tablesaw-subrow",
  2241. ignoreRow: "data-tablesaw-ignorerow"
  2242. },
  2243. classes = {
  2244. head: pluginName + "-head",
  2245. ascend: pluginName + "-ascending",
  2246. descend: pluginName + "-descending",
  2247. switcher: pluginName + "-switch",
  2248. tableToolbar: "tablesaw-bar-section",
  2249. sortButton: pluginName + "-btn"
  2250. },
  2251. methods = {
  2252. _create: function(o) {
  2253. return $(this).each(function() {
  2254. var init = $(this).data(pluginName + "-init");
  2255. if (init) {
  2256. return false;
  2257. }
  2258. $(this)
  2259. .data(pluginName + "-init", true)
  2260. .trigger("beforecreate." + pluginName)
  2261. [pluginName]("_init", o)
  2262. .trigger("create." + pluginName);
  2263. });
  2264. },
  2265. _init: function() {
  2266. var el = $(this);
  2267. var tblsaw = el.data("tablesaw");
  2268. var heads;
  2269. var $switcher;
  2270. function addClassToHeads(h) {
  2271. $.each(h, function(i, v) {
  2272. $(v).addClass(classes.head);
  2273. });
  2274. }
  2275. function makeHeadsActionable(h, fn) {
  2276. $.each(h, function(i, col) {
  2277. var b = $("<button class='" + classes.sortButton + "'/>");
  2278. b.on("click", { col: col }, fn);
  2279. $(col)
  2280. .wrapInner(b)
  2281. .find("button")
  2282. .append("<span class='tablesaw-sortable-arrow'>");
  2283. });
  2284. }
  2285. function clearOthers(headcells) {
  2286. $.each(headcells, function(i, v) {
  2287. var col = $(v);
  2288. col.removeAttr(attrs.defaultCol);
  2289. col.removeClass(classes.ascend);
  2290. col.removeClass(classes.descend);
  2291. });
  2292. }
  2293. function headsOnAction(e) {
  2294. if ($(e.target).is("a[href]")) {
  2295. return;
  2296. }
  2297. e.stopPropagation();
  2298. var headCell = $(e.target).closest("[" + attrs.sortCol + "]"),
  2299. v = e.data.col,
  2300. newSortValue = heads.index(headCell[0]);
  2301. clearOthers(
  2302. headCell
  2303. .closest("thead")
  2304. .find("th")
  2305. .filter(function() {
  2306. return this !== headCell[0];
  2307. })
  2308. );
  2309. if (headCell.is("." + classes.descend) || !headCell.is("." + classes.ascend)) {
  2310. el[pluginName]("sortBy", v, true);
  2311. newSortValue += "_asc";
  2312. } else {
  2313. el[pluginName]("sortBy", v);
  2314. newSortValue += "_desc";
  2315. }
  2316. if ($switcher) {
  2317. $switcher
  2318. .find("select")
  2319. .val(newSortValue)
  2320. .trigger("refresh");
  2321. }
  2322. e.preventDefault();
  2323. }
  2324. function handleDefault(heads) {
  2325. $.each(heads, function(idx, el) {
  2326. var $el = $(el);
  2327. if ($el.is("[" + attrs.defaultCol + "]")) {
  2328. if (!$el.is("." + classes.descend)) {
  2329. $el.addClass(classes.ascend);
  2330. }
  2331. }
  2332. });
  2333. }
  2334. function addSwitcher(heads) {
  2335. $switcher = $("<div>")
  2336. .addClass(classes.switcher)
  2337. .addClass(classes.tableToolbar);
  2338. var html = ["<label>" + Tablesaw.i18n.sort + ":"];
  2339. // TODO next major version: remove .btn
  2340. html.push('<span class="btn tablesaw-btn"><select>');
  2341. heads.each(function(j) {
  2342. var $t = $(this);
  2343. var isDefaultCol = $t.is("[" + attrs.defaultCol + "]");
  2344. var isDescending = $t.is("." + classes.descend);
  2345. var hasNumericAttribute = $t.is("[" + attrs.numericCol + "]");
  2346. var numericCount = 0;
  2347. // Check only the first four rows to see if the column is numbers.
  2348. var numericCountMax = 5;
  2349. $(this.cells.slice(0, numericCountMax)).each(function() {
  2350. if (!isNaN(parseInt(getSortValue(this), 10))) {
  2351. numericCount++;
  2352. }
  2353. });
  2354. var isNumeric = numericCount === numericCountMax;
  2355. if (!hasNumericAttribute) {
  2356. $t.attr(attrs.numericCol, isNumeric ? "" : "false");
  2357. }
  2358. html.push(
  2359. "<option" +
  2360. (isDefaultCol && !isDescending ? " selected" : "") +
  2361. ' value="' +
  2362. j +
  2363. '_asc">' +
  2364. $t.text() +
  2365. " " +
  2366. (isNumeric ? "&#x2191;" : "(A-Z)") +
  2367. "</option>"
  2368. );
  2369. html.push(
  2370. "<option" +
  2371. (isDefaultCol && isDescending ? " selected" : "") +
  2372. ' value="' +
  2373. j +
  2374. '_desc">' +
  2375. $t.text() +
  2376. " " +
  2377. (isNumeric ? "&#x2193;" : "(Z-A)") +
  2378. "</option>"
  2379. );
  2380. });
  2381. html.push("</select></span></label>");
  2382. $switcher.html(html.join(""));
  2383. var $firstChild = tblsaw.$toolbar.children().eq(0);
  2384. if ($firstChild.length) {
  2385. $switcher.insertBefore($firstChild);
  2386. } else {
  2387. $switcher.appendTo(tblsaw.$toolbar);
  2388. }
  2389. $switcher.find(".tablesaw-btn").tablesawbtn();
  2390. $switcher.find("select").on("change", function() {
  2391. var val = $(this)
  2392. .val()
  2393. .split("_"),
  2394. head = heads.eq(val[0]);
  2395. clearOthers(head.siblings());
  2396. el[pluginName]("sortBy", head.get(0), val[1] === "asc");
  2397. });
  2398. }
  2399. el.addClass(pluginName);
  2400. heads = el
  2401. .children()
  2402. .filter("thead")
  2403. .find("th[" + attrs.sortCol + "]");
  2404. addClassToHeads(heads);
  2405. makeHeadsActionable(heads, headsOnAction);
  2406. handleDefault(heads);
  2407. if (el.is(sortableSwitchSelector)) {
  2408. addSwitcher(heads);
  2409. }
  2410. },
  2411. sortRows: function(rows, colNum, ascending, col, tbody) {
  2412. function convertCells(cellArr, belongingToTbody) {
  2413. var cells = [];
  2414. $.each(cellArr, function(i, cell) {
  2415. var row = cell.parentNode;
  2416. var $row = $(row);
  2417. // next row is a subrow
  2418. var subrows = [];
  2419. var $next = $row.next();
  2420. while ($next.is("[" + attrs.subRow + "]")) {
  2421. subrows.push($next[0]);
  2422. $next = $next.next();
  2423. }
  2424. var tbody = row.parentNode;
  2425. // current row is a subrow
  2426. if ($row.is("[" + attrs.subRow + "]")) {
  2427. } else if (tbody === belongingToTbody) {
  2428. cells.push({
  2429. element: cell,
  2430. cell: getSortValue(cell),
  2431. row: row,
  2432. subrows: subrows.length ? subrows : null,
  2433. ignored: $row.is("[" + attrs.ignoreRow + "]")
  2434. });
  2435. }
  2436. });
  2437. return cells;
  2438. }
  2439. function getSortFxn(ascending, forceNumeric) {
  2440. var fn,
  2441. regex = /[^\-\+\d\.]/g;
  2442. if (ascending) {
  2443. fn = function(a, b) {
  2444. if (a.ignored || b.ignored) {
  2445. return 0;
  2446. }
  2447. if (forceNumeric) {
  2448. return (
  2449. parseFloat(a.cell.replace(regex, "")) - parseFloat(b.cell.replace(regex, ""))
  2450. );
  2451. } else {
  2452. return a.cell.toLowerCase() > b.cell.toLowerCase() ? 1 : -1;
  2453. }
  2454. };
  2455. } else {
  2456. fn = function(a, b) {
  2457. if (a.ignored || b.ignored) {
  2458. return 0;
  2459. }
  2460. if (forceNumeric) {
  2461. return (
  2462. parseFloat(b.cell.replace(regex, "")) - parseFloat(a.cell.replace(regex, ""))
  2463. );
  2464. } else {
  2465. return a.cell.toLowerCase() < b.cell.toLowerCase() ? 1 : -1;
  2466. }
  2467. };
  2468. }
  2469. return fn;
  2470. }
  2471. function convertToRows(sorted) {
  2472. var newRows = [],
  2473. i,
  2474. l;
  2475. for (i = 0, l = sorted.length; i < l; i++) {
  2476. newRows.push(sorted[i].row);
  2477. if (sorted[i].subrows) {
  2478. newRows.push(sorted[i].subrows);
  2479. }
  2480. }
  2481. return newRows;
  2482. }
  2483. var fn;
  2484. var sorted;
  2485. var cells = convertCells(col.cells, tbody);
  2486. var customFn = $(col).data("tablesaw-sort");
  2487. fn =
  2488. (customFn && typeof customFn === "function" ? customFn(ascending) : false) ||
  2489. getSortFxn(
  2490. ascending,
  2491. $(col).is("[" + attrs.numericCol + "]") &&
  2492. !$(col).is("[" + attrs.numericCol + '="false"]')
  2493. );
  2494. sorted = cells.sort(fn);
  2495. rows = convertToRows(sorted);
  2496. return rows;
  2497. },
  2498. makeColDefault: function(col, a) {
  2499. var c = $(col);
  2500. c.attr(attrs.defaultCol, "true");
  2501. if (a) {
  2502. c.removeClass(classes.descend);
  2503. c.addClass(classes.ascend);
  2504. } else {
  2505. c.removeClass(classes.ascend);
  2506. c.addClass(classes.descend);
  2507. }
  2508. },
  2509. sortBy: function(col, ascending) {
  2510. var el = $(this);
  2511. var colNum;
  2512. var tbl = el.data("tablesaw");
  2513. tbl.$tbody.each(function() {
  2514. var tbody = this;
  2515. var $tbody = $(this);
  2516. var rows = tbl.getBodyRows(tbody);
  2517. var sortedRows;
  2518. var map = tbl.headerMapping[0];
  2519. var j, k;
  2520. // find the column number that we’re sorting
  2521. for (j = 0, k = map.length; j < k; j++) {
  2522. if (map[j] === col) {
  2523. colNum = j;
  2524. break;
  2525. }
  2526. }
  2527. sortedRows = el[pluginName]("sortRows", rows, colNum, ascending, col, tbody);
  2528. // replace Table rows
  2529. for (j = 0, k = sortedRows.length; j < k; j++) {
  2530. $tbody.append(sortedRows[j]);
  2531. }
  2532. });
  2533. el[pluginName]("makeColDefault", col, ascending);
  2534. el.trigger("tablesaw-sorted");
  2535. }
  2536. };
  2537. // Collection method.
  2538. $.fn[pluginName] = function(arrg) {
  2539. var args = Array.prototype.slice.call(arguments, 1),
  2540. returnVal;
  2541. // if it's a method
  2542. if (arrg && typeof arrg === "string") {
  2543. returnVal = $.fn[pluginName].prototype[arrg].apply(this[0], args);
  2544. return typeof returnVal !== "undefined" ? returnVal : $(this);
  2545. }
  2546. // check init
  2547. if (!$(this).data(pluginName + "-active")) {
  2548. $(this).data(pluginName + "-active", true);
  2549. $.fn[pluginName].prototype._create.call(this, arrg);
  2550. }
  2551. return $(this);
  2552. };
  2553. // add methods
  2554. $.extend($.fn[pluginName].prototype, methods);
  2555. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  2556. if (Tablesaw.$table.is(initSelector)) {
  2557. Tablesaw.$table[pluginName]();
  2558. }
  2559. });
  2560. // TODO OOP this and add to Tablesaw object
  2561. })();
  2562. (function() {
  2563. var classes = {
  2564. hideBtn: "disabled",
  2565. persistWidths: "tablesaw-fix-persist",
  2566. hiddenCol: "tablesaw-swipe-cellhidden",
  2567. persistCol: "tablesaw-swipe-cellpersist",
  2568. allColumnsVisible: "tablesaw-all-cols-visible"
  2569. };
  2570. var attrs = {
  2571. disableTouchEvents: "data-tablesaw-no-touch",
  2572. ignorerow: "data-tablesaw-ignorerow",
  2573. subrow: "data-tablesaw-subrow"
  2574. };
  2575. function createSwipeTable(tbl, $table) {
  2576. var tblsaw = $table.data("tablesaw");
  2577. var $btns = $("<div class='tablesaw-advance'></div>");
  2578. // TODO next major version: remove .btn
  2579. var $prevBtn = $(
  2580. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro left'>" +
  2581. Tablesaw.i18n.swipePreviousColumn +
  2582. "</a>"
  2583. ).appendTo($btns);
  2584. // TODO next major version: remove .btn
  2585. var $nextBtn = $(
  2586. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro right'>" +
  2587. Tablesaw.i18n.swipeNextColumn +
  2588. "</a>"
  2589. ).appendTo($btns);
  2590. var $headerCells = tbl._getPrimaryHeaderCells();
  2591. var $headerCellsNoPersist = $headerCells.not('[data-tablesaw-priority="persist"]');
  2592. var headerWidths = [];
  2593. var headerWidthsNoPersist = [];
  2594. var $head = $(document.head || "head");
  2595. var tableId = $table.attr("id");
  2596. if (!$headerCells.length) {
  2597. throw new Error("tablesaw swipe: no header cells found.");
  2598. }
  2599. $table.addClass("tablesaw-swipe");
  2600. function initMinHeaderWidths() {
  2601. $table.css({
  2602. width: "1px"
  2603. });
  2604. // remove any hidden columns
  2605. $table.find("." + classes.hiddenCol).removeClass(classes.hiddenCol);
  2606. headerWidths = [];
  2607. headerWidthsNoPersist = [];
  2608. // Calculate initial widths
  2609. $headerCells.each(function() {
  2610. var width = this.offsetWidth;
  2611. headerWidths.push(width);
  2612. if (!isPersistent(this)) {
  2613. headerWidthsNoPersist.push(width);
  2614. }
  2615. });
  2616. // reset props
  2617. $table.css({
  2618. width: ""
  2619. });
  2620. }
  2621. initMinHeaderWidths();
  2622. $btns.appendTo(tblsaw.$toolbar);
  2623. if (!tableId) {
  2624. tableId = "tableswipe-" + Math.round(Math.random() * 10000);
  2625. $table.attr("id", tableId);
  2626. }
  2627. function showColumn(headerCell) {
  2628. tblsaw._$getCells(headerCell).removeClass(classes.hiddenCol);
  2629. }
  2630. function hideColumn(headerCell) {
  2631. tblsaw._$getCells(headerCell).addClass(classes.hiddenCol);
  2632. }
  2633. function persistColumn(headerCell) {
  2634. tblsaw._$getCells(headerCell).addClass(classes.persistCol);
  2635. }
  2636. function isPersistent(headerCell) {
  2637. return $(headerCell).is('[data-tablesaw-priority="persist"]');
  2638. }
  2639. function unmaintainWidths() {
  2640. $table.removeClass(classes.persistWidths);
  2641. $("#" + tableId + "-persist").remove();
  2642. }
  2643. function maintainWidths() {
  2644. var prefix = "#" + tableId + ".tablesaw-swipe ";
  2645. var styles = [];
  2646. var tableWidth = $table.width();
  2647. var tableWidthNoPersistantColumns = tableWidth;
  2648. var hash = [];
  2649. var newHash;
  2650. // save persistent column widths (as long as they take up less than 75% of table width)
  2651. $headerCells.each(function(index) {
  2652. var width;
  2653. if (isPersistent(this)) {
  2654. width = this.offsetWidth;
  2655. tableWidthNoPersistantColumns -= width;
  2656. if (width < tableWidth * 0.75) {
  2657. hash.push(index + "-" + width);
  2658. styles.push(
  2659. prefix +
  2660. " ." +
  2661. classes.persistCol +
  2662. ":nth-child(" +
  2663. (index + 1) +
  2664. ") { width: " +
  2665. width +
  2666. "px; }"
  2667. );
  2668. }
  2669. }
  2670. });
  2671. newHash = hash.join("_");
  2672. if (styles.length) {
  2673. $table.addClass(classes.persistWidths);
  2674. var $style = $("#" + tableId + "-persist");
  2675. // If style element not yet added OR if the widths have changed
  2676. if (!$style.length || $style.data("tablesaw-hash") !== newHash) {
  2677. // Remove existing
  2678. $style.remove();
  2679. $("<style>" + styles.join("\n") + "</style>")
  2680. .attr("id", tableId + "-persist")
  2681. .data("tablesaw-hash", newHash)
  2682. .appendTo($head);
  2683. }
  2684. }
  2685. return tableWidthNoPersistantColumns;
  2686. }
  2687. function getNext() {
  2688. var next = [];
  2689. var checkFound;
  2690. $headerCellsNoPersist.each(function(i) {
  2691. var $t = $(this);
  2692. var isHidden = $t.css("display") === "none" || $t.is("." + classes.hiddenCol);
  2693. if (!isHidden && !checkFound) {
  2694. checkFound = true;
  2695. next[0] = i;
  2696. } else if (isHidden && checkFound) {
  2697. next[1] = i;
  2698. return false;
  2699. }
  2700. });
  2701. return next;
  2702. }
  2703. function getPrev() {
  2704. var next = getNext();
  2705. return [next[1] - 1, next[0] - 1];
  2706. }
  2707. function canNavigate(pair) {
  2708. return pair[1] > -1 && pair[1] < $headerCellsNoPersist.length;
  2709. }
  2710. function matchesMedia() {
  2711. var matchMedia = $table.attr("data-tablesaw-swipe-media");
  2712. return !matchMedia || ("matchMedia" in window && window.matchMedia(matchMedia).matches);
  2713. }
  2714. function fakeBreakpoints() {
  2715. if (!matchesMedia()) {
  2716. return;
  2717. }
  2718. var containerWidth = $table.parent().width(),
  2719. persist = [],
  2720. sum = 0,
  2721. sums = [],
  2722. visibleNonPersistantCount = $headerCells.length;
  2723. $headerCells.each(function(index) {
  2724. var $t = $(this),
  2725. isPersist = $t.is('[data-tablesaw-priority="persist"]');
  2726. persist.push(isPersist);
  2727. sum += headerWidths[index];
  2728. sums.push(sum);
  2729. // is persistent or is hidden
  2730. if (isPersist || sum > containerWidth) {
  2731. visibleNonPersistantCount--;
  2732. }
  2733. });
  2734. // We need at least one column to swipe.
  2735. var needsNonPersistentColumn = visibleNonPersistantCount === 0;
  2736. $headerCells.each(function(index) {
  2737. if (sums[index] > containerWidth) {
  2738. hideColumn(this);
  2739. }
  2740. });
  2741. var firstPersist = true;
  2742. $headerCells.each(function(index) {
  2743. if (persist[index]) {
  2744. // for visual box-shadow
  2745. persistColumn(this);
  2746. if (firstPersist) {
  2747. tblsaw._$getCells(this).css("width", sums[index] + "px");
  2748. firstPersist = false;
  2749. }
  2750. return;
  2751. }
  2752. if (sums[index] <= containerWidth || needsNonPersistentColumn) {
  2753. needsNonPersistentColumn = false;
  2754. showColumn(this);
  2755. tblsaw.updateColspanCells(classes.hiddenCol, this, true);
  2756. }
  2757. });
  2758. unmaintainWidths();
  2759. $table.trigger("tablesawcolumns");
  2760. }
  2761. function goForward() {
  2762. navigate(true);
  2763. }
  2764. function goBackward() {
  2765. navigate(false);
  2766. }
  2767. function navigate(isNavigateForward) {
  2768. var pair;
  2769. if (isNavigateForward) {
  2770. pair = getNext();
  2771. } else {
  2772. pair = getPrev();
  2773. }
  2774. if (canNavigate(pair)) {
  2775. if (isNaN(pair[0])) {
  2776. if (isNavigateForward) {
  2777. pair[0] = 0;
  2778. } else {
  2779. pair[0] = $headerCellsNoPersist.length - 1;
  2780. }
  2781. }
  2782. var roomForColumnsWidth = maintainWidths();
  2783. var hideColumnIndex = pair[0];
  2784. var showColumnIndex = pair[1];
  2785. // Hide one column, show one or more based on how much space was freed up
  2786. var columnToShow;
  2787. var columnToHide = $headerCellsNoPersist.get(hideColumnIndex);
  2788. var wasAtLeastOneColumnShown = false;
  2789. var atLeastOneColumnIsVisible = false;
  2790. hideColumn(columnToHide);
  2791. tblsaw.updateColspanCells(classes.hiddenCol, columnToHide, true);
  2792. var columnIndex = hideColumnIndex + (isNavigateForward ? 1 : -1);
  2793. while (columnIndex >= 0 && columnIndex < headerWidthsNoPersist.length) {
  2794. roomForColumnsWidth -= headerWidthsNoPersist[columnIndex];
  2795. var $columnToShow = $headerCellsNoPersist.eq(columnIndex);
  2796. if ($columnToShow.is(".tablesaw-swipe-cellhidden")) {
  2797. if (roomForColumnsWidth > 0) {
  2798. columnToShow = $columnToShow.get(0);
  2799. wasAtLeastOneColumnShown = true;
  2800. atLeastOneColumnIsVisible = true;
  2801. showColumn(columnToShow);
  2802. tblsaw.updateColspanCells(classes.hiddenCol, columnToShow, false);
  2803. }
  2804. } else {
  2805. atLeastOneColumnIsVisible = true;
  2806. }
  2807. if (isNavigateForward) {
  2808. columnIndex++;
  2809. } else {
  2810. columnIndex--;
  2811. }
  2812. }
  2813. if (!atLeastOneColumnIsVisible) {
  2814. // if no columns are showing, at least show the first one we were aiming for.
  2815. columnToShow = $headerCellsNoPersist.get(showColumnIndex);
  2816. showColumn(columnToShow);
  2817. tblsaw.updateColspanCells(classes.hiddenCol, columnToShow, false);
  2818. } else if (
  2819. !wasAtLeastOneColumnShown &&
  2820. canNavigate(isNavigateForward ? getNext() : getPrev())
  2821. ) {
  2822. // if our one new column was hidden but no new columns were shown, let’s navigate again automatically.
  2823. navigate(isNavigateForward);
  2824. }
  2825. $table.trigger("tablesawcolumns");
  2826. }
  2827. }
  2828. $prevBtn.add($nextBtn).on("click", function(e) {
  2829. if (!!$(e.target).closest($nextBtn).length) {
  2830. goForward();
  2831. } else {
  2832. goBackward();
  2833. }
  2834. e.preventDefault();
  2835. });
  2836. function getCoord(event, key) {
  2837. return (event.touches || event.originalEvent.touches)[0][key];
  2838. }
  2839. if (!$table.is("[" + attrs.disableTouchEvents + "]")) {
  2840. $table.on("touchstart.swipetoggle", function(e) {
  2841. var originX = getCoord(e, "pageX");
  2842. var originY = getCoord(e, "pageY");
  2843. var x;
  2844. var y;
  2845. var scrollTop = window.pageYOffset;
  2846. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  2847. $(this)
  2848. .on("touchmove.swipetoggle", function(e) {
  2849. x = getCoord(e, "pageX");
  2850. y = getCoord(e, "pageY");
  2851. })
  2852. .on("touchend.swipetoggle", function() {
  2853. var cfg = tbl.getConfig({
  2854. swipeHorizontalThreshold: 30,
  2855. swipeVerticalThreshold: 30
  2856. });
  2857. // This config code is a little awkward because shoestring doesn’t support deep $.extend
  2858. // Trying to work around when devs only override one of (not both) horizontalThreshold or
  2859. // verticalThreshold in their TablesawConfig.
  2860. // @TODO major version bump: remove cfg.swipe, move to just use the swipePrefix keys
  2861. var verticalThreshold = cfg.swipe
  2862. ? cfg.swipe.verticalThreshold
  2863. : cfg.swipeVerticalThreshold;
  2864. var horizontalThreshold = cfg.swipe
  2865. ? cfg.swipe.horizontalThreshold
  2866. : cfg.swipeHorizontalThreshold;
  2867. var isPageScrolled = Math.abs(window.pageYOffset - scrollTop) >= verticalThreshold;
  2868. var isVerticalSwipe = Math.abs(y - originY) >= verticalThreshold;
  2869. if (!isVerticalSwipe && !isPageScrolled) {
  2870. if (x - originX < -1 * horizontalThreshold) {
  2871. goForward();
  2872. }
  2873. if (x - originX > horizontalThreshold) {
  2874. goBackward();
  2875. }
  2876. }
  2877. window.setTimeout(function() {
  2878. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  2879. }, 300);
  2880. $(this).off("touchmove.swipetoggle touchend.swipetoggle");
  2881. });
  2882. });
  2883. }
  2884. $table
  2885. .on("tablesawcolumns.swipetoggle", function() {
  2886. var canGoPrev = canNavigate(getPrev());
  2887. var canGoNext = canNavigate(getNext());
  2888. $prevBtn[canGoPrev ? "removeClass" : "addClass"](classes.hideBtn);
  2889. $nextBtn[canGoNext ? "removeClass" : "addClass"](classes.hideBtn);
  2890. tblsaw.$toolbar[!canGoPrev && !canGoNext ? "addClass" : "removeClass"](
  2891. classes.allColumnsVisible
  2892. );
  2893. })
  2894. .on("tablesawnext.swipetoggle", function() {
  2895. goForward();
  2896. })
  2897. .on("tablesawprev.swipetoggle", function() {
  2898. goBackward();
  2899. })
  2900. .on(Tablesaw.events.destroy + ".swipetoggle", function() {
  2901. var $t = $(this);
  2902. $t.removeClass("tablesaw-swipe");
  2903. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  2904. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  2905. $t.off(".swipetoggle");
  2906. })
  2907. .on(Tablesaw.events.refresh, function() {
  2908. unmaintainWidths();
  2909. initMinHeaderWidths();
  2910. fakeBreakpoints();
  2911. });
  2912. fakeBreakpoints();
  2913. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  2914. }
  2915. // on tablecreate, init
  2916. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2917. if (tablesaw.mode === "swipe") {
  2918. createSwipeTable(tablesaw, tablesaw.$table);
  2919. }
  2920. });
  2921. // TODO OOP this and add to Tablesaw object
  2922. })();
  2923. (function() {
  2924. var MiniMap = {
  2925. attr: {
  2926. init: "data-tablesaw-minimap"
  2927. },
  2928. show: function(table) {
  2929. var mq = table.getAttribute(MiniMap.attr.init);
  2930. if (mq === "") {
  2931. // value-less but exists
  2932. return true;
  2933. } else if (mq && "matchMedia" in window) {
  2934. // has a mq value
  2935. return window.matchMedia(mq).matches;
  2936. }
  2937. return false;
  2938. }
  2939. };
  2940. function createMiniMap($table) {
  2941. var tblsaw = $table.data("tablesaw");
  2942. var $btns = $('<div class="tablesaw-advance minimap">');
  2943. var $dotNav = $('<ul class="tablesaw-advance-dots">').appendTo($btns);
  2944. var hideDot = "tablesaw-advance-dots-hide";
  2945. var $headerCells = $table.data("tablesaw")._getPrimaryHeaderCells();
  2946. // populate dots
  2947. $headerCells.each(function() {
  2948. $dotNav.append("<li><i></i></li>");
  2949. });
  2950. $btns.appendTo(tblsaw.$toolbar);
  2951. function showHideNav() {
  2952. if (!MiniMap.show($table[0])) {
  2953. $btns.css("display", "none");
  2954. return;
  2955. }
  2956. $btns.css("display", "block");
  2957. // show/hide dots
  2958. var dots = $dotNav.find("li").removeClass(hideDot);
  2959. $table.find("thead th").each(function(i) {
  2960. if ($(this).css("display") === "none") {
  2961. dots.eq(i).addClass(hideDot);
  2962. }
  2963. });
  2964. }
  2965. // run on init and resize
  2966. showHideNav();
  2967. $(window).on(Tablesaw.events.resize, showHideNav);
  2968. $table
  2969. .on("tablesawcolumns.minimap", function() {
  2970. showHideNav();
  2971. })
  2972. .on(Tablesaw.events.destroy + ".minimap", function() {
  2973. var $t = $(this);
  2974. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  2975. $(window).off(Tablesaw.events.resize, showHideNav);
  2976. $t.off(".minimap");
  2977. });
  2978. }
  2979. // on tablecreate, init
  2980. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  2981. if (
  2982. (tablesaw.mode === "swipe" || tablesaw.mode === "columntoggle") &&
  2983. tablesaw.$table.is("[ " + MiniMap.attr.init + "]")
  2984. ) {
  2985. createMiniMap(tablesaw.$table);
  2986. }
  2987. });
  2988. // TODO OOP this better
  2989. Tablesaw.MiniMap = MiniMap;
  2990. })();
  2991. (function() {
  2992. var S = {
  2993. selectors: {
  2994. init: "table[data-tablesaw-mode-switch]"
  2995. },
  2996. attributes: {
  2997. excludeMode: "data-tablesaw-mode-exclude"
  2998. },
  2999. classes: {
  3000. main: "tablesaw-modeswitch",
  3001. toolbar: "tablesaw-bar-section"
  3002. },
  3003. modes: ["stack", "swipe", "columntoggle"],
  3004. init: function(table) {
  3005. var $table = $(table);
  3006. var tblsaw = $table.data("tablesaw");
  3007. var ignoreMode = $table.attr(S.attributes.excludeMode);
  3008. var $toolbar = tblsaw.$toolbar;
  3009. var $switcher = $("<div>").addClass(S.classes.main + " " + S.classes.toolbar);
  3010. var html = [
  3011. '<label><span class="abbreviated">' +
  3012. Tablesaw.i18n.modeSwitchColumnsAbbreviated +
  3013. '</span><span class="longform">' +
  3014. Tablesaw.i18n.modeSwitchColumns +
  3015. "</span>:"
  3016. ],
  3017. dataMode = $table.attr("data-tablesaw-mode"),
  3018. isSelected;
  3019. // TODO next major version: remove .btn
  3020. html.push('<span class="btn tablesaw-btn"><select>');
  3021. for (var j = 0, k = S.modes.length; j < k; j++) {
  3022. if (ignoreMode && ignoreMode.toLowerCase() === S.modes[j]) {
  3023. continue;
  3024. }
  3025. isSelected = dataMode === S.modes[j];
  3026. html.push(
  3027. "<option" +
  3028. (isSelected ? " selected" : "") +
  3029. ' value="' +
  3030. S.modes[j] +
  3031. '">' +
  3032. Tablesaw.i18n.modes[j] +
  3033. "</option>"
  3034. );
  3035. }
  3036. html.push("</select></span></label>");
  3037. $switcher.html(html.join(""));
  3038. var $otherToolbarItems = $toolbar.find(".tablesaw-advance").eq(0);
  3039. if ($otherToolbarItems.length) {
  3040. $switcher.insertBefore($otherToolbarItems);
  3041. } else {
  3042. $switcher.appendTo($toolbar);
  3043. }
  3044. $switcher.find(".tablesaw-btn").tablesawbtn();
  3045. $switcher.find("select").on("change", function(event) {
  3046. return S.onModeChange.call(table, event, $(this).val());
  3047. });
  3048. },
  3049. onModeChange: function(event, val) {
  3050. var $table = $(this);
  3051. var tblsaw = $table.data("tablesaw");
  3052. var $switcher = tblsaw.$toolbar.find("." + S.classes.main);
  3053. $switcher.remove();
  3054. tblsaw.destroy();
  3055. $table.attr("data-tablesaw-mode", val);
  3056. $table.tablesaw();
  3057. }
  3058. };
  3059. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  3060. if (Tablesaw.$table.is(S.selectors.init)) {
  3061. S.init(Tablesaw.table);
  3062. }
  3063. });
  3064. // TODO OOP this and add to Tablesaw object
  3065. })();
  3066. (function() {
  3067. var pluginName = "tablesawCheckAll";
  3068. function CheckAll(tablesaw) {
  3069. this.tablesaw = tablesaw;
  3070. this.$table = tablesaw.$table;
  3071. this.attr = "data-tablesaw-checkall";
  3072. this.checkAllSelector = "[" + this.attr + "]";
  3073. this.forceCheckedSelector = "[" + this.attr + "-checked]";
  3074. this.forceUncheckedSelector = "[" + this.attr + "-unchecked]";
  3075. this.checkboxSelector = 'input[type="checkbox"]';
  3076. this.$triggers = null;
  3077. this.$checkboxes = null;
  3078. if (this.$table.data(pluginName)) {
  3079. return;
  3080. }
  3081. this.$table.data(pluginName, this);
  3082. this.init();
  3083. }
  3084. CheckAll.prototype._filterCells = function($checkboxes) {
  3085. return $checkboxes
  3086. .filter(function() {
  3087. return !$(this)
  3088. .closest("tr")
  3089. .is("[data-tablesaw-subrow],[data-tablesaw-ignorerow]");
  3090. })
  3091. .find(this.checkboxSelector)
  3092. .not(this.checkAllSelector);
  3093. };
  3094. // With buttons you can use a scoping selector like: data-tablesaw-checkall="#my-scoped-id input[type='checkbox']"
  3095. CheckAll.prototype.getCheckboxesForButton = function(button) {
  3096. return this._filterCells($($(button).attr(this.attr)));
  3097. };
  3098. CheckAll.prototype.getCheckboxesForCheckbox = function(checkbox) {
  3099. return this._filterCells($($(checkbox).closest("th")[0].cells));
  3100. };
  3101. CheckAll.prototype.init = function() {
  3102. var self = this;
  3103. this.$table.find(this.checkAllSelector).each(function() {
  3104. var $trigger = $(this);
  3105. if ($trigger.is(self.checkboxSelector)) {
  3106. self.addCheckboxEvents(this);
  3107. } else {
  3108. self.addButtonEvents(this);
  3109. }
  3110. });
  3111. };
  3112. CheckAll.prototype.addButtonEvents = function(trigger) {
  3113. var self = this;
  3114. // Update body checkboxes when header checkbox is changed
  3115. $(trigger).on("click", function(event) {
  3116. event.preventDefault();
  3117. var $checkboxes = self.getCheckboxesForButton(this);
  3118. var allChecked = true;
  3119. $checkboxes.each(function() {
  3120. if (!this.checked) {
  3121. allChecked = false;
  3122. }
  3123. });
  3124. var setChecked;
  3125. if ($(this).is(self.forceCheckedSelector)) {
  3126. setChecked = true;
  3127. } else if ($(this).is(self.forceUncheckedSelector)) {
  3128. setChecked = false;
  3129. } else {
  3130. setChecked = allChecked ? false : true;
  3131. }
  3132. $checkboxes.each(function() {
  3133. this.checked = setChecked;
  3134. $(this).trigger("change." + pluginName);
  3135. });
  3136. });
  3137. };
  3138. CheckAll.prototype.addCheckboxEvents = function(trigger) {
  3139. var self = this;
  3140. // Update body checkboxes when header checkbox is changed
  3141. $(trigger).on("change", function() {
  3142. var setChecked = this.checked;
  3143. self.getCheckboxesForCheckbox(this).each(function() {
  3144. this.checked = setChecked;
  3145. });
  3146. });
  3147. var $checkboxes = self.getCheckboxesForCheckbox(trigger);
  3148. // Update header checkbox when body checkboxes are changed
  3149. $checkboxes.on("change." + pluginName, function() {
  3150. var checkedCount = 0;
  3151. $checkboxes.each(function() {
  3152. if (this.checked) {
  3153. checkedCount++;
  3154. }
  3155. });
  3156. var allSelected = checkedCount === $checkboxes.length;
  3157. trigger.checked = allSelected;
  3158. // only indeterminate if some are selected (not all and not none)
  3159. trigger.indeterminate = checkedCount !== 0 && !allSelected;
  3160. });
  3161. };
  3162. // on tablecreate, init
  3163. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  3164. new CheckAll(tablesaw);
  3165. });
  3166. Tablesaw.CheckAll = CheckAll;
  3167. })();
  3168. return Tablesaw;
  3169. }));