tablesaw.jquery.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156
  1. /*! Tablesaw - v3.1.2 - 2019-03-19
  2. * https://github.com/filamentgroup/tablesaw
  3. * Copyright (c) 2019 Filament Group; Licensed MIT */
  4. (function (root, factory) {
  5. if (typeof define === 'function' && define.amd) {
  6. define(["jquery"], function (jQuery) {
  7. return (root.Tablesaw = factory(jQuery, root));
  8. });
  9. } else if (typeof exports === 'object') {
  10. if( "document" in root ) {
  11. module.exports = factory(require('jquery'), root);
  12. } else {
  13. // special jQuery case for CommonJS (pass in a window)
  14. module.exports = factory(require('jquery')(root), root);
  15. }
  16. } else {
  17. root.Tablesaw = factory(jQuery, root);
  18. }
  19. }(typeof window !== "undefined" ? window : this, function ($, window) {
  20. "use strict";
  21. var document = window.document;
  22. // Account for Tablesaw being loaded either before or after the DOMContentLoaded event is fired.
  23. var domContentLoadedTriggered = /complete|loaded/.test(document.readyState);
  24. document.addEventListener("DOMContentLoaded", function() {
  25. domContentLoadedTriggered = true;
  26. });
  27. var Tablesaw = {
  28. i18n: {
  29. modeStack: "Stack",
  30. modeSwipe: "Swipe",
  31. modeToggle: "Toggle",
  32. modeSwitchColumnsAbbreviated: "Cols",
  33. modeSwitchColumns: "Columns",
  34. columnToggleButton: "Columns",
  35. columnToggleError: "No eligible columns.",
  36. sort: "Sort",
  37. swipePreviousColumn: "Previous column",
  38. swipeNextColumn: "Next column"
  39. },
  40. // cut the mustard
  41. mustard:
  42. "head" in document && // IE9+, Firefox 4+, Safari 5.1+, Mobile Safari 4.1+, Opera 11.5+, Android 2.3+
  43. (!window.blackberry || window.WebKitPoint) && // only WebKit Blackberry (OS 6+)
  44. !window.operamini,
  45. $: $,
  46. _init: function(element) {
  47. Tablesaw.$(element || document).trigger("enhance.tablesaw");
  48. },
  49. init: function(element) {
  50. // Account for Tablesaw being loaded either before or after the DOMContentLoaded event is fired.
  51. domContentLoadedTriggered =
  52. domContentLoadedTriggered || /complete|loaded/.test(document.readyState);
  53. if (!domContentLoadedTriggered) {
  54. if ("addEventListener" in document) {
  55. // Use raw DOMContentLoaded instead of shoestring (may have issues in Android 2.3, exhibited by stack table)
  56. document.addEventListener("DOMContentLoaded", function() {
  57. Tablesaw._init(element);
  58. });
  59. }
  60. } else {
  61. Tablesaw._init(element);
  62. }
  63. }
  64. };
  65. $(document).on("enhance.tablesaw", function() {
  66. // Extend i18n config, if one exists.
  67. if (typeof TablesawConfig !== "undefined" && TablesawConfig.i18n) {
  68. Tablesaw.i18n = $.extend(Tablesaw.i18n, TablesawConfig.i18n || {});
  69. }
  70. Tablesaw.i18n.modes = [
  71. Tablesaw.i18n.modeStack,
  72. Tablesaw.i18n.modeSwipe,
  73. Tablesaw.i18n.modeToggle
  74. ];
  75. });
  76. if (Tablesaw.mustard) {
  77. $(document.documentElement).addClass("tablesaw-enhanced");
  78. }
  79. (function() {
  80. var pluginName = "tablesaw";
  81. var classes = {
  82. toolbar: "tablesaw-bar"
  83. };
  84. var events = {
  85. create: "tablesawcreate",
  86. destroy: "tablesawdestroy",
  87. refresh: "tablesawrefresh",
  88. resize: "tablesawresize"
  89. };
  90. var defaultMode = "stack";
  91. var initSelector = "table";
  92. var initFilterSelector = "[data-tablesaw],[data-tablesaw-mode],[data-tablesaw-sortable]";
  93. var defaultConfig = {};
  94. Tablesaw.events = events;
  95. var Table = function(element) {
  96. if (!element) {
  97. throw new Error("Tablesaw requires an element.");
  98. }
  99. this.table = element;
  100. this.$table = $(element);
  101. // only one <thead> and <tfoot> are allowed, per the specification
  102. this.$thead = this.$table
  103. .children()
  104. .filter("thead")
  105. .eq(0);
  106. // multiple <tbody> are allowed, per the specification
  107. this.$tbody = this.$table.children().filter("tbody");
  108. this.mode = this.$table.attr("data-tablesaw-mode") || defaultMode;
  109. this.$toolbar = null;
  110. this.attributes = {
  111. subrow: "data-tablesaw-subrow",
  112. ignorerow: "data-tablesaw-ignorerow"
  113. };
  114. this.init();
  115. };
  116. Table.prototype.init = function() {
  117. if (!this.$thead.length) {
  118. throw new Error("tablesaw: a <thead> is required, but none was found.");
  119. }
  120. if (!this.$thead.find("th").length) {
  121. throw new Error("tablesaw: no header cells found. Are you using <th> inside of <thead>?");
  122. }
  123. // assign an id if there is none
  124. if (!this.$table.attr("id")) {
  125. this.$table.attr("id", pluginName + "-" + Math.round(Math.random() * 10000));
  126. }
  127. this.createToolbar();
  128. this._initCells();
  129. this.$table.data(pluginName, this);
  130. this.$table.trigger(events.create, [this]);
  131. };
  132. Table.prototype.getConfig = function(pluginSpecificConfig) {
  133. // shoestring extend doesn’t support arbitrary args
  134. var configs = $.extend(defaultConfig, pluginSpecificConfig || {});
  135. return $.extend(configs, typeof TablesawConfig !== "undefined" ? TablesawConfig : {});
  136. };
  137. Table.prototype._getPrimaryHeaderRow = function() {
  138. return this._getHeaderRows().eq(0);
  139. };
  140. Table.prototype._getHeaderRows = function() {
  141. return this.$thead
  142. .children()
  143. .filter("tr")
  144. .filter(function() {
  145. return !$(this).is("[data-tablesaw-ignorerow]");
  146. });
  147. };
  148. Table.prototype._getRowIndex = function($row) {
  149. return $row.prevAll().length;
  150. };
  151. Table.prototype._getHeaderRowIndeces = function() {
  152. var self = this;
  153. var indeces = [];
  154. this._getHeaderRows().each(function() {
  155. indeces.push(self._getRowIndex($(this)));
  156. });
  157. return indeces;
  158. };
  159. Table.prototype._getPrimaryHeaderCells = function($row) {
  160. return ($row || this._getPrimaryHeaderRow()).find("th");
  161. };
  162. Table.prototype._$getCells = function(th) {
  163. var self = this;
  164. return $(th)
  165. .add(th.cells)
  166. .filter(function() {
  167. var $t = $(this);
  168. var $row = $t.parent();
  169. var hasColspan = $t.is("[colspan]");
  170. // no subrows or ignored rows (keep cells in ignored rows that do not have a colspan)
  171. return (
  172. !$row.is("[" + self.attributes.subrow + "]") &&
  173. (!$row.is("[" + self.attributes.ignorerow + "]") || !hasColspan)
  174. );
  175. });
  176. };
  177. Table.prototype._getVisibleColspan = function() {
  178. var colspan = 0;
  179. this._getPrimaryHeaderCells().each(function() {
  180. var $t = $(this);
  181. if ($t.css("display") !== "none") {
  182. colspan += parseInt($t.attr("colspan"), 10) || 1;
  183. }
  184. });
  185. return colspan;
  186. };
  187. Table.prototype.getColspanForCell = function($cell) {
  188. var visibleColspan = this._getVisibleColspan();
  189. var visibleSiblingColumns = 0;
  190. if ($cell.closest("tr").data("tablesaw-rowspanned")) {
  191. visibleSiblingColumns++;
  192. }
  193. $cell.siblings().each(function() {
  194. var $t = $(this);
  195. var colColspan = parseInt($t.attr("colspan"), 10) || 1;
  196. if ($t.css("display") !== "none") {
  197. visibleSiblingColumns += colColspan;
  198. }
  199. });
  200. // console.log( $cell[ 0 ], visibleColspan, visibleSiblingColumns );
  201. return visibleColspan - visibleSiblingColumns;
  202. };
  203. Table.prototype.isCellInColumn = function(header, cell) {
  204. return $(header)
  205. .add(header.cells)
  206. .filter(function() {
  207. return this === cell;
  208. }).length;
  209. };
  210. Table.prototype.updateColspanCells = function(cls, header, userAction) {
  211. var self = this;
  212. var primaryHeaderRow = self._getPrimaryHeaderRow();
  213. // find persistent column rowspans
  214. this.$table.find("[rowspan][data-tablesaw-priority]").each(function() {
  215. var $t = $(this);
  216. if ($t.attr("data-tablesaw-priority") !== "persist") {
  217. return;
  218. }
  219. var $row = $t.closest("tr");
  220. var rowspan = parseInt($t.attr("rowspan"), 10);
  221. if (rowspan > 1) {
  222. $row = $row.next();
  223. $row.data("tablesaw-rowspanned", true);
  224. rowspan--;
  225. }
  226. });
  227. this.$table
  228. .find("[colspan],[data-tablesaw-maxcolspan]")
  229. .filter(function() {
  230. // is not in primary header row
  231. return $(this).closest("tr")[0] !== primaryHeaderRow[0];
  232. })
  233. .each(function() {
  234. var $cell = $(this);
  235. if (userAction === undefined || self.isCellInColumn(header, this)) {
  236. } else {
  237. // if is not a user action AND the cell is not in the updating column, kill it
  238. return;
  239. }
  240. var colspan = self.getColspanForCell($cell);
  241. if (cls && userAction !== undefined) {
  242. // console.log( colspan === 0 ? "addClass" : "removeClass", $cell );
  243. $cell[colspan === 0 ? "addClass" : "removeClass"](cls);
  244. }
  245. // cache original colspan
  246. var maxColspan = parseInt($cell.attr("data-tablesaw-maxcolspan"), 10);
  247. if (!maxColspan) {
  248. $cell.attr("data-tablesaw-maxcolspan", $cell.attr("colspan"));
  249. } else if (colspan > maxColspan) {
  250. colspan = maxColspan;
  251. }
  252. // console.log( this, "setting colspan to ", colspan );
  253. $cell.attr("colspan", colspan);
  254. });
  255. };
  256. Table.prototype._findPrimaryHeadersForCell = function(cell) {
  257. var $headerRow = this._getPrimaryHeaderRow();
  258. var headerRowIndex = this._getRowIndex($headerRow);
  259. var results = [];
  260. for (var rowNumber = 0; rowNumber < this.headerMapping.length; rowNumber++) {
  261. if (rowNumber === headerRowIndex) {
  262. continue;
  263. }
  264. for (var colNumber = 0; colNumber < this.headerMapping[rowNumber].length; colNumber++) {
  265. if (this.headerMapping[rowNumber][colNumber] === cell) {
  266. results.push(this.headerMapping[headerRowIndex][colNumber]);
  267. }
  268. }
  269. }
  270. return results;
  271. };
  272. // used by init cells
  273. Table.prototype.getRows = function() {
  274. var self = this;
  275. return this.$table.find("tr").filter(function() {
  276. return $(this)
  277. .closest("table")
  278. .is(self.$table);
  279. });
  280. };
  281. // used by sortable
  282. Table.prototype.getBodyRows = function(tbody) {
  283. return (tbody ? $(tbody) : this.$tbody).children().filter("tr");
  284. };
  285. Table.prototype.getHeaderCellIndex = function(cell) {
  286. var lookup = this.headerMapping[0];
  287. for (var colIndex = 0; colIndex < lookup.length; colIndex++) {
  288. if (lookup[colIndex] === cell) {
  289. return colIndex;
  290. }
  291. }
  292. return -1;
  293. };
  294. Table.prototype._initCells = function() {
  295. // re-establish original colspans
  296. this.$table.find("[data-tablesaw-maxcolspan]").each(function() {
  297. var $t = $(this);
  298. $t.attr("colspan", $t.attr("data-tablesaw-maxcolspan"));
  299. });
  300. var $rows = this.getRows();
  301. var columnLookup = [];
  302. $rows.each(function(rowNumber) {
  303. columnLookup[rowNumber] = [];
  304. });
  305. $rows.each(function(rowNumber) {
  306. var coltally = 0;
  307. var $t = $(this);
  308. var children = $t.children();
  309. children.each(function() {
  310. var colspan = parseInt(
  311. this.getAttribute("data-tablesaw-maxcolspan") || this.getAttribute("colspan"),
  312. 10
  313. );
  314. var rowspan = parseInt(this.getAttribute("rowspan"), 10);
  315. // set in a previous rowspan
  316. while (columnLookup[rowNumber][coltally]) {
  317. coltally++;
  318. }
  319. columnLookup[rowNumber][coltally] = this;
  320. // TODO? both colspan and rowspan
  321. if (colspan) {
  322. for (var k = 0; k < colspan - 1; k++) {
  323. coltally++;
  324. columnLookup[rowNumber][coltally] = this;
  325. }
  326. }
  327. if (rowspan) {
  328. for (var j = 1; j < rowspan; j++) {
  329. columnLookup[rowNumber + j][coltally] = this;
  330. }
  331. }
  332. coltally++;
  333. });
  334. });
  335. var headerRowIndeces = this._getHeaderRowIndeces();
  336. for (var colNumber = 0; colNumber < columnLookup[0].length; colNumber++) {
  337. for (var headerIndex = 0, k = headerRowIndeces.length; headerIndex < k; headerIndex++) {
  338. var headerCol = columnLookup[headerRowIndeces[headerIndex]][colNumber];
  339. var rowNumber = headerRowIndeces[headerIndex];
  340. var rowCell;
  341. if (!headerCol.cells) {
  342. headerCol.cells = [];
  343. }
  344. while (rowNumber < columnLookup.length) {
  345. rowCell = columnLookup[rowNumber][colNumber];
  346. if (headerCol !== rowCell) {
  347. headerCol.cells.push(rowCell);
  348. }
  349. rowNumber++;
  350. }
  351. }
  352. }
  353. this.headerMapping = columnLookup;
  354. };
  355. Table.prototype.refresh = function() {
  356. this._initCells();
  357. this.$table.trigger(events.refresh, [this]);
  358. };
  359. Table.prototype._getToolbarAnchor = function() {
  360. var $parent = this.$table.parent();
  361. if ($parent.is(".tablesaw-overflow")) {
  362. return $parent;
  363. }
  364. return this.$table;
  365. };
  366. Table.prototype._getToolbar = function($anchor) {
  367. if (!$anchor) {
  368. $anchor = this._getToolbarAnchor();
  369. }
  370. return $anchor.prev().filter("." + classes.toolbar);
  371. };
  372. Table.prototype.createToolbar = function() {
  373. // Insert the toolbar
  374. // TODO move this into a separate component
  375. var $anchor = this._getToolbarAnchor();
  376. var $toolbar = this._getToolbar($anchor);
  377. if (!$toolbar.length) {
  378. $toolbar = $("<div>")
  379. .addClass(classes.toolbar)
  380. .insertBefore($anchor);
  381. }
  382. this.$toolbar = $toolbar;
  383. if (this.mode) {
  384. this.$toolbar.addClass("tablesaw-mode-" + this.mode);
  385. }
  386. };
  387. Table.prototype.destroy = function() {
  388. // Don’t remove the toolbar, just erase the classes on it.
  389. // Some of the table features are not yet destroy-friendly.
  390. this._getToolbar().each(function() {
  391. this.className = this.className.replace(/\btablesaw-mode\-\w*\b/gi, "");
  392. });
  393. var tableId = this.$table.attr("id");
  394. $(document).off("." + tableId);
  395. $(window).off("." + tableId);
  396. // other plugins
  397. this.$table.trigger(events.destroy, [this]);
  398. this.$table.removeData(pluginName);
  399. };
  400. // Collection method.
  401. $.fn[pluginName] = function() {
  402. return this.each(function() {
  403. var $t = $(this);
  404. if ($t.data(pluginName)) {
  405. return;
  406. }
  407. new Table(this);
  408. });
  409. };
  410. var $doc = $(document);
  411. $doc.on("enhance.tablesaw", function(e) {
  412. // Cut the mustard
  413. if (Tablesaw.mustard) {
  414. var $target = $(e.target);
  415. if ($target.parent().length) {
  416. $target = $target.parent();
  417. }
  418. $target
  419. .find(initSelector)
  420. .filter(initFilterSelector)
  421. [pluginName]();
  422. }
  423. });
  424. // Avoid a resize during scroll:
  425. // Some Mobile devices trigger a resize during scroll (sometimes when
  426. // doing elastic stretch at the end of the document or from the
  427. // location bar hide)
  428. var isScrolling = false;
  429. var scrollTimeout;
  430. $doc.on("scroll.tablesaw", function() {
  431. isScrolling = true;
  432. window.clearTimeout(scrollTimeout);
  433. scrollTimeout = window.setTimeout(function() {
  434. isScrolling = false;
  435. }, 300); // must be greater than the resize timeout below
  436. });
  437. var resizeTimeout;
  438. $(window).on("resize", function() {
  439. if (!isScrolling) {
  440. window.clearTimeout(resizeTimeout);
  441. resizeTimeout = window.setTimeout(function() {
  442. $doc.trigger(events.resize);
  443. }, 150); // must be less than the scrolling timeout above.
  444. }
  445. });
  446. Tablesaw.Table = Table;
  447. })();
  448. (function() {
  449. var classes = {
  450. stackTable: "tablesaw-stack",
  451. cellLabels: "tablesaw-cell-label",
  452. cellContentLabels: "tablesaw-cell-content"
  453. };
  454. var data = {
  455. key: "tablesaw-stack"
  456. };
  457. var attrs = {
  458. labelless: "data-tablesaw-no-labels",
  459. hideempty: "data-tablesaw-hide-empty"
  460. };
  461. var Stack = function(element, tablesaw) {
  462. this.tablesaw = tablesaw;
  463. this.$table = $(element);
  464. this.labelless = this.$table.is("[" + attrs.labelless + "]");
  465. this.hideempty = this.$table.is("[" + attrs.hideempty + "]");
  466. this.$table.data(data.key, this);
  467. };
  468. Stack.prototype.init = function() {
  469. this.$table.addClass(classes.stackTable);
  470. if (this.labelless) {
  471. return;
  472. }
  473. var self = this;
  474. this.$table
  475. .find("th, td")
  476. .filter(function() {
  477. return !$(this).closest("thead").length;
  478. })
  479. .filter(function() {
  480. return (
  481. !$(this).is("[" + attrs.labelless + "]") &&
  482. !$(this)
  483. .closest("tr")
  484. .is("[" + attrs.labelless + "]") &&
  485. (!self.hideempty || !!$(this).html())
  486. );
  487. })
  488. .each(function() {
  489. var $newHeader = $(document.createElement("b")).addClass(classes.cellLabels);
  490. var $cell = $(this);
  491. $(self.tablesaw._findPrimaryHeadersForCell(this)).each(function(index) {
  492. var $header = $(this.cloneNode(true));
  493. // TODO decouple from sortable better
  494. // Changed from .text() in https://github.com/filamentgroup/tablesaw/commit/b9c12a8f893ec192830ec3ba2d75f062642f935b
  495. // to preserve structural html in headers, like <a>
  496. var $sortableButton = $header.find(".tablesaw-sortable-btn");
  497. $header.find(".tablesaw-sortable-arrow").remove();
  498. // TODO decouple from checkall better
  499. var $checkall = $header.find("[data-tablesaw-checkall]");
  500. $checkall.closest("label").remove();
  501. if ($checkall.length) {
  502. $newHeader = $([]);
  503. return;
  504. }
  505. if (index > 0) {
  506. $newHeader.append(document.createTextNode(", "));
  507. }
  508. var parentNode = $sortableButton.length ? $sortableButton[0] : $header[0];
  509. var el;
  510. while ((el = parentNode.firstChild)) {
  511. $newHeader[0].appendChild(el);
  512. }
  513. });
  514. if ($newHeader.length && !$cell.find("." + classes.cellContentLabels).length) {
  515. $cell.wrapInner("<span class='" + classes.cellContentLabels + "'></span>");
  516. }
  517. // Update if already exists.
  518. var $label = $cell.find("." + classes.cellLabels);
  519. if (!$label.length) {
  520. $cell.prepend(document.createTextNode(" "));
  521. $cell.prepend($newHeader);
  522. } else {
  523. // only if changed
  524. $label.replaceWith($newHeader);
  525. }
  526. });
  527. };
  528. Stack.prototype.destroy = function() {
  529. this.$table.removeClass(classes.stackTable);
  530. this.$table.find("." + classes.cellLabels).remove();
  531. this.$table.find("." + classes.cellContentLabels).each(function() {
  532. $(this).replaceWith($(this.childNodes));
  533. });
  534. };
  535. // on tablecreate, init
  536. $(document)
  537. .on(Tablesaw.events.create, function(e, tablesaw) {
  538. if (tablesaw.mode === "stack") {
  539. var table = new Stack(tablesaw.table, tablesaw);
  540. table.init();
  541. }
  542. })
  543. .on(Tablesaw.events.refresh, function(e, tablesaw) {
  544. if (tablesaw.mode === "stack") {
  545. $(tablesaw.table)
  546. .data(data.key)
  547. .init();
  548. }
  549. })
  550. .on(Tablesaw.events.destroy, function(e, tablesaw) {
  551. if (tablesaw.mode === "stack") {
  552. $(tablesaw.table)
  553. .data(data.key)
  554. .destroy();
  555. }
  556. });
  557. Tablesaw.Stack = Stack;
  558. })();
  559. (function() {
  560. var pluginName = "tablesawbtn",
  561. methods = {
  562. _create: function() {
  563. return $(this).each(function() {
  564. $(this)
  565. .trigger("beforecreate." + pluginName)
  566. [pluginName]("_init")
  567. .trigger("create." + pluginName);
  568. });
  569. },
  570. _init: function() {
  571. var oEl = $(this),
  572. sel = this.getElementsByTagName("select")[0];
  573. if (sel) {
  574. // TODO next major version: remove .btn-select
  575. $(this)
  576. .addClass("btn-select tablesaw-btn-select")
  577. [pluginName]("_select", sel);
  578. }
  579. return oEl;
  580. },
  581. _select: function(sel) {
  582. var update = function(oEl, sel) {
  583. var opts = $(sel).find("option");
  584. var label = document.createElement("span");
  585. var el;
  586. var children;
  587. var found = false;
  588. label.setAttribute("aria-hidden", "true");
  589. label.innerHTML = "&#160;";
  590. opts.each(function() {
  591. var opt = this;
  592. if (opt.selected) {
  593. label.innerHTML = opt.text;
  594. }
  595. });
  596. children = oEl.childNodes;
  597. if (opts.length > 0) {
  598. for (var i = 0, l = children.length; i < l; i++) {
  599. el = children[i];
  600. if (el && el.nodeName.toUpperCase() === "SPAN") {
  601. oEl.replaceChild(label, el);
  602. found = true;
  603. }
  604. }
  605. if (!found) {
  606. oEl.insertBefore(label, oEl.firstChild);
  607. }
  608. }
  609. };
  610. update(this, sel);
  611. // todo should this be tablesawrefresh?
  612. $(this).on("change refresh", function() {
  613. update(this, sel);
  614. });
  615. }
  616. };
  617. // Collection method.
  618. $.fn[pluginName] = function(arrg, a, b, c) {
  619. return this.each(function() {
  620. // if it's a method
  621. if (arrg && typeof arrg === "string") {
  622. return $.fn[pluginName].prototype[arrg].call(this, a, b, c);
  623. }
  624. // don't re-init
  625. if ($(this).data(pluginName + "active")) {
  626. return $(this);
  627. }
  628. $(this).data(pluginName + "active", true);
  629. $.fn[pluginName].prototype._create.call(this);
  630. });
  631. };
  632. // add methods
  633. $.extend($.fn[pluginName].prototype, methods);
  634. // TODO OOP this and add to Tablesaw object
  635. })();
  636. (function() {
  637. var data = {
  638. key: "tablesaw-coltoggle"
  639. };
  640. var ColumnToggle = function(element) {
  641. this.$table = $(element);
  642. if (!this.$table.length) {
  643. return;
  644. }
  645. this.tablesaw = this.$table.data("tablesaw");
  646. this.attributes = {
  647. btnTarget: "data-tablesaw-columntoggle-btn-target",
  648. set: "data-tablesaw-columntoggle-set"
  649. };
  650. this.classes = {
  651. columnToggleTable: "tablesaw-columntoggle",
  652. columnBtnContain: "tablesaw-columntoggle-btnwrap tablesaw-advance",
  653. columnBtn: "tablesaw-columntoggle-btn tablesaw-nav-btn down",
  654. popup: "tablesaw-columntoggle-popup",
  655. priorityPrefix: "tablesaw-priority-"
  656. };
  657. this.set = [];
  658. this.$headers = this.tablesaw._getPrimaryHeaderCells();
  659. this.$table.data(data.key, this);
  660. };
  661. // Column Toggle Sets (one column chooser can control multiple tables)
  662. ColumnToggle.prototype.initSet = function() {
  663. var set = this.$table.attr(this.attributes.set);
  664. if (set) {
  665. // Should not include the current table
  666. var table = this.$table[0];
  667. this.set = $("table[" + this.attributes.set + "='" + set + "']")
  668. .filter(function() {
  669. return this !== table;
  670. })
  671. .get();
  672. }
  673. };
  674. ColumnToggle.prototype.init = function() {
  675. if (!this.$table.length) {
  676. return;
  677. }
  678. var tableId,
  679. id,
  680. $menuButton,
  681. $popup,
  682. $menu,
  683. $btnContain,
  684. self = this;
  685. var cfg = this.tablesaw.getConfig({
  686. getColumnToggleLabelTemplate: function(text) {
  687. return "<label><input type='checkbox' checked>" + text + "</label>";
  688. }
  689. });
  690. this.$table.addClass(this.classes.columnToggleTable);
  691. tableId = this.$table.attr("id");
  692. id = tableId + "-popup";
  693. $btnContain = $("<div class='" + this.classes.columnBtnContain + "'></div>");
  694. // TODO next major version: remove .btn
  695. $menuButton = $(
  696. "<a href='#" +
  697. id +
  698. "' class='btn tablesaw-btn btn-micro " +
  699. this.classes.columnBtn +
  700. "' data-popup-link>" +
  701. "<span>" +
  702. Tablesaw.i18n.columnToggleButton +
  703. "</span></a>"
  704. );
  705. $popup = $("<div class='" + this.classes.popup + "' id='" + id + "'></div>");
  706. $menu = $("<div class='tablesaw-btn-group'></div>");
  707. this.$popup = $popup;
  708. var hasNonPersistentHeaders = false;
  709. this.$headers.each(function() {
  710. var $this = $(this),
  711. priority = $this.attr("data-tablesaw-priority"),
  712. $cells = self.tablesaw._$getCells(this);
  713. if (priority && priority !== "persist") {
  714. $cells.addClass(self.classes.priorityPrefix + priority);
  715. $(cfg.getColumnToggleLabelTemplate($this.text()))
  716. .appendTo($menu)
  717. .find('input[type="checkbox"]')
  718. .data("tablesaw-header", this);
  719. hasNonPersistentHeaders = true;
  720. }
  721. });
  722. if (!hasNonPersistentHeaders) {
  723. $menu.append("<label>" + Tablesaw.i18n.columnToggleError + "</label>");
  724. }
  725. $menu.appendTo($popup);
  726. function onToggleCheckboxChange(checkbox) {
  727. var checked = checkbox.checked;
  728. var header = self.getHeaderFromCheckbox(checkbox);
  729. var $cells = self.tablesaw._$getCells(header);
  730. $cells[!checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellhidden");
  731. $cells[checked ? "addClass" : "removeClass"]("tablesaw-toggle-cellvisible");
  732. self.updateColspanCells(header, checked);
  733. self.$table.trigger("tablesawcolumns");
  734. }
  735. // bind change event listeners to inputs - TODO: move to a private method?
  736. $menu.find('input[type="checkbox"]').on("change", function(e) {
  737. onToggleCheckboxChange(e.target);
  738. if (self.set.length) {
  739. var index;
  740. $(self.$popup)
  741. .find("input[type='checkbox']")
  742. .each(function(j) {
  743. if (this === e.target) {
  744. index = j;
  745. return false;
  746. }
  747. });
  748. $(self.set).each(function() {
  749. var checkbox = $(this)
  750. .data(data.key)
  751. .$popup.find("input[type='checkbox']")
  752. .get(index);
  753. if (checkbox) {
  754. checkbox.checked = e.target.checked;
  755. onToggleCheckboxChange(checkbox);
  756. }
  757. });
  758. }
  759. });
  760. $menuButton.appendTo($btnContain);
  761. // Use a different target than the toolbar
  762. var $btnTarget = $(this.$table.attr(this.attributes.btnTarget));
  763. $btnContain.appendTo($btnTarget.length ? $btnTarget : this.tablesaw.$toolbar);
  764. function closePopup(event) {
  765. // Click came from inside the popup, ignore.
  766. if (event && $(event.target).closest("." + self.classes.popup).length) {
  767. return;
  768. }
  769. $(document).off("click." + tableId);
  770. $menuButton.removeClass("up").addClass("down");
  771. $btnContain.removeClass("visible");
  772. }
  773. var closeTimeout;
  774. function openPopup() {
  775. $btnContain.addClass("visible");
  776. $menuButton.removeClass("down").addClass("up");
  777. $(document).off("click." + tableId, closePopup);
  778. window.clearTimeout(closeTimeout);
  779. closeTimeout = window.setTimeout(function() {
  780. $(document).on("click." + tableId, closePopup);
  781. }, 15);
  782. }
  783. $menuButton.on("click.tablesaw", function(event) {
  784. event.preventDefault();
  785. if (!$btnContain.is(".visible")) {
  786. openPopup();
  787. } else {
  788. closePopup();
  789. }
  790. });
  791. $popup.appendTo($btnContain);
  792. this.$menu = $menu;
  793. // Fix for iOS not rendering shadows correctly when using `-webkit-overflow-scrolling`
  794. var $overflow = this.$table.closest(".tablesaw-overflow");
  795. if ($overflow.css("-webkit-overflow-scrolling")) {
  796. var timeout;
  797. $overflow.on("scroll", function() {
  798. var $div = $(this);
  799. window.clearTimeout(timeout);
  800. timeout = window.setTimeout(function() {
  801. $div.css("-webkit-overflow-scrolling", "auto");
  802. window.setTimeout(function() {
  803. $div.css("-webkit-overflow-scrolling", "touch");
  804. }, 0);
  805. }, 100);
  806. });
  807. }
  808. $(window).on(Tablesaw.events.resize + "." + tableId, function() {
  809. self.refreshToggle();
  810. });
  811. this.initSet();
  812. this.refreshToggle();
  813. };
  814. ColumnToggle.prototype.getHeaderFromCheckbox = function(checkbox) {
  815. return $(checkbox).data("tablesaw-header");
  816. };
  817. ColumnToggle.prototype.refreshToggle = function() {
  818. var self = this;
  819. var invisibleColumns = 0;
  820. this.$menu.find("input").each(function() {
  821. var header = self.getHeaderFromCheckbox(this);
  822. this.checked =
  823. self.tablesaw
  824. ._$getCells(header)
  825. .eq(0)
  826. .css("display") === "table-cell";
  827. });
  828. this.updateColspanCells();
  829. };
  830. ColumnToggle.prototype.updateColspanCells = function(header, userAction) {
  831. this.tablesaw.updateColspanCells("tablesaw-toggle-cellhidden", header, userAction);
  832. };
  833. ColumnToggle.prototype.destroy = function() {
  834. this.$table.removeClass(this.classes.columnToggleTable);
  835. this.$table.find("th, td").each(function() {
  836. var $cell = $(this);
  837. $cell.removeClass("tablesaw-toggle-cellhidden").removeClass("tablesaw-toggle-cellvisible");
  838. this.className = this.className.replace(/\bui\-table\-priority\-\d\b/g, "");
  839. });
  840. };
  841. // on tablecreate, init
  842. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  843. if (tablesaw.mode === "columntoggle") {
  844. var table = new ColumnToggle(tablesaw.table);
  845. table.init();
  846. }
  847. });
  848. $(document).on(Tablesaw.events.destroy, function(e, tablesaw) {
  849. if (tablesaw.mode === "columntoggle") {
  850. $(tablesaw.table)
  851. .data(data.key)
  852. .destroy();
  853. }
  854. });
  855. $(document).on(Tablesaw.events.refresh, function(e, tablesaw) {
  856. if (tablesaw.mode === "columntoggle") {
  857. $(tablesaw.table)
  858. .data(data.key)
  859. .refreshToggle();
  860. }
  861. });
  862. Tablesaw.ColumnToggle = ColumnToggle;
  863. })();
  864. (function() {
  865. function getSortValue(cell) {
  866. var text = [];
  867. $(cell.childNodes).each(function() {
  868. var $el = $(this);
  869. if ($el.is("input, select")) {
  870. text.push($el.val());
  871. } else if ($el.is(".tablesaw-cell-label")) {
  872. } else {
  873. text.push(($el.text() || "").replace(/^\s+|\s+$/g, ""));
  874. }
  875. });
  876. return text.join("");
  877. }
  878. var pluginName = "tablesaw-sortable",
  879. initSelector = "table[data-" + pluginName + "]",
  880. sortableSwitchSelector = "[data-" + pluginName + "-switch]",
  881. attrs = {
  882. sortCol: "data-tablesaw-sortable-col",
  883. defaultCol: "data-tablesaw-sortable-default-col",
  884. numericCol: "data-tablesaw-sortable-numeric",
  885. subRow: "data-tablesaw-subrow",
  886. ignoreRow: "data-tablesaw-ignorerow"
  887. },
  888. classes = {
  889. head: pluginName + "-head",
  890. ascend: pluginName + "-ascending",
  891. descend: pluginName + "-descending",
  892. switcher: pluginName + "-switch",
  893. tableToolbar: "tablesaw-bar-section",
  894. sortButton: pluginName + "-btn"
  895. },
  896. methods = {
  897. _create: function(o) {
  898. return $(this).each(function() {
  899. var init = $(this).data(pluginName + "-init");
  900. if (init) {
  901. return false;
  902. }
  903. $(this)
  904. .data(pluginName + "-init", true)
  905. .trigger("beforecreate." + pluginName)
  906. [pluginName]("_init", o)
  907. .trigger("create." + pluginName);
  908. });
  909. },
  910. _init: function() {
  911. var el = $(this);
  912. var tblsaw = el.data("tablesaw");
  913. var heads;
  914. var $switcher;
  915. function addClassToHeads(h) {
  916. $.each(h, function(i, v) {
  917. $(v).addClass(classes.head);
  918. });
  919. }
  920. function makeHeadsActionable(h, fn) {
  921. $.each(h, function(i, col) {
  922. var b = $("<button class='" + classes.sortButton + "'/>");
  923. b.on("click", { col: col }, fn);
  924. $(col)
  925. .wrapInner(b)
  926. .find("button")
  927. .append("<span class='tablesaw-sortable-arrow'>");
  928. });
  929. }
  930. function clearOthers(headcells) {
  931. $.each(headcells, function(i, v) {
  932. var col = $(v);
  933. col.removeAttr(attrs.defaultCol);
  934. col.removeClass(classes.ascend);
  935. col.removeClass(classes.descend);
  936. });
  937. }
  938. function headsOnAction(e) {
  939. if ($(e.target).is("a[href]")) {
  940. return;
  941. }
  942. e.stopPropagation();
  943. var headCell = $(e.target).closest("[" + attrs.sortCol + "]"),
  944. v = e.data.col,
  945. newSortValue = heads.index(headCell[0]);
  946. clearOthers(
  947. headCell
  948. .closest("thead")
  949. .find("th")
  950. .filter(function() {
  951. return this !== headCell[0];
  952. })
  953. );
  954. if (headCell.is("." + classes.descend) || !headCell.is("." + classes.ascend)) {
  955. el[pluginName]("sortBy", v, true);
  956. newSortValue += "_asc";
  957. } else {
  958. el[pluginName]("sortBy", v);
  959. newSortValue += "_desc";
  960. }
  961. if ($switcher) {
  962. $switcher
  963. .find("select")
  964. .val(newSortValue)
  965. .trigger("refresh");
  966. }
  967. e.preventDefault();
  968. }
  969. function handleDefault(heads) {
  970. $.each(heads, function(idx, el) {
  971. var $el = $(el);
  972. if ($el.is("[" + attrs.defaultCol + "]")) {
  973. if (!$el.is("." + classes.descend)) {
  974. $el.addClass(classes.ascend);
  975. }
  976. }
  977. });
  978. }
  979. function addSwitcher(heads) {
  980. $switcher = $("<div>")
  981. .addClass(classes.switcher)
  982. .addClass(classes.tableToolbar);
  983. var html = ["<label>" + Tablesaw.i18n.sort + ":"];
  984. // TODO next major version: remove .btn
  985. html.push('<span class="btn tablesaw-btn"><select>');
  986. heads.each(function(j) {
  987. var $t = $(this);
  988. var isDefaultCol = $t.is("[" + attrs.defaultCol + "]");
  989. var isDescending = $t.is("." + classes.descend);
  990. var hasNumericAttribute = $t.is("[" + attrs.numericCol + "]");
  991. var numericCount = 0;
  992. // Check only the first four rows to see if the column is numbers.
  993. var numericCountMax = 5;
  994. $(this.cells.slice(0, numericCountMax)).each(function() {
  995. if (!isNaN(parseInt(getSortValue(this), 10))) {
  996. numericCount++;
  997. }
  998. });
  999. var isNumeric = numericCount === numericCountMax;
  1000. if (!hasNumericAttribute) {
  1001. $t.attr(attrs.numericCol, isNumeric ? "" : "false");
  1002. }
  1003. html.push(
  1004. "<option" +
  1005. (isDefaultCol && !isDescending ? " selected" : "") +
  1006. ' value="' +
  1007. j +
  1008. '_asc">' +
  1009. $t.text() +
  1010. " " +
  1011. (isNumeric ? "&#x2191;" : "(A-Z)") +
  1012. "</option>"
  1013. );
  1014. html.push(
  1015. "<option" +
  1016. (isDefaultCol && isDescending ? " selected" : "") +
  1017. ' value="' +
  1018. j +
  1019. '_desc">' +
  1020. $t.text() +
  1021. " " +
  1022. (isNumeric ? "&#x2193;" : "(Z-A)") +
  1023. "</option>"
  1024. );
  1025. });
  1026. html.push("</select></span></label>");
  1027. $switcher.html(html.join(""));
  1028. var $firstChild = tblsaw.$toolbar.children().eq(0);
  1029. if ($firstChild.length) {
  1030. $switcher.insertBefore($firstChild);
  1031. } else {
  1032. $switcher.appendTo(tblsaw.$toolbar);
  1033. }
  1034. $switcher.find(".tablesaw-btn").tablesawbtn();
  1035. $switcher.find("select").on("change", function() {
  1036. var val = $(this)
  1037. .val()
  1038. .split("_"),
  1039. head = heads.eq(val[0]);
  1040. clearOthers(head.siblings());
  1041. el[pluginName]("sortBy", head.get(0), val[1] === "asc");
  1042. });
  1043. }
  1044. el.addClass(pluginName);
  1045. heads = el
  1046. .children()
  1047. .filter("thead")
  1048. .find("th[" + attrs.sortCol + "]");
  1049. addClassToHeads(heads);
  1050. makeHeadsActionable(heads, headsOnAction);
  1051. handleDefault(heads);
  1052. if (el.is(sortableSwitchSelector)) {
  1053. addSwitcher(heads);
  1054. }
  1055. },
  1056. sortRows: function(rows, colNum, ascending, col, tbody) {
  1057. function convertCells(cellArr, belongingToTbody) {
  1058. var cells = [];
  1059. $.each(cellArr, function(i, cell) {
  1060. var row = cell.parentNode;
  1061. var $row = $(row);
  1062. // next row is a subrow
  1063. var subrows = [];
  1064. var $next = $row.next();
  1065. while ($next.is("[" + attrs.subRow + "]")) {
  1066. subrows.push($next[0]);
  1067. $next = $next.next();
  1068. }
  1069. var tbody = row.parentNode;
  1070. // current row is a subrow
  1071. if ($row.is("[" + attrs.subRow + "]")) {
  1072. } else if (tbody === belongingToTbody) {
  1073. cells.push({
  1074. element: cell,
  1075. cell: getSortValue(cell),
  1076. row: row,
  1077. subrows: subrows.length ? subrows : null,
  1078. ignored: $row.is("[" + attrs.ignoreRow + "]")
  1079. });
  1080. }
  1081. });
  1082. return cells;
  1083. }
  1084. function getSortFxn(ascending, forceNumeric) {
  1085. var fn,
  1086. regex = /[^\-\+\d\.]/g;
  1087. if (ascending) {
  1088. fn = function(a, b) {
  1089. if (a.ignored || b.ignored) {
  1090. return 0;
  1091. }
  1092. if (forceNumeric) {
  1093. return (
  1094. parseFloat(a.cell.replace(regex, "")) - parseFloat(b.cell.replace(regex, ""))
  1095. );
  1096. } else {
  1097. return a.cell.toLowerCase() > b.cell.toLowerCase() ? 1 : -1;
  1098. }
  1099. };
  1100. } else {
  1101. fn = function(a, b) {
  1102. if (a.ignored || b.ignored) {
  1103. return 0;
  1104. }
  1105. if (forceNumeric) {
  1106. return (
  1107. parseFloat(b.cell.replace(regex, "")) - parseFloat(a.cell.replace(regex, ""))
  1108. );
  1109. } else {
  1110. return a.cell.toLowerCase() < b.cell.toLowerCase() ? 1 : -1;
  1111. }
  1112. };
  1113. }
  1114. return fn;
  1115. }
  1116. function convertToRows(sorted) {
  1117. var newRows = [],
  1118. i,
  1119. l;
  1120. for (i = 0, l = sorted.length; i < l; i++) {
  1121. newRows.push(sorted[i].row);
  1122. if (sorted[i].subrows) {
  1123. newRows.push(sorted[i].subrows);
  1124. }
  1125. }
  1126. return newRows;
  1127. }
  1128. var fn;
  1129. var sorted;
  1130. var cells = convertCells(col.cells, tbody);
  1131. var customFn = $(col).data("tablesaw-sort");
  1132. fn =
  1133. (customFn && typeof customFn === "function" ? customFn(ascending) : false) ||
  1134. getSortFxn(
  1135. ascending,
  1136. $(col).is("[" + attrs.numericCol + "]") &&
  1137. !$(col).is("[" + attrs.numericCol + '="false"]')
  1138. );
  1139. sorted = cells.sort(fn);
  1140. rows = convertToRows(sorted);
  1141. return rows;
  1142. },
  1143. makeColDefault: function(col, a) {
  1144. var c = $(col);
  1145. c.attr(attrs.defaultCol, "true");
  1146. if (a) {
  1147. c.removeClass(classes.descend);
  1148. c.addClass(classes.ascend);
  1149. } else {
  1150. c.removeClass(classes.ascend);
  1151. c.addClass(classes.descend);
  1152. }
  1153. },
  1154. sortBy: function(col, ascending) {
  1155. var el = $(this);
  1156. var colNum;
  1157. var tbl = el.data("tablesaw");
  1158. tbl.$tbody.each(function() {
  1159. var tbody = this;
  1160. var $tbody = $(this);
  1161. var rows = tbl.getBodyRows(tbody);
  1162. var sortedRows;
  1163. var map = tbl.headerMapping[0];
  1164. var j, k;
  1165. // find the column number that we’re sorting
  1166. for (j = 0, k = map.length; j < k; j++) {
  1167. if (map[j] === col) {
  1168. colNum = j;
  1169. break;
  1170. }
  1171. }
  1172. sortedRows = el[pluginName]("sortRows", rows, colNum, ascending, col, tbody);
  1173. // replace Table rows
  1174. for (j = 0, k = sortedRows.length; j < k; j++) {
  1175. $tbody.append(sortedRows[j]);
  1176. }
  1177. });
  1178. el[pluginName]("makeColDefault", col, ascending);
  1179. el.trigger("tablesaw-sorted");
  1180. }
  1181. };
  1182. // Collection method.
  1183. $.fn[pluginName] = function(arrg) {
  1184. var args = Array.prototype.slice.call(arguments, 1),
  1185. returnVal;
  1186. // if it's a method
  1187. if (arrg && typeof arrg === "string") {
  1188. returnVal = $.fn[pluginName].prototype[arrg].apply(this[0], args);
  1189. return typeof returnVal !== "undefined" ? returnVal : $(this);
  1190. }
  1191. // check init
  1192. if (!$(this).data(pluginName + "-active")) {
  1193. $(this).data(pluginName + "-active", true);
  1194. $.fn[pluginName].prototype._create.call(this, arrg);
  1195. }
  1196. return $(this);
  1197. };
  1198. // add methods
  1199. $.extend($.fn[pluginName].prototype, methods);
  1200. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  1201. if (Tablesaw.$table.is(initSelector)) {
  1202. Tablesaw.$table[pluginName]();
  1203. }
  1204. });
  1205. // TODO OOP this and add to Tablesaw object
  1206. })();
  1207. (function() {
  1208. var classes = {
  1209. hideBtn: "disabled",
  1210. persistWidths: "tablesaw-fix-persist",
  1211. hiddenCol: "tablesaw-swipe-cellhidden",
  1212. persistCol: "tablesaw-swipe-cellpersist",
  1213. allColumnsVisible: "tablesaw-all-cols-visible"
  1214. };
  1215. var attrs = {
  1216. disableTouchEvents: "data-tablesaw-no-touch",
  1217. ignorerow: "data-tablesaw-ignorerow",
  1218. subrow: "data-tablesaw-subrow"
  1219. };
  1220. function createSwipeTable(tbl, $table) {
  1221. var tblsaw = $table.data("tablesaw");
  1222. var $btns = $("<div class='tablesaw-advance'></div>");
  1223. // TODO next major version: remove .btn
  1224. var $prevBtn = $(
  1225. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro left'>" +
  1226. Tablesaw.i18n.swipePreviousColumn +
  1227. "</a>"
  1228. ).appendTo($btns);
  1229. // TODO next major version: remove .btn
  1230. var $nextBtn = $(
  1231. "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro right'>" +
  1232. Tablesaw.i18n.swipeNextColumn +
  1233. "</a>"
  1234. ).appendTo($btns);
  1235. var $headerCells = tbl._getPrimaryHeaderCells();
  1236. var $headerCellsNoPersist = $headerCells.not('[data-tablesaw-priority="persist"]');
  1237. var headerWidths = [];
  1238. var headerWidthsNoPersist = [];
  1239. var $head = $(document.head || "head");
  1240. var tableId = $table.attr("id");
  1241. if (!$headerCells.length) {
  1242. throw new Error("tablesaw swipe: no header cells found.");
  1243. }
  1244. $table.addClass("tablesaw-swipe");
  1245. function initMinHeaderWidths() {
  1246. $table.css({
  1247. width: "1px"
  1248. });
  1249. // remove any hidden columns
  1250. $table.find("." + classes.hiddenCol).removeClass(classes.hiddenCol);
  1251. headerWidths = [];
  1252. headerWidthsNoPersist = [];
  1253. // Calculate initial widths
  1254. $headerCells.each(function() {
  1255. var width = this.offsetWidth;
  1256. headerWidths.push(width);
  1257. if (!isPersistent(this)) {
  1258. headerWidthsNoPersist.push(width);
  1259. }
  1260. });
  1261. // reset props
  1262. $table.css({
  1263. width: ""
  1264. });
  1265. }
  1266. initMinHeaderWidths();
  1267. $btns.appendTo(tblsaw.$toolbar);
  1268. if (!tableId) {
  1269. tableId = "tableswipe-" + Math.round(Math.random() * 10000);
  1270. $table.attr("id", tableId);
  1271. }
  1272. function showColumn(headerCell) {
  1273. tblsaw._$getCells(headerCell).removeClass(classes.hiddenCol);
  1274. }
  1275. function hideColumn(headerCell) {
  1276. tblsaw._$getCells(headerCell).addClass(classes.hiddenCol);
  1277. }
  1278. function persistColumn(headerCell) {
  1279. tblsaw._$getCells(headerCell).addClass(classes.persistCol);
  1280. }
  1281. function isPersistent(headerCell) {
  1282. return $(headerCell).is('[data-tablesaw-priority="persist"]');
  1283. }
  1284. function unmaintainWidths() {
  1285. $table.removeClass(classes.persistWidths);
  1286. $("#" + tableId + "-persist").remove();
  1287. }
  1288. function maintainWidths() {
  1289. var prefix = "#" + tableId + ".tablesaw-swipe ";
  1290. var styles = [];
  1291. var tableWidth = $table.width();
  1292. var tableWidthNoPersistantColumns = tableWidth;
  1293. var hash = [];
  1294. var newHash;
  1295. // save persistent column widths (as long as they take up less than 75% of table width)
  1296. $headerCells.each(function(index) {
  1297. var width;
  1298. if (isPersistent(this)) {
  1299. width = this.offsetWidth;
  1300. tableWidthNoPersistantColumns -= width;
  1301. if (width < tableWidth * 0.75) {
  1302. hash.push(index + "-" + width);
  1303. styles.push(
  1304. prefix +
  1305. " ." +
  1306. classes.persistCol +
  1307. ":nth-child(" +
  1308. (index + 1) +
  1309. ") { width: " +
  1310. width +
  1311. "px; }"
  1312. );
  1313. }
  1314. }
  1315. });
  1316. newHash = hash.join("_");
  1317. if (styles.length) {
  1318. $table.addClass(classes.persistWidths);
  1319. var $style = $("#" + tableId + "-persist");
  1320. // If style element not yet added OR if the widths have changed
  1321. if (!$style.length || $style.data("tablesaw-hash") !== newHash) {
  1322. // Remove existing
  1323. $style.remove();
  1324. $("<style>" + styles.join("\n") + "</style>")
  1325. .attr("id", tableId + "-persist")
  1326. .data("tablesaw-hash", newHash)
  1327. .appendTo($head);
  1328. }
  1329. }
  1330. return tableWidthNoPersistantColumns;
  1331. }
  1332. function getNext() {
  1333. var next = [];
  1334. var checkFound;
  1335. $headerCellsNoPersist.each(function(i) {
  1336. var $t = $(this);
  1337. var isHidden = $t.css("display") === "none" || $t.is("." + classes.hiddenCol);
  1338. if (!isHidden && !checkFound) {
  1339. checkFound = true;
  1340. next[0] = i;
  1341. } else if (isHidden && checkFound) {
  1342. next[1] = i;
  1343. return false;
  1344. }
  1345. });
  1346. return next;
  1347. }
  1348. function getPrev() {
  1349. var next = getNext();
  1350. return [next[1] - 1, next[0] - 1];
  1351. }
  1352. function canNavigate(pair) {
  1353. return pair[1] > -1 && pair[1] < $headerCellsNoPersist.length;
  1354. }
  1355. function matchesMedia() {
  1356. var matchMedia = $table.attr("data-tablesaw-swipe-media");
  1357. return !matchMedia || ("matchMedia" in window && window.matchMedia(matchMedia).matches);
  1358. }
  1359. function fakeBreakpoints() {
  1360. if (!matchesMedia()) {
  1361. return;
  1362. }
  1363. var containerWidth = $table.parent().width(),
  1364. persist = [],
  1365. sum = 0,
  1366. sums = [],
  1367. visibleNonPersistantCount = $headerCells.length;
  1368. $headerCells.each(function(index) {
  1369. var $t = $(this),
  1370. isPersist = $t.is('[data-tablesaw-priority="persist"]');
  1371. persist.push(isPersist);
  1372. sum += headerWidths[index];
  1373. sums.push(sum);
  1374. // is persistent or is hidden
  1375. if (isPersist || sum > containerWidth) {
  1376. visibleNonPersistantCount--;
  1377. }
  1378. });
  1379. // We need at least one column to swipe.
  1380. var needsNonPersistentColumn = visibleNonPersistantCount === 0;
  1381. $headerCells.each(function(index) {
  1382. if (sums[index] > containerWidth) {
  1383. hideColumn(this);
  1384. }
  1385. });
  1386. var firstPersist = true;
  1387. $headerCells.each(function(index) {
  1388. if (persist[index]) {
  1389. // for visual box-shadow
  1390. persistColumn(this);
  1391. if (firstPersist) {
  1392. tblsaw._$getCells(this).css("width", sums[index] + "px");
  1393. firstPersist = false;
  1394. }
  1395. return;
  1396. }
  1397. if (sums[index] <= containerWidth || needsNonPersistentColumn) {
  1398. needsNonPersistentColumn = false;
  1399. showColumn(this);
  1400. tblsaw.updateColspanCells(classes.hiddenCol, this, true);
  1401. }
  1402. });
  1403. unmaintainWidths();
  1404. $table.trigger("tablesawcolumns");
  1405. }
  1406. function goForward() {
  1407. navigate(true);
  1408. }
  1409. function goBackward() {
  1410. navigate(false);
  1411. }
  1412. function navigate(isNavigateForward) {
  1413. var pair;
  1414. if (isNavigateForward) {
  1415. pair = getNext();
  1416. } else {
  1417. pair = getPrev();
  1418. }
  1419. if (canNavigate(pair)) {
  1420. if (isNaN(pair[0])) {
  1421. if (isNavigateForward) {
  1422. pair[0] = 0;
  1423. } else {
  1424. pair[0] = $headerCellsNoPersist.length - 1;
  1425. }
  1426. }
  1427. var roomForColumnsWidth = maintainWidths();
  1428. var hideColumnIndex = pair[0];
  1429. var showColumnIndex = pair[1];
  1430. // Hide one column, show one or more based on how much space was freed up
  1431. var columnToShow;
  1432. var columnToHide = $headerCellsNoPersist.get(hideColumnIndex);
  1433. var wasAtLeastOneColumnShown = false;
  1434. var atLeastOneColumnIsVisible = false;
  1435. hideColumn(columnToHide);
  1436. tblsaw.updateColspanCells(classes.hiddenCol, columnToHide, true);
  1437. var columnIndex = hideColumnIndex + (isNavigateForward ? 1 : -1);
  1438. while (columnIndex >= 0 && columnIndex < headerWidthsNoPersist.length) {
  1439. roomForColumnsWidth -= headerWidthsNoPersist[columnIndex];
  1440. var $columnToShow = $headerCellsNoPersist.eq(columnIndex);
  1441. if ($columnToShow.is(".tablesaw-swipe-cellhidden")) {
  1442. if (roomForColumnsWidth > 0) {
  1443. columnToShow = $columnToShow.get(0);
  1444. wasAtLeastOneColumnShown = true;
  1445. atLeastOneColumnIsVisible = true;
  1446. showColumn(columnToShow);
  1447. tblsaw.updateColspanCells(classes.hiddenCol, columnToShow, false);
  1448. }
  1449. } else {
  1450. atLeastOneColumnIsVisible = true;
  1451. }
  1452. if (isNavigateForward) {
  1453. columnIndex++;
  1454. } else {
  1455. columnIndex--;
  1456. }
  1457. }
  1458. if (!atLeastOneColumnIsVisible) {
  1459. // if no columns are showing, at least show the first one we were aiming for.
  1460. columnToShow = $headerCellsNoPersist.get(showColumnIndex);
  1461. showColumn(columnToShow);
  1462. tblsaw.updateColspanCells(classes.hiddenCol, columnToShow, false);
  1463. } else if (
  1464. !wasAtLeastOneColumnShown &&
  1465. canNavigate(isNavigateForward ? getNext() : getPrev())
  1466. ) {
  1467. // if our one new column was hidden but no new columns were shown, let’s navigate again automatically.
  1468. navigate(isNavigateForward);
  1469. }
  1470. $table.trigger("tablesawcolumns");
  1471. }
  1472. }
  1473. $prevBtn.add($nextBtn).on("click", function(e) {
  1474. if (!!$(e.target).closest($nextBtn).length) {
  1475. goForward();
  1476. } else {
  1477. goBackward();
  1478. }
  1479. e.preventDefault();
  1480. });
  1481. function getCoord(event, key) {
  1482. return (event.touches || event.originalEvent.touches)[0][key];
  1483. }
  1484. if (!$table.is("[" + attrs.disableTouchEvents + "]")) {
  1485. $table.on("touchstart.swipetoggle", function(e) {
  1486. var originX = getCoord(e, "pageX");
  1487. var originY = getCoord(e, "pageY");
  1488. var x;
  1489. var y;
  1490. var scrollTop = window.pageYOffset;
  1491. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  1492. $(this)
  1493. .on("touchmove.swipetoggle", function(e) {
  1494. x = getCoord(e, "pageX");
  1495. y = getCoord(e, "pageY");
  1496. })
  1497. .on("touchend.swipetoggle", function() {
  1498. var cfg = tbl.getConfig({
  1499. swipeHorizontalThreshold: 30,
  1500. swipeVerticalThreshold: 30
  1501. });
  1502. // This config code is a little awkward because shoestring doesn’t support deep $.extend
  1503. // Trying to work around when devs only override one of (not both) horizontalThreshold or
  1504. // verticalThreshold in their TablesawConfig.
  1505. // @TODO major version bump: remove cfg.swipe, move to just use the swipePrefix keys
  1506. var verticalThreshold = cfg.swipe
  1507. ? cfg.swipe.verticalThreshold
  1508. : cfg.swipeVerticalThreshold;
  1509. var horizontalThreshold = cfg.swipe
  1510. ? cfg.swipe.horizontalThreshold
  1511. : cfg.swipeHorizontalThreshold;
  1512. var isPageScrolled = Math.abs(window.pageYOffset - scrollTop) >= verticalThreshold;
  1513. var isVerticalSwipe = Math.abs(y - originY) >= verticalThreshold;
  1514. if (!isVerticalSwipe && !isPageScrolled) {
  1515. if (x - originX < -1 * horizontalThreshold) {
  1516. goForward();
  1517. }
  1518. if (x - originX > horizontalThreshold) {
  1519. goBackward();
  1520. }
  1521. }
  1522. window.setTimeout(function() {
  1523. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  1524. }, 300);
  1525. $(this).off("touchmove.swipetoggle touchend.swipetoggle");
  1526. });
  1527. });
  1528. }
  1529. $table
  1530. .on("tablesawcolumns.swipetoggle", function() {
  1531. var canGoPrev = canNavigate(getPrev());
  1532. var canGoNext = canNavigate(getNext());
  1533. $prevBtn[canGoPrev ? "removeClass" : "addClass"](classes.hideBtn);
  1534. $nextBtn[canGoNext ? "removeClass" : "addClass"](classes.hideBtn);
  1535. tblsaw.$toolbar[!canGoPrev && !canGoNext ? "addClass" : "removeClass"](
  1536. classes.allColumnsVisible
  1537. );
  1538. })
  1539. .on("tablesawnext.swipetoggle", function() {
  1540. goForward();
  1541. })
  1542. .on("tablesawprev.swipetoggle", function() {
  1543. goBackward();
  1544. })
  1545. .on(Tablesaw.events.destroy + ".swipetoggle", function() {
  1546. var $t = $(this);
  1547. $t.removeClass("tablesaw-swipe");
  1548. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  1549. $(window).off(Tablesaw.events.resize, fakeBreakpoints);
  1550. $t.off(".swipetoggle");
  1551. })
  1552. .on(Tablesaw.events.refresh, function() {
  1553. unmaintainWidths();
  1554. initMinHeaderWidths();
  1555. fakeBreakpoints();
  1556. });
  1557. fakeBreakpoints();
  1558. $(window).on(Tablesaw.events.resize, fakeBreakpoints);
  1559. }
  1560. // on tablecreate, init
  1561. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  1562. if (tablesaw.mode === "swipe") {
  1563. createSwipeTable(tablesaw, tablesaw.$table);
  1564. }
  1565. });
  1566. // TODO OOP this and add to Tablesaw object
  1567. })();
  1568. (function() {
  1569. var MiniMap = {
  1570. attr: {
  1571. init: "data-tablesaw-minimap"
  1572. },
  1573. show: function(table) {
  1574. var mq = table.getAttribute(MiniMap.attr.init);
  1575. if (mq === "") {
  1576. // value-less but exists
  1577. return true;
  1578. } else if (mq && "matchMedia" in window) {
  1579. // has a mq value
  1580. return window.matchMedia(mq).matches;
  1581. }
  1582. return false;
  1583. }
  1584. };
  1585. function createMiniMap($table) {
  1586. var tblsaw = $table.data("tablesaw");
  1587. var $btns = $('<div class="tablesaw-advance minimap">');
  1588. var $dotNav = $('<ul class="tablesaw-advance-dots">').appendTo($btns);
  1589. var hideDot = "tablesaw-advance-dots-hide";
  1590. var $headerCells = $table.data("tablesaw")._getPrimaryHeaderCells();
  1591. // populate dots
  1592. $headerCells.each(function() {
  1593. $dotNav.append("<li><i></i></li>");
  1594. });
  1595. $btns.appendTo(tblsaw.$toolbar);
  1596. function showHideNav() {
  1597. if (!MiniMap.show($table[0])) {
  1598. $btns.css("display", "none");
  1599. return;
  1600. }
  1601. $btns.css("display", "block");
  1602. // show/hide dots
  1603. var dots = $dotNav.find("li").removeClass(hideDot);
  1604. $table.find("thead th").each(function(i) {
  1605. if ($(this).css("display") === "none") {
  1606. dots.eq(i).addClass(hideDot);
  1607. }
  1608. });
  1609. }
  1610. // run on init and resize
  1611. showHideNav();
  1612. $(window).on(Tablesaw.events.resize, showHideNav);
  1613. $table
  1614. .on("tablesawcolumns.minimap", function() {
  1615. showHideNav();
  1616. })
  1617. .on(Tablesaw.events.destroy + ".minimap", function() {
  1618. var $t = $(this);
  1619. tblsaw.$toolbar.find(".tablesaw-advance").remove();
  1620. $(window).off(Tablesaw.events.resize, showHideNav);
  1621. $t.off(".minimap");
  1622. });
  1623. }
  1624. // on tablecreate, init
  1625. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  1626. if (
  1627. (tablesaw.mode === "swipe" || tablesaw.mode === "columntoggle") &&
  1628. tablesaw.$table.is("[ " + MiniMap.attr.init + "]")
  1629. ) {
  1630. createMiniMap(tablesaw.$table);
  1631. }
  1632. });
  1633. // TODO OOP this better
  1634. Tablesaw.MiniMap = MiniMap;
  1635. })();
  1636. (function() {
  1637. var S = {
  1638. selectors: {
  1639. init: "table[data-tablesaw-mode-switch]"
  1640. },
  1641. attributes: {
  1642. excludeMode: "data-tablesaw-mode-exclude"
  1643. },
  1644. classes: {
  1645. main: "tablesaw-modeswitch",
  1646. toolbar: "tablesaw-bar-section"
  1647. },
  1648. modes: ["stack", "swipe", "columntoggle"],
  1649. init: function(table) {
  1650. var $table = $(table);
  1651. var tblsaw = $table.data("tablesaw");
  1652. var ignoreMode = $table.attr(S.attributes.excludeMode);
  1653. var $toolbar = tblsaw.$toolbar;
  1654. var $switcher = $("<div>").addClass(S.classes.main + " " + S.classes.toolbar);
  1655. var html = [
  1656. '<label><span class="abbreviated">' +
  1657. Tablesaw.i18n.modeSwitchColumnsAbbreviated +
  1658. '</span><span class="longform">' +
  1659. Tablesaw.i18n.modeSwitchColumns +
  1660. "</span>:"
  1661. ],
  1662. dataMode = $table.attr("data-tablesaw-mode"),
  1663. isSelected;
  1664. // TODO next major version: remove .btn
  1665. html.push('<span class="btn tablesaw-btn"><select>');
  1666. for (var j = 0, k = S.modes.length; j < k; j++) {
  1667. if (ignoreMode && ignoreMode.toLowerCase() === S.modes[j]) {
  1668. continue;
  1669. }
  1670. isSelected = dataMode === S.modes[j];
  1671. html.push(
  1672. "<option" +
  1673. (isSelected ? " selected" : "") +
  1674. ' value="' +
  1675. S.modes[j] +
  1676. '">' +
  1677. Tablesaw.i18n.modes[j] +
  1678. "</option>"
  1679. );
  1680. }
  1681. html.push("</select></span></label>");
  1682. $switcher.html(html.join(""));
  1683. var $otherToolbarItems = $toolbar.find(".tablesaw-advance").eq(0);
  1684. if ($otherToolbarItems.length) {
  1685. $switcher.insertBefore($otherToolbarItems);
  1686. } else {
  1687. $switcher.appendTo($toolbar);
  1688. }
  1689. $switcher.find(".tablesaw-btn").tablesawbtn();
  1690. $switcher.find("select").on("change", function(event) {
  1691. return S.onModeChange.call(table, event, $(this).val());
  1692. });
  1693. },
  1694. onModeChange: function(event, val) {
  1695. var $table = $(this);
  1696. var tblsaw = $table.data("tablesaw");
  1697. var $switcher = tblsaw.$toolbar.find("." + S.classes.main);
  1698. $switcher.remove();
  1699. tblsaw.destroy();
  1700. $table.attr("data-tablesaw-mode", val);
  1701. $table.tablesaw();
  1702. }
  1703. };
  1704. $(document).on(Tablesaw.events.create, function(e, Tablesaw) {
  1705. if (Tablesaw.$table.is(S.selectors.init)) {
  1706. S.init(Tablesaw.table);
  1707. }
  1708. });
  1709. // TODO OOP this and add to Tablesaw object
  1710. })();
  1711. (function() {
  1712. var pluginName = "tablesawCheckAll";
  1713. function CheckAll(tablesaw) {
  1714. this.tablesaw = tablesaw;
  1715. this.$table = tablesaw.$table;
  1716. this.attr = "data-tablesaw-checkall";
  1717. this.checkAllSelector = "[" + this.attr + "]";
  1718. this.forceCheckedSelector = "[" + this.attr + "-checked]";
  1719. this.forceUncheckedSelector = "[" + this.attr + "-unchecked]";
  1720. this.checkboxSelector = 'input[type="checkbox"]';
  1721. this.$triggers = null;
  1722. this.$checkboxes = null;
  1723. if (this.$table.data(pluginName)) {
  1724. return;
  1725. }
  1726. this.$table.data(pluginName, this);
  1727. this.init();
  1728. }
  1729. CheckAll.prototype._filterCells = function($checkboxes) {
  1730. return $checkboxes
  1731. .filter(function() {
  1732. return !$(this)
  1733. .closest("tr")
  1734. .is("[data-tablesaw-subrow],[data-tablesaw-ignorerow]");
  1735. })
  1736. .find(this.checkboxSelector)
  1737. .not(this.checkAllSelector);
  1738. };
  1739. // With buttons you can use a scoping selector like: data-tablesaw-checkall="#my-scoped-id input[type='checkbox']"
  1740. CheckAll.prototype.getCheckboxesForButton = function(button) {
  1741. return this._filterCells($($(button).attr(this.attr)));
  1742. };
  1743. CheckAll.prototype.getCheckboxesForCheckbox = function(checkbox) {
  1744. return this._filterCells($($(checkbox).closest("th")[0].cells));
  1745. };
  1746. CheckAll.prototype.init = function() {
  1747. var self = this;
  1748. this.$table.find(this.checkAllSelector).each(function() {
  1749. var $trigger = $(this);
  1750. if ($trigger.is(self.checkboxSelector)) {
  1751. self.addCheckboxEvents(this);
  1752. } else {
  1753. self.addButtonEvents(this);
  1754. }
  1755. });
  1756. };
  1757. CheckAll.prototype.addButtonEvents = function(trigger) {
  1758. var self = this;
  1759. // Update body checkboxes when header checkbox is changed
  1760. $(trigger).on("click", function(event) {
  1761. event.preventDefault();
  1762. var $checkboxes = self.getCheckboxesForButton(this);
  1763. var allChecked = true;
  1764. $checkboxes.each(function() {
  1765. if (!this.checked) {
  1766. allChecked = false;
  1767. }
  1768. });
  1769. var setChecked;
  1770. if ($(this).is(self.forceCheckedSelector)) {
  1771. setChecked = true;
  1772. } else if ($(this).is(self.forceUncheckedSelector)) {
  1773. setChecked = false;
  1774. } else {
  1775. setChecked = allChecked ? false : true;
  1776. }
  1777. $checkboxes.each(function() {
  1778. this.checked = setChecked;
  1779. $(this).trigger("change." + pluginName);
  1780. });
  1781. });
  1782. };
  1783. CheckAll.prototype.addCheckboxEvents = function(trigger) {
  1784. var self = this;
  1785. // Update body checkboxes when header checkbox is changed
  1786. $(trigger).on("change", function() {
  1787. var setChecked = this.checked;
  1788. self.getCheckboxesForCheckbox(this).each(function() {
  1789. this.checked = setChecked;
  1790. });
  1791. });
  1792. var $checkboxes = self.getCheckboxesForCheckbox(trigger);
  1793. // Update header checkbox when body checkboxes are changed
  1794. $checkboxes.on("change." + pluginName, function() {
  1795. var checkedCount = 0;
  1796. $checkboxes.each(function() {
  1797. if (this.checked) {
  1798. checkedCount++;
  1799. }
  1800. });
  1801. var allSelected = checkedCount === $checkboxes.length;
  1802. trigger.checked = allSelected;
  1803. // only indeterminate if some are selected (not all and not none)
  1804. trigger.indeterminate = checkedCount !== 0 && !allSelected;
  1805. });
  1806. };
  1807. // on tablecreate, init
  1808. $(document).on(Tablesaw.events.create, function(e, tablesaw) {
  1809. new CheckAll(tablesaw);
  1810. });
  1811. Tablesaw.CheckAll = CheckAll;
  1812. })();
  1813. return Tablesaw;
  1814. }));