@twistedandy/better-carousel 1.1.1 → 1.1.2

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,17 +1928,19 @@ 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,
1937
1946
  // The location at rest or at the end of the motion. During a free motion, the location now.
@@ -1968,8 +1977,7 @@ function carousel(element, userOptions, defaults, features) {
1968
1977
  api.on = events.on;
1969
1978
  api.off = events.off;
1970
1979
 
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).
1980
+ // 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
1981
  let resolved = resolve(element, defaults, userOptions),
1974
1982
  waiting = resolved.lazy ? waitNear(element, resolved.lazy, reinit) : null;
1975
1983
 
@@ -2016,6 +2024,8 @@ function carousel(element, userOptions, defaults, features) {
2016
2024
  }
2017
2025
 
2018
2026
  viewport.addEventListener('scroll', onScroll);
2027
+ viewport.addEventListener('click', onClick);
2028
+ viewport.addEventListener('input', onInput);
2019
2029
  if (options.loop && options.clones === 'fill') {
2020
2030
  addEventListener('resize', onWindow);
2021
2031
  }
@@ -2052,21 +2062,23 @@ function carousel(element, userOptions, defaults, features) {
2052
2062
  dragging = free = false;
2053
2063
  setClones(0);
2054
2064
  viewport.removeEventListener('scroll', onScroll);
2065
+ viewport.removeEventListener('click', onClick);
2066
+ viewport.removeEventListener('input', onInput);
2055
2067
  removeEventListener('resize', onWindow);
2056
2068
 
2057
2069
  for (const node of nodes) {
2058
2070
  setStyle(node, 'translate', '');
2059
- node.style.removeProperty('--better-offset');
2071
+ setStyle(node, '--better-offset', '');
2060
2072
  setClass(node, cls.selected, false);
2061
2073
  setClass(node, cls.inView, false);
2062
2074
  cleanStyle(node);
2063
2075
  }
2064
2076
 
2065
2077
  setStyle(container, 'translate', '');
2066
- setStyle(container, 'willChange', '');
2067
- setStyle(viewport, 'touchAction', '');
2078
+ setStyle(container, 'will-change', '');
2079
+ setStyle(viewport, 'touch-action', '');
2068
2080
  setStyle(viewport, 'height', '');
2069
- root.style.removeProperty('--better-progress');
2081
+ setStyle(root, '--better-progress', '');
2070
2082
 
2071
2083
  for (const name of ['horizontal', 'vertical', 'fit', 'dragging']) {
2072
2084
  setClass(root, cls[name], false);
@@ -2100,7 +2112,7 @@ function carousel(element, userOptions, defaults, features) {
2100
2112
  }
2101
2113
  const keep = geo ? selectedSlide() : requested;
2102
2114
  // 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() };
2115
+ context.playing = newOptions ? null : {};
2104
2116
  teardown(true);
2105
2117
  setup();
2106
2118
  requested = keep;
@@ -2131,13 +2143,15 @@ function carousel(element, userOptions, defaults, features) {
2131
2143
  }
2132
2144
 
2133
2145
  /**
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.
2146
+ * Copy a changed slide into its clones, for example after the page changed a text or an image source. The carousel writes the classes
2147
+ * 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"
2148
+ * callback can write the styles of the elements in the slides on each frame.
2135
2149
  *
2136
- * @param {MutationRecord[]} records
2150
+ * @param {MutationRecord[]} [records] With no records, copy all slides.
2137
2151
  */
2138
2152
  function onCopy(records) {
2139
2153
  slides.forEach((node, index) => {
2140
- if (records.some(({ type, target }) => node.contains(target) && (type !== 'attributes' || target !== node))) {
2154
+ if (!records || records.some(({ type, target }) => node.contains(target) && (type !== 'attributes' || target !== node))) {
2141
2155
  for (let item = index; item < clones.length; item += slides.length) {
2142
2156
  copyContent(clones[item], node);
2143
2157
  }
@@ -2145,6 +2159,11 @@ function carousel(element, userOptions, defaults, features) {
2145
2159
  });
2146
2160
  }
2147
2161
 
2162
+ // 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.
2163
+ function onInput() {
2164
+ onCopy();
2165
+ }
2166
+
2148
2167
  /**
2149
2168
  * Watch the size of the viewport, the container and the slides.
2150
2169
  *
@@ -2226,15 +2245,14 @@ function carousel(element, userOptions, defaults, features) {
2226
2245
  function measure() {
2227
2246
  const sign = geo?.sign || 1,
2228
2247
  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 });
2248
+ layout = readLayout(container, options);
2232
2249
 
2233
2250
  // With clones: 'fill', the loop fills the window
2234
2251
  lastWindow = options.loop && options.clones === 'fill' ? windowSize(layout.axis) : 0;
2235
2252
 
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])];
2253
+ // The translate values that show now: the written values, or the values of a motion
2254
+ const rects = readRects(viewport, nodes, layout, at === null ? written : { axis: written.axis, container: sign * at, slides: motion.shifts(sign) || written.slides }, lastWindow),
2255
+ 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
2256
 
2239
2257
  // 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
2258
  if (ready && values.length === signature.length && values.every((value, index) => value === signature[index] || abs(value - signature[index]) < 0.5)) {
@@ -2245,7 +2263,7 @@ function carousel(element, userOptions, defaults, features) {
2245
2263
 
2246
2264
  // After a change of the slides, onMutation() gives the slide to keep
2247
2265
  const keep = ready && !changed ? selectedSlide() : requested,
2248
- next = compute(layout, rects, area, slides.length, options);
2266
+ next = compute(layout, rects, slides.length, options);
2249
2267
 
2250
2268
  if (!next.snaps) {
2251
2269
  pending = next.copies;
@@ -2333,8 +2351,13 @@ function carousel(element, userOptions, defaults, features) {
2333
2351
  setClass(root, cls.horizontal, x);
2334
2352
  setClass(root, cls.vertical, !x);
2335
2353
  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');
2354
+ // 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
2355
+ // or down. Safari has no pan-up and pan-down, so there the carousel keeps the touch.
2356
+ const first = !can(-1),
2357
+ last = !can(1),
2358
+ edge = !x && (first || last) && (directional ??= CSS.supports('touch-action', 'pan-up')) ? (first && last ? 'pan-y ' : first ? 'pan-up ' : 'pan-down ') : '';
2359
+ setStyle(viewport, 'touch-action', geo.fit ? '' : x ? 'pan-y pinch-zoom' : 'pan-x ' + edge + 'pinch-zoom');
2360
+ setStyle(container, 'will-change', geo.fit ? '' : 'translate');
2338
2361
 
2339
2362
  if (!keep) {
2340
2363
  write(geo.fit ? 0 : location);
@@ -2342,11 +2365,11 @@ function carousel(element, userOptions, defaults, features) {
2342
2365
 
2343
2366
  // Auto height: the height of the tallest slide in view at the target location
2344
2367
  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' : '');
2368
+ setStyle(viewport, 'height', x ? Math.max(...inView(geo, location, 0).map((index) => geo.slides[index].cross)) + 'px' : '');
2346
2369
  }
2347
2370
 
2348
2371
  const chosen = selectedSlide(),
2349
- list = [...new Set(inView(geo.slides, location, geo.view, options.inViewThreshold, geo.period).map(original))].sort((a, b) => a - b);
2372
+ list = [...new Set(inView(geo, location, options.inViewThreshold).map(original))].sort((a, b) => a - b);
2350
2373
 
2351
2374
  nodes.forEach((node, index) => setClass(node, cls.selected, original(index) === chosen));
2352
2375
 
@@ -2392,9 +2415,7 @@ function carousel(element, userOptions, defaults, features) {
2392
2415
  written.container = screen(value);
2393
2416
  setStyle(container, 'translate', translate(written.container));
2394
2417
  place(value, value);
2395
- if (options.progress || options.offset) {
2396
- track(value, written.slides);
2397
- }
2418
+ track(value, written.slides);
2398
2419
  }
2399
2420
 
2400
2421
  /**
@@ -2665,6 +2686,27 @@ function carousel(element, userOptions, defaults, features) {
2665
2686
  function onScroll() {
2666
2687
  viewport.scrollLeft = viewport.scrollTop = 0;
2667
2688
  }
2689
+
2690
+ /**
2691
+ * 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.
2692
+ * A click after a drag is cancelled, and it does not pass.
2693
+ *
2694
+ * @param {MouseEvent} event
2695
+ */
2696
+ function onClick(event) {
2697
+ if (event.defaultPrevented || !clones.length || (event.target !== viewport && event.target !== container)) {
2698
+ return;
2699
+ }
2700
+
2701
+ // Find the element under the pointer in the clones, and the element at the same place in the slide
2702
+ clones.forEach((node) => node.inert = false);
2703
+ const node = document.elementFromPoint(event.clientX, event.clientY),
2704
+ index = clones.findIndex((clone) => clone.contains(node)),
2705
+ all = (item) => item ? [item, ...item.querySelectorAll('*')] : [];
2706
+ clones.forEach((item) => item.inert = true);
2707
+
2708
+ all(slides[index % slides.length])[all(clones[index]).indexOf(node)]?.dispatchEvent(new MouseEvent('click', event));
2709
+ }
2668
2710
  }
2669
2711
 
2670
2712
  /*
@@ -2674,7 +2716,7 @@ function carousel(element, userOptions, defaults, features) {
2674
2716
  */
2675
2717
 
2676
2718
 
2677
- // The targets that keep their own pointer behavior
2719
+ // The targets that keep their own pointer and key behavior
2678
2720
  const fields = 'input,textarea,select,[contenteditable]';
2679
2721
 
2680
2722
  // The pointerdown events that a carousel took for a drag
@@ -2891,7 +2933,8 @@ function drag(context) {
2891
2933
  const geo = context.geo(),
2892
2934
  location = context.location(),
2893
2935
  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 }),
2936
+ // The snaps and the limits come from the geometry, and skipSnaps, dragFree and dragFriction from the options
2937
+ target = releaseTarget({ ...geo, ...options, location, from: base, velocity: speed, current: snap }),
2895
2938
  curve = options.dragFree === true ? GLIDE : EASE;
2896
2939
 
2897
2940
  block = true;
@@ -2950,7 +2993,8 @@ function scrolls(node, viewport, axis, delta) {
2950
2993
  }
2951
2994
 
2952
2995
  /**
2953
- * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
2996
+ * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. With wheel: 'axis',
2997
+ * 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
2998
  * 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
2999
  * location, the page scrolls.
2956
3000
  *
@@ -2983,7 +3027,7 @@ function wheel(context) {
2983
3027
  side = geo.axis === 'x' && abs(event.deltaX) > abs(event.deltaY),
2984
3028
  delta = side ? event.deltaX * geo.sign : event.deltaY;
2985
3029
 
2986
- if (event.ctrlKey || !delta || context.dragging()) {
3030
+ if (event.ctrlKey || !delta || context.dragging() || (options.wheel === 'axis' && geo.axis === 'x' && !side)) {
2987
3031
  return;
2988
3032
  }
2989
3033
 
@@ -3050,10 +3094,10 @@ function wheel(context) {
3050
3094
  // Add it only where the wheel moves the carousel.
3051
3095
  const listen = bind(viewport, [['wheel', onWheel, { passive: false }]]);
3052
3096
 
3053
- ['init', 'reinit', 'resize'].forEach((name) => context.on(name, () => {
3097
+ context.on('init reinit resize', () => {
3054
3098
  const geo = context.geo();
3055
- listen(!geo.fit && (geo.axis === 'y' || options.wheel === 'both'));
3056
- }));
3099
+ listen(!geo.fit && (geo.axis === 'y' || options.wheel !== true));
3100
+ });
3057
3101
 
3058
3102
  return {
3059
3103
  remove() {
@@ -3084,7 +3128,7 @@ function keys(context) {
3084
3128
  direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
3085
3129
  name = direction > 0 ? 'Next' : 'Prev';
3086
3130
  // 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]()) {
3131
+ if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.closest(fields)) && api['canGoTo' + name]()) {
3088
3132
  event.preventDefault();
3089
3133
  api['goTo' + name]();
3090
3134
  }
@@ -3122,7 +3166,7 @@ function focus(context) {
3122
3166
  if (!geo || index < 0 || event.timeStamp - pressed < 600) {
3123
3167
  return;
3124
3168
  }
3125
- if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
3169
+ if (options.focus && !inView(geo, context.location(), 1).map((item) => item % geo.count).includes(index)) {
3126
3170
  api.goToSlide(index);
3127
3171
  }
3128
3172
  context.emit('slidefocus');
@@ -3180,7 +3224,7 @@ function nav(context) {
3180
3224
 
3181
3225
  function update() {
3182
3226
  const fit = api.isFit(),
3183
- count = fit ? 0 : api.snapProgress().length,
3227
+ count = fit ? 0 : context.geo().logical.length,
3184
3228
  selected = api.selectedSnap();
3185
3229
 
3186
3230
  buttons.forEach((item, index) => {
@@ -3254,19 +3298,12 @@ function nav(context) {
3254
3298
 
3255
3299
  // 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
3300
  if (windowed) {
3257
- variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3301
+ setStyle(list, '--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
3258
3302
  }
3259
- variable('--better-dot', selected);
3303
+ setStyle(list, '--better-dot', selected);
3260
3304
  }
3261
3305
 
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));
3306
+ context.on('init reinit resize select slideschanged', update);
3270
3307
 
3271
3308
  return {
3272
3309
  remove() {
@@ -3300,11 +3337,11 @@ function sync(context) {
3300
3337
  api.goToSlide(index, instant === true);
3301
3338
  }
3302
3339
 
3340
+ // A click on a clone comes to its slide. See onClick() in carousel.js.
3303
3341
  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));
3342
+ const index = api.slideNodes().findIndex((node) => node.contains(event.target));
3306
3343
  if (other && index > -1) {
3307
- other.goToSlide(index % api.slideNodes().length);
3344
+ other.goToSlide(index);
3308
3345
  }
3309
3346
  }
3310
3347
 
@@ -3313,15 +3350,14 @@ function sync(context) {
3313
3350
  if (other) {
3314
3351
  return;
3315
3352
  }
3316
- other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
3353
+ other = target.goToSnap ? target : context.find(typeof target === 'string' ? optionElement(target, context.root) : target);
3317
3354
  if (other) {
3318
3355
  other.on('select', show);
3319
3356
  show(true);
3320
3357
  }
3321
3358
  }
3322
3359
 
3323
- context.on('init', connect);
3324
- context.on('reinit', connect);
3360
+ context.on('init reinit', connect);
3325
3361
  const listen = bind(container, [['click', click]]);
3326
3362
 
3327
3363
  listen(true);
@@ -3371,11 +3407,6 @@ BetterCarousel.get = find;
3371
3407
  * @param {object} [options]
3372
3408
  * @returns {object[]}
3373
3409
  */
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
- };
3410
+ BetterCarousel.initAll = (selector, options) => [...document.querySelectorAll(selector)].map((element) => BetterCarousel(element, options));
3380
3411
 
3381
3412
  export { BetterCarousel as default };