@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.
@@ -48,19 +48,21 @@ export function readLayout(container, options) {
48
48
 
49
49
  /**
50
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.
51
- * 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
52
- * 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.
53
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.
54
54
  *
55
55
  * @param {HTMLElement} viewport
56
56
  * @param {HTMLElement[]} nodes All slides, clones included.
57
57
  * @param {object} layout The result of readLayout().
58
58
  * @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
59
- * @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}}}
60
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.
61
- * 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.
62
64
  */
63
- export function readRects(viewport, nodes, layout, written) {
65
+ export function readRects(viewport, nodes, layout, written, size) {
64
66
  const box = viewport.getBoundingClientRect(),
65
67
  x = layout.axis === 'x',
66
68
  sign = layout.sign,
@@ -68,11 +70,9 @@ export function readRects(viewport, nodes, layout, written) {
68
70
  shift = known ? written.container : 0,
69
71
  width = viewport.offsetWidth,
70
72
  height = viewport.offsetHeight,
71
- // offsetWidth is a whole number: a difference of less than 1 px is not a transform
72
- transformed = width && height && (abs(box.width - width) >= 1 || abs(box.height - height) >= 1),
73
- // A scale s and a rotation by an angle a give a box of s(w cos a + h sin a) by s(w sin a + h cos a). The main axis gets s cos a.
74
- scale = !transformed ? 1 : abs(width - height) > 1 ? (width * box.width - height * box.height) / (width * width - height * height) : box.width / width,
75
- 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,
76
76
  style = getComputedStyle(viewport),
77
77
  side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'],
78
78
  pad = { start: parseFloat(style['padding' + side[0]]) || 0, end: parseFloat(style['padding' + side[1]]) || 0 };
@@ -110,12 +110,23 @@ export function readRects(viewport, nodes, layout, written) {
110
110
  gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
111
111
  }
112
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
+
113
124
  return {
114
- view: view - pad.start - pad.end,
125
+ view: inner,
115
126
  slides,
116
127
  gap,
117
128
  scale,
118
- pad
129
+ area: { start: -before, size: before + after }
119
130
  };
120
131
  }
121
132
 
@@ -129,28 +140,6 @@ export function windowSize(axis) {
129
140
  return axis === 'x' ? document.documentElement.clientWidth : innerHeight;
130
141
  }
131
142
 
132
- /**
133
- * Get the part of the main axis where the loop must show slides, relative to the inner edge of the viewport padding.
134
- * 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.
135
- *
136
- * @param {HTMLElement} viewport
137
- * @param {{axis: string, rtl: boolean}} layout
138
- * @param {number} view The viewport size without the padding.
139
- * @param {{start: number, end: number}} pad The viewport padding.
140
- * @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
141
- * @returns {{start: number, size: number}}
142
- */
143
- export function visibleArea(viewport, layout, view, pad, size) {
144
- if (!size) {
145
- return { start: -pad.start, size: pad.start + view + pad.end };
146
- }
147
-
148
- const box = viewport.getBoundingClientRect(),
149
- before = Math.max(0, round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top)) + pad.start;
150
-
151
- return { start: -before, size: before + Math.max(view + pad.end, round(size - before)) };
152
- }
153
-
154
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
155
144
  // come after the writes of another carousel, and the browser does one layout for all of them.
156
145
  const owners = new WeakMap(),
@@ -170,14 +159,13 @@ let resizer;
170
159
  */
171
160
  export function observeSize(nodes, owner) {
172
161
  resizer ||= new ResizeObserver((entries) => {
173
- const list = new Set(entries.filter((entry) => {
162
+ const changed = [...new Set(entries.filter((entry) => {
174
163
  const { inlineSize, blockSize } = entry.borderBoxSize[0],
175
164
  size = inlineSize + ',' + blockSize,
176
165
  same = sizes.get(entry.target) === size;
177
166
  sizes.set(entry.target, size);
178
167
  return !same && !owners.get(entry.target)?.skip(entry);
179
- }).map((entry) => owners.get(entry.target)));
180
- const changed = [...list].filter((item) => item && item.read());
168
+ }).map((entry) => owners.get(entry.target)))].filter((item) => item?.read());
181
169
  changed.forEach((item) => item.write());
182
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
183
171
  // a change to report after its callback, the browser sends the "ResizeObserver loop" error to window.onerror. Stop the watch of these
@@ -204,49 +192,63 @@ export function observeSize(nodes, owner) {
204
192
  }
205
193
  }
206
194
 
207
- // 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]
208
196
  const watchers = new Map(),
209
- waiters = new WeakMap(),
210
- boxes = new WeakMap();
197
+ waiters = new WeakMap();
211
198
 
212
- /**
213
- * 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.
214
- * waitNear() uses each box one time.
215
- *
216
- * @param {Element[]} elements
217
- */
218
- export function readBoxes(elements) {
219
- elements.forEach((element) => boxes.set(element, element.getBoundingClientRect()));
220
- }
199
+ let queue = [];
221
200
 
222
201
  /**
223
- * 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.
224
205
  *
225
206
  * @param {Element} node
226
207
  * @param {true|number} lazy The "lazy" option: true for one screen height, or a distance in px.
227
208
  * @param {Function} callback
228
- * @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.
229
210
  */
230
211
  export function waitNear(node, lazy, callback) {
231
- const near = lazy === true ? innerHeight : lazy,
232
- rect = boxes.get(node) || node.getBoundingClientRect(),
233
- margin = lazy === true ? '100%' : lazy + 'px';
212
+ const margin = lazy === true ? '100%' : lazy + 'px';
234
213
 
235
- boxes.delete(node);
236
-
237
- if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
238
- return null;
239
- }
240
-
241
- let observer = watchers.get(margin);
242
- if (!observer) {
243
- observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
244
- watchers.set(margin, observer);
214
+ if (!queue.length) {
215
+ queueMicrotask(check);
245
216
  }
217
+ queue.push([node, lazy, margin]);
246
218
  waiters.set(node, callback);
247
- observer.observe(node);
219
+
248
220
  return () => {
249
- observer.unobserve(node);
221
+ watchers.get(margin)?.unobserve(node);
250
222
  waiters.delete(node);
251
223
  };
252
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
 
@@ -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
  export 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 @@ export 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 @@ export 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
 
@@ -4,8 +4,7 @@
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 { find } from './carousel.js';
8
- import { bind, create, createButton, optionElement, setAttribute, setClass } from './markup.js';
7
+ import { bind, create, createButton, optionElement, setAttribute, setClass, setStyle } from './markup.js';
9
8
 
10
9
  /**
11
10
  * Make the arrows and the dots of a carousel. They update on the carousel events.
@@ -45,7 +44,7 @@ export function nav(context) {
45
44
 
46
45
  function update() {
47
46
  const fit = api.isFit(),
48
- count = fit ? 0 : api.snapProgress().length,
47
+ count = fit ? 0 : context.geo().logical.length,
49
48
  selected = api.selectedSnap();
50
49
 
51
50
  buttons.forEach((item, index) => {
@@ -119,19 +118,12 @@ export function nav(context) {
119
118
 
120
119
  // 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".
121
120
  if (windowed) {
122
- variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
121
+ setStyle(list, '--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
123
122
  }
124
- variable('--better-dot', selected);
123
+ setStyle(list, '--better-dot', selected);
125
124
  }
126
125
 
127
- // Set a CSS variable on the window of the dots, if its value changes
128
- function variable(name, value) {
129
- if (list.style.getPropertyValue(name) !== String(value)) {
130
- list.style.setProperty(name, value);
131
- }
132
- }
133
-
134
- ['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
126
+ context.on('init reinit resize select slideschanged', update);
135
127
 
136
128
  return {
137
129
  remove() {
@@ -165,11 +157,11 @@ export function sync(context) {
165
157
  api.goToSlide(index, instant === true);
166
158
  }
167
159
 
160
+ // A click on a clone comes to its slide. See onClick() in carousel.js.
168
161
  function click(event) {
169
- // The slide or the clone that gets the click, and then its original slide
170
- const index = context.nodes().findIndex((node) => node.contains(event.target));
162
+ const index = api.slideNodes().findIndex((node) => node.contains(event.target));
171
163
  if (other && index > -1) {
172
- other.goToSlide(index % api.slideNodes().length);
164
+ other.goToSlide(index);
173
165
  }
174
166
  }
175
167
 
@@ -178,15 +170,14 @@ export function sync(context) {
178
170
  if (other) {
179
171
  return;
180
172
  }
181
- other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
173
+ other = target.goToSnap ? target : context.find(typeof target === 'string' ? optionElement(target, context.root) : target);
182
174
  if (other) {
183
175
  other.on('select', show);
184
176
  show(true);
185
177
  }
186
178
  }
187
179
 
188
- context.on('init', connect);
189
- context.on('reinit', connect);
180
+ context.on('init reinit', connect);
190
181
  const listen = bind(container, [['click', click]]);
191
182
 
192
183
  listen(true);
@@ -29,6 +29,11 @@ $better-arrow: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'
29
29
  z-index: 1;
30
30
  }
31
31
 
32
+ // The width comes from the parent, not from the slides. Without it, a carousel in a flex item or a grid column grows to the width of all slides.
33
+ .#{$better}_horizontal .#{$better}_viewport {
34
+ contain: inline-size;
35
+ }
36
+
32
37
  .#{$better}_horizontal .#{$better}_container {
33
38
  overflow: visible;
34
39
  --gap-grid-y: 0px;
@@ -163,10 +163,10 @@ export interface Options {
163
163
  startSnap?: number;
164
164
  /** `true`: start when the carousel comes within one screen of the view. A number: the distance in px. @default false @see {@link https://twistedandy.github.io/better-carousel/#lazy | example} */
165
165
  lazy?: boolean | number;
166
- /** Drag with the mouse, the pen and the finger. @default true */
166
+ /** Drag with the mouse, the pen and the finger. A press on a form field does not start a drag. To keep the drag off another element, such as a map in a slide, stop the propagation of its `pointerdown` event. @default true */
167
167
  drag?: boolean;
168
- /** The mouse wheel moves a vertical carousel. `'both'`: also a horizontal carousel. `false`: the wheel does not move the carousel. @default true @see {@link https://twistedandy.github.io/better-carousel/#vertical | example} */
169
- wheel?: boolean | 'both';
168
+ /** The mouse wheel moves a vertical carousel. `'axis'`: also a horizontal carousel, but only with a horizontal wheel motion, such as a trackpad swipe. A vertical wheel scrolls the page. `'both'`: also a horizontal carousel, with all wheel motions. `false`: the wheel does not move the carousel. @default true @see {@link https://twistedandy.github.io/better-carousel/#vertical | example} */
169
+ wheel?: boolean | 'axis' | 'both';
170
170
  /** The arrow keys move the carousel while the keyboard focus is in it: left and right in a horizontal carousel, up and down in a vertical carousel. A key in a form field does not move the carousel. @default true */
171
171
  keys?: boolean;
172
172
  /** Measure again when a size changes. @default true @see {@link https://twistedandy.github.io/better-carousel/#options-usage | example} */
@@ -193,7 +193,7 @@ export interface Options {
193
193
  dots?: boolean | Element | string;
194
194
  /** The style of the dots. `'zoom'`: a window of 5 dots that slides, with smaller dots at the ends. `'all'`: all dots with the same size. @default 'zoom' */
195
195
  dotsStyle?: 'zoom' | 'all';
196
- /** The texts for screen readers: `carousel`, `slide` (`'%d of %n'`), `prev`, `next`, `dot` (`'Go to slide %d'`), `play`, `pause`. `%d` is the slide number, and `%n` is the number of slides. @see {@link https://twistedandy.github.io/better-carousel/#accessibility | example} */
196
+ /** The texts for screen readers: `carousel`, `slide` (`'%d of %n'`), `prev`, `next`, `dot` (`'Go to slide %d'`), `play`, `pause`. `%d` is the slide number, and `%n` is the number of slides. An empty text adds no name. @see {@link https://twistedandy.github.io/better-carousel/#accessibility | example} */
197
197
  labels?: Labels;
198
198
  /** A class prefix such as `'embla'`, or an object with the names to change. The Classes table gives all names. @default null @see {@link https://twistedandy.github.io/better-carousel/#embla | example} */
199
199
  classes?: string | ClassNames | null;