@twistedandy/better-carousel 1.1.1 → 1.1.3

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.
@@ -34,12 +34,12 @@ function setAttribute(element, name, value) {
34
34
  * Set an inline style property.
35
35
  *
36
36
  * @param {HTMLElement} element
37
- * @param {string} name
38
- * @param {string} value An empty string removes the property.
37
+ * @param {string} name The CSS name, such as 'touch-action' or '--better-dot'.
38
+ * @param {string|number} value An empty string removes the property.
39
39
  */
40
40
  function setStyle(element, name, value) {
41
- if (element.style[name] !== value) {
42
- element.style[name] = value;
41
+ if (element.style.getPropertyValue(name) !== String(value)) {
42
+ element.style.setProperty(name, value);
43
43
  }
44
44
  }
45
45
 
@@ -128,16 +128,14 @@ const marked = new WeakMap(),
128
128
  *
129
129
  * @param {Element} node
130
130
  * @param {string} name
131
- * @param {string} value
131
+ * @param {string} value An empty value removes the attribute, for example an empty label.
132
132
  */
133
133
  function own(node, name, value) {
134
134
  const list = marked.get(node) || new Set();
135
135
  if (list.has(name) || !node.hasAttribute(name)) {
136
136
  list.add(name);
137
137
  marked.set(node, list);
138
- if (node.getAttribute(name) !== value) {
139
- node.setAttribute(name, value);
140
- }
138
+ setAttribute(node, name, value);
141
139
  }
142
140
  }
143
141
 
@@ -252,7 +250,8 @@ function readSlides(container, selector) {
252
250
  }
253
251
 
254
252
  /**
255
- * Make the clones: full copies of the slides, which the screen reader and the keyboard do not see.
253
+ * Make the clones: full copies of the slides, which the screen reader and the keyboard do not see. A clone is inert, so the pointer
254
+ * does not see it either: the carousel passes a click on a clone to its slide.
256
255
  *
257
256
  * @param {HTMLElement[]} slides
258
257
  * @param {number} count The number of copies of all slides.
@@ -278,12 +277,16 @@ function copySlides(slides, count, className) {
278
277
  return list;
279
278
  }
280
279
 
281
- // Copy a node with its content. An id must be unique in the page, so the copy has no ids.
280
+ // Copy a node with its content. An id must be unique in the page, so the copy has no ids. A form field in the copy has no name and is not
281
+ // required: it does not join the radio group of its slide, the form does not send it, and the form check does not stop at it.
282
282
  function copy(node) {
283
- const result = node.cloneNode(true);
284
- for (const item of [result, ...result.querySelectorAll('[id]')]) {
285
- item.removeAttribute('id');
283
+ const result = node.cloneNode(true),
284
+ selects = node.querySelectorAll('select');
285
+ for (const item of [result, ...result.querySelectorAll('[id],[name],[required]')]) {
286
+ ['id', 'name', 'required'].forEach((name) => item.removeAttribute(name));
286
287
  }
288
+ // The copy keeps the values and the checks of the fields, but not the selected option
289
+ result.querySelectorAll('select').forEach((item, index) => item.selectedIndex = selects[index].selectedIndex);
287
290
  return result;
288
291
  }
289
292
 
@@ -448,13 +451,17 @@ function controller(context, key, options, hooks) {
448
451
  isPlaying: () => playing,
449
452
  paused: () => !playing || watch.paused(),
450
453
  remove() {
454
+ // Keep the play state for the setup after a breakpoint change. See reinit() in carousel.js.
455
+ if (context.playing) {
456
+ context.playing[key] = playing;
457
+ }
451
458
  control.stop();
452
459
  button.remove();
453
460
  delete api[key];
454
461
  }
455
462
  };
456
463
 
457
- [['init', show], ['reinit', show], ['resize', show], ...hooks.events].forEach(([event, handler]) => context.on(event, handler));
464
+ [['init reinit resize', show], ...hooks.events].forEach(([names, handler]) => context.on(names, handler));
458
465
  update();
459
466
  api[key] = control;
460
467
 
@@ -965,15 +972,11 @@ function activeSlide(slides, location, view, align, period, from = 0, to = slide
965
972
  /**
966
973
  * Find the snap of a slide: the snap whose active slide it is, or the snap nearest to the raw location of the slide.
967
974
  *
968
- * @param {Array<{location: number, slide: number}>} list The snaps.
969
- * @param {Array<{start: number, end: number}>} slides
975
+ * @param {{snaps: Array<{location: number, slide: number}>, slides: Array<{start: number, end: number}>, view: number, align: string|Function, period?: number}} geo
970
976
  * @param {number} index The slide index.
971
- * @param {number} view
972
- * @param {string|Function} align
973
- * @param {number} [period]
974
977
  * @returns {number} The snap index.
975
978
  */
976
- function snapOfSlide(list, slides, index, view, align, period) {
979
+ function snapOfSlide({ snaps: list, slides, view, align, period }, index) {
977
980
  const found = list.findIndex((snap) => snap.slide === index),
978
981
  slide = slides[index];
979
982
 
@@ -1039,14 +1042,12 @@ function progress(location, { min, max, period }) {
1039
1042
  /**
1040
1043
  * Find the slides that show at a location.
1041
1044
  *
1042
- * @param {Array<{start: number, end: number}>} slides
1045
+ * @param {{slides: Array<{start: number, end: number}>, view: number, period?: number}} geo
1043
1046
  * @param {number} location
1044
- * @param {number} view
1045
1047
  * @param {number} threshold The part of a slide that must show, from 0 to 1. With 0, any part is enough.
1046
- * @param {number} [period]
1047
1048
  * @returns {number[]} The slide indexes.
1048
1049
  */
1049
- function inView(slides, location, view, threshold, period) {
1050
+ function inView({ slides, view, period }, location, threshold) {
1050
1051
  const result = [];
1051
1052
 
1052
1053
  slides.forEach((slide, index) => {
@@ -1093,26 +1094,27 @@ function snapPosition(list, location, period) {
1093
1094
  * With clones, a logical snap is a snap whose active slide is an original slide.
1094
1095
  *
1095
1096
  * @param {object} layout The result of readLayout().
1096
- * @param {{view: number, slides: Array<{start: number, end: number}>, gap: number}} rects The result of readRects(). The slides after the first count slides are clones.
1097
- * @param {{start: number, size: number}} area The result of visibleArea().
1097
+ * @param {{view: number, slides: Array<{start: number, end: number}>, gap: number, area: {start: number, size: number}}} rects The result of readRects().
1098
+ * The slides after the first count slides are clones.
1098
1099
  * @param {number} count The number of original slides.
1099
1100
  * @param {object} options The options of the carousel.
1100
1101
  * @returns {object} The geometry. If the carousel needs a different number of clones, only { copies }: the number of copies of all slides.
1101
1102
  * map gives the logical snap of each snap.
1102
1103
  */
1103
- function compute(layout, rects, area, count, options) {
1104
+ function compute(layout, rects, count, options) {
1104
1105
  const content = bounds(rects.slides.slice(0, count)),
1105
- fit = content.size <= rects.view + 1 && !(options.autoScroll && options.loop),
1106
+ // The auto scroll with the loop never fits, unless no slide shows, for example in a hidden tab
1107
+ fit = content.size <= rects.view + 1 && !(options.autoScroll && options.loop && content.max),
1106
1108
  loop = options.loop && !fit && count,
1107
1109
  // The loop period: the distance from the first slide start to the same point in the next copy of the slides
1108
1110
  period = loop ? bounds(rects.slides).size + rects.gap : 0,
1109
- copies = loop && options.clones ? cloneCount(content.size + rects.gap, area.size, content.max) : 0;
1111
+ copies = loop && options.clones ? cloneCount(content.size + rects.gap, rects.area.size, content.max) : 0;
1110
1112
 
1111
1113
  if (copies * count !== rects.slides.length - count) {
1112
1114
  return { copies };
1113
1115
  }
1114
1116
 
1115
- const geo = { ...layout, ...rects, area, fit, count, period, min: 0, max: 0 };
1117
+ const geo = { ...layout, ...rects, fit, count, period, min: 0, max: 0 };
1116
1118
 
1117
1119
  if (fit) {
1118
1120
  geo.snaps = [{ location: 0, slide: Math.max(0, activeSlide(rects.slides, 0, rects.view, layout.align)) }];
@@ -1191,19 +1193,21 @@ function readLayout(container, options) {
1191
1193
 
1192
1194
  /**
1193
1195
  * 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
+ * The values are in the px of the carousel: in a parent with a CSS scale or zoom, such as a modal window that opens with a scale animation,
1197
+ * the values do not change. A rotation of a parent is not supported.
1196
1198
  * 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.
1197
1199
  *
1198
1200
  * @param {HTMLElement} viewport
1199
1201
  * @param {HTMLElement[]} nodes All slides, clones included.
1200
1202
  * @param {object} layout The result of readLayout().
1201
1203
  * @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
1202
- * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, pad: {start: number, end: number}}}
1204
+ * @param {number} [size] The window size on the main axis, for clones: 'fill'.
1205
+ * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, area: {start: number, size: number}}}
1203
1206
  * 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.
1207
+ * scale is the screen px of one px of the carousel. area is the part of the main axis where the loop must show slides: the viewport with its
1208
+ * padding, or with a size, the window, so that the slides fill it when the viewport overflow shows.
1205
1209
  */
1206
- function readRects(viewport, nodes, layout, written) {
1210
+ function readRects(viewport, nodes, layout, written, size) {
1207
1211
  const box = viewport.getBoundingClientRect(),
1208
1212
  x = layout.axis === 'x',
1209
1213
  sign = layout.sign,
@@ -1211,11 +1215,9 @@ function readRects(viewport, nodes, layout, written) {
1211
1215
  shift = known ? written.container : 0,
1212
1216
  width = viewport.offsetWidth,
1213
1217
  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,
1218
+ // offsetWidth is a whole number: a difference of less than 1 px is not a scale
1219
+ scale = width && height && (abs(box.width - width) >= 1 || abs(box.height - height) >= 1) ? (x ? box.width / width : box.height / height) : 1,
1220
+ view = (x ? box.width : box.height) / scale,
1219
1221
  style = getComputedStyle(viewport),
1220
1222
  side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
1221
1223
  pad = { start: parseFloat(style['padding' + side[0]]) || 0, end: parseFloat(style['padding' + side[1]]) || 0 };
@@ -1253,12 +1255,23 @@ function readRects(viewport, nodes, layout, written) {
1253
1255
  gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
1254
1256
  }
1255
1257
 
1258
+ const inner = view - pad.start - pad.end;
1259
+
1260
+ // The area before and after the inner edge of the viewport padding: the padding, or the window
1261
+ let before = pad.start,
1262
+ after = inner + pad.end;
1263
+
1264
+ if (size) {
1265
+ before += Math.max(0, round(x ? (layout.rtl ? size - box.right : box.left) : box.top));
1266
+ after = Math.max(after, round(size - before));
1267
+ }
1268
+
1256
1269
  return {
1257
- view: view - pad.start - pad.end,
1270
+ view: inner,
1258
1271
  slides,
1259
1272
  gap,
1260
1273
  scale,
1261
- pad
1274
+ area: { start: -before, size: before + after }
1262
1275
  };
1263
1276
  }
1264
1277
 
@@ -1272,28 +1285,6 @@ function windowSize(axis) {
1272
1285
  return axis === 'x' ? document.documentElement.clientWidth : innerHeight;
1273
1286
  }
1274
1287
 
1275
- /**
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.
1278
- *
1279
- * @param {HTMLElement} viewport
1280
- * @param {{axis: string, rtl: boolean}} layout
1281
- * @param {number} view The viewport size without the padding.
1282
- * @param {{start: number, end: number}} pad The viewport padding.
1283
- * @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
1284
- * @returns {{start: number, size: number}}
1285
- */
1286
- function visibleArea(viewport, layout, view, pad, size) {
1287
- if (!size) {
1288
- return { start: -pad.start, size: pad.start + view + pad.end };
1289
- }
1290
-
1291
- const box = viewport.getBoundingClientRect(),
1292
- before = Math.max(0, round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
1293
-
1294
- return { start: -before, size: before + Math.max(view + pad.end, round(size - before)) };
1295
- }
1296
-
1297
1288
  // 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
1298
1289
  // come after the writes of another carousel, and the browser does one layout for all of them.
1299
1290
  const owners = new WeakMap(),
@@ -1313,14 +1304,13 @@ let resizer;
1313
1304
  */
1314
1305
  function observeSize(nodes, owner) {
1315
1306
  resizer ||= new ResizeObserver((entries) => {
1316
- const list = new Set(entries.filter((entry) => {
1307
+ const changed = [...new Set(entries.filter((entry) => {
1317
1308
  const { inlineSize, blockSize } = entry.borderBoxSize[0],
1318
1309
  size = inlineSize + ',' + blockSize,
1319
1310
  same = sizes.get(entry.target) === size;
1320
1311
  sizes.set(entry.target, size);
1321
1312
  return !same && !owners.get(entry.target)?.skip(entry);
1322
- }).map((entry) => owners.get(entry.target)));
1323
- const changed = [...list].filter((item) => item && item.read());
1313
+ }).map((entry) => owners.get(entry.target)))].filter((item) => item?.read());
1324
1314
  changed.forEach((item) => item.write());
1325
1315
  // 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
1316
  // a change to report after its callback, the browser sends the "ResizeObserver loop" error to window.onerror. Stop the watch of these
@@ -1347,53 +1337,67 @@ function observeSize(nodes, owner) {
1347
1337
  }
1348
1338
  }
1349
1339
 
1350
- // The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the boxes that readBoxes() read
1340
+ // The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the elements to check: [node, lazy, margin]
1351
1341
  const watchers = new Map(),
1352
- waiters = new WeakMap(),
1353
- boxes = new WeakMap();
1342
+ waiters = new WeakMap();
1354
1343
 
1355
- /**
1356
- * Read the boxes of elements before a carousel writes to the DOM. Then the reads of all carousels cause one layout, not one for each carousel.
1357
- * waitNear() uses each box one time.
1358
- *
1359
- * @param {Element[]} elements
1360
- */
1361
- function readBoxes(elements) {
1362
- elements.forEach((element) => boxes.set(element, element.getBoundingClientRect()));
1363
- }
1344
+ let queue = [];
1364
1345
 
1365
1346
  /**
1366
- * Wait until an element comes near the screen.
1347
+ * Wait until an element comes near the screen. One microtask reads the boxes of all elements that started to wait, after the writes of
1348
+ * the carousels that started without a wait. Then the reads cause one layout, not one for each carousel. The microtask runs before the
1349
+ * first paint, so a carousel near the screen starts before the page shows, and it does not move the page.
1367
1350
  *
1368
1351
  * @param {Element} node
1369
1352
  * @param {true|number} lazy The "lazy" option: true for one screen height, or a distance in px.
1370
1353
  * @param {Function} callback
1371
- * @returns {Function|null} A function that stops the wait, or null if the element is near the screen now.
1354
+ * @returns {Function} A function that stops the wait.
1372
1355
  */
1373
1356
  function waitNear(node, lazy, callback) {
1374
- const near = lazy === true ? innerHeight : lazy,
1375
- rect = boxes.get(node) || node.getBoundingClientRect(),
1376
- margin = lazy === true ? '100%' : lazy + 'px';
1377
-
1378
- boxes.delete(node);
1379
-
1380
- if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
1381
- return null;
1382
- }
1357
+ const margin = lazy === true ? '100%' : lazy + 'px';
1383
1358
 
1384
- let observer = watchers.get(margin);
1385
- if (!observer) {
1386
- observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
1387
- watchers.set(margin, observer);
1359
+ if (!queue.length) {
1360
+ queueMicrotask(check);
1388
1361
  }
1362
+ queue.push([node, lazy, margin]);
1389
1363
  waiters.set(node, callback);
1390
- observer.observe(node);
1364
+
1391
1365
  return () => {
1392
- observer.unobserve(node);
1366
+ watchers.get(margin)?.unobserve(node);
1393
1367
  waiters.delete(node);
1394
1368
  };
1395
1369
  }
1396
1370
 
1371
+ // Call the callback of each element near the screen, and watch the other elements. An element whose wait stopped has no callback.
1372
+ function check() {
1373
+ const list = queue,
1374
+ rects = list.map(([node]) => node.getBoundingClientRect());
1375
+
1376
+ queue = [];
1377
+
1378
+ list.forEach(([node, lazy, margin], index) => {
1379
+ const near = lazy === true ? innerHeight : lazy,
1380
+ rect = rects[index],
1381
+ callback = waiters.get(node);
1382
+
1383
+ if (!callback) {
1384
+ return;
1385
+ }
1386
+
1387
+ if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
1388
+ callback();
1389
+ return;
1390
+ }
1391
+
1392
+ let observer = watchers.get(margin);
1393
+ if (!observer) {
1394
+ observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
1395
+ watchers.set(margin, observer);
1396
+ }
1397
+ observer.observe(node);
1398
+ });
1399
+ }
1400
+
1397
1401
  /*
1398
1402
  * Motion: the easing, the duration of a goToSnap() motion, and the motion engine.
1399
1403
  */
@@ -1791,6 +1795,9 @@ function breakpoints(base, change) {
1791
1795
  // The instance of each root, viewport and container
1792
1796
  const registry = new WeakMap();
1793
1797
 
1798
+ // true if the browser supports the pan-up and pan-down values of touch-action
1799
+ let directional;
1800
+
1794
1801
  /**
1795
1802
  * Get the carousel of a root, a viewport or a container.
1796
1803
  *
@@ -1801,7 +1808,7 @@ const find = (element) => registry.get(element);
1801
1808
 
1802
1809
  /**
1803
1810
  * Make an event emitter. A handler gets (api, name), as in Embla.
1804
- * The handlers of the features run before the handlers of the page, and clear() removes them.
1811
+ * The handlers of the features run before the handlers of the page, and clear() removes them. listen() takes event names with spaces between them.
1805
1812
  *
1806
1813
  * @param {object} api
1807
1814
  * @returns {{on: Function, off: Function, listen: Function, clear: Function, emit: Function, has: Function}}
@@ -1820,7 +1827,7 @@ function emitter(api) {
1820
1827
  user[name]?.delete(handler);
1821
1828
  return api;
1822
1829
  },
1823
- listen: (name, handler) => add(own, name, handler),
1830
+ listen: (names, handler) => names.split(' ').forEach((name) => add(own, name, handler)),
1824
1831
  clear: () => Object.values(own).forEach((set) => set.clear()),
1825
1832
  emit(name) {
1826
1833
  own[name]?.forEach((handler) => handler(api, name));
@@ -1897,7 +1904,7 @@ function carousel(element, userOptions, defaults, features) {
1897
1904
  selectedSnap: () => logical(selected),
1898
1905
  previousSnap: () => logical(previous),
1899
1906
  selectedSlide,
1900
- snapOfSlide: (index) => geo ? logical(snapOfSlide(geo.snaps, geo.slides, index, geo.view, geo.align, geo.period)) : index,
1907
+ snapOfSlide: (index) => geo ? logical(snapOfSlide(geo, index)) : index,
1901
1908
  snapProgress: () => geo ? geo.logical.map((index) => progress(geo.snaps[index].location, geo)) : [],
1902
1909
  progress: () => geo ? progress(current(), geo) : 0,
1903
1910
  slideNodes: () => slides.slice(),
@@ -1921,19 +1928,23 @@ function carousel(element, userOptions, defaults, features) {
1921
1928
  each = { node: null, index: 0, offset: 0, distance: 0, size: 0, visible: 0 },
1922
1929
  /**
1923
1930
  * What the features share: the API, the events, and the state and the actions of the carousel.
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.
1931
+ * setup() adds root, viewport, container, cls and options. reinit() adds playing: an object where the autoplay and the auto scroll
1932
+ * keep their play state for the next setup after a breakpoint change.
1925
1933
  */
1926
1934
  context = {
1927
1935
  api,
1928
1936
  emit: events.emit,
1929
- // Listen to an event until the teardown
1937
+ // Listen to events, such as 'init reinit', until the teardown
1930
1938
  on: events.listen,
1939
+ // Get the carousel of an element, for the sync option
1940
+ find,
1931
1941
 
1932
1942
  // The state
1933
1943
  geo: () => geo,
1934
- nodes: () => nodes,
1935
1944
  selected: () => selected,
1936
1945
  dragging: () => dragging,
1946
+ // true while a motion to a location runs, such as a goToSnap() motion or a glide. The auto scroll is not such a motion.
1947
+ moving: () => !free && motion.current() !== null,
1937
1948
  // The location at rest or at the end of the motion. During a free motion, the location now.
1938
1949
  location: () => free ? current() : location,
1939
1950
  current,
@@ -1968,8 +1979,7 @@ function carousel(element, userOptions, defaults, features) {
1968
1979
  api.on = events.on;
1969
1980
  api.off = events.off;
1970
1981
 
1971
- // The options of the first setup. The lazy option: a carousel that is not near the screen waits. A carousel near the screen starts now:
1972
- // a start after the first paint adds the arrows and the dots in view, and this moves the page (CLS).
1982
+ // The options of the first setup. The lazy option: the carousel waits, and waitNear() starts it before the first paint if it is near the screen.
1973
1983
  let resolved = resolve(element, defaults, userOptions),
1974
1984
  waiting = resolved.lazy ? waitNear(element, resolved.lazy, reinit) : null;
1975
1985
 
@@ -2016,6 +2026,8 @@ function carousel(element, userOptions, defaults, features) {
2016
2026
  }
2017
2027
 
2018
2028
  viewport.addEventListener('scroll', onScroll);
2029
+ viewport.addEventListener('click', onClick);
2030
+ viewport.addEventListener('input', onInput);
2019
2031
  if (options.loop && options.clones === 'fill') {
2020
2032
  addEventListener('resize', onWindow);
2021
2033
  }
@@ -2052,21 +2064,17 @@ function carousel(element, userOptions, defaults, features) {
2052
2064
  dragging = free = false;
2053
2065
  setClones(0);
2054
2066
  viewport.removeEventListener('scroll', onScroll);
2067
+ viewport.removeEventListener('click', onClick);
2068
+ viewport.removeEventListener('input', onInput);
2055
2069
  removeEventListener('resize', onWindow);
2056
2070
 
2057
- for (const node of nodes) {
2058
- setStyle(node, 'translate', '');
2059
- node.style.removeProperty('--better-offset');
2060
- setClass(node, cls.selected, false);
2061
- setClass(node, cls.inView, false);
2062
- cleanStyle(node);
2063
- }
2071
+ nodes.forEach(clean);
2064
2072
 
2065
2073
  setStyle(container, 'translate', '');
2066
- setStyle(container, 'willChange', '');
2067
- setStyle(viewport, 'touchAction', '');
2074
+ setStyle(container, 'will-change', '');
2075
+ setStyle(viewport, 'touch-action', '');
2068
2076
  setStyle(viewport, 'height', '');
2069
- root.style.removeProperty('--better-progress');
2077
+ setStyle(root, '--better-progress', '');
2070
2078
 
2071
2079
  for (const name of ['horizontal', 'vertical', 'fit', 'dragging']) {
2072
2080
  setClass(root, cls[name], false);
@@ -2100,7 +2108,7 @@ function carousel(element, userOptions, defaults, features) {
2100
2108
  }
2101
2109
  const keep = geo ? selectedSlide() : requested;
2102
2110
  // 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() };
2111
+ context.playing = newOptions ? null : {};
2104
2112
  teardown(true);
2105
2113
  setup();
2106
2114
  requested = keep;
@@ -2131,13 +2139,15 @@ function carousel(element, userOptions, defaults, features) {
2131
2139
  }
2132
2140
 
2133
2141
  /**
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.
2142
+ * Copy a changed slide into its clones, for example after the page changed a text or an image source. The carousel writes the classes
2143
+ * of the slides, so a change of a slide's own attributes does not count. A style change does not count: a "progress" or an "offset"
2144
+ * callback can write the styles of the elements in the slides on each frame.
2135
2145
  *
2136
- * @param {MutationRecord[]} records
2146
+ * @param {MutationRecord[]} [records] With no records, copy all slides.
2137
2147
  */
2138
2148
  function onCopy(records) {
2139
2149
  slides.forEach((node, index) => {
2140
- if (records.some(({ type, target }) => node.contains(target) && (type !== 'attributes' || target !== node))) {
2150
+ if (!records || records.some(({ type, target }) => node.contains(target) && (type !== 'attributes' || target !== node))) {
2141
2151
  for (let item = index; item < clones.length; item += slides.length) {
2142
2152
  copyContent(clones[item], node);
2143
2153
  }
@@ -2145,6 +2155,11 @@ function carousel(element, userOptions, defaults, features) {
2145
2155
  });
2146
2156
  }
2147
2157
 
2158
+ // A form field changes its value or its check with no mutation. A checked radio also changes the radios of its group in other slides, so copy all slides.
2159
+ function onInput() {
2160
+ onCopy();
2161
+ }
2162
+
2148
2163
  /**
2149
2164
  * Watch the size of the viewport, the container and the slides.
2150
2165
  *
@@ -2172,17 +2187,37 @@ function carousel(element, userOptions, defaults, features) {
2172
2187
  return same && options.autoHeight && geo?.axis === 'x';
2173
2188
  }
2174
2189
 
2190
+ /**
2191
+ * Remove the styles and the classes that the carousel wrote on a slide or a clone.
2192
+ *
2193
+ * @param {HTMLElement} node
2194
+ */
2195
+ function clean(node) {
2196
+ setStyle(node, 'translate', '');
2197
+ setStyle(node, '--better-offset', '');
2198
+ setClass(node, cls.selected, false);
2199
+ setClass(node, cls.inView, false);
2200
+ cleanStyle(node);
2201
+ }
2202
+
2175
2203
  // Keep the selected slide. If the page removed it, select the slide that is now at its index, or the last slide.
2204
+ // The loop shift of a slide stays with the slide at its new index, because the measure pass subtracts it from the slide box.
2205
+ // A new slide can have the same size as the slide that it replaced, so the measure pass must not skip.
2176
2206
  function onMutation() {
2177
2207
  const old = ready ? selectedSlide() : -1,
2178
- node = slides[old];
2208
+ node = slides[old],
2209
+ shifts = new Map(slides.map((item, index) => [item, written.slides[index]]));
2179
2210
  slides = readSlides(container, options.slides);
2180
2211
  if (old > -1) {
2181
2212
  const index = slides.indexOf(node);
2182
2213
  requested = index > -1 ? index : Math.min(old, slides.length - 1);
2183
2214
  }
2215
+ // A removed slide can come back later, for example after a sort. It must not keep a loop shift.
2216
+ shifts.forEach((shift, item) => slides.includes(item) || clean(item));
2184
2217
  setClones(0);
2185
2218
  nodes = slides;
2219
+ written.slides = slides.map((item) => shifts.get(item) || 0);
2220
+ signature = [];
2186
2221
  changed = true;
2187
2222
  observe(true);
2188
2223
  }
@@ -2226,15 +2261,14 @@ function carousel(element, userOptions, defaults, features) {
2226
2261
  function measure() {
2227
2262
  const sign = geo?.sign || 1,
2228
2263
  at = motion.current(),
2229
- layout = readLayout(container, options),
2230
- // The translate values that show now: the written values, or the values of a motion
2231
- rects = readRects(viewport, nodes, layout, at === null ? written : { axis: written.axis, container: sign * at, slides: motion.shifts(sign) || written.slides });
2264
+ layout = readLayout(container, options);
2232
2265
 
2233
2266
  // With clones: 'fill', the loop fills the window
2234
2267
  lastWindow = options.loop && options.clones === 'fill' ? windowSize(layout.axis) : 0;
2235
2268
 
2236
- const area = visibleArea(viewport, layout, rects.view, rects.pad, lastWindow),
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])];
2269
+ // The translate values that show now: the written values, or the values of a motion
2270
+ const rects = readRects(viewport, nodes, layout, at === null ? written : { axis: written.axis, container: sign * at, slides: motion.shifts(sign) || written.slides }, lastWindow),
2271
+ values = [layout.axis, layout.rtl, typeof layout.align === 'string' && layout.align, rects.view, rects.gap, rects.area.start, rects.area.size, ...rects.slides.flatMap((slide) => [slide.start, slide.end, slide.cross])];
2238
2272
 
2239
2273
  // 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.
2240
2274
  if (ready && values.length === signature.length && values.every((value, index) => value === signature[index] || abs(value - signature[index]) < 0.5)) {
@@ -2245,7 +2279,7 @@ function carousel(element, userOptions, defaults, features) {
2245
2279
 
2246
2280
  // After a change of the slides, onMutation() gives the slide to keep
2247
2281
  const keep = ready && !changed ? selectedSlide() : requested,
2248
- next = compute(layout, rects, area, slides.length, options);
2282
+ next = compute(layout, rects, slides.length, options);
2249
2283
 
2250
2284
  if (!next.snaps) {
2251
2285
  pending = next.copies;
@@ -2333,8 +2367,13 @@ function carousel(element, userOptions, defaults, features) {
2333
2367
  setClass(root, cls.horizontal, x);
2334
2368
  setClass(root, cls.vertical, !x);
2335
2369
  setClass(root, cls.fit, geo.fit);
2336
- setStyle(viewport, 'touchAction', geo.fit ? '' : x ? 'pan-y pinch-zoom' : 'pan-x pinch-zoom');
2337
- setStyle(container, 'willChange', geo.fit ? '' : 'translate');
2370
+ // A touch can scroll the page across the axis. At the first or the last snap of a vertical carousel, it can also scroll the page up
2371
+ // or down. Safari has no pan-up and pan-down, so there the carousel keeps the touch.
2372
+ const first = !can(-1),
2373
+ last = !can(1),
2374
+ edge = !x && (first || last) && (directional ??= CSS.supports('touch-action', 'pan-up')) ? (first && last ? 'pan-y ' : first ? 'pan-up ' : 'pan-down ') : '';
2375
+ setStyle(viewport, 'touch-action', geo.fit ? '' : x ? 'pan-y pinch-zoom' : 'pan-x ' + edge + 'pinch-zoom');
2376
+ setStyle(container, 'will-change', geo.fit ? '' : 'translate');
2338
2377
 
2339
2378
  if (!keep) {
2340
2379
  write(geo.fit ? 0 : location);
@@ -2342,11 +2381,11 @@ function carousel(element, userOptions, defaults, features) {
2342
2381
 
2343
2382
  // Auto height: the height of the tallest slide in view at the target location
2344
2383
  if (options.autoHeight) {
2345
- setStyle(viewport, 'height', x ? Math.max(...inView(geo.slides, location, geo.view, 0, geo.period).map((index) => geo.slides[index].cross)) + 'px' : '');
2384
+ setStyle(viewport, 'height', x ? Math.max(...inView(geo, location, 0).map((index) => geo.slides[index].cross)) + 'px' : '');
2346
2385
  }
2347
2386
 
2348
2387
  const chosen = selectedSlide(),
2349
- list = [...new Set(inView(geo.slides, location, geo.view, options.inViewThreshold, geo.period).map(original))].sort((a, b) => a - b);
2388
+ list = [...new Set(inView(geo, location, options.inViewThreshold).map(original))].sort((a, b) => a - b);
2350
2389
 
2351
2390
  nodes.forEach((node, index) => setClass(node, cls.selected, original(index) === chosen));
2352
2391
 
@@ -2392,9 +2431,7 @@ function carousel(element, userOptions, defaults, features) {
2392
2431
  written.container = screen(value);
2393
2432
  setStyle(container, 'translate', translate(written.container));
2394
2433
  place(value, value);
2395
- if (options.progress || options.offset) {
2396
- track(value, written.slides);
2397
- }
2434
+ track(value, written.slides);
2398
2435
  }
2399
2436
 
2400
2437
  /**
@@ -2665,6 +2702,27 @@ function carousel(element, userOptions, defaults, features) {
2665
2702
  function onScroll() {
2666
2703
  viewport.scrollLeft = viewport.scrollTop = 0;
2667
2704
  }
2705
+
2706
+ /**
2707
+ * Pass a click on a clone to the same element in its slide. A clone is inert, so the click goes to the viewport or the container.
2708
+ * A click after a drag is cancelled, and it does not pass.
2709
+ *
2710
+ * @param {MouseEvent} event
2711
+ */
2712
+ function onClick(event) {
2713
+ if (event.defaultPrevented || !clones.length || (event.target !== viewport && event.target !== container)) {
2714
+ return;
2715
+ }
2716
+
2717
+ // Find the element under the pointer in the clones, and the element at the same place in the slide
2718
+ clones.forEach((node) => node.inert = false);
2719
+ const node = document.elementFromPoint(event.clientX, event.clientY),
2720
+ index = clones.findIndex((clone) => clone.contains(node)),
2721
+ all = (item) => item ? [item, ...item.querySelectorAll('*')] : [];
2722
+ clones.forEach((item) => item.inert = true);
2723
+
2724
+ all(slides[index % slides.length])[all(clones[index]).indexOf(node)]?.dispatchEvent(new MouseEvent('click', event));
2725
+ }
2668
2726
  }
2669
2727
 
2670
2728
  /*
@@ -2674,7 +2732,7 @@ function carousel(element, userOptions, defaults, features) {
2674
2732
  */
2675
2733
 
2676
2734
 
2677
- // The targets that keep their own pointer behavior
2735
+ // The targets that keep their own pointer and key behavior
2678
2736
  const fields = 'input,textarea,select,[contenteditable]';
2679
2737
 
2680
2738
  // The pointerdown events that a carousel took for a drag
@@ -2797,6 +2855,8 @@ function drag(context) {
2797
2855
  base,
2798
2856
  axis,
2799
2857
  block = false,
2858
+ // true if the press stopped a motion
2859
+ stopped = false,
2800
2860
  samples = [],
2801
2861
  // The selected snap at the drag start
2802
2862
  snap = 0;
@@ -2825,6 +2885,16 @@ function drag(context) {
2825
2885
  axis = { x: geo.axis === 'x', sign: geo.sign, scale: geo.scale };
2826
2886
  start = [event.clientX, event.clientY];
2827
2887
  samples = [];
2888
+
2889
+ // A press stops a motion where it is. The release goes to a snap, and the click after it does not count.
2890
+ // The auto scroll does not stop here: its feature stops it during the press and starts it again after the release.
2891
+ stopped = context.moving();
2892
+ if (stopped) {
2893
+ base = context.halt();
2894
+ snap = context.selected();
2895
+ context.emit('interact');
2896
+ }
2897
+
2828
2898
  listen(true);
2829
2899
  }
2830
2900
 
@@ -2884,27 +2954,35 @@ function drag(context) {
2884
2954
  listen();
2885
2955
  pointer = null;
2886
2956
 
2887
- if (!context.dragging()) {
2957
+ const dragged = context.dragging();
2958
+
2959
+ if (!dragged && !stopped) {
2888
2960
  return;
2889
2961
  }
2890
2962
 
2891
2963
  const geo = context.geo(),
2892
2964
  location = context.location(),
2893
- speed = up ? velocity(samples) : 0,
2894
- target = releaseTarget({ location, from: base, velocity: speed, current: snap, snaps: geo.snaps, min: geo.min, max: geo.max, period: geo.period, skipSnaps: options.skipSnaps, dragFree: options.dragFree, dragFriction: options.dragFriction }),
2965
+ // A press that only stopped a motion has no samples
2966
+ speed = up && samples.length ? velocity(samples) : 0,
2967
+ // The snaps and the limits come from the geometry, and skipSnaps, dragFree and dragFriction from the options
2968
+ target = releaseTarget({ ...geo, ...options, location, from: base, velocity: speed, current: snap }),
2895
2969
  curve = options.dragFree === true ? GLIDE : EASE;
2896
2970
 
2897
2971
  block = true;
2898
- context.drag(false);
2972
+ if (dragged) {
2973
+ context.drag(false);
2974
+ }
2899
2975
  context.move(target.snap, target.location, releaseDuration(target.location - location, speed, curve, options.duration), curve);
2900
2976
  }
2901
2977
 
2978
+ // Cancel the click after a drag. A touch drag sends no click, so the next click can come from the keyboard or a script.
2979
+ // Such a click has no detail (the click count), and it is not cancelled.
2902
2980
  function click(event) {
2903
- if (block) {
2904
- block = false;
2981
+ if (block && event.detail) {
2905
2982
  event.preventDefault();
2906
2983
  event.stopPropagation();
2907
2984
  }
2985
+ block = false;
2908
2986
  }
2909
2987
 
2910
2988
  const prevent = (event) => event.preventDefault();
@@ -2950,7 +3028,8 @@ function scrolls(node, viewport, axis, delta) {
2950
3028
  }
2951
3029
 
2952
3030
  /**
2953
- * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
3031
+ * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. With wheel: 'axis',
3032
+ * a horizontal carousel follows only a horizontal wheel motion, such as a trackpad swipe, and a vertical wheel scrolls the page. The carousel follows
2954
3033
  * 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
2955
3034
  * location, the page scrolls.
2956
3035
  *
@@ -2983,7 +3062,7 @@ function wheel(context) {
2983
3062
  side = geo.axis === 'x' && abs(event.deltaX) > abs(event.deltaY),
2984
3063
  delta = side ? event.deltaX * geo.sign : event.deltaY;
2985
3064
 
2986
- if (event.ctrlKey || !delta || context.dragging()) {
3065
+ if (event.ctrlKey || !delta || context.dragging() || (options.wheel === 'axis' && geo.axis === 'x' && !side)) {
2987
3066
  return;
2988
3067
  }
2989
3068
 
@@ -3050,10 +3129,10 @@ function wheel(context) {
3050
3129
  // Add it only where the wheel moves the carousel.
3051
3130
  const listen = bind(viewport, [['wheel', onWheel, { passive: false }]]);
3052
3131
 
3053
- ['init', 'reinit', 'resize'].forEach((name) => context.on(name, () => {
3132
+ context.on('init reinit resize', () => {
3054
3133
  const geo = context.geo();
3055
- listen(!geo.fit && (geo.axis === 'y' || options.wheel === 'both'));
3056
- }));
3134
+ listen(!geo.fit && (geo.axis === 'y' || options.wheel !== true));
3135
+ });
3057
3136
 
3058
3137
  return {
3059
3138
  remove() {
@@ -3084,7 +3163,7 @@ function keys(context) {
3084
3163
  direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
3085
3164
  name = direction > 0 ? 'Next' : 'Prev';
3086
3165
  // At the first and the last slide, the key scrolls the page
3087
- if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) && api['canGoTo' + name]()) {
3166
+ if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.closest(fields)) && api['canGoTo' + name]()) {
3088
3167
  event.preventDefault();
3089
3168
  api['goTo' + name]();
3090
3169
  }
@@ -3122,7 +3201,7 @@ function focus(context) {
3122
3201
  if (!geo || index < 0 || event.timeStamp - pressed < 600) {
3123
3202
  return;
3124
3203
  }
3125
- if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
3204
+ if (options.focus && !inView(geo, context.location(), 1).map((item) => item % geo.count).includes(index)) {
3126
3205
  api.goToSlide(index);
3127
3206
  }
3128
3207
  context.emit('slidefocus');
@@ -3180,7 +3259,7 @@ function nav(context) {
3180
3259
 
3181
3260
  function update() {
3182
3261
  const fit = api.isFit(),
3183
- count = fit ? 0 : api.snapProgress().length,
3262
+ count = fit ? 0 : context.geo().logical.length,
3184
3263
  selected = api.selectedSnap();
3185
3264
 
3186
3265
  buttons.forEach((item, index) => {
@@ -3254,19 +3333,12 @@ function nav(context) {
3254
3333
 
3255
3334
  // 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
3335
  if (windowed) {
3257
- variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3336
+ setStyle(list, '--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3258
3337
  }
3259
- variable('--better-dot', selected);
3338
+ setStyle(list, '--better-dot', selected);
3260
3339
  }
3261
3340
 
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));
3341
+ context.on('init reinit resize select slideschanged', update);
3270
3342
 
3271
3343
  return {
3272
3344
  remove() {
@@ -3300,11 +3372,11 @@ function sync(context) {
3300
3372
  api.goToSlide(index, instant === true);
3301
3373
  }
3302
3374
 
3375
+ // A click on a clone comes to its slide. See onClick() in carousel.js.
3303
3376
  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));
3377
+ const index = api.slideNodes().findIndex((node) => node.contains(event.target));
3306
3378
  if (other && index > -1) {
3307
- other.goToSlide(index % api.slideNodes().length);
3379
+ other.goToSlide(index);
3308
3380
  }
3309
3381
  }
3310
3382
 
@@ -3313,15 +3385,14 @@ function sync(context) {
3313
3385
  if (other) {
3314
3386
  return;
3315
3387
  }
3316
- other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
3388
+ other = target.goToSnap ? target : context.find(typeof target === 'string' ? optionElement(target, context.root) : target);
3317
3389
  if (other) {
3318
3390
  other.on('select', show);
3319
3391
  show(true);
3320
3392
  }
3321
3393
  }
3322
3394
 
3323
- context.on('init', connect);
3324
- context.on('reinit', connect);
3395
+ context.on('init reinit', connect);
3325
3396
  const listen = bind(container, [['click', click]]);
3326
3397
 
3327
3398
  listen(true);
@@ -3371,11 +3442,6 @@ BetterCarousel.get = find;
3371
3442
  * @param {object} [options]
3372
3443
  * @returns {object[]}
3373
3444
  */
3374
- BetterCarousel.initAll = (selector, options) => {
3375
- const elements = [...document.querySelectorAll(selector)];
3376
- // Read the boxes of the lazy carousels before the first setup() writes. Then the reads cause one layout, not one for each carousel.
3377
- readBoxes(elements.filter((element) => !find(element) && resolve(element, BetterCarousel.defaults, options).lazy));
3378
- return elements.map((element) => BetterCarousel(element, options));
3379
- };
3445
+ BetterCarousel.initAll = (selector, options) => [...document.querySelectorAll(selector)].map((element) => BetterCarousel(element, options));
3380
3446
 
3381
3447
  export { BetterCarousel as default };