@twistedandy/better-carousel 1.1.0 → 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.
@@ -4,10 +4,11 @@
4
4
  * Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
5
5
  */
6
6
 
7
- import { clamp, inView, nearestSnap, snapIndex, targetLocation } from './geometry.js';
7
+ import { abs, clamp, inView, nearestSnap, snapIndex, targetLocation } from './geometry.js';
8
+ import { bind } from './markup.js';
8
9
  import { EASE, GLIDE } from './motion.js';
9
10
 
10
- // The targets that keep their own pointer behavior
11
+ // The targets that keep their own pointer and key behavior
11
12
  const fields = 'input,textarea,select,[contenteditable]';
12
13
 
13
14
  // The pointerdown events that a carousel took for a drag
@@ -29,10 +30,10 @@ const MOMENTUM = 325;
29
30
  * @returns {number}
30
31
  */
31
32
  export function releaseDuration(path, velocity, curve, fallback) {
32
- if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
33
+ if (Math.sign(path) !== Math.sign(velocity) || abs(velocity) < 0.05) {
33
34
  return fallback;
34
35
  }
35
- return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
36
+ return clamp(abs(path) * curve[1] / curve[0] / abs(velocity), 200, 1200);
36
37
  }
37
38
 
38
39
  /**
@@ -97,9 +98,9 @@ export function releaseTarget({ location, from, velocity, current, snaps, min, m
97
98
 
98
99
  let direction = 0;
99
100
 
100
- if (Math.abs(velocity) > 0.3) {
101
+ if (abs(velocity) > 0.3) {
101
102
  direction = velocity < 0 ? 1 : -1;
102
- } else if (Math.abs(moved) > 20) {
103
+ } else if (abs(moved) > 20) {
103
104
  direction = moved < 0 ? 1 : -1;
104
105
  }
105
106
 
@@ -134,7 +135,7 @@ export function drag(context) {
134
135
  // The selected snap at the drag start
135
136
  snap = 0;
136
137
 
137
- const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
138
+ const listen = bind(window, [['pointermove', handle], ['pointerup', handle], ['pointercancel', handle]]);
138
139
 
139
140
  function down(event) {
140
141
  block = false;
@@ -158,7 +159,7 @@ export function drag(context) {
158
159
  axis = { x: geo.axis === 'x', sign: geo.sign, scale: geo.scale };
159
160
  start = [event.clientX, event.clientY];
160
161
  samples = [];
161
- listen('addEventListener');
162
+ listen(true);
162
163
  }
163
164
 
164
165
  function handle(event) {
@@ -181,10 +182,10 @@ export function drag(context) {
181
182
 
182
183
  if (!context.dragging()) {
183
184
  // A touch move across the axis scrolls the page
184
- if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
185
+ if (event.pointerType !== 'mouse' && abs(cross) > abs(main)) {
185
186
  return end();
186
187
  }
187
- if (Math.abs(main) < options.dragThreshold) {
188
+ if (abs(main) < options.dragThreshold) {
188
189
  return;
189
190
  }
190
191
  // Stop the motion, and start the drag at the location where the carousel is now
@@ -214,7 +215,7 @@ export function drag(context) {
214
215
  * @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
215
216
  */
216
217
  function end(up) {
217
- listen('removeEventListener');
218
+ listen();
218
219
  pointer = null;
219
220
 
220
221
  if (!context.dragging()) {
@@ -224,7 +225,8 @@ export function drag(context) {
224
225
  const geo = context.geo(),
225
226
  location = context.location(),
226
227
  speed = up ? velocity(samples) : 0,
227
- 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 }),
228
+ // The snaps and the limits come from the geometry, and skipSnaps, dragFree and dragFriction from the options
229
+ target = releaseTarget({ ...geo, ...options, location, from: base, velocity: speed, current: snap }),
228
230
  curve = options.dragFree === true ? GLIDE : EASE;
229
231
 
230
232
  block = true;
@@ -245,18 +247,14 @@ export function drag(context) {
245
247
  // Stop a text selection during a drag. A "user-select" rule on the dragging class does the same, but its change paints all layers of the carousel.
246
248
  const select = (event) => context.dragging() && event.preventDefault();
247
249
 
248
- viewport.addEventListener('pointerdown', down);
249
- viewport.addEventListener('click', click, true);
250
- viewport.addEventListener('dragstart', prevent);
251
- viewport.addEventListener('selectstart', select);
250
+ const own = bind(viewport, [['pointerdown', down], ['click', click, true], ['dragstart', prevent], ['selectstart', select]]);
251
+
252
+ own(true);
252
253
 
253
254
  return {
254
255
  remove() {
255
- listen('removeEventListener');
256
- viewport.removeEventListener('pointerdown', down);
257
- viewport.removeEventListener('click', click, true);
258
- viewport.removeEventListener('dragstart', prevent);
259
- viewport.removeEventListener('selectstart', select);
256
+ listen();
257
+ own();
260
258
  }
261
259
  };
262
260
  }
@@ -276,7 +274,7 @@ function scrolls(node, viewport, axis, delta) {
276
274
  for (; node && node !== viewport; node = node.parentElement) {
277
275
  // Read the style only for an element with more content than space
278
276
  if (node[size] > node[client] && /auto|scroll/.test(getComputedStyle(node)[overflow])) {
279
- const at = Math.abs(node[position]);
277
+ const at = abs(node[position]);
280
278
  if (delta > 0 ? at + node[client] < node[size] - 1 : at > 0) {
281
279
  return true;
282
280
  }
@@ -287,7 +285,8 @@ function scrolls(node, viewport, axis, delta) {
287
285
  }
288
286
 
289
287
  /**
290
- * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
288
+ * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. With wheel: 'axis',
289
+ * a horizontal carousel follows only a horizontal wheel motion, such as a trackpad swipe, and a vertical wheel scrolls the page. The carousel follows
291
290
  * 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
292
291
  * location, the page scrolls.
293
292
  *
@@ -317,31 +316,28 @@ export function wheel(context) {
317
316
 
318
317
  function onWheel(event) {
319
318
  const geo = context.geo(),
320
- side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
319
+ side = geo.axis === 'x' && abs(event.deltaX) > abs(event.deltaY),
321
320
  delta = side ? event.deltaX * geo.sign : event.deltaY;
322
321
 
323
- if (event.ctrlKey || !delta || context.dragging()) {
322
+ if (event.ctrlKey || !delta || context.dragging() || (options.wheel === 'axis' && geo.axis === 'x' && !side)) {
324
323
  return;
325
324
  }
326
325
 
327
326
  const now = event.timeStamp,
328
327
  gesture = now - time < 200,
329
- size = Math.abs(delta),
328
+ size = abs(delta),
330
329
  // A delta that does not grow is the inertia of the gesture, not a new push
331
330
  inertia = gesture && size <= last;
332
331
 
332
+ time = now;
333
333
  last = size;
334
- if (!gesture) {
335
- held = false;
336
- }
334
+ held &&= gesture;
337
335
 
338
336
  // An element in a slide that can scroll in the wheel direction scrolls, also for the rest of its gesture
339
- if ((gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta)) {
340
- inner = true;
341
- time = now;
337
+ inner = (gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta);
338
+ if (inner) {
342
339
  return;
343
340
  }
344
- inner = false;
345
341
 
346
342
  const base = context.location(),
347
343
  path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
@@ -351,10 +347,8 @@ export function wheel(context) {
351
347
  target = clamp(target, geo.min, geo.max);
352
348
  }
353
349
 
354
- time = now;
355
-
356
350
  // At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
357
- if (Math.abs(target - base) < 0.5) {
351
+ if (abs(target - base) < 0.5) {
358
352
  if (held && inertia) {
359
353
  event.preventDefault();
360
354
  }
@@ -383,23 +377,23 @@ export function wheel(context) {
383
377
  const geo = context.geo(),
384
378
  at = context.current(),
385
379
  index = nearestSnap(geo.snaps, at, geo.period),
386
- away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
380
+ away = abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
387
381
 
388
382
  context.step(index, index === snap && away ? direction : 0);
389
383
  }
390
384
 
391
385
  // A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
392
386
  // Add it only where the wheel moves the carousel.
393
- function listen() {
394
- const geo = context.geo();
395
- viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
396
- }
387
+ const listen = bind(viewport, [['wheel', onWheel, { passive: false }]]);
397
388
 
398
- ['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
389
+ context.on('init reinit resize', () => {
390
+ const geo = context.geo();
391
+ listen(!geo.fit && (geo.axis === 'y' || options.wheel !== true));
392
+ });
399
393
 
400
394
  return {
401
395
  remove() {
402
- viewport.removeEventListener('wheel', onWheel);
396
+ listen();
403
397
  clearTimeout(timer);
404
398
  }
405
399
  };
@@ -426,19 +420,17 @@ export function keys(context) {
426
420
  direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
427
421
  name = direction > 0 ? 'Next' : 'Prev';
428
422
  // At the first and the last slide, the key scrolls the page
429
- if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) && api['canGoTo' + name]()) {
423
+ if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.closest(fields)) && api['canGoTo' + name]()) {
430
424
  event.preventDefault();
431
425
  api['goTo' + name]();
432
426
  }
433
427
  }
434
428
 
435
- root.addEventListener('keydown', onKey);
429
+ const listen = bind(root, [['keydown', onKey]]);
436
430
 
437
- return {
438
- remove() {
439
- root.removeEventListener('keydown', onKey);
440
- }
441
- };
431
+ listen(true);
432
+
433
+ return { remove: listen };
442
434
  }
443
435
 
444
436
  /**
@@ -466,19 +458,15 @@ export function focus(context) {
466
458
  if (!geo || index < 0 || event.timeStamp - pressed < 600) {
467
459
  return;
468
460
  }
469
- if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
461
+ if (options.focus && !inView(geo, context.location(), 1).map((item) => item % geo.count).includes(index)) {
470
462
  api.goToSlide(index);
471
463
  }
472
464
  context.emit('slidefocus');
473
465
  }
474
466
 
475
- container.addEventListener('pointerdown', press);
476
- container.addEventListener('focusin', onFocus);
467
+ const listen = bind(container, [['pointerdown', press], ['focusin', onFocus]]);
477
468
 
478
- return {
479
- remove() {
480
- container.removeEventListener('pointerdown', press);
481
- container.removeEventListener('focusin', onFocus);
482
- }
483
- };
469
+ listen(true);
470
+
471
+ return { remove: listen };
484
472
  }
@@ -4,6 +4,8 @@
4
4
  * The reads run in the ResizeObserver callback, when the layout is clean.
5
5
  */
6
6
 
7
+ import { abs, round } from './geometry.js';
8
+
7
9
  /**
8
10
  * Read the axis, the alignment, the direction and the gap from the computed style of the container.
9
11
  *
@@ -46,19 +48,21 @@ export function readLayout(container, options) {
46
48
 
47
49
  /**
48
50
  * 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.
49
- * 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
50
- * values do not change with a scale or a rotation of a parent.
51
+ * 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,
52
+ * the values do not change. A rotation of a parent is not supported.
51
53
  * 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.
52
54
  *
53
55
  * @param {HTMLElement} viewport
54
56
  * @param {HTMLElement[]} nodes All slides, clones included.
55
57
  * @param {object} layout The result of readLayout().
56
58
  * @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
57
- * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, pad: {start: number, end: number}}}
59
+ * @param {number} [size] The window size on the main axis, for clones: 'fill'.
60
+ * @returns {{view: number, slides: Array<{start: number, end: number, cross: number, hidden: boolean}>, gap: number, scale: number, area: {start: number, size: number}}}
58
61
  * 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.
59
- * scale is the screen px of one px of the carousel. pad is the viewport padding at the start and at the end.
62
+ * 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
63
+ * padding, or with a size, the window, so that the slides fill it when the viewport overflow shows.
60
64
  */
61
- export function readRects(viewport, nodes, layout, written) {
65
+ export function readRects(viewport, nodes, layout, written, size) {
62
66
  const box = viewport.getBoundingClientRect(),
63
67
  x = layout.axis === 'x',
64
68
  sign = layout.sign,
@@ -66,14 +70,12 @@ export function readRects(viewport, nodes, layout, written) {
66
70
  shift = known ? written.container : 0,
67
71
  width = viewport.offsetWidth,
68
72
  height = viewport.offsetHeight,
69
- // offsetWidth is a whole number: a difference of less than 1 px is not a transform
70
- transformed = width && height && (Math.abs(box.width - width) >= 1 || Math.abs(box.height - height) >= 1),
71
- // A scale s and a rotation by an angle a give a box of s(w cos a + h sin a) by s(w sin a + h cos a). The main axis gets s cos a.
72
- scale = !transformed ? 1 : Math.abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
73
- view = !transformed ? (x ? box.width : box.height) : x ? width : height,
73
+ // offsetWidth is a whole number: a difference of less than 1 px is not a scale
74
+ scale = width && height && (abs(box.width - width) >= 1 || abs(box.height - height) >= 1) ? (x ? box.width / width : box.height / height) : 1,
75
+ view = (x ? box.width : box.height) / scale,
74
76
  style = getComputedStyle(viewport),
75
- [before, after] = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
76
- pad = { start: parseFloat(style['padding' + before]) || 0, end: parseFloat(style['padding' + after]) || 0 };
77
+ side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
78
+ pad = { start: parseFloat(style['padding' + side[0]]) || 0, end: parseFloat(style['padding' + side[1]]) || 0 };
77
79
 
78
80
  const slides = nodes.map((node, index) => {
79
81
  const rect = node.getBoundingClientRect(),
@@ -84,44 +86,47 @@ export function readRects(viewport, nodes, layout, written) {
84
86
  return { start, end: start + size, cross: (x ? rect.height : rect.width) / scale, hidden: !rect.width && !rect.height };
85
87
  });
86
88
 
87
- let edge = slides.find((slide) => !slide.hidden)?.start || 0;
88
-
89
- for (const slide of slides) {
90
- if (slide.hidden) {
91
- slide.start = slide.end = edge;
92
- } else {
93
- edge = slide.end;
94
- }
95
- }
96
-
97
- let first = Math.max(0, slides.findIndex((slide) => !slide.hidden)),
98
- last = first;
89
+ // A hidden slide goes to the end of the visible slide before it. The first and the last visible slides give the margins of the loop gap.
90
+ let edge = slides.find((slide) => !slide.hidden)?.start || 0,
91
+ first = -1,
92
+ last = -1,
93
+ gap = layout.gap;
99
94
 
100
95
  slides.forEach((slide, index) => {
101
96
  if (slide.hidden) {
97
+ slide.start = slide.end = edge;
102
98
  return;
103
99
  }
104
- if (slide.start < slides[first].start) {
100
+ edge = slide.end;
101
+ if (first < 0 || slide.start < slides[first].start) {
105
102
  first = index;
106
103
  }
107
- if (slide.end > slides[last].end) {
104
+ if (last < 0 || slide.end > slides[last].end) {
108
105
  last = index;
109
106
  }
110
107
  });
111
108
 
112
- let gap = layout.gap;
113
-
114
- if (slides.length) {
115
- const side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'];
109
+ if (first > -1) {
116
110
  gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
117
111
  }
118
112
 
113
+ const inner = view - pad.start - pad.end;
114
+
115
+ // The area before and after the inner edge of the viewport padding: the padding, or the window
116
+ let before = pad.start,
117
+ after = inner + pad.end;
118
+
119
+ if (size) {
120
+ before += Math.max(0, round(x ? (layout.rtl ? size - box.right : box.left) : box.top));
121
+ after = Math.max(after, round(size - before));
122
+ }
123
+
119
124
  return {
120
- view: view - pad.start - pad.end,
125
+ view: inner,
121
126
  slides,
122
127
  gap,
123
128
  scale,
124
- pad
129
+ area: { start: -before, size: before + after }
125
130
  };
126
131
  }
127
132
 
@@ -135,28 +140,6 @@ export function windowSize(axis) {
135
140
  return axis === 'x' ? document.documentElement.clientWidth : innerHeight;
136
141
  }
137
142
 
138
- /**
139
- * Get the part of the main axis where the loop must show slides, relative to the inner edge of the viewport padding.
140
- * 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.
141
- *
142
- * @param {HTMLElement} viewport
143
- * @param {{axis: string, rtl: boolean}} layout
144
- * @param {number} view The viewport size without the padding.
145
- * @param {{start: number, end: number}} pad The viewport padding.
146
- * @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
147
- * @returns {{start: number, size: number}}
148
- */
149
- export function visibleArea(viewport, layout, view, pad, size) {
150
- if (!size) {
151
- return { start: -pad.start, size: pad.start + view + pad.end };
152
- }
153
-
154
- const box = viewport.getBoundingClientRect(),
155
- before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
156
-
157
- return { start: -before, size: before + Math.max(view + pad.end, Math.round(size - before)) };
158
- }
159
-
160
143
  // 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
161
144
  // come after the writes of another carousel, and the browser does one layout for all of them.
162
145
  const owners = new WeakMap(),
@@ -176,14 +159,13 @@ let resizer;
176
159
  */
177
160
  export function observeSize(nodes, owner) {
178
161
  resizer ||= new ResizeObserver((entries) => {
179
- const list = new Set(entries.filter((entry) => {
162
+ const changed = [...new Set(entries.filter((entry) => {
180
163
  const { inlineSize, blockSize } = entry.borderBoxSize[0],
181
164
  size = inlineSize + ',' + blockSize,
182
165
  same = sizes.get(entry.target) === size;
183
166
  sizes.set(entry.target, size);
184
167
  return !same && !owners.get(entry.target)?.skip(entry);
185
- }).map((entry) => owners.get(entry.target)));
186
- const changed = [...list].filter((item) => item && item.read());
168
+ }).map((entry) => owners.get(entry.target)))].filter((item) => item?.read());
187
169
  changed.forEach((item) => item.write());
188
170
  // 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
189
171
  // a change to report after its callback, the browser sends the "ResizeObserver loop" error to window.onerror. Stop the watch of these
@@ -210,49 +192,63 @@ export function observeSize(nodes, owner) {
210
192
  }
211
193
  }
212
194
 
213
- // The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the boxes that readBoxes() read
195
+ // The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the elements to check: [node, lazy, margin]
214
196
  const watchers = new Map(),
215
- waiters = new WeakMap(),
216
- boxes = new WeakMap();
197
+ waiters = new WeakMap();
217
198
 
218
- /**
219
- * 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.
220
- * waitNear() uses each box one time.
221
- *
222
- * @param {Element[]} elements
223
- */
224
- export function readBoxes(elements) {
225
- elements.forEach((element) => boxes.set(element, element.getBoundingClientRect()));
226
- }
199
+ let queue = [];
227
200
 
228
201
  /**
229
- * Wait until an element comes near the screen.
202
+ * Wait until an element comes near the screen. One microtask reads the boxes of all elements that started to wait, after the writes of
203
+ * the carousels that started without a wait. Then the reads cause one layout, not one for each carousel. The microtask runs before the
204
+ * first paint, so a carousel near the screen starts before the page shows, and it does not move the page.
230
205
  *
231
206
  * @param {Element} node
232
207
  * @param {true|number} lazy The "lazy" option: true for one screen height, or a distance in px.
233
208
  * @param {Function} callback
234
- * @returns {Function|null} A function that stops the wait, or null if the element is near the screen now.
209
+ * @returns {Function} A function that stops the wait.
235
210
  */
236
211
  export function waitNear(node, lazy, callback) {
237
- const near = lazy === true ? innerHeight : lazy,
238
- rect = boxes.get(node) || node.getBoundingClientRect(),
239
- margin = lazy === true ? '100%' : lazy + 'px';
240
-
241
- boxes.delete(node);
212
+ const margin = lazy === true ? '100%' : lazy + 'px';
242
213
 
243
- if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
244
- return null;
245
- }
246
-
247
- let observer = watchers.get(margin);
248
- if (!observer) {
249
- observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
250
- watchers.set(margin, observer);
214
+ if (!queue.length) {
215
+ queueMicrotask(check);
251
216
  }
217
+ queue.push([node, lazy, margin]);
252
218
  waiters.set(node, callback);
253
- observer.observe(node);
219
+
254
220
  return () => {
255
- observer.unobserve(node);
221
+ watchers.get(margin)?.unobserve(node);
256
222
  waiters.delete(node);
257
223
  };
258
224
  }
225
+
226
+ // Call the callback of each element near the screen, and watch the other elements. An element whose wait stopped has no callback.
227
+ function check() {
228
+ const list = queue,
229
+ rects = list.map(([node]) => node.getBoundingClientRect());
230
+
231
+ queue = [];
232
+
233
+ list.forEach(([node, lazy, margin], index) => {
234
+ const near = lazy === true ? innerHeight : lazy,
235
+ rect = rects[index],
236
+ callback = waiters.get(node);
237
+
238
+ if (!callback) {
239
+ return;
240
+ }
241
+
242
+ if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
243
+ callback();
244
+ return;
245
+ }
246
+
247
+ let observer = watchers.get(margin);
248
+ if (!observer) {
249
+ observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
250
+ watchers.set(margin, observer);
251
+ }
252
+ observer.observe(node);
253
+ });
254
+ }
@@ -34,12 +34,12 @@ export 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
  export 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
 
@@ -54,6 +54,17 @@ export function cleanStyle(element) {
54
54
  }
55
55
  }
56
56
 
57
+ /**
58
+ * Make a function that adds or removes event listeners on a target.
59
+ *
60
+ * @param {EventTarget} target
61
+ * @param {Array<Array>} list [name, handler, options] for each listener.
62
+ * @returns {(on?: boolean) => void} With true, it adds the listeners. Without a value, it removes them.
63
+ */
64
+ export function bind(target, list) {
65
+ return (on) => list.forEach(([name, handler, options]) => target[on ? 'addEventListener' : 'removeEventListener'](name, handler, options));
66
+ }
67
+
57
68
  /**
58
69
  * Make an element.
59
70
  *
@@ -69,6 +80,24 @@ export function create(tag, className) {
69
80
  return element;
70
81
  }
71
82
 
83
+ /**
84
+ * Make a control button of a carousel.
85
+ *
86
+ * @param {string} className
87
+ * @param {HTMLElement} container The container of the slides, which the button controls.
88
+ * @param {string} label The aria-label. An empty label adds no attribute.
89
+ * @param {() => void} click
90
+ * @returns {HTMLButtonElement}
91
+ */
92
+ export function createButton(className, container, label, click) {
93
+ const element = create('button', className);
94
+ element.type = 'button';
95
+ setAttribute(element, 'aria-label', label);
96
+ element.setAttribute('aria-controls', container.id);
97
+ element.addEventListener('click', click);
98
+ return element;
99
+ }
100
+
72
101
  /**
73
102
  * Find the element of an option, such as "arrows", "dots" or "sync". true gives the root, and false gives null.
74
103
  * The library searches for a selector in the root and then in each parent of the root, so that it finds a heading in the section of the carousel.
@@ -99,16 +128,14 @@ const marked = new WeakMap(),
99
128
  *
100
129
  * @param {Element} node
101
130
  * @param {string} name
102
- * @param {string} value
131
+ * @param {string} value An empty value removes the attribute, for example an empty label.
103
132
  */
104
133
  export function own(node, name, value) {
105
134
  const list = marked.get(node) || new Set();
106
135
  if (list.has(name) || !node.hasAttribute(name)) {
107
136
  list.add(name);
108
137
  marked.set(node, list);
109
- if (node.getAttribute(name) !== value) {
110
- node.setAttribute(name, value);
111
- }
138
+ setAttribute(node, name, value);
112
139
  }
113
140
  }
114
141
 
@@ -223,7 +250,8 @@ export function readSlides(container, selector) {
223
250
  }
224
251
 
225
252
  /**
226
- * 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.
227
255
  *
228
256
  * @param {HTMLElement[]} slides
229
257
  * @param {number} count The number of copies of all slides.
@@ -233,10 +261,9 @@ export function readSlides(container, selector) {
233
261
  export function copySlides(slides, count, className) {
234
262
  const list = [];
235
263
 
236
- for (let copy = 0; copy < count; copy++) {
264
+ for (let pass = 0; pass < count; pass++) {
237
265
  for (const node of slides) {
238
- const clone = node.cloneNode(true);
239
- removeIds(clone);
266
+ const clone = copy(node);
240
267
  clone.setAttribute('aria-hidden', 'true');
241
268
  clone.inert = true;
242
269
  clone.style.translate = '';
@@ -250,11 +277,17 @@ export function copySlides(slides, count, className) {
250
277
  return list;
251
278
  }
252
279
 
253
- // An id must be unique in the page, so a copy has no ids
254
- function removeIds(node) {
255
- for (const item of [node, ...node.querySelectorAll('[id]')]) {
256
- item.removeAttribute('id');
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
+ function copy(node) {
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));
257
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);
290
+ return result;
258
291
  }
259
292
 
260
293
  /**
@@ -264,9 +297,7 @@ function removeIds(node) {
264
297
  * @param {HTMLElement} node The slide.
265
298
  */
266
299
  export function copyContent(clone, node) {
267
- const copy = node.cloneNode(true);
268
- removeIds(copy);
269
- clone.replaceChildren(...copy.childNodes);
300
+ clone.replaceChildren(...copy(node).childNodes);
270
301
  }
271
302
 
272
303
  /**