@twistedandy/better-carousel 1.0.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.
@@ -54,6 +54,17 @@ 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
+ 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 @@ 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
+ 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.
@@ -208,15 +237,18 @@ const controls = 'a[href],button,input,select,textarea,[tabindex],[role]';
208
237
  // The slides that can get the "group" role. An element with its own role, such as an article or a list item, does not permit "group".
209
238
  const generic = 'div,span,section';
210
239
 
240
+ // The elements that never show, so they are not slides
241
+ const skipped = new Set(['template', 'script', 'style']);
242
+
211
243
  /**
212
- * Get the slides of a container. The clones that the library made are not slides.
244
+ * Get the slides of a container. The clones that the library made, and the template, script and style elements, are not slides.
213
245
  *
214
246
  * @param {HTMLElement} container
215
247
  * @param {string} [selector] The "slides" option.
216
248
  * @returns {HTMLElement[]}
217
249
  */
218
250
  function readSlides(container, selector) {
219
- return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node));
251
+ return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node) && !skipped.has(node.localName));
220
252
  }
221
253
 
222
254
  /**
@@ -230,12 +262,9 @@ function readSlides(container, selector) {
230
262
  function copySlides(slides, count, className) {
231
263
  const list = [];
232
264
 
233
- for (let copy = 0; copy < count; copy++) {
265
+ for (let pass = 0; pass < count; pass++) {
234
266
  for (const node of slides) {
235
- const clone = node.cloneNode(true);
236
- for (const item of [clone, ...clone.querySelectorAll('[id]')]) {
237
- item.removeAttribute('id');
238
- }
267
+ const clone = copy(node);
239
268
  clone.setAttribute('aria-hidden', 'true');
240
269
  clone.inert = true;
241
270
  clone.style.translate = '';
@@ -249,6 +278,25 @@ function copySlides(slides, count, className) {
249
278
  return list;
250
279
  }
251
280
 
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]')]) {
285
+ item.removeAttribute('id');
286
+ }
287
+ return result;
288
+ }
289
+
290
+ /**
291
+ * Copy the content of a slide into its clone again.
292
+ *
293
+ * @param {HTMLElement} clone
294
+ * @param {HTMLElement} node The slide.
295
+ */
296
+ function copyContent(clone, node) {
297
+ clone.replaceChildren(...copy(node).childNodes);
298
+ }
299
+
252
300
  /**
253
301
  * Give each slide the slide role and a name such as "2 of 8". A slide with its own role, such as an article, keeps it.
254
302
  *
@@ -346,17 +394,13 @@ function pauser(root, options, change) {
346
394
  function controller(context, key, options, hooks) {
347
395
  const { api, root, container, cls, emit } = context,
348
396
  labels = context.options.labels,
349
- button = create('button', cls.button + ' ' + cls.playButton);
397
+ button = createButton(cls.button + ' ' + cls.playButton, container, '', () => playing ? control.stop() : control.play());
350
398
 
351
399
  let playing = false,
352
400
  watch = null,
353
401
  // true until the first init
354
402
  first = true;
355
403
 
356
- button.type = 'button';
357
- button.setAttribute('aria-controls', container.id);
358
- button.addEventListener('click', () => playing ? control.stop() : control.play());
359
-
360
404
  function update() {
361
405
  setAttribute(button, 'aria-label', playing ? labels.pause : labels.play);
362
406
  setClass(root, cls.playing, playing);
@@ -370,10 +414,13 @@ function controller(context, key, options, hooks) {
370
414
  } else if (!button.isConnected) {
371
415
  root.append(button);
372
416
  }
373
- // Start at the first init, unless the user prefers less motion
417
+ // Start at the first init, unless the user prefers less motion. After a breakpoint change, the play state stays.
418
+ // A play() before the first init starts now, because the carousel had no size before.
374
419
  if (first) {
375
420
  first = false;
376
- if (options.playOnInit && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
421
+ if (playing) {
422
+ hooks.play();
423
+ } else if (context.playing?.[key] ?? (options.playOnInit && !matchMedia('(prefers-reduced-motion: reduce)').matches)) {
377
424
  control.play();
378
425
  }
379
426
  }
@@ -501,12 +548,19 @@ function autoScroll(context) {
501
548
 
502
549
  const options = settings(autoScrollDefaults, 'speed', context.options.autoScroll);
503
550
 
504
- // The start delay
505
- let timer = 0;
551
+ // The start delay, and true while a pointer presses the viewport
552
+ let timer = 0,
553
+ pressed = false;
506
554
 
507
555
  const control = controller(context, 'autoScroll', options, {
508
- play: wait,
556
+ play() {
557
+ presses(true);
558
+ wait();
559
+ },
509
560
  stop() {
561
+ presses();
562
+ listen();
563
+ pressed = false;
510
564
  wait(-1);
511
565
  context.halt();
512
566
  },
@@ -547,11 +601,33 @@ function autoScroll(context) {
547
601
  function run() {
548
602
  timer = 0;
549
603
  const geo = context.geo();
550
- if (geo && !geo.fit && !context.dragging() && !control.paused()) {
604
+ if (geo && !geo.fit && !pressed && !context.dragging() && !control.paused()) {
551
605
  context.scroll(options.direction === 'prev' ? -1 : 1, options.speed / 1000);
552
606
  }
553
607
  }
554
608
 
609
+ // While the auto scroll plays, a press stops the slides under the pointer. A release without a drag starts them again after the delay.
610
+ // A drag is an interaction.
611
+ const listen = bind(window, [['pointerup', release], ['pointercancel', release]]),
612
+ presses = bind(context.viewport, [['pointerdown', press]]);
613
+
614
+ function press(event) {
615
+ if (!event.button && !pressed) {
616
+ pressed = true;
617
+ wait(-1);
618
+ context.halt();
619
+ listen(true);
620
+ }
621
+ }
622
+
623
+ function release() {
624
+ pressed = false;
625
+ listen();
626
+ if (!context.dragging()) {
627
+ wait();
628
+ }
629
+ }
630
+
555
631
  return control;
556
632
  }
557
633
 
@@ -648,6 +724,9 @@ function normalize(location, length) {
648
724
  */
649
725
 
650
726
 
727
+ // Short names of the Math functions, which the minified file can make shorter
728
+ const { abs, floor, round } = Math;
729
+
651
730
  /**
652
731
  * Keep a value between two limits.
653
732
  *
@@ -700,6 +779,9 @@ function bounds(slides) {
700
779
  max = 0;
701
780
 
702
781
  for (const slide of slides) {
782
+ if (slide.hidden) {
783
+ continue;
784
+ }
703
785
  start = Math.min(start, slide.start);
704
786
  end = Math.max(end, slide.end);
705
787
  max = Math.max(max, slide.end - slide.start);
@@ -709,14 +791,14 @@ function bounds(slides) {
709
791
  }
710
792
 
711
793
  /**
712
- * Put the slides that start at the same position (1 px or less) into one column.
794
+ * Put the slides that start at the same position (1 px or less) into one column. A hidden slide is in no column.
713
795
  * In a flex row, one column has one slide. In a grid, a column can have more slides.
714
796
  *
715
797
  * @param {Array<{start: number, end: number}>} slides
716
798
  * @returns {Array<{start: number, end: number}>} The columns, sorted by start.
717
799
  */
718
800
  function columns(slides) {
719
- const order = slides.map((slide, index) => index).sort((a, b) => slides[a].start - slides[b].start || a - b),
801
+ const order = slides.map((slide, index) => index).filter((index) => !slides[index].hidden).sort((a, b) => slides[a].start - slides[b].start || a - b),
720
802
  list = [];
721
803
 
722
804
  let column;
@@ -763,6 +845,29 @@ function groups(list, view, count) {
763
845
  return result;
764
846
  }
765
847
 
848
+ /**
849
+ * Find the item with the lowest score.
850
+ *
851
+ * @param {Array} list
852
+ * @param {(item: *, index: number) => number} score Infinity excludes an item.
853
+ * @param {number} [margin] A score must be lower than the best score by more than this value. Then the lower index wins a tie.
854
+ * @returns {number} The index, or -1 if all items are excluded.
855
+ */
856
+ function lowest(list, score, margin = 0) {
857
+ let best = -1,
858
+ gap = Infinity;
859
+
860
+ list.forEach((item, index) => {
861
+ const value = score(item, index);
862
+ if (value < gap - margin) {
863
+ gap = value;
864
+ best = index;
865
+ }
866
+ });
867
+
868
+ return best;
869
+ }
870
+
766
871
  /**
767
872
  * Get the distance between two locations. In loop mode, use the shortest distance modulo the period.
768
873
  *
@@ -773,7 +878,7 @@ function groups(list, view, count) {
773
878
  */
774
879
  function distance(a, b, period) {
775
880
  const value = a - b;
776
- return period ? value - Math.round(value / period) * period : value;
881
+ return period ? value - round(value / period) * period : value;
777
882
  }
778
883
 
779
884
  /**
@@ -807,8 +912,8 @@ function snaps({ slides, view, align, slidesPerSnap, containScroll, period = 0 }
807
912
  }
808
913
 
809
914
  if (period || containScroll !== 'keepSnaps') {
810
- list = list.filter((location, index) => !index || Math.abs(distance(location, list[index - 1], period)) > 1);
811
- if (period && list.length > 1 && Math.abs(distance(list[0], list[list.length - 1], period)) <= 1) {
915
+ list = list.filter((location, index) => !index || abs(distance(location, list[index - 1], period)) > 1);
916
+ if (period && list.length > 1 && abs(distance(list[0], list[list.length - 1], period)) <= 1) {
812
917
  list.pop();
813
918
  }
814
919
  }
@@ -842,7 +947,7 @@ function snaps({ slides, view, align, slidesPerSnap, containScroll, period = 0 }
842
947
  /**
843
948
  * Find the slide whose anchor is nearest to the align point at a location.
844
949
  * The anchor is the start for 'start', the center for 'center' and the end for 'end'.
845
- * If two slides have the same distance, the lower index wins.
950
+ * If two slides have the same distance, the lower index wins. A hidden slide is never the active slide.
846
951
  *
847
952
  * @param {Array<{start: number, end: number}>} slides
848
953
  * @param {number} location
@@ -854,18 +959,7 @@ function snaps({ slides, view, align, slidesPerSnap, containScroll, period = 0 }
854
959
  * @returns {number} The slide index, or -1 if the range is empty.
855
960
  */
856
961
  function activeSlide(slides, location, view, align, period, from = 0, to = slides.length) {
857
- let best = -1,
858
- gap = Infinity;
859
-
860
- slides.forEach((slide, index) => {
861
- const value = Math.abs(distance(slide.start + location, alignOffset(align, view, slide.end - slide.start, index), period));
862
- if (index >= from && index < to && value < gap - 0.5) {
863
- gap = value;
864
- best = index;
865
- }
866
- });
867
-
868
- return best;
962
+ return lowest(slides, (slide, index) => index >= from && index < to && !slide.hidden ? abs(distance(slide.start + location, alignOffset(align, view, slide.end - slide.start, index), period)) : Infinity, 0.5);
869
963
  }
870
964
 
871
965
  /**
@@ -899,18 +993,7 @@ function snapOfSlide(list, slides, index, view, align, period) {
899
993
  * @returns {number} The snap index.
900
994
  */
901
995
  function nearestSnap(list, location, period) {
902
- let best = 0,
903
- gap = Infinity;
904
-
905
- list.forEach((snap, index) => {
906
- const value = Math.abs(distance(snap.location, location, period));
907
- if (value < gap) {
908
- gap = value;
909
- best = index;
910
- }
911
- });
912
-
913
- return best;
996
+ return Math.max(0, lowest(list, (snap) => abs(distance(snap.location, location, period))));
914
997
  }
915
998
 
916
999
  /**
@@ -932,7 +1015,7 @@ function targetLocation(target, location, period, direction = 0) {
932
1015
  }
933
1016
 
934
1017
  if (direction < 0) {
935
- return target + (Math.floor((location + 0.5 - target) / period) + 1) * period;
1018
+ return target + (floor((location + 0.5 - target) / period) + 1) * period;
936
1019
  }
937
1020
 
938
1021
  return location + distance(target, location, period);
@@ -948,7 +1031,7 @@ function targetLocation(target, location, period, direction = 0) {
948
1031
  function progress(location, { min, max, period }) {
949
1032
  if (period) {
950
1033
  const value = (max - location) / period;
951
- return value - Math.floor(value);
1034
+ return value - floor(value);
952
1035
  }
953
1036
  return max > min ? clamp((max - location) / (max - min), 0, 1) : 0;
954
1037
  }
@@ -971,7 +1054,7 @@ function inView(slides, location, view, threshold, period) {
971
1054
  start = period ? distance(slide.start + location + size / 2, view / 2, period) + view / 2 - size / 2 : slide.start + location,
972
1055
  visible = Math.min(start + size, view) - Math.max(start, 0);
973
1056
 
974
- if (visible > 0 && visible >= threshold * size - 0.5) {
1057
+ if (!slide.hidden && visible > 0 && visible >= threshold * size - 0.5) {
975
1058
  result.push(index);
976
1059
  }
977
1060
  });
@@ -1032,7 +1115,7 @@ function compute(layout, rects, area, count, options) {
1032
1115
  const geo = { ...layout, ...rects, area, fit, count, period, min: 0, max: 0 };
1033
1116
 
1034
1117
  if (fit) {
1035
- geo.snaps = [{ location: 0, slide: activeSlide(rects.slides, 0, rects.view, layout.align) }];
1118
+ geo.snaps = [{ location: 0, slide: Math.max(0, activeSlide(rects.slides, 0, rects.view, layout.align)) }];
1036
1119
  } else {
1037
1120
  Object.assign(geo, snaps({ ...rects, align: layout.align, slidesPerSnap: options.slidesPerSnap, containScroll: options.containScroll, period }));
1038
1121
  }
@@ -1054,16 +1137,7 @@ function compute(layout, rects, area, count, options) {
1054
1137
  * @returns {number} The snap index.
1055
1138
  */
1056
1139
  function physicalSnap(geo, index, location) {
1057
- let best = -1,
1058
- gap = Infinity;
1059
-
1060
- geo.snaps.forEach((snap, item) => {
1061
- const value = Math.abs(distance(snap.location, location, geo.period));
1062
- if (geo.map[item] === index && value < gap) {
1063
- gap = value;
1064
- best = item;
1065
- }
1066
- });
1140
+ const best = lowest(geo.snaps, (snap, item) => geo.map[item] === index ? abs(distance(snap.location, location, geo.period)) : Infinity);
1067
1141
 
1068
1142
  return best < 0 ? clamp(index, 0, geo.snaps.length - 1) : best;
1069
1143
  }
@@ -1074,6 +1148,7 @@ function physicalSnap(geo, index, location) {
1074
1148
  * The reads run in the ResizeObserver callback, when the layout is clean.
1075
1149
  */
1076
1150
 
1151
+
1077
1152
  /**
1078
1153
  * Read the axis, the alignment, the direction and the gap from the computed style of the container.
1079
1154
  *
@@ -1115,54 +1190,75 @@ function readLayout(container, options) {
1115
1190
  }
1116
1191
 
1117
1192
  /**
1118
- * Read the slide boxes on the main axis, relative to the viewport start at location 0.
1193
+ * Read the slide boxes on the main axis, relative to the inner edge of the viewport padding at location 0. The snaps align to this edge.
1194
+ * The values are in the px of the carousel: in a parent with a CSS scale, such as a modal window that opens with a scale animation, the
1195
+ * values do not change with a scale or a rotation of a parent.
1196
+ * A slide with no box, such as a slide with display: none, is hidden. It gets no snap, and it stays at the end of the slide before it.
1119
1197
  *
1120
1198
  * @param {HTMLElement} viewport
1121
1199
  * @param {HTMLElement[]} nodes All slides, clones included.
1122
1200
  * @param {object} layout The result of readLayout().
1123
1201
  * @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
1124
- * @returns {{view: number, slides: Array<{start: number, end: number, cross: number}>, gap: number}}
1125
- * gap is the loop gap: the space between the last slide and the next copy of the first slide.
1202
+ * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, pad: {start: number, end: number}}}
1203
+ * view is the viewport size without the padding. gap is the loop gap: the space between the last slide and the next copy of the first slide.
1204
+ * scale is the screen px of one px of the carousel. pad is the viewport padding at the start and at the end.
1126
1205
  */
1127
1206
  function readRects(viewport, nodes, layout, written) {
1128
1207
  const box = viewport.getBoundingClientRect(),
1129
1208
  x = layout.axis === 'x',
1130
1209
  sign = layout.sign,
1131
1210
  known = written.axis === layout.axis,
1132
- shift = known ? written.container : 0;
1133
-
1134
- let first = 0,
1135
- last = 0;
1211
+ shift = known ? written.container : 0,
1212
+ width = viewport.offsetWidth,
1213
+ height = viewport.offsetHeight,
1214
+ // offsetWidth is a whole number: a difference of less than 1 px is not a transform
1215
+ transformed = width && height && (abs(box.width - width) >= 1 || abs(box.height - height) >= 1),
1216
+ // 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.
1217
+ scale = !transformed ? 1 : abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
1218
+ view = !transformed ? (x ? box.width : box.height) : x ? width : height,
1219
+ style = getComputedStyle(viewport),
1220
+ side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
1221
+ pad = { start: parseFloat(style['padding' + side[0]]) || 0, end: parseFloat(style['padding' + side[1]]) || 0 };
1136
1222
 
1137
1223
  const slides = nodes.map((node, index) => {
1138
1224
  const rect = node.getBoundingClientRect(),
1139
1225
  offset = sign * (shift + (known && written.slides[index] || 0)),
1140
- start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) - offset,
1141
- size = x ? rect.width : rect.height;
1226
+ start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) / scale - pad.start - offset,
1227
+ size = (x ? rect.width : rect.height) / scale;
1142
1228
 
1143
- return { start, end: start + size, cross: x ? rect.height : rect.width };
1229
+ return { start, end: start + size, cross: (x ? rect.height : rect.width) / scale, hidden: !rect.width && !rect.height };
1144
1230
  });
1145
1231
 
1232
+ // 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.
1233
+ let edge = slides.find((slide) => !slide.hidden)?.start || 0,
1234
+ first = -1,
1235
+ last = -1,
1236
+ gap = layout.gap;
1237
+
1146
1238
  slides.forEach((slide, index) => {
1147
- if (slide.start < slides[first].start) {
1239
+ if (slide.hidden) {
1240
+ slide.start = slide.end = edge;
1241
+ return;
1242
+ }
1243
+ edge = slide.end;
1244
+ if (first < 0 || slide.start < slides[first].start) {
1148
1245
  first = index;
1149
1246
  }
1150
- if (slide.end > slides[last].end) {
1247
+ if (last < 0 || slide.end > slides[last].end) {
1151
1248
  last = index;
1152
1249
  }
1153
1250
  });
1154
1251
 
1155
- let gap = layout.gap;
1156
-
1157
- if (slides.length) {
1158
- const side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'];
1252
+ if (first > -1) {
1159
1253
  gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
1160
1254
  }
1161
1255
 
1162
1256
  return {
1163
- view: x ? box.width : box.height,
1257
+ view: view - pad.start - pad.end,
1164
1258
  slides,
1165
- gap
1259
+ gap,
1260
+ scale,
1261
+ pad
1166
1262
  };
1167
1263
  }
1168
1264
 
@@ -1177,46 +1273,70 @@ function windowSize(axis) {
1177
1273
  }
1178
1274
 
1179
1275
  /**
1180
- * Get the part of the main axis where the loop must show slides, relative to the viewport start.
1181
- * It is the viewport. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
1276
+ * Get the part of the main axis where the loop must show slides, relative to the inner edge of the viewport padding.
1277
+ * It is the viewport with its padding. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
1182
1278
  *
1183
1279
  * @param {HTMLElement} viewport
1184
1280
  * @param {{axis: string, rtl: boolean}} layout
1185
- * @param {number} view The viewport size.
1281
+ * @param {number} view The viewport size without the padding.
1282
+ * @param {{start: number, end: number}} pad The viewport padding.
1186
1283
  * @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
1187
1284
  * @returns {{start: number, size: number}}
1188
1285
  */
1189
- function visibleArea(viewport, layout, view, size) {
1286
+ function visibleArea(viewport, layout, view, pad, size) {
1190
1287
  if (!size) {
1191
- return { start: 0, size: view };
1288
+ return { start: -pad.start, size: pad.start + view + pad.end };
1192
1289
  }
1193
1290
 
1194
1291
  const box = viewport.getBoundingClientRect(),
1195
- before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top));
1292
+ before = Math.max(0, round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
1196
1293
 
1197
- return { start: -before, size: before + Math.max(view, Math.round(size - before)) };
1294
+ return { start: -before, size: before + Math.max(view + pad.end, round(size - before)) };
1198
1295
  }
1199
1296
 
1200
1297
  // 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
1201
1298
  // come after the writes of another carousel, and the browser does one layout for all of them.
1202
- const owners = new WeakMap();
1299
+ const owners = new WeakMap(),
1300
+ // The elements of each owner, and the last size of each element
1301
+ watched = new WeakMap(),
1302
+ sizes = new WeakMap();
1203
1303
 
1204
1304
  let resizer;
1205
1305
 
1206
1306
  /**
1207
1307
  * Watch the size of elements. The ResizeObserver callback calls owner.read() for each owner, and then owner.write() for each owner whose read() returned true.
1208
- * An entry for which owner.skip() returns true does not count.
1308
+ * An entry for which owner.skip() returns true does not count. An entry with the same size as the last entry of its element does not count:
1309
+ * a new watch of an element after a write sends such an entry. observeSize() clears the last size, so its first entry always counts.
1209
1310
  *
1210
1311
  * @param {Element[]} nodes
1211
1312
  * @param {{read: () => boolean, write: () => void, skip: (entry: ResizeObserverEntry) => boolean}} [owner] Without an owner, stop the watch.
1212
1313
  */
1213
1314
  function observeSize(nodes, owner) {
1214
1315
  resizer ||= new ResizeObserver((entries) => {
1215
- const list = new Set(entries.filter((entry) => !owners.get(entry.target)?.skip(entry)).map((entry) => owners.get(entry.target)));
1216
- [...list].filter((item) => item && item.read()).forEach((item) => item.write());
1316
+ const list = new Set(entries.filter((entry) => {
1317
+ const { inlineSize, blockSize } = entry.borderBoxSize[0],
1318
+ size = inlineSize + ',' + blockSize,
1319
+ same = sizes.get(entry.target) === size;
1320
+ sizes.set(entry.target, size);
1321
+ return !same && !owners.get(entry.target)?.skip(entry);
1322
+ }).map((entry) => owners.get(entry.target)));
1323
+ const changed = [...list].filter((item) => item && item.read());
1324
+ changed.forEach((item) => item.write());
1325
+ // A write can change the size of an element that the observer watches, for example the auto height or the clones. If the observer has
1326
+ // a change to report after its callback, the browser sends the "ResizeObserver loop" error to window.onerror. Stop the watch of these
1327
+ // elements, and watch them again in the next frame. Then the first callback measures again and finds no change.
1328
+ if (changed.length) {
1329
+ changed.forEach((item) => watched.get(item)?.forEach((node) => resizer.unobserve(node)));
1330
+ requestAnimationFrame(() => changed.forEach((item) => watched.get(item)?.forEach((node) => owners.get(node) === item && resizer.observe(node))));
1331
+ }
1217
1332
  });
1218
1333
 
1334
+ if (owner) {
1335
+ watched.set(owner, nodes);
1336
+ }
1337
+
1219
1338
  for (const node of nodes) {
1339
+ sizes.delete(node);
1220
1340
  if (owner) {
1221
1341
  owners.set(node, owner);
1222
1342
  resizer.observe(node);
@@ -1305,10 +1425,10 @@ function bezier([x1, y1, x2, y2]) {
1305
1425
  for (let i = 0; i < 6; i++) {
1306
1426
  const error = axis(x1, x2, t) - x,
1307
1427
  slope = 3 * (1 + 3 * x1 - 3 * x2) * t * t + 2 * (3 * x2 - 6 * x1) * t + 3 * x1;
1308
- if (Math.abs(error) < 1e-5) {
1428
+ if (abs(error) < 1e-5) {
1309
1429
  return axis(y1, y2, t);
1310
1430
  }
1311
- if (Math.abs(slope) < 1e-6) {
1431
+ if (abs(slope) < 1e-6) {
1312
1432
  break;
1313
1433
  }
1314
1434
  t -= error / slope;
@@ -1741,6 +1861,8 @@ function carousel(element, userOptions, defaults, features) {
1741
1861
  // The observers and the measure state
1742
1862
  let observed = [],
1743
1863
  mutationObserver,
1864
+ // Watches the content of the slides while the carousel has clones
1865
+ copyObserver,
1744
1866
  media = null,
1745
1867
  ready = false,
1746
1868
  started = false,
@@ -1767,11 +1889,11 @@ function carousel(element, userOptions, defaults, features) {
1767
1889
 
1768
1890
  const api = {
1769
1891
  goToSnap: (index, instant) => go(physical(index), instant),
1770
- goToNext: (instant) => api.canGoToNext() && step(selected, 1, instant),
1771
- goToPrev: (instant) => api.canGoToPrev() && step(selected, -1, instant),
1892
+ goToNext: (instant) => advance(1, instant),
1893
+ goToPrev: (instant) => advance(-1, instant),
1772
1894
  goToSlide: (index, instant) => go(physical(api.snapOfSlide(index)), instant, index),
1773
- canGoToNext: () => !!geo && !geo.fit && (!!geo.period || selected < geo.snaps.length - 1),
1774
- canGoToPrev: () => !!geo && !geo.fit && (!!geo.period || selected > 0),
1895
+ canGoToNext: () => can(1),
1896
+ canGoToPrev: () => can(-1),
1775
1897
  selectedSnap: () => logical(selected),
1776
1898
  previousSnap: () => logical(previous),
1777
1899
  selectedSlide,
@@ -1799,7 +1921,7 @@ function carousel(element, userOptions, defaults, features) {
1799
1921
  each = { node: null, index: 0, offset: 0, distance: 0, size: 0, visible: 0 },
1800
1922
  /**
1801
1923
  * What the features share: the API, the events, and the state and the actions of the carousel.
1802
- * setup() adds root, viewport, container, cls and options.
1924
+ * setup() adds root, viewport, container, cls and options. reinit() adds playing: the play state of the autoplay and the auto scroll before a breakpoint change.
1803
1925
  */
1804
1926
  context = {
1805
1927
  api,
@@ -1977,6 +2099,8 @@ function carousel(element, userOptions, defaults, features) {
1977
2099
  resolved = null;
1978
2100
  }
1979
2101
  const keep = geo ? selectedSlide() : requested;
2102
+ // After a breakpoint change, the new autoplay and auto scroll keep the play state. New options start them again.
2103
+ context.playing = newOptions ? null : { autoplay: api.autoplay?.isPlaying(), autoScroll: api.autoScroll?.isPlaying() };
1980
2104
  teardown(true);
1981
2105
  setup();
1982
2106
  requested = keep;
@@ -1998,6 +2122,27 @@ function carousel(element, userOptions, defaults, features) {
1998
2122
  nodes = slides.concat(clones);
1999
2123
  written.slides.length = slides.length;
2000
2124
  mutationObserver?.takeRecords();
2125
+
2126
+ copyObserver?.disconnect();
2127
+ if (clones.length) {
2128
+ copyObserver ||= new MutationObserver(onCopy);
2129
+ slides.forEach((node) => copyObserver.observe(node, { childList: true, characterData: true, subtree: true, attributeFilter: ['class', 'src', 'srcset', 'href', 'value'] }));
2130
+ }
2131
+ }
2132
+
2133
+ /**
2134
+ * Copy a changed slide into its clones. The carousel writes the classes of the slides, so a change of a slide's own attributes does not count.
2135
+ *
2136
+ * @param {MutationRecord[]} records
2137
+ */
2138
+ function onCopy(records) {
2139
+ slides.forEach((node, index) => {
2140
+ if (records.some(({ type, target }) => node.contains(target) && (type !== 'attributes' || target !== node))) {
2141
+ for (let item = index; item < clones.length; item += slides.length) {
2142
+ copyContent(clones[item], node);
2143
+ }
2144
+ }
2145
+ });
2001
2146
  }
2002
2147
 
2003
2148
  /**
@@ -2027,8 +2172,15 @@ function carousel(element, userOptions, defaults, features) {
2027
2172
  return same && options.autoHeight && geo?.axis === 'x';
2028
2173
  }
2029
2174
 
2175
+ // Keep the selected slide. If the page removed it, select the slide that is now at its index, or the last slide.
2030
2176
  function onMutation() {
2177
+ const old = ready ? selectedSlide() : -1,
2178
+ node = slides[old];
2031
2179
  slides = readSlides(container, options.slides);
2180
+ if (old > -1) {
2181
+ const index = slides.indexOf(node);
2182
+ requested = index > -1 ? index : Math.min(old, slides.length - 1);
2183
+ }
2032
2184
  setClones(0);
2033
2185
  nodes = slides;
2034
2186
  changed = true;
@@ -2081,17 +2233,18 @@ function carousel(element, userOptions, defaults, features) {
2081
2233
  // With clones: 'fill', the loop fills the window
2082
2234
  lastWindow = options.loop && options.clones === 'fill' ? windowSize(layout.axis) : 0;
2083
2235
 
2084
- const area = visibleArea(viewport, layout, rects.view, lastWindow),
2236
+ const area = visibleArea(viewport, layout, rects.view, rects.pad, lastWindow),
2085
2237
  values = [layout.axis, layout.rtl, typeof layout.align === 'string' && layout.align, rects.view, rects.gap, area.start, area.size, ...rects.slides.flatMap((slide) => [slide.start, slide.end, slide.cross])];
2086
2238
 
2087
2239
  // A change of less than 0.5 px is not a change. During a motion, the rects have small errors, because the browser and bezier() round the easing differently.
2088
- if (ready && values.length === signature.length && values.every((value, index) => value === signature[index] || Math.abs(value - signature[index]) < 0.5)) {
2240
+ if (ready && values.length === signature.length && values.every((value, index) => value === signature[index] || abs(value - signature[index]) < 0.5)) {
2089
2241
  return false;
2090
2242
  }
2091
2243
 
2092
2244
  signature = values;
2093
2245
 
2094
- const keep = ready ? selectedSlide() : requested,
2246
+ // After a change of the slides, onMutation() gives the slide to keep
2247
+ const keep = ready && !changed ? selectedSlide() : requested,
2095
2248
  next = compute(layout, rects, area, slides.length, options);
2096
2249
 
2097
2250
  if (!next.snaps) {
@@ -2103,8 +2256,9 @@ function carousel(element, userOptions, defaults, features) {
2103
2256
 
2104
2257
  const total = geo.snaps.length;
2105
2258
 
2106
- // Before the first measure pass, selected is the logical snap of the startSnap option or of goToSnap()
2107
- selected = keep >= 0 ? physical(api.snapOfSlide(keep)) : Math.min(total - 1, ready ? selected : physical(selected));
2259
+ // Before the first measure pass, selected is the logical snap of the startSnap option, of goToSnap() or of goToNext().
2260
+ // In loop mode, a step before the first snap goes to the last snap.
2261
+ selected = keep >= 0 ? physical(api.snapOfSlide(keep)) : Math.min(total - 1, ready ? selected : physical(snapIndex(selected, geo.logical.length, geo.period)));
2108
2262
  previous = Math.min(previous, total - 1);
2109
2263
  requested = keep;
2110
2264
  if (!dragging) {
@@ -2211,7 +2365,7 @@ function carousel(element, userOptions, defaults, features) {
2211
2365
  */
2212
2366
  function screen(value) {
2213
2367
  const scale = devicePixelRatio || 1;
2214
- return Math.round(value * scale) / scale * geo.sign;
2368
+ return round(value * scale) / scale * geo.sign;
2215
2369
  }
2216
2370
 
2217
2371
  /**
@@ -2255,7 +2409,7 @@ function carousel(element, userOptions, defaults, features) {
2255
2409
  root.style.setProperty('--better-progress', progress(at, geo));
2256
2410
  } else if (options.progress) {
2257
2411
  const value = snapPosition(geo.snaps, at, geo.period),
2258
- snap = Math.floor(value);
2412
+ snap = floor(value);
2259
2413
  whole.progress = progress(at, geo);
2260
2414
  whole.snap = logical(snap) + value - snap;
2261
2415
  options.progress(whole, api);
@@ -2308,6 +2462,30 @@ function carousel(element, userOptions, defaults, features) {
2308
2462
  return translate(screen(value)) || '0px';
2309
2463
  }
2310
2464
 
2465
+ /**
2466
+ * Find if the carousel can go one snap in a direction.
2467
+ *
2468
+ * @param {number} direction 1 or -1.
2469
+ * @returns {boolean}
2470
+ */
2471
+ function can(direction) {
2472
+ return !!geo && !geo.fit && (!!geo.period || (direction > 0 ? selected < geo.snaps.length - 1 : selected > 0));
2473
+ }
2474
+
2475
+ /**
2476
+ * Go one snap in a direction, if the carousel can. Before the first measure pass, keep the step in the selected snap.
2477
+ *
2478
+ * @param {number} direction 1 or -1.
2479
+ * @param {boolean} [instant]
2480
+ */
2481
+ function advance(direction, instant) {
2482
+ if (!geo) {
2483
+ go(selected + direction, instant);
2484
+ } else if (can(direction)) {
2485
+ step(selected, direction, instant);
2486
+ }
2487
+ }
2488
+
2311
2489
  /**
2312
2490
  * Go to the snap after a snap in a direction. In loop mode, the first snap follows the last snap.
2313
2491
  *
@@ -2339,7 +2517,7 @@ function carousel(element, userOptions, defaults, features) {
2339
2517
  }
2340
2518
 
2341
2519
  const target = targetLocation(geo.snaps[index].location, current(), geo.period, direction),
2342
- span = Math.abs(index - selected),
2520
+ span = abs(index - selected),
2343
2521
  count = geo.period ? Math.min(span, geo.snaps.length - span) : span;
2344
2522
 
2345
2523
  move(index, target, instant ? 0 : snapDuration(options.duration, count), EASE);
@@ -2356,7 +2534,7 @@ function carousel(element, userOptions, defaults, features) {
2356
2534
  function move(index, target, duration, curve) {
2357
2535
  const from = halt(),
2358
2536
  picked = select(index),
2359
- jump = !duration || geo.fit || Math.abs(target - from) < 0.5;
2537
+ jump = !duration || geo.fit || abs(target - from) < 0.5;
2360
2538
 
2361
2539
  location = target;
2362
2540
 
@@ -2396,10 +2574,10 @@ function carousel(element, userOptions, defaults, features) {
2396
2574
  // Start in the first period, so that the location does not grow after each pause
2397
2575
  location = normalize(from, geo.period);
2398
2576
  motion.loop(location, direction, geo.period / speed, geo, nodes);
2399
- } else if (Math.abs(to - from) > 1) {
2577
+ } else if (abs(to - from) > 1) {
2400
2578
  free = true;
2401
2579
  location = to;
2402
- motion.run(from, to, Math.abs(to - from) / speed, [0, 0, 1, 1], events.has('scroll'));
2580
+ motion.run(from, to, abs(to - from) / speed, [0, 0, 1, 1], events.has('scroll'));
2403
2581
  }
2404
2582
  }
2405
2583
 
@@ -2499,6 +2677,9 @@ function carousel(element, userOptions, defaults, features) {
2499
2677
  // The targets that keep their own pointer behavior
2500
2678
  const fields = 'input,textarea,select,[contenteditable]';
2501
2679
 
2680
+ // The pointerdown events that a carousel took for a drag
2681
+ const claimed = new WeakSet();
2682
+
2502
2683
  // The duration of the motion for one wheel event, in ms
2503
2684
  const WHEEL = 180;
2504
2685
 
@@ -2515,10 +2696,10 @@ const MOMENTUM = 325;
2515
2696
  * @returns {number}
2516
2697
  */
2517
2698
  function releaseDuration(path, velocity, curve, fallback) {
2518
- if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
2699
+ if (Math.sign(path) !== Math.sign(velocity) || abs(velocity) < 0.05) {
2519
2700
  return fallback;
2520
2701
  }
2521
- return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
2702
+ return clamp(abs(path) * curve[1] / curve[0] / abs(velocity), 200, 1200);
2522
2703
  }
2523
2704
 
2524
2705
  /**
@@ -2583,9 +2764,9 @@ function releaseTarget({ location, from, velocity, current, snaps, min, max, per
2583
2764
 
2584
2765
  let direction = 0;
2585
2766
 
2586
- if (Math.abs(velocity) > 0.3) {
2767
+ if (abs(velocity) > 0.3) {
2587
2768
  direction = velocity < 0 ? 1 : -1;
2588
- } else if (Math.abs(moved) > 20) {
2769
+ } else if (abs(moved) > 20) {
2589
2770
  direction = moved < 0 ? 1 : -1;
2590
2771
  }
2591
2772
 
@@ -2620,27 +2801,31 @@ function drag(context) {
2620
2801
  // The selected snap at the drag start
2621
2802
  snap = 0;
2622
2803
 
2623
- const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
2804
+ const listen = bind(window, [['pointermove', handle], ['pointerup', handle], ['pointercancel', handle]]);
2624
2805
 
2625
2806
  function down(event) {
2626
2807
  block = false;
2627
2808
 
2628
2809
  const geo = context.geo();
2629
2810
 
2630
- if (pointer !== null || event.button || !geo || geo.fit || event.target.closest(fields)) {
2811
+ // In nested carousels, the inner carousel gets the press first and claims it
2812
+ if (pointer !== null || event.button || !geo || geo.fit || claimed.has(event) || event.target.closest(fields)) {
2631
2813
  return;
2632
2814
  }
2633
2815
 
2816
+ claimed.add(event);
2817
+
2634
2818
  // Stop the text selection and the native image drag
2635
2819
  if (event.pointerType === 'mouse') {
2636
2820
  event.preventDefault();
2637
2821
  }
2638
2822
 
2639
2823
  pointer = event.pointerId;
2640
- axis = { x: geo.axis === 'x', sign: geo.sign };
2824
+ // In a parent with a CSS scale, one px of the pointer is not one px of the carousel
2825
+ axis = { x: geo.axis === 'x', sign: geo.sign, scale: geo.scale };
2641
2826
  start = [event.clientX, event.clientY];
2642
2827
  samples = [];
2643
- listen('addEventListener');
2828
+ listen(true);
2644
2829
  }
2645
2830
 
2646
2831
  function handle(event) {
@@ -2656,17 +2841,17 @@ function drag(context) {
2656
2841
  return end(event.type === 'pointerup');
2657
2842
  }
2658
2843
 
2659
- const dx = event.clientX - start[0],
2660
- dy = event.clientY - start[1],
2844
+ const dx = (event.clientX - start[0]) / axis.scale,
2845
+ dy = (event.clientY - start[1]) / axis.scale,
2661
2846
  main = axis.x ? dx * axis.sign : dy,
2662
2847
  cross = axis.x ? dy : dx;
2663
2848
 
2664
2849
  if (!context.dragging()) {
2665
2850
  // A touch move across the axis scrolls the page
2666
- if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
2851
+ if (event.pointerType !== 'mouse' && abs(cross) > abs(main)) {
2667
2852
  return end();
2668
2853
  }
2669
- if (Math.abs(main) < options.dragThreshold) {
2854
+ if (abs(main) < options.dragThreshold) {
2670
2855
  return;
2671
2856
  }
2672
2857
  // Stop the motion, and start the drag at the location where the carousel is now
@@ -2696,7 +2881,7 @@ function drag(context) {
2696
2881
  * @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
2697
2882
  */
2698
2883
  function end(up) {
2699
- listen('removeEventListener');
2884
+ listen();
2700
2885
  pointer = null;
2701
2886
 
2702
2887
  if (!context.dragging()) {
@@ -2727,22 +2912,43 @@ function drag(context) {
2727
2912
  // 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.
2728
2913
  const select = (event) => context.dragging() && event.preventDefault();
2729
2914
 
2730
- viewport.addEventListener('pointerdown', down);
2731
- viewport.addEventListener('click', click, true);
2732
- viewport.addEventListener('dragstart', prevent);
2733
- viewport.addEventListener('selectstart', select);
2915
+ const own = bind(viewport, [['pointerdown', down], ['click', click, true], ['dragstart', prevent], ['selectstart', select]]);
2916
+
2917
+ own(true);
2734
2918
 
2735
2919
  return {
2736
2920
  remove() {
2737
- listen('removeEventListener');
2738
- viewport.removeEventListener('pointerdown', down);
2739
- viewport.removeEventListener('click', click, true);
2740
- viewport.removeEventListener('dragstart', prevent);
2741
- viewport.removeEventListener('selectstart', select);
2921
+ listen();
2922
+ own();
2742
2923
  }
2743
2924
  };
2744
2925
  }
2745
2926
 
2927
+ /**
2928
+ * Find an element between a node and the viewport that can scroll in a direction.
2929
+ *
2930
+ * @param {Element} node The target of the wheel event.
2931
+ * @param {Element} viewport
2932
+ * @param {string} axis 'x' or 'y'.
2933
+ * @param {number} delta The wheel delta on the axis.
2934
+ * @returns {boolean}
2935
+ */
2936
+ function scrolls(node, viewport, axis, delta) {
2937
+ const [size, client, position, overflow] = axis === 'x' ? ['scrollWidth', 'clientWidth', 'scrollLeft', 'overflowX'] : ['scrollHeight', 'clientHeight', 'scrollTop', 'overflowY'];
2938
+
2939
+ for (; node && node !== viewport; node = node.parentElement) {
2940
+ // Read the style only for an element with more content than space
2941
+ if (node[size] > node[client] && /auto|scroll/.test(getComputedStyle(node)[overflow])) {
2942
+ const at = abs(node[position]);
2943
+ if (delta > 0 ? at + node[client] < node[size] - 1 : at > 0) {
2944
+ return true;
2945
+ }
2946
+ }
2947
+ }
2948
+
2949
+ return false;
2950
+ }
2951
+
2746
2952
  /**
2747
2953
  * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
2748
2954
  * the wheel distance with a short motion on the compositor. When the wheel stops, the carousel goes to a snap. At the first and the last
@@ -2760,9 +2966,12 @@ function wheel(context) {
2760
2966
  return;
2761
2967
  }
2762
2968
 
2763
- // The time of the last wheel event, and of the last event that moved the carousel
2969
+ // The time and the delta size of the last wheel event, and true if the gesture moved the carousel
2764
2970
  let time = 0,
2765
- moved = 0,
2971
+ last = 0,
2972
+ held = false,
2973
+ // true while a gesture scrolls an element in a slide
2974
+ inner = false,
2766
2975
  // The timer that finds the end of a gesture
2767
2976
  timer = 0,
2768
2977
  // The selected snap at the gesture start, and the direction of the last step
@@ -2771,7 +2980,7 @@ function wheel(context) {
2771
2980
 
2772
2981
  function onWheel(event) {
2773
2982
  const geo = context.geo(),
2774
- side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
2983
+ side = geo.axis === 'x' && abs(event.deltaX) > abs(event.deltaY),
2775
2984
  delta = side ? event.deltaX * geo.sign : event.deltaY;
2776
2985
 
2777
2986
  if (event.ctrlKey || !delta || context.dragging()) {
@@ -2780,7 +2989,21 @@ function wheel(context) {
2780
2989
 
2781
2990
  const now = event.timeStamp,
2782
2991
  gesture = now - time < 200,
2783
- base = context.location(),
2992
+ size = abs(delta),
2993
+ // A delta that does not grow is the inertia of the gesture, not a new push
2994
+ inertia = gesture && size <= last;
2995
+
2996
+ time = now;
2997
+ last = size;
2998
+ held &&= gesture;
2999
+
3000
+ // An element in a slide that can scroll in the wheel direction scrolls, also for the rest of its gesture
3001
+ inner = (gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta);
3002
+ if (inner) {
3003
+ return;
3004
+ }
3005
+
3006
+ const base = context.location(),
2784
3007
  path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
2785
3008
 
2786
3009
  let target = base - path;
@@ -2788,11 +3011,9 @@ function wheel(context) {
2788
3011
  target = clamp(target, geo.min, geo.max);
2789
3012
  }
2790
3013
 
2791
- time = now;
2792
-
2793
3014
  // At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
2794
- if (Math.abs(target - base) < 0.5) {
2795
- if (gesture && now - moved < 1000) {
3015
+ if (abs(target - base) < 0.5) {
3016
+ if (held && inertia) {
2796
3017
  event.preventDefault();
2797
3018
  }
2798
3019
  return;
@@ -2804,7 +3025,7 @@ function wheel(context) {
2804
3025
  if (!timer) {
2805
3026
  snap = context.selected();
2806
3027
  }
2807
- moved = now;
3028
+ held = true;
2808
3029
  direction = path > 0 ? 1 : -1;
2809
3030
  context.move(nearestSnap(geo.snaps, target, geo.period), target, WHEEL, EASE);
2810
3031
 
@@ -2820,23 +3041,23 @@ function wheel(context) {
2820
3041
  const geo = context.geo(),
2821
3042
  at = context.current(),
2822
3043
  index = nearestSnap(geo.snaps, at, geo.period),
2823
- away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
3044
+ away = abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
2824
3045
 
2825
3046
  context.step(index, index === snap && away ? direction : 0);
2826
3047
  }
2827
3048
 
2828
3049
  // A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
2829
3050
  // Add it only where the wheel moves the carousel.
2830
- function listen() {
2831
- const geo = context.geo();
2832
- viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
2833
- }
3051
+ const listen = bind(viewport, [['wheel', onWheel, { passive: false }]]);
2834
3052
 
2835
- ['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
3053
+ ['init', 'reinit', 'resize'].forEach((name) => context.on(name, () => {
3054
+ const geo = context.geo();
3055
+ listen(!geo.fit && (geo.axis === 'y' || options.wheel === 'both'));
3056
+ }));
2836
3057
 
2837
3058
  return {
2838
3059
  remove() {
2839
- viewport.removeEventListener('wheel', onWheel);
3060
+ listen();
2840
3061
  clearTimeout(timer);
2841
3062
  }
2842
3063
  };
@@ -2869,13 +3090,11 @@ function keys(context) {
2869
3090
  }
2870
3091
  }
2871
3092
 
2872
- root.addEventListener('keydown', onKey);
3093
+ const listen = bind(root, [['keydown', onKey]]);
2873
3094
 
2874
- return {
2875
- remove() {
2876
- root.removeEventListener('keydown', onKey);
2877
- }
2878
- };
3095
+ listen(true);
3096
+
3097
+ return { remove: listen };
2879
3098
  }
2880
3099
 
2881
3100
  /**
@@ -2909,223 +3128,210 @@ function focus(context) {
2909
3128
  context.emit('slidefocus');
2910
3129
  }
2911
3130
 
2912
- container.addEventListener('pointerdown', press);
2913
- container.addEventListener('focusin', onFocus);
3131
+ const listen = bind(container, [['pointerdown', press], ['focusin', onFocus]]);
3132
+
3133
+ listen(true);
3134
+
3135
+ return { remove: listen };
3136
+ }
3137
+
3138
+ /*
3139
+ * Navigation: the arrows, the dots, and the link to another carousel (the sync option).
3140
+ *
3141
+ * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
3142
+ */
3143
+
3144
+
3145
+ /**
3146
+ * Make the arrows and the dots of a carousel. They update on the carousel events.
3147
+ *
3148
+ * @param {object} context What the features share. See carousel.js.
3149
+ * @returns {{remove: () => void}|undefined} remove() removes the arrows and the dots.
3150
+ */
3151
+ function nav(context) {
3152
+ const { api, root, cls, options } = context,
3153
+ labels = options.labels,
3154
+ arrows = optionElement(options.arrows, root),
3155
+ box = optionElement(options.dots, root),
3156
+ buttons = [],
3157
+ dots = [],
3158
+ // The window of 5 dots, or all dots with dotsStyle: 'all'
3159
+ windowed = options.dotsStyle !== 'all',
3160
+ // The window of the dots, the track that slides in it, and the marker of the selected dot
3161
+ list = box && create('div', windowed ? cls.dots : cls.dots + ' ' + cls.dotsAll),
3162
+ track = list && create('div', cls.dotsTrack);
3163
+
3164
+ let marks = new Map();
3165
+
3166
+ if (!arrows && !box) {
3167
+ return;
3168
+ }
3169
+
3170
+ // Add the window of the dots now: its CSS height is fixed, so the dots that the first measure adds do not shift the page
3171
+ if (list) {
3172
+ track.append(create('span', cls.dotsMarker));
3173
+ list.append(track);
3174
+ box.append(list);
3175
+ }
3176
+
3177
+ if (arrows) {
3178
+ buttons.push(createButton(cls.button + ' ' + cls.prevButton, context.container, labels.prev, () => api.goToPrev()), createButton(cls.button + ' ' + cls.nextButton, context.container, labels.next, () => api.goToNext()));
3179
+ }
3180
+
3181
+ function update() {
3182
+ const fit = api.isFit(),
3183
+ count = fit ? 0 : api.snapProgress().length,
3184
+ selected = api.selectedSnap();
3185
+
3186
+ buttons.forEach((item, index) => {
3187
+ if (fit) {
3188
+ item.remove();
3189
+ } else {
3190
+ if (!item.isConnected) {
3191
+ // Before the dots, for the tab order
3192
+ list?.parentNode === arrows ? list.before(item) : arrows.append(item);
3193
+ }
3194
+ const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
3195
+ if (item.disabled !== disabled) {
3196
+ item.disabled = disabled;
3197
+ }
3198
+ }
3199
+ });
3200
+
3201
+ if (!list) {
3202
+ return;
3203
+ }
3204
+
3205
+ if (count < 2) {
3206
+ list.remove();
3207
+ return;
3208
+ }
3209
+
3210
+ while (dots.length > count) {
3211
+ dots.pop().remove();
3212
+ marks.delete(dots.length);
3213
+ }
3214
+
3215
+ while (dots.length < count) {
3216
+ const index = dots.length,
3217
+ dot = createButton(cls.dot, context.container, labels.dot.replace('%d', index + 1), () => api.goToSnap(index));
3218
+ // The window of the dots hides the dots out of the zoom: keep them out of the tab order
3219
+ if (windowed) {
3220
+ dot.tabIndex = -1;
3221
+ }
3222
+ dots.push(dot);
3223
+ track.append(dot);
3224
+ }
3225
+
3226
+ if (!list.isConnected) {
3227
+ box.append(list);
3228
+ }
3229
+
3230
+ // The zoom effect: the 5 dots around the selected dot get state classes
3231
+ const next = new Map();
3232
+
3233
+ ['first', 'prev', 'current', 'next', 'last'].forEach((key, offset) => {
3234
+ if (dots[selected + offset - 2]) {
3235
+ next.set(selected + offset - 2, cls[key]);
3236
+ }
3237
+ });
3238
+
3239
+ marks.forEach((name, index) => {
3240
+ if (next.get(index) !== name) {
3241
+ setClass(dots[index], name, false);
3242
+ setAttribute(dots[index], 'aria-current', false);
3243
+ dots[index].tabIndex = windowed ? -1 : 0;
3244
+ }
3245
+ });
3246
+
3247
+ next.forEach((name, index) => {
3248
+ setClass(dots[index], name, true);
3249
+ setAttribute(dots[index], 'aria-current', index === selected && 'true');
3250
+ dots[index].tabIndex = 0;
3251
+ });
3252
+
3253
+ marks = next;
3254
+
3255
+ // Center the group of up to 5 dots in the window of the dots, and move the marker to the selected dot. The CSS moves the track and the marker with "translate".
3256
+ if (windowed) {
3257
+ variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3258
+ }
3259
+ variable('--better-dot', selected);
3260
+ }
3261
+
3262
+ // Set a CSS variable on the window of the dots, if its value changes
3263
+ function variable(name, value) {
3264
+ if (list.style.getPropertyValue(name) !== String(value)) {
3265
+ list.style.setProperty(name, value);
3266
+ }
3267
+ }
3268
+
3269
+ ['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
2914
3270
 
2915
3271
  return {
2916
3272
  remove() {
2917
- container.removeEventListener('pointerdown', press);
2918
- container.removeEventListener('focusin', onFocus);
3273
+ buttons.forEach((item) => item.remove());
3274
+ list?.remove();
2919
3275
  }
2920
3276
  };
2921
3277
  }
2922
3278
 
2923
- /*
2924
- * Navigation: the arrows, the dots, and the link to another carousel (the sync option).
2925
- *
2926
- * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
2927
- */
2928
-
2929
-
2930
- /**
2931
- * Make the arrows and the dots of a carousel. They update on the carousel events.
2932
- *
2933
- * @param {object} context What the features share. See carousel.js.
2934
- * @returns {{remove: () => void}|undefined} remove() removes the arrows and the dots.
2935
- */
2936
- function nav(context) {
2937
- const { api, root, cls, options } = context,
2938
- labels = options.labels,
2939
- arrows = optionElement(options.arrows, root),
2940
- box = optionElement(options.dots, root),
2941
- buttons = [],
2942
- dots = [],
2943
- // The window of 5 dots, or all dots with dotsStyle: 'all'
2944
- windowed = options.dotsStyle !== 'all',
2945
- // The window of the dots, the track that slides in it, and the marker of the selected dot
2946
- list = box && create('div', windowed ? cls.dots : cls.dots + ' ' + cls.dotsAll),
2947
- track = list && create('div', cls.dotsTrack);
2948
-
2949
- let marks = new Map();
2950
-
2951
- if (!arrows && !box) {
2952
- return;
2953
- }
2954
-
2955
- // Add the window of the dots now: its CSS height is fixed, so the dots that the first measure adds do not shift the page
2956
- if (list) {
2957
- track.append(create('span', cls.dotsMarker));
2958
- list.append(track);
2959
- box.append(list);
2960
- }
2961
-
2962
- if (arrows) {
2963
- [['prev', 'goToPrev'], ['next', 'goToNext']].forEach(([key, method]) => {
2964
- const button = create('button', cls.button + ' ' + cls[key + 'Button']);
2965
- button.type = 'button';
2966
- button.setAttribute('aria-label', labels[key]);
2967
- button.setAttribute('aria-controls', context.container.id);
2968
- button.addEventListener('click', () => api[method]());
2969
- buttons.push(button);
2970
- });
2971
- }
2972
-
2973
- function update() {
2974
- const fit = api.isFit(),
2975
- count = fit ? 0 : api.snapProgress().length,
2976
- selected = api.selectedSnap();
2977
-
2978
- buttons.forEach((button, index) => {
2979
- if (fit) {
2980
- button.remove();
2981
- } else {
2982
- if (!button.isConnected) {
2983
- // Before the dots, for the tab order
2984
- list?.parentNode === arrows ? list.before(button) : arrows.append(button);
2985
- }
2986
- const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
2987
- if (button.disabled !== disabled) {
2988
- button.disabled = disabled;
2989
- }
2990
- }
2991
- });
2992
-
2993
- if (!list) {
2994
- return;
2995
- }
2996
-
2997
- if (count < 2) {
2998
- list.remove();
2999
- return;
3000
- }
3001
-
3002
- while (dots.length > count) {
3003
- dots.pop().remove();
3004
- marks.delete(dots.length);
3005
- }
3006
-
3007
- while (dots.length < count) {
3008
- const dot = create('button', cls.dot),
3009
- index = dots.length;
3010
- dot.type = 'button';
3011
- dot.setAttribute('aria-label', labels.dot.replace('%d', index + 1));
3012
- dot.setAttribute('aria-controls', context.container.id);
3013
- // The window of the dots hides the dots out of the zoom: keep them out of the tab order
3014
- if (windowed) {
3015
- dot.tabIndex = -1;
3016
- }
3017
- dot.addEventListener('click', () => api.goToSnap(index));
3018
- dots.push(dot);
3019
- track.append(dot);
3020
- }
3021
-
3022
- if (!list.isConnected) {
3023
- box.append(list);
3024
- }
3025
-
3026
- // The zoom effect: the 5 dots around the selected dot get state classes
3027
- const next = new Map();
3028
-
3029
- ['first', 'prev', 'current', 'next', 'last'].forEach((key, offset) => {
3030
- if (dots[selected + offset - 2]) {
3031
- next.set(selected + offset - 2, cls[key]);
3032
- }
3033
- });
3034
-
3035
- marks.forEach((name, index) => {
3036
- if (next.get(index) !== name) {
3037
- setClass(dots[index], name, false);
3038
- setAttribute(dots[index], 'aria-current', false);
3039
- dots[index].tabIndex = windowed ? -1 : 0;
3040
- }
3041
- });
3042
-
3043
- next.forEach((name, index) => {
3044
- setClass(dots[index], name, true);
3045
- setAttribute(dots[index], 'aria-current', index === selected && 'true');
3046
- dots[index].tabIndex = 0;
3047
- });
3048
-
3049
- marks = next;
3050
-
3051
- // Center the group of up to 5 dots in the window of the dots, and move the marker to the selected dot. The CSS moves the track and the marker with "translate".
3052
- if (windowed) {
3053
- variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3054
- }
3055
- variable('--better-dot', selected);
3056
- }
3057
-
3058
- // Set a CSS variable on the window of the dots, if its value changes
3059
- function variable(name, value) {
3060
- if (list.style.getPropertyValue(name) !== String(value)) {
3061
- list.style.setProperty(name, value);
3062
- }
3063
- }
3064
-
3065
- ['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
3066
-
3067
- return {
3068
- remove() {
3069
- buttons.forEach((button) => button.remove());
3070
- list?.remove();
3071
- }
3072
- };
3073
- }
3074
-
3075
- /**
3076
- * Connect a carousel to another carousel with the same slides, such as thumbnails to a main gallery. This carousel follows the slide
3077
- * that the other carousel selects. Only a click on a slide of this carousel selects that slide in the other carousel: a drag does not.
3078
- *
3079
- * @param {object} context What the features share. See carousel.js. The "sync" option is the other carousel, its container or a selector.
3080
- * @returns {{remove: () => void}|undefined} remove() disconnects the carousels.
3081
- */
3082
- function sync(context) {
3083
- const { api, container } = context,
3084
- target = context.options.sync;
3085
-
3086
- let other = null;
3087
-
3088
- if (!target) {
3089
- return;
3090
- }
3091
-
3092
- // Show the slide that the other carousel selects
3093
- function show(instant) {
3094
- const index = other.selectedSlide();
3095
- context.follow(index);
3096
- api.goToSlide(index, instant === true);
3097
- }
3098
-
3099
- function click(event) {
3100
- // The slide or the clone that gets the click, and then its original slide
3101
- const index = context.nodes().findIndex((node) => node.contains(event.target));
3102
- if (other && index > -1) {
3103
- other.goToSlide(index % api.slideNodes().length);
3104
- }
3105
- }
3106
-
3107
- // The other carousel can come later than this one, so find it at the init
3108
- function connect() {
3109
- if (other) {
3110
- return;
3111
- }
3112
- other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
3113
- if (other) {
3114
- other.on('select', show);
3115
- show(true);
3116
- }
3117
- }
3118
-
3119
- context.on('init', connect);
3120
- context.on('reinit', connect);
3121
- container.addEventListener('click', click);
3122
-
3123
- return {
3124
- remove() {
3125
- other?.off('select', show);
3126
- container.removeEventListener('click', click);
3127
- }
3128
- };
3279
+ /**
3280
+ * Connect a carousel to another carousel with the same slides, such as thumbnails to a main gallery. This carousel follows the slide
3281
+ * that the other carousel selects. Only a click on a slide of this carousel selects that slide in the other carousel: a drag does not.
3282
+ *
3283
+ * @param {object} context What the features share. See carousel.js. The "sync" option is the other carousel, its container or a selector.
3284
+ * @returns {{remove: () => void}|undefined} remove() disconnects the carousels.
3285
+ */
3286
+ function sync(context) {
3287
+ const { api, container } = context,
3288
+ target = context.options.sync;
3289
+
3290
+ let other = null;
3291
+
3292
+ if (!target) {
3293
+ return;
3294
+ }
3295
+
3296
+ // Show the slide that the other carousel selects
3297
+ function show(instant) {
3298
+ const index = other.selectedSlide();
3299
+ context.follow(index);
3300
+ api.goToSlide(index, instant === true);
3301
+ }
3302
+
3303
+ function click(event) {
3304
+ // The slide or the clone that gets the click, and then its original slide
3305
+ const index = context.nodes().findIndex((node) => node.contains(event.target));
3306
+ if (other && index > -1) {
3307
+ other.goToSlide(index % api.slideNodes().length);
3308
+ }
3309
+ }
3310
+
3311
+ // The other carousel can come later than this one, so find it at the init
3312
+ function connect() {
3313
+ if (other) {
3314
+ return;
3315
+ }
3316
+ other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
3317
+ if (other) {
3318
+ other.on('select', show);
3319
+ show(true);
3320
+ }
3321
+ }
3322
+
3323
+ context.on('init', connect);
3324
+ context.on('reinit', connect);
3325
+ const listen = bind(container, [['click', click]]);
3326
+
3327
+ listen(true);
3328
+
3329
+ return {
3330
+ remove() {
3331
+ other?.off('select', show);
3332
+ listen();
3333
+ }
3334
+ };
3129
3335
  }
3130
3336
 
3131
3337
  /*