@twistedandy/better-carousel 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,8 @@
4
4
  * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
5
5
  */
6
6
 
7
- import { clamp, inView, nearestSnap, snapIndex, targetLocation } from './geometry.js';
7
+ import { abs, clamp, inView, nearestSnap, snapIndex, targetLocation } from './geometry.js';
8
+ import { bind } from './markup.js';
8
9
  import { EASE, GLIDE } from './motion.js';
9
10
 
10
11
  // The targets that keep their own pointer behavior
@@ -29,10 +30,10 @@ const MOMENTUM = 325;
29
30
  * @returns {number}
30
31
  */
31
32
  export function releaseDuration(path, velocity, curve, fallback) {
32
- if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
33
+ if (Math.sign(path) !== Math.sign(velocity) || abs(velocity) < 0.05) {
33
34
  return fallback;
34
35
  }
35
- return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
36
+ return clamp(abs(path) * curve[1] / curve[0] / abs(velocity), 200, 1200);
36
37
  }
37
38
 
38
39
  /**
@@ -97,9 +98,9 @@ export function releaseTarget({ location, from, velocity, current, snaps, min, m
97
98
 
98
99
  let direction = 0;
99
100
 
100
- if (Math.abs(velocity) > 0.3) {
101
+ if (abs(velocity) > 0.3) {
101
102
  direction = velocity < 0 ? 1 : -1;
102
- } else if (Math.abs(moved) > 20) {
103
+ } else if (abs(moved) > 20) {
103
104
  direction = moved < 0 ? 1 : -1;
104
105
  }
105
106
 
@@ -134,7 +135,7 @@ export function drag(context) {
134
135
  // The selected snap at the drag start
135
136
  snap = 0;
136
137
 
137
- const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
138
+ const listen = bind(window, [['pointermove', handle], ['pointerup', handle], ['pointercancel', handle]]);
138
139
 
139
140
  function down(event) {
140
141
  block = false;
@@ -158,7 +159,7 @@ export function drag(context) {
158
159
  axis = { x: geo.axis === 'x', sign: geo.sign, scale: geo.scale };
159
160
  start = [event.clientX, event.clientY];
160
161
  samples = [];
161
- listen('addEventListener');
162
+ listen(true);
162
163
  }
163
164
 
164
165
  function handle(event) {
@@ -181,10 +182,10 @@ export function drag(context) {
181
182
 
182
183
  if (!context.dragging()) {
183
184
  // A touch move across the axis scrolls the page
184
- if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
185
+ if (event.pointerType !== 'mouse' && abs(cross) > abs(main)) {
185
186
  return end();
186
187
  }
187
- if (Math.abs(main) < options.dragThreshold) {
188
+ if (abs(main) < options.dragThreshold) {
188
189
  return;
189
190
  }
190
191
  // Stop the motion, and start the drag at the location where the carousel is now
@@ -214,7 +215,7 @@ export function drag(context) {
214
215
  * @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
215
216
  */
216
217
  function end(up) {
217
- listen('removeEventListener');
218
+ listen();
218
219
  pointer = null;
219
220
 
220
221
  if (!context.dragging()) {
@@ -245,18 +246,14 @@ export function drag(context) {
245
246
  // Stop a text selection during a drag. A "user-select" rule on the dragging class does the same, but its change paints all layers of the carousel.
246
247
  const select = (event) => context.dragging() && event.preventDefault();
247
248
 
248
- viewport.addEventListener('pointerdown', down);
249
- viewport.addEventListener('click', click, true);
250
- viewport.addEventListener('dragstart', prevent);
251
- viewport.addEventListener('selectstart', select);
249
+ const own = bind(viewport, [['pointerdown', down], ['click', click, true], ['dragstart', prevent], ['selectstart', select]]);
250
+
251
+ own(true);
252
252
 
253
253
  return {
254
254
  remove() {
255
- listen('removeEventListener');
256
- viewport.removeEventListener('pointerdown', down);
257
- viewport.removeEventListener('click', click, true);
258
- viewport.removeEventListener('dragstart', prevent);
259
- viewport.removeEventListener('selectstart', select);
255
+ listen();
256
+ own();
260
257
  }
261
258
  };
262
259
  }
@@ -276,7 +273,7 @@ function scrolls(node, viewport, axis, delta) {
276
273
  for (; node && node !== viewport; node = node.parentElement) {
277
274
  // Read the style only for an element with more content than space
278
275
  if (node[size] > node[client] && /auto|scroll/.test(getComputedStyle(node)[overflow])) {
279
- const at = Math.abs(node[position]);
276
+ const at = abs(node[position]);
280
277
  if (delta > 0 ? at + node[client] < node[size] - 1 : at > 0) {
281
278
  return true;
282
279
  }
@@ -317,7 +314,7 @@ export function wheel(context) {
317
314
 
318
315
  function onWheel(event) {
319
316
  const geo = context.geo(),
320
- side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
317
+ side = geo.axis === 'x' && abs(event.deltaX) > abs(event.deltaY),
321
318
  delta = side ? event.deltaX * geo.sign : event.deltaY;
322
319
 
323
320
  if (event.ctrlKey || !delta || context.dragging()) {
@@ -326,22 +323,19 @@ export function wheel(context) {
326
323
 
327
324
  const now = event.timeStamp,
328
325
  gesture = now - time < 200,
329
- size = Math.abs(delta),
326
+ size = abs(delta),
330
327
  // A delta that does not grow is the inertia of the gesture, not a new push
331
328
  inertia = gesture && size <= last;
332
329
 
330
+ time = now;
333
331
  last = size;
334
- if (!gesture) {
335
- held = false;
336
- }
332
+ held &&= gesture;
337
333
 
338
334
  // An element in a slide that can scroll in the wheel direction scrolls, also for the rest of its gesture
339
- if ((gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta)) {
340
- inner = true;
341
- time = now;
335
+ inner = (gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta);
336
+ if (inner) {
342
337
  return;
343
338
  }
344
- inner = false;
345
339
 
346
340
  const base = context.location(),
347
341
  path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
@@ -351,10 +345,8 @@ export function wheel(context) {
351
345
  target = clamp(target, geo.min, geo.max);
352
346
  }
353
347
 
354
- time = now;
355
-
356
348
  // At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
357
- if (Math.abs(target - base) < 0.5) {
349
+ if (abs(target - base) < 0.5) {
358
350
  if (held && inertia) {
359
351
  event.preventDefault();
360
352
  }
@@ -383,23 +375,23 @@ export function wheel(context) {
383
375
  const geo = context.geo(),
384
376
  at = context.current(),
385
377
  index = nearestSnap(geo.snaps, at, geo.period),
386
- away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
378
+ away = abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
387
379
 
388
380
  context.step(index, index === snap && away ? direction : 0);
389
381
  }
390
382
 
391
383
  // A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
392
384
  // Add it only where the wheel moves the carousel.
393
- function listen() {
394
- const geo = context.geo();
395
- viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
396
- }
385
+ const listen = bind(viewport, [['wheel', onWheel, { passive: false }]]);
397
386
 
398
- ['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
387
+ ['init', 'reinit', 'resize'].forEach((name) => context.on(name, () => {
388
+ const geo = context.geo();
389
+ listen(!geo.fit && (geo.axis === 'y' || options.wheel === 'both'));
390
+ }));
399
391
 
400
392
  return {
401
393
  remove() {
402
- viewport.removeEventListener('wheel', onWheel);
394
+ listen();
403
395
  clearTimeout(timer);
404
396
  }
405
397
  };
@@ -432,13 +424,11 @@ export function keys(context) {
432
424
  }
433
425
  }
434
426
 
435
- root.addEventListener('keydown', onKey);
427
+ const listen = bind(root, [['keydown', onKey]]);
436
428
 
437
- return {
438
- remove() {
439
- root.removeEventListener('keydown', onKey);
440
- }
441
- };
429
+ listen(true);
430
+
431
+ return { remove: listen };
442
432
  }
443
433
 
444
434
  /**
@@ -472,13 +462,9 @@ export function focus(context) {
472
462
  context.emit('slidefocus');
473
463
  }
474
464
 
475
- container.addEventListener('pointerdown', press);
476
- container.addEventListener('focusin', onFocus);
465
+ const listen = bind(container, [['pointerdown', press], ['focusin', onFocus]]);
477
466
 
478
- return {
479
- remove() {
480
- container.removeEventListener('pointerdown', press);
481
- container.removeEventListener('focusin', onFocus);
482
- }
483
- };
467
+ listen(true);
468
+
469
+ return { remove: listen };
484
470
  }
@@ -4,6 +4,8 @@
4
4
  * The reads run in the ResizeObserver callback, when the layout is clean.
5
5
  */
6
6
 
7
+ import { abs, round } from './geometry.js';
8
+
7
9
  /**
8
10
  * Read the axis, the alignment, the direction and the gap from the computed style of the container.
9
11
  *
@@ -67,13 +69,13 @@ export function readRects(viewport, nodes, layout, written) {
67
69
  width = viewport.offsetWidth,
68
70
  height = viewport.offsetHeight,
69
71
  // offsetWidth is a whole number: a difference of less than 1 px is not a transform
70
- transformed = width && height && (Math.abs(box.width - width) >= 1 || Math.abs(box.height - height) >= 1),
72
+ transformed = width && height && (abs(box.width - width) >= 1 || abs(box.height - height) >= 1),
71
73
  // A scale s and a rotation by an angle a give a box of s(w cos a + h sin a) by s(w sin a + h cos a). The main axis gets s cos a.
72
- scale = !transformed ? 1 : Math.abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
74
+ scale = !transformed ? 1 : abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
73
75
  view = !transformed ? (x ? box.width : box.height) : x ? width : height,
74
76
  style = getComputedStyle(viewport),
75
- [before, after] = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
76
- pad = { start: parseFloat(style['padding' + before]) || 0, end: parseFloat(style['padding' + after]) || 0 };
77
+ side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
78
+ pad = { start: parseFloat(style['padding' + side[0]]) || 0, end: parseFloat(style['padding' + side[1]]) || 0 };
77
79
 
78
80
  const slides = nodes.map((node, index) => {
79
81
  const rect = node.getBoundingClientRect(),
@@ -84,35 +86,27 @@ export function readRects(viewport, nodes, layout, written) {
84
86
  return { start, end: start + size, cross: (x ? rect.height : rect.width) / scale, hidden: !rect.width && !rect.height };
85
87
  });
86
88
 
87
- let edge = slides.find((slide) => !slide.hidden)?.start || 0;
88
-
89
- for (const slide of slides) {
90
- if (slide.hidden) {
91
- slide.start = slide.end = edge;
92
- } else {
93
- edge = slide.end;
94
- }
95
- }
96
-
97
- let first = Math.max(0, slides.findIndex((slide) => !slide.hidden)),
98
- last = first;
89
+ // A hidden slide goes to the end of the visible slide before it. The first and the last visible slides give the margins of the loop gap.
90
+ let edge = slides.find((slide) => !slide.hidden)?.start || 0,
91
+ first = -1,
92
+ last = -1,
93
+ gap = layout.gap;
99
94
 
100
95
  slides.forEach((slide, index) => {
101
96
  if (slide.hidden) {
97
+ slide.start = slide.end = edge;
102
98
  return;
103
99
  }
104
- if (slide.start < slides[first].start) {
100
+ edge = slide.end;
101
+ if (first < 0 || slide.start < slides[first].start) {
105
102
  first = index;
106
103
  }
107
- if (slide.end > slides[last].end) {
104
+ if (last < 0 || slide.end > slides[last].end) {
108
105
  last = index;
109
106
  }
110
107
  });
111
108
 
112
- let gap = layout.gap;
113
-
114
- if (slides.length) {
115
- const side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'];
109
+ if (first > -1) {
116
110
  gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
117
111
  }
118
112
 
@@ -152,9 +146,9 @@ export function visibleArea(viewport, layout, view, pad, size) {
152
146
  }
153
147
 
154
148
  const box = viewport.getBoundingClientRect(),
155
- before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
149
+ before = Math.max(0, round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
156
150
 
157
- return { start: -before, size: before + Math.max(view + pad.end, Math.round(size - before)) };
151
+ return { start: -before, size: before + Math.max(view + pad.end, round(size - before)) };
158
152
  }
159
153
 
160
154
  // One ResizeObserver for all carousels. Each callback first reads the layout of all carousels, then writes. In this way, the reads of one carousel do not
@@ -54,6 +54,17 @@ export function cleanStyle(element) {
54
54
  }
55
55
  }
56
56
 
57
+ /**
58
+ * Make a function that adds or removes event listeners on a target.
59
+ *
60
+ * @param {EventTarget} target
61
+ * @param {Array<Array>} list [name, handler, options] for each listener.
62
+ * @returns {(on?: boolean) => void} With true, it adds the listeners. Without a value, it removes them.
63
+ */
64
+ export function bind(target, list) {
65
+ return (on) => list.forEach(([name, handler, options]) => target[on ? 'addEventListener' : 'removeEventListener'](name, handler, options));
66
+ }
67
+
57
68
  /**
58
69
  * Make an element.
59
70
  *
@@ -69,6 +80,24 @@ export function create(tag, className) {
69
80
  return element;
70
81
  }
71
82
 
83
+ /**
84
+ * Make a control button of a carousel.
85
+ *
86
+ * @param {string} className
87
+ * @param {HTMLElement} container The container of the slides, which the button controls.
88
+ * @param {string} label The aria-label. An empty label adds no attribute.
89
+ * @param {() => void} click
90
+ * @returns {HTMLButtonElement}
91
+ */
92
+ export function createButton(className, container, label, click) {
93
+ const element = create('button', className);
94
+ element.type = 'button';
95
+ setAttribute(element, 'aria-label', label);
96
+ element.setAttribute('aria-controls', container.id);
97
+ element.addEventListener('click', click);
98
+ return element;
99
+ }
100
+
72
101
  /**
73
102
  * Find the element of an option, such as "arrows", "dots" or "sync". true gives the root, and false gives null.
74
103
  * The library searches for a selector in the root and then in each parent of the root, so that it finds a heading in the section of the carousel.
@@ -233,10 +262,9 @@ export function readSlides(container, selector) {
233
262
  export function copySlides(slides, count, className) {
234
263
  const list = [];
235
264
 
236
- for (let copy = 0; copy < count; copy++) {
265
+ for (let pass = 0; pass < count; pass++) {
237
266
  for (const node of slides) {
238
- const clone = node.cloneNode(true);
239
- removeIds(clone);
267
+ const clone = copy(node);
240
268
  clone.setAttribute('aria-hidden', 'true');
241
269
  clone.inert = true;
242
270
  clone.style.translate = '';
@@ -250,11 +278,13 @@ export function copySlides(slides, count, className) {
250
278
  return list;
251
279
  }
252
280
 
253
- // An id must be unique in the page, so a copy has no ids
254
- function removeIds(node) {
255
- for (const item of [node, ...node.querySelectorAll('[id]')]) {
281
+ // Copy a node with its content. An id must be unique in the page, so the copy has no ids.
282
+ function copy(node) {
283
+ const result = node.cloneNode(true);
284
+ for (const item of [result, ...result.querySelectorAll('[id]')]) {
256
285
  item.removeAttribute('id');
257
286
  }
287
+ return result;
258
288
  }
259
289
 
260
290
  /**
@@ -264,9 +294,7 @@ function removeIds(node) {
264
294
  * @param {HTMLElement} node The slide.
265
295
  */
266
296
  export function copyContent(clone, node) {
267
- const copy = node.cloneNode(true);
268
- removeIds(copy);
269
- clone.replaceChildren(...copy.childNodes);
297
+ clone.replaceChildren(...copy(node).childNodes);
270
298
  }
271
299
 
272
300
  /**
@@ -2,6 +2,7 @@
2
2
  * Motion: the easing, the duration of a goToSnap() motion, and the motion engine.
3
3
  */
4
4
 
5
+ import { abs } from './geometry.js';
5
6
  import { steps } from './loop.js';
6
7
 
7
8
  // The easing of a goToSnap() motion
@@ -30,10 +31,10 @@ export function bezier([x1, y1, x2, y2]) {
30
31
  for (let i = 0; i < 6; i++) {
31
32
  const error = axis(x1, x2, t) - x,
32
33
  slope = 3 * (1 + 3 * x1 - 3 * x2) * t * t + 2 * (3 * x2 - 6 * x1) * t + 3 * x1;
33
- if (Math.abs(error) < 1e-5) {
34
+ if (abs(error) < 1e-5) {
34
35
  return axis(y1, y2, t);
35
36
  }
36
- if (Math.abs(slope) < 1e-6) {
37
+ if (abs(slope) < 1e-6) {
37
38
  break;
38
39
  }
39
40
  t -= error / slope;
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import { find } from './carousel.js';
8
- import { create, optionElement, setAttribute, setClass } from './markup.js';
8
+ import { bind, create, createButton, optionElement, setAttribute, setClass } from './markup.js';
9
9
 
10
10
  /**
11
11
  * Make the arrows and the dots of a carousel. They update on the carousel events.
@@ -40,14 +40,7 @@ export function nav(context) {
40
40
  }
41
41
 
42
42
  if (arrows) {
43
- [['prev', 'goToPrev'], ['next', 'goToNext']].forEach(([key, method]) => {
44
- const button = create('button', cls.button + ' ' + cls[key + 'Button']);
45
- button.type = 'button';
46
- button.setAttribute('aria-label', labels[key]);
47
- button.setAttribute('aria-controls', context.container.id);
48
- button.addEventListener('click', () => api[method]());
49
- buttons.push(button);
50
- });
43
+ buttons.push(createButton(cls.button + ' ' + cls.prevButton, context.container, labels.prev, () => api.goToPrev()), createButton(cls.button + ' ' + cls.nextButton, context.container, labels.next, () => api.goToNext()));
51
44
  }
52
45
 
53
46
  function update() {
@@ -55,17 +48,17 @@ export function nav(context) {
55
48
  count = fit ? 0 : api.snapProgress().length,
56
49
  selected = api.selectedSnap();
57
50
 
58
- buttons.forEach((button, index) => {
51
+ buttons.forEach((item, index) => {
59
52
  if (fit) {
60
- button.remove();
53
+ item.remove();
61
54
  } else {
62
- if (!button.isConnected) {
55
+ if (!item.isConnected) {
63
56
  // Before the dots, for the tab order
64
- list?.parentNode === arrows ? list.before(button) : arrows.append(button);
57
+ list?.parentNode === arrows ? list.before(item) : arrows.append(item);
65
58
  }
66
59
  const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
67
- if (button.disabled !== disabled) {
68
- button.disabled = disabled;
60
+ if (item.disabled !== disabled) {
61
+ item.disabled = disabled;
69
62
  }
70
63
  }
71
64
  });
@@ -85,16 +78,12 @@ export function nav(context) {
85
78
  }
86
79
 
87
80
  while (dots.length < count) {
88
- const dot = create('button', cls.dot),
89
- index = dots.length;
90
- dot.type = 'button';
91
- dot.setAttribute('aria-label', labels.dot.replace('%d', index + 1));
92
- dot.setAttribute('aria-controls', context.container.id);
81
+ const index = dots.length,
82
+ dot = createButton(cls.dot, context.container, labels.dot.replace('%d', index + 1), () => api.goToSnap(index));
93
83
  // The window of the dots hides the dots out of the zoom: keep them out of the tab order
94
84
  if (windowed) {
95
85
  dot.tabIndex = -1;
96
86
  }
97
- dot.addEventListener('click', () => api.goToSnap(index));
98
87
  dots.push(dot);
99
88
  track.append(dot);
100
89
  }
@@ -146,7 +135,7 @@ export function nav(context) {
146
135
 
147
136
  return {
148
137
  remove() {
149
- buttons.forEach((button) => button.remove());
138
+ buttons.forEach((item) => item.remove());
150
139
  list?.remove();
151
140
  }
152
141
  };
@@ -198,12 +187,14 @@ export function sync(context) {
198
187
 
199
188
  context.on('init', connect);
200
189
  context.on('reinit', connect);
201
- container.addEventListener('click', click);
190
+ const listen = bind(container, [['click', click]]);
191
+
192
+ listen(true);
202
193
 
203
194
  return {
204
195
  remove() {
205
196
  other?.off('select', show);
206
- container.removeEventListener('click', click);
197
+ listen();
207
198
  }
208
199
  };
209
200
  }