comparison default/node_modules/tablesaw/src/tables.swipetoggle.js @ 0:1d038bc9b3d2 default tip

Up:default
author Liny <dev@neowd.com>
date Sat, 31 May 2025 09:21:51 +0800
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:1d038bc9b3d2
1 /*
2 * tablesaw: A set of plugins for responsive tables
3 * Swipe Toggle: swipe gesture (or buttons) to navigate which columns are shown.
4 * Copyright (c) 2013 Filament Group, Inc.
5 * MIT License
6 */
7
8 (function() {
9 var classes = {
10 hideBtn: "disabled",
11 persistWidths: "tablesaw-fix-persist",
12 hiddenCol: "tablesaw-swipe-cellhidden",
13 persistCol: "tablesaw-swipe-cellpersist",
14 allColumnsVisible: "tablesaw-all-cols-visible"
15 };
16 var attrs = {
17 disableTouchEvents: "data-tablesaw-no-touch",
18 ignorerow: "data-tablesaw-ignorerow",
19 subrow: "data-tablesaw-subrow"
20 };
21
22 function createSwipeTable(tbl, $table) {
23 var tblsaw = $table.data("tablesaw");
24
25 var $btns = $("<div class='tablesaw-advance'></div>");
26 // TODO next major version: remove .btn
27 var $prevBtn = $(
28 "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro left'>" +
29 Tablesaw.i18n.swipePreviousColumn +
30 "</a>"
31 ).appendTo($btns);
32 // TODO next major version: remove .btn
33 var $nextBtn = $(
34 "<a href='#' class='btn tablesaw-nav-btn tablesaw-btn btn-micro right'>" +
35 Tablesaw.i18n.swipeNextColumn +
36 "</a>"
37 ).appendTo($btns);
38
39 var $headerCells = tbl._getPrimaryHeaderCells();
40 var $headerCellsNoPersist = $headerCells.not('[data-tablesaw-priority="persist"]');
41 var headerWidths = [];
42 var $head = $(document.head || "head");
43 var tableId = $table.attr("id");
44
45 if (!$headerCells.length) {
46 throw new Error("tablesaw swipe: no header cells found.");
47 }
48
49 $table.addClass("tablesaw-swipe");
50
51 function initMinHeaderWidths() {
52 $table.css({
53 width: "1px"
54 });
55
56 // remove any hidden columns
57 $table.find("." + classes.hiddenCol).removeClass(classes.hiddenCol);
58
59 headerWidths = [];
60 // Calculate initial widths
61 $headerCells.each(function() {
62 headerWidths.push(this.offsetWidth);
63 });
64
65 // reset props
66 $table.css({
67 width: ""
68 });
69 }
70
71 initMinHeaderWidths();
72
73 $btns.appendTo(tblsaw.$toolbar);
74
75 if (!tableId) {
76 tableId = "tableswipe-" + Math.round(Math.random() * 10000);
77 $table.attr("id", tableId);
78 }
79
80 function showColumn(headerCell) {
81 tblsaw._$getCells(headerCell).removeClass(classes.hiddenCol);
82 }
83
84 function hideColumn(headerCell) {
85 tblsaw._$getCells(headerCell).addClass(classes.hiddenCol);
86 }
87
88 function persistColumn(headerCell) {
89 tblsaw._$getCells(headerCell).addClass(classes.persistCol);
90 }
91
92 function isPersistent(headerCell) {
93 return $(headerCell).is('[data-tablesaw-priority="persist"]');
94 }
95
96 function unmaintainWidths() {
97 $table.removeClass(classes.persistWidths);
98 $("#" + tableId + "-persist").remove();
99 }
100
101 function maintainWidths() {
102 var prefix = "#" + tableId + ".tablesaw-swipe ",
103 styles = [],
104 tableWidth = $table.width(),
105 hash = [],
106 newHash;
107
108 // save persistent column widths (as long as they take up less than 75% of table width)
109 $headerCells.each(function(index) {
110 var width;
111 if (isPersistent(this)) {
112 width = this.offsetWidth;
113
114 if (width < tableWidth * 0.75) {
115 hash.push(index + "-" + width);
116 styles.push(
117 prefix +
118 " ." +
119 classes.persistCol +
120 ":nth-child(" +
121 (index + 1) +
122 ") { width: " +
123 width +
124 "px; }"
125 );
126 }
127 }
128 });
129 newHash = hash.join("_");
130
131 if (styles.length) {
132 $table.addClass(classes.persistWidths);
133 var $style = $("#" + tableId + "-persist");
134 // If style element not yet added OR if the widths have changed
135 if (!$style.length || $style.data("tablesaw-hash") !== newHash) {
136 // Remove existing
137 $style.remove();
138
139 $("<style>" + styles.join("\n") + "</style>")
140 .attr("id", tableId + "-persist")
141 .data("tablesaw-hash", newHash)
142 .appendTo($head);
143 }
144 }
145 }
146
147 function getNext() {
148 var next = [],
149 checkFound;
150
151 $headerCellsNoPersist.each(function(i) {
152 var $t = $(this),
153 isHidden = $t.css("display") === "none" || $t.is("." + classes.hiddenCol);
154
155 if (!isHidden && !checkFound) {
156 checkFound = true;
157 next[0] = i;
158 } else if (isHidden && checkFound) {
159 next[1] = i;
160
161 return false;
162 }
163 });
164
165 return next;
166 }
167
168 function getPrev() {
169 var next = getNext();
170 return [next[1] - 1, next[0] - 1];
171 }
172
173 function nextpair(fwd) {
174 return fwd ? getNext() : getPrev();
175 }
176
177 function canAdvance(pair) {
178 return pair[1] > -1 && pair[1] < $headerCellsNoPersist.length;
179 }
180
181 function matchesMedia() {
182 var matchMedia = $table.attr("data-tablesaw-swipe-media");
183 return !matchMedia || ("matchMedia" in window && window.matchMedia(matchMedia).matches);
184 }
185
186 function fakeBreakpoints() {
187 if (!matchesMedia()) {
188 return;
189 }
190
191 var containerWidth = $table.parent().width(),
192 persist = [],
193 sum = 0,
194 sums = [],
195 visibleNonPersistantCount = $headerCells.length;
196
197 $headerCells.each(function(index) {
198 var $t = $(this),
199 isPersist = $t.is('[data-tablesaw-priority="persist"]');
200
201 persist.push(isPersist);
202 sum += headerWidths[index];
203 sums.push(sum);
204
205 // is persistent or is hidden
206 if (isPersist || sum > containerWidth) {
207 visibleNonPersistantCount--;
208 }
209 });
210
211 // We need at least one column to swipe.
212 var needsNonPersistentColumn = visibleNonPersistantCount === 0;
213
214 $headerCells.each(function(index) {
215 if (sums[index] > containerWidth) {
216 hideColumn(this);
217 }
218 });
219
220 $headerCells.each(function(index) {
221 if (persist[index]) {
222 // for visual box-shadow
223 persistColumn(this);
224 return;
225 }
226
227 if (sums[index] <= containerWidth || needsNonPersistentColumn) {
228 needsNonPersistentColumn = false;
229 showColumn(this);
230 tblsaw.updateColspanCells(classes.hiddenCol, this, true);
231 }
232 });
233
234 unmaintainWidths();
235
236 $table.trigger("tablesawcolumns");
237 }
238
239 function advance(fwd) {
240 var pair = nextpair(fwd);
241 if (canAdvance(pair)) {
242 if (isNaN(pair[0])) {
243 if (fwd) {
244 pair[0] = 0;
245 } else {
246 pair[0] = $headerCellsNoPersist.length - 1;
247 }
248 }
249
250 // TODO just blindly hiding the previous column and showing the next column can result in
251 // column content overflow
252 maintainWidths();
253 hideColumn($headerCellsNoPersist.get(pair[0]));
254 tblsaw.updateColspanCells(classes.hiddenCol, $headerCellsNoPersist.get(pair[0]), false);
255
256 showColumn($headerCellsNoPersist.get(pair[1]));
257 tblsaw.updateColspanCells(classes.hiddenCol, $headerCellsNoPersist.get(pair[1]), true);
258
259 $table.trigger("tablesawcolumns");
260 }
261 }
262
263 $prevBtn.add($nextBtn).on("click", function(e) {
264 advance(!!$(e.target).closest($nextBtn).length);
265 e.preventDefault();
266 });
267
268 function getCoord(event, key) {
269 return (event.touches || event.originalEvent.touches)[0][key];
270 }
271
272 if (!$table.is("[" + attrs.disableTouchEvents + "]")) {
273 $table.on("touchstart.swipetoggle", function(e) {
274 var originX = getCoord(e, "pageX");
275 var originY = getCoord(e, "pageY");
276 var x;
277 var y;
278 var scrollTop = window.pageYOffset;
279
280 $(window).off(Tablesaw.events.resize, fakeBreakpoints);
281
282 $(this)
283 .on("touchmove.swipetoggle", function(e) {
284 x = getCoord(e, "pageX");
285 y = getCoord(e, "pageY");
286 })
287 .on("touchend.swipetoggle", function() {
288 var cfg = tbl.getConfig({
289 swipeHorizontalThreshold: 30,
290 swipeVerticalThreshold: 30
291 });
292
293 // This config code is a little awkward because shoestring doesn’t support deep $.extend
294 // Trying to work around when devs only override one of (not both) horizontalThreshold or
295 // verticalThreshold in their TablesawConfig.
296 // @TODO major version bump: remove cfg.swipe, move to just use the swipePrefix keys
297 var verticalThreshold = cfg.swipe
298 ? cfg.swipe.verticalThreshold
299 : cfg.swipeVerticalThreshold;
300 var horizontalThreshold = cfg.swipe
301 ? cfg.swipe.horizontalThreshold
302 : cfg.swipeHorizontalThreshold;
303
304 var isPageScrolled = Math.abs(window.pageYOffset - scrollTop) >= verticalThreshold;
305 var isVerticalSwipe = Math.abs(y - originY) >= verticalThreshold;
306
307 if (!isVerticalSwipe && !isPageScrolled) {
308 if (x - originX < -1 * horizontalThreshold) {
309 advance(true);
310 }
311 if (x - originX > horizontalThreshold) {
312 advance(false);
313 }
314 }
315
316 window.setTimeout(function() {
317 $(window).on(Tablesaw.events.resize, fakeBreakpoints);
318 }, 300);
319
320 $(this).off("touchmove.swipetoggle touchend.swipetoggle");
321 });
322 });
323 }
324
325 $table
326 .on("tablesawcolumns.swipetoggle", function() {
327 var canGoPrev = canAdvance(getPrev());
328 var canGoNext = canAdvance(getNext());
329 $prevBtn[canGoPrev ? "removeClass" : "addClass"](classes.hideBtn);
330 $nextBtn[canGoNext ? "removeClass" : "addClass"](classes.hideBtn);
331
332 tblsaw.$toolbar[!canGoPrev && !canGoNext ? "addClass" : "removeClass"](
333 classes.allColumnsVisible
334 );
335 })
336 .on("tablesawnext.swipetoggle", function() {
337 advance(true);
338 })
339 .on("tablesawprev.swipetoggle", function() {
340 advance(false);
341 })
342 .on(Tablesaw.events.destroy + ".swipetoggle", function() {
343 var $t = $(this);
344
345 $t.removeClass("tablesaw-swipe");
346 tblsaw.$toolbar.find(".tablesaw-advance").remove();
347 $(window).off(Tablesaw.events.resize, fakeBreakpoints);
348
349 $t.off(".swipetoggle");
350 })
351 .on(Tablesaw.events.refresh, function() {
352 unmaintainWidths();
353 initMinHeaderWidths();
354 fakeBreakpoints();
355 });
356
357 fakeBreakpoints();
358 $(window).on(Tablesaw.events.resize, fakeBreakpoints);
359 }
360
361 // on tablecreate, init
362 $(document).on(Tablesaw.events.create, function(e, tablesaw) {
363 if (tablesaw.mode === "swipe") {
364 createSwipeTable(tablesaw, tablesaw.$table);
365 }
366 });
367
368 // TODO OOP this and add to Tablesaw object
369 })();