@twistedandy/better-carousel 0.0.0-stage → 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +838 -2
- package/dist/better-carousel.css +1 -0
- package/dist/better-carousel.js +3175 -0
- package/dist/better-carousel.min.js +1 -0
- package/package.json +55 -5
- package/src/index.js +49 -0
- package/src/scripts/autoplay.js +288 -0
- package/src/scripts/carousel.js +834 -0
- package/src/scripts/geometry.js +429 -0
- package/src/scripts/input.js +432 -0
- package/src/scripts/layout.js +205 -0
- package/src/scripts/loop.js +83 -0
- package/src/scripts/markup.js +268 -0
- package/src/scripts/motion.js +232 -0
- package/src/scripts/navigation.js +209 -0
- package/src/scripts/options.js +153 -0
- package/src/styles/better-carousel.scss +323 -0
- package/src/types/better-carousel.d.ts +309 -0
|
@@ -0,0 +1,3175 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Markup: the wrapper, the slides, the clones, the ARIA attributes, and the helpers that write to the DOM.
|
|
3
|
+
*
|
|
4
|
+
* The helpers that set a value write only when the value changes. restore() removes all that the library added.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Add or remove a class.
|
|
9
|
+
*
|
|
10
|
+
* @param {Element} element
|
|
11
|
+
* @param {string} name An empty name does nothing.
|
|
12
|
+
* @param {boolean} on
|
|
13
|
+
*/
|
|
14
|
+
function setClass(element, name, on) {
|
|
15
|
+
if (name && element.classList.contains(name) !== !!on) {
|
|
16
|
+
element.classList.toggle(name, !!on);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Set an attribute, or remove it if the value is false.
|
|
22
|
+
*
|
|
23
|
+
* @param {Element} element
|
|
24
|
+
* @param {string} name
|
|
25
|
+
* @param {string|false} value
|
|
26
|
+
*/
|
|
27
|
+
function setAttribute(element, name, value) {
|
|
28
|
+
if (element.getAttribute(name) !== (value || null)) {
|
|
29
|
+
value ? element.setAttribute(name, value) : element.removeAttribute(name);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Set an inline style property.
|
|
35
|
+
*
|
|
36
|
+
* @param {HTMLElement} element
|
|
37
|
+
* @param {string} name
|
|
38
|
+
* @param {string} value An empty string removes the property.
|
|
39
|
+
*/
|
|
40
|
+
function setStyle(element, name, value) {
|
|
41
|
+
if (element.style[name] !== value) {
|
|
42
|
+
element.style[name] = value;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Remove an empty style attribute that the library left.
|
|
48
|
+
*
|
|
49
|
+
* @param {Element} element
|
|
50
|
+
*/
|
|
51
|
+
function cleanStyle(element) {
|
|
52
|
+
if (element.getAttribute('style') === '') {
|
|
53
|
+
element.removeAttribute('style');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Make an element.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} tag
|
|
61
|
+
* @param {string} className
|
|
62
|
+
* @returns {HTMLElement}
|
|
63
|
+
*/
|
|
64
|
+
function create(tag, className) {
|
|
65
|
+
const element = document.createElement(tag);
|
|
66
|
+
if (className) {
|
|
67
|
+
element.className = className;
|
|
68
|
+
}
|
|
69
|
+
return element;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Find the element of an option, such as "arrows", "dots" or "sync". true gives the root, and false gives null.
|
|
74
|
+
* 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.
|
|
75
|
+
*
|
|
76
|
+
* @param {boolean|string|Element} value The option value.
|
|
77
|
+
* @param {HTMLElement} root
|
|
78
|
+
* @returns {Element|null}
|
|
79
|
+
*/
|
|
80
|
+
function optionElement(value, root) {
|
|
81
|
+
if (typeof value === 'string') {
|
|
82
|
+
for (let node = root; node; node = node.parentElement) {
|
|
83
|
+
const found = node.querySelector(value);
|
|
84
|
+
if (found) {
|
|
85
|
+
return found;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
return value === true ? root : value || null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The attributes and the classes that the library added: element => names
|
|
94
|
+
const marked = new WeakMap(),
|
|
95
|
+
added = new WeakMap();
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Set an attribute that the page did not set. restore() removes it.
|
|
99
|
+
*
|
|
100
|
+
* @param {Element} node
|
|
101
|
+
* @param {string} name
|
|
102
|
+
* @param {string} value
|
|
103
|
+
*/
|
|
104
|
+
function own(node, name, value) {
|
|
105
|
+
const list = marked.get(node) || new Set();
|
|
106
|
+
if (list.has(name) || !node.hasAttribute(name)) {
|
|
107
|
+
list.add(name);
|
|
108
|
+
marked.set(node, list);
|
|
109
|
+
if (node.getAttribute(name) !== value) {
|
|
110
|
+
node.setAttribute(name, value);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Add a class that the element does not have. restore() removes it.
|
|
117
|
+
*
|
|
118
|
+
* @param {Element} node
|
|
119
|
+
* @param {string} name An empty name does nothing.
|
|
120
|
+
*/
|
|
121
|
+
function addClass(node, name) {
|
|
122
|
+
if (name && !node.classList.contains(name)) {
|
|
123
|
+
const list = added.get(node) || new Set();
|
|
124
|
+
node.classList.add(name);
|
|
125
|
+
list.add(name);
|
|
126
|
+
added.set(node, list);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The elements that the library made: the wrapper and the clones
|
|
131
|
+
const made = new WeakSet();
|
|
132
|
+
|
|
133
|
+
// A counter for container ids
|
|
134
|
+
let uid = 0;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Find or make the root, the viewport and the container of a carousel. Then add their classes and the ARIA attributes of the
|
|
138
|
+
* carousel pattern of the WAI-ARIA Authoring Practices. A new setup after reinit() uses the wrapper that the library made before.
|
|
139
|
+
*
|
|
140
|
+
* @param {HTMLElement} element The container of the slides, or its viewport.
|
|
141
|
+
* @param {object} options
|
|
142
|
+
* @param {object} cls The class names.
|
|
143
|
+
* @returns {{root: HTMLElement, viewport: HTMLElement, container: HTMLElement}}
|
|
144
|
+
*/
|
|
145
|
+
function build(element, options, cls) {
|
|
146
|
+
let container = options.container ? element.querySelector(options.container) : element;
|
|
147
|
+
|
|
148
|
+
if (container.classList.contains(cls.viewport)) {
|
|
149
|
+
container = container.firstElementChild;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let viewport = container.parentElement,
|
|
153
|
+
root = viewport.parentElement;
|
|
154
|
+
|
|
155
|
+
if (!made.has(viewport) && !viewport.classList.contains(cls.viewport) && options.wrapper) {
|
|
156
|
+
root = create('div');
|
|
157
|
+
viewport = create('div');
|
|
158
|
+
made.add(root).add(viewport);
|
|
159
|
+
container.before(root);
|
|
160
|
+
root.append(viewport);
|
|
161
|
+
viewport.append(container);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
addClass(root, cls.root);
|
|
165
|
+
addClass(viewport, cls.viewport);
|
|
166
|
+
addClass(container, cls.container);
|
|
167
|
+
|
|
168
|
+
own(root, 'role', 'region');
|
|
169
|
+
own(root, 'aria-roledescription', 'carousel');
|
|
170
|
+
if (!root.hasAttribute('aria-labelledby')) {
|
|
171
|
+
own(root, 'aria-label', options.labels.carousel);
|
|
172
|
+
}
|
|
173
|
+
own(container, 'id', container.id || 'carousel-' + ++uid);
|
|
174
|
+
own(container, 'aria-live', 'polite');
|
|
175
|
+
|
|
176
|
+
return { root, viewport, container };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Remove the classes and the attributes that own() and addClass() added, an empty class attribute, and the wrapper that build() made.
|
|
181
|
+
*
|
|
182
|
+
* @param {HTMLElement} root
|
|
183
|
+
* @param {HTMLElement} viewport
|
|
184
|
+
* @param {HTMLElement} container
|
|
185
|
+
* @param {HTMLElement[]} slides
|
|
186
|
+
* @param {boolean} keep Keep the wrapper for a new setup.
|
|
187
|
+
*/
|
|
188
|
+
function restore(root, viewport, container, slides, keep) {
|
|
189
|
+
for (const node of [root, viewport, container, ...slides]) {
|
|
190
|
+
marked.get(node)?.forEach((name) => node.removeAttribute(name));
|
|
191
|
+
added.get(node)?.forEach((name) => node.classList.remove(name));
|
|
192
|
+
marked.delete(node);
|
|
193
|
+
added.delete(node);
|
|
194
|
+
if (node.getAttribute('class') === '') {
|
|
195
|
+
node.removeAttribute('class');
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (!keep && made.has(root)) {
|
|
200
|
+
root.before(container);
|
|
201
|
+
root.remove();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Slides that are a control keep their own role and name
|
|
206
|
+
const controls = 'a[href],button,input,select,textarea,[tabindex],[role]';
|
|
207
|
+
|
|
208
|
+
// The slides that can get the "group" role. An element with its own role, such as an article or a list item, does not permit "group".
|
|
209
|
+
const generic = 'div,span,section';
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Get the slides of a container. The clones that the library made are not slides.
|
|
213
|
+
*
|
|
214
|
+
* @param {HTMLElement} container
|
|
215
|
+
* @param {string} [selector] The "slides" option.
|
|
216
|
+
* @returns {HTMLElement[]}
|
|
217
|
+
*/
|
|
218
|
+
function readSlides(container, selector) {
|
|
219
|
+
return [...(selector ? container.querySelectorAll(selector) : container.children)].filter((node) => !made.has(node));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Make the clones: full copies of the slides, which the screen reader and the keyboard do not see.
|
|
224
|
+
*
|
|
225
|
+
* @param {HTMLElement[]} slides
|
|
226
|
+
* @param {number} count The number of copies of all slides.
|
|
227
|
+
* @param {string} className The class of a clone.
|
|
228
|
+
* @returns {HTMLElement[]}
|
|
229
|
+
*/
|
|
230
|
+
function copySlides(slides, count, className) {
|
|
231
|
+
const list = [];
|
|
232
|
+
|
|
233
|
+
for (let copy = 0; copy < count; copy++) {
|
|
234
|
+
for (const node of slides) {
|
|
235
|
+
const clone = node.cloneNode(true);
|
|
236
|
+
for (const item of [clone, ...clone.querySelectorAll('[id]')]) {
|
|
237
|
+
item.removeAttribute('id');
|
|
238
|
+
}
|
|
239
|
+
clone.setAttribute('aria-hidden', 'true');
|
|
240
|
+
clone.inert = true;
|
|
241
|
+
clone.style.translate = '';
|
|
242
|
+
setClass(clone, className, true);
|
|
243
|
+
cleanStyle(clone);
|
|
244
|
+
made.add(clone);
|
|
245
|
+
list.push(clone);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return list;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Give each slide the slide role and a name such as "2 of 8". A slide with its own role, such as an article, keeps it.
|
|
254
|
+
*
|
|
255
|
+
* @param {HTMLElement[]} slides
|
|
256
|
+
* @param {string} text The "slide" label, with %d for the slide number and %n for the number of slides.
|
|
257
|
+
*/
|
|
258
|
+
function labelSlides(slides, text) {
|
|
259
|
+
slides.forEach((node, index) => {
|
|
260
|
+
if (!node.matches(controls) || marked.get(node)?.has('role')) {
|
|
261
|
+
if (node.matches(generic)) {
|
|
262
|
+
own(node, 'role', 'group');
|
|
263
|
+
}
|
|
264
|
+
own(node, 'aria-roledescription', 'slide');
|
|
265
|
+
own(node, 'aria-label', text.replace('%d', index + 1).replace('%n', slides.length));
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/*
|
|
271
|
+
* Autoplay: the autoplay, the auto scroll, and the play control that they share.
|
|
272
|
+
*
|
|
273
|
+
* Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
|
|
274
|
+
*/
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
// The defaults of the "autoplay" option
|
|
278
|
+
const autoplayDefaults = { delay: 4000, stopOnInteraction: true, pauseOnHover: false, pauseOnFocus: true, stopOnLastSnap: false, playOnInit: true, instant: false, timer: null };
|
|
279
|
+
|
|
280
|
+
// The defaults of the "autoScroll" option
|
|
281
|
+
const autoScrollDefaults = { speed: 120, direction: 'next', startDelay: 1000, stopOnInteraction: true, pauseOnHover: false, pauseOnFocus: true, playOnInit: true };
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Merge the value of the "autoplay" or the "autoScroll" option over the defaults of the feature.
|
|
285
|
+
*
|
|
286
|
+
* @param {object} base The defaults.
|
|
287
|
+
* @param {string} key The setting that a number sets: 'delay' or 'speed'.
|
|
288
|
+
* @param {boolean|number|object} value true, a number or an object.
|
|
289
|
+
* @returns {object}
|
|
290
|
+
*/
|
|
291
|
+
function settings(base, key, value) {
|
|
292
|
+
return { ...base, ...(typeof value === 'number' ? { [key]: value } : value) };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Watch the reasons to pause: the root is out of view, the tab is hidden, the mouse is on the root, or the keyboard focus is in the root.
|
|
297
|
+
* Make it only while a feature plays, so that a carousel at rest has no listeners on the document.
|
|
298
|
+
*
|
|
299
|
+
* @param {HTMLElement} root
|
|
300
|
+
* @param {{pauseOnHover: boolean, pauseOnFocus: boolean}} options
|
|
301
|
+
* @param {() => void} change Called when the paused state changes.
|
|
302
|
+
* @returns {{paused: () => boolean, remove: () => void}}
|
|
303
|
+
*/
|
|
304
|
+
function pauser(root, options, change) {
|
|
305
|
+
const reasons = new Set(),
|
|
306
|
+
set = (reason, on) => {
|
|
307
|
+
const before = reasons.size;
|
|
308
|
+
reasons[on ? 'add' : 'delete'](reason);
|
|
309
|
+
if (!before !== !reasons.size) {
|
|
310
|
+
change();
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
observer = new IntersectionObserver(([entry]) => set('view', !entry.isIntersecting)),
|
|
314
|
+
listeners = [
|
|
315
|
+
[document, 'visibilitychange', () => set('tab', document.hidden)],
|
|
316
|
+
[root, 'pointerenter', (event) => set('mouse', options.pauseOnHover && event.pointerType === 'mouse')],
|
|
317
|
+
[root, 'pointerleave', () => set('mouse', false)],
|
|
318
|
+
// A mouse click also moves the focus to a button. Only the keyboard focus pauses.
|
|
319
|
+
[root, 'focusin', (event) => set('focus', options.pauseOnFocus && event.target.matches(':focus-visible'))],
|
|
320
|
+
[root, 'focusout', (event) => set('focus', root.contains(event.relatedTarget) && reasons.has('focus'))]
|
|
321
|
+
];
|
|
322
|
+
|
|
323
|
+
observer.observe(root);
|
|
324
|
+
listeners.forEach(([node, name, handler]) => node.addEventListener(name, handler));
|
|
325
|
+
|
|
326
|
+
return {
|
|
327
|
+
paused: () => reasons.size > 0,
|
|
328
|
+
remove() {
|
|
329
|
+
observer.disconnect();
|
|
330
|
+
listeners.forEach(([node, name, handler]) => node.removeEventListener(name, handler));
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* The part that autoplay and auto scroll share: the play and pause button (WCAG 2.2.2), the "playing" class, aria-live, the pause reasons and the events.
|
|
337
|
+
* The control goes into the API of the carousel, and remove() removes it.
|
|
338
|
+
*
|
|
339
|
+
* @param {object} context What the features share. See carousel.js.
|
|
340
|
+
* @param {string} key The API key of the control: 'autoplay' or 'autoScroll'. Its lowercase form is the prefix of the events.
|
|
341
|
+
* @param {object} options The feature options.
|
|
342
|
+
* @param {{play: () => void, stop: () => void, pause: (paused: boolean) => void, events: Array<[string, Function]>}} hooks
|
|
343
|
+
* events: more handlers of carousel events.
|
|
344
|
+
* @returns {{play: () => void, stop: () => void, isPlaying: () => boolean, paused: () => boolean, remove: () => void}}
|
|
345
|
+
*/
|
|
346
|
+
function controller(context, key, options, hooks) {
|
|
347
|
+
const { api, root, container, cls, emit } = context,
|
|
348
|
+
labels = context.options.labels,
|
|
349
|
+
button = create('button', cls.button + ' ' + cls.playButton);
|
|
350
|
+
|
|
351
|
+
let playing = false,
|
|
352
|
+
watch = null,
|
|
353
|
+
// true until the first init
|
|
354
|
+
first = true;
|
|
355
|
+
|
|
356
|
+
button.type = 'button';
|
|
357
|
+
button.setAttribute('aria-controls', container.id);
|
|
358
|
+
button.addEventListener('click', () => playing ? control.stop() : control.play());
|
|
359
|
+
|
|
360
|
+
function update() {
|
|
361
|
+
setAttribute(button, 'aria-label', playing ? labels.pause : labels.play);
|
|
362
|
+
setClass(root, cls.playing, playing);
|
|
363
|
+
// A screen reader does not read each automatic change
|
|
364
|
+
own(container, 'aria-live', playing ? 'off' : 'polite');
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function show() {
|
|
368
|
+
if (api.isFit()) {
|
|
369
|
+
button.remove();
|
|
370
|
+
} else if (!button.isConnected) {
|
|
371
|
+
root.append(button);
|
|
372
|
+
}
|
|
373
|
+
// Start at the first init, unless the user prefers less motion
|
|
374
|
+
if (first) {
|
|
375
|
+
first = false;
|
|
376
|
+
if (options.playOnInit && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
|
377
|
+
control.play();
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const control = {
|
|
383
|
+
play() {
|
|
384
|
+
if (!playing) {
|
|
385
|
+
playing = true;
|
|
386
|
+
watch = pauser(root, options, () => hooks.pause(watch.paused()));
|
|
387
|
+
update();
|
|
388
|
+
hooks.play();
|
|
389
|
+
emit(key.toLowerCase() + ':play');
|
|
390
|
+
}
|
|
391
|
+
},
|
|
392
|
+
stop() {
|
|
393
|
+
if (playing) {
|
|
394
|
+
playing = false;
|
|
395
|
+
watch.remove();
|
|
396
|
+
update();
|
|
397
|
+
hooks.stop();
|
|
398
|
+
emit(key.toLowerCase() + ':stop');
|
|
399
|
+
}
|
|
400
|
+
},
|
|
401
|
+
isPlaying: () => playing,
|
|
402
|
+
paused: () => !playing || watch.paused(),
|
|
403
|
+
remove() {
|
|
404
|
+
control.stop();
|
|
405
|
+
button.remove();
|
|
406
|
+
delete api[key];
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
[['init', show], ['reinit', show], ['resize', show], ...hooks.events].forEach(([event, handler]) => context.on(event, handler));
|
|
411
|
+
update();
|
|
412
|
+
api[key] = control;
|
|
413
|
+
|
|
414
|
+
return control;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Go to the next snap after a delay. The timer starts at "settle", so that a slow motion does not make the delay shorter.
|
|
419
|
+
*
|
|
420
|
+
* @param {object} context What the features share. See carousel.js.
|
|
421
|
+
* @returns {object|undefined} The control: play(), stop(), reset(), isPlaying(), remove().
|
|
422
|
+
*/
|
|
423
|
+
function autoplay(context) {
|
|
424
|
+
if (!context.options.autoplay) {
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const api = context.api,
|
|
429
|
+
options = settings(autoplayDefaults, 'delay', context.options.autoplay);
|
|
430
|
+
|
|
431
|
+
let timer = 0,
|
|
432
|
+
// The function that the "timer" callback returned for the timer
|
|
433
|
+
done = null,
|
|
434
|
+
// true while the autoplay goes to the next slide, so that its own goToSnap() is not an interaction
|
|
435
|
+
self = false;
|
|
436
|
+
|
|
437
|
+
// Stop the timer, and call the function that the "timer" callback returned
|
|
438
|
+
function clear() {
|
|
439
|
+
clearTimeout(timer);
|
|
440
|
+
done?.();
|
|
441
|
+
done = null;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function reset() {
|
|
445
|
+
clear();
|
|
446
|
+
if (!control.paused() && !api.isFit()) {
|
|
447
|
+
// The delay: data-delay on the selected slide, one value for each snap, or one value
|
|
448
|
+
const value = api.slideNodes()[api.selectedSlide()]?.dataset.delay || options.delay,
|
|
449
|
+
delay = +(Array.isArray(value) ? value[api.selectedSnap()] : value);
|
|
450
|
+
timer = setTimeout(next, delay);
|
|
451
|
+
done = options.timer?.(delay, api);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function next() {
|
|
456
|
+
clear();
|
|
457
|
+
self = true;
|
|
458
|
+
if (api.canGoToNext()) {
|
|
459
|
+
api.goToNext(options.instant);
|
|
460
|
+
} else if (options.stopOnLastSnap) {
|
|
461
|
+
control.stop();
|
|
462
|
+
} else {
|
|
463
|
+
api.goToSnap(0, options.instant);
|
|
464
|
+
}
|
|
465
|
+
self = false;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// A drag, a wheel step, an arrow, a dot or the keyboard stops the autoplay. With stopOnInteraction: false, the timer starts again at "settle".
|
|
469
|
+
function interact() {
|
|
470
|
+
if (!self) {
|
|
471
|
+
clear();
|
|
472
|
+
if (options.stopOnInteraction) {
|
|
473
|
+
control.stop();
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const control = controller(context, 'autoplay', options, {
|
|
479
|
+
play: reset,
|
|
480
|
+
stop: clear,
|
|
481
|
+
pause: reset,
|
|
482
|
+
events: [['settle', reset], ['interact', interact]]
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
control.reset = reset;
|
|
486
|
+
|
|
487
|
+
return control;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Move the slides at a constant speed: with loop, without an end; without loop, to the end. The carousel makes the motion,
|
|
492
|
+
* and this feature starts it, stops it and pauses it.
|
|
493
|
+
*
|
|
494
|
+
* @param {object} context What the features share. See carousel.js.
|
|
495
|
+
* @returns {object|undefined} The control: play(), stop(), isPlaying(), remove().
|
|
496
|
+
*/
|
|
497
|
+
function autoScroll(context) {
|
|
498
|
+
if (!context.options.autoScroll) {
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const options = settings(autoScrollDefaults, 'speed', context.options.autoScroll);
|
|
503
|
+
|
|
504
|
+
// The start delay
|
|
505
|
+
let timer = 0;
|
|
506
|
+
|
|
507
|
+
const control = controller(context, 'autoScroll', options, {
|
|
508
|
+
play: wait,
|
|
509
|
+
stop() {
|
|
510
|
+
wait(-1);
|
|
511
|
+
context.halt();
|
|
512
|
+
},
|
|
513
|
+
pause(paused) {
|
|
514
|
+
if (paused) {
|
|
515
|
+
context.halt();
|
|
516
|
+
} else if (!timer) {
|
|
517
|
+
run();
|
|
518
|
+
}
|
|
519
|
+
},
|
|
520
|
+
events: [
|
|
521
|
+
// A motion stopped: start again after the delay
|
|
522
|
+
['settle', () => control.isPlaying() && wait()],
|
|
523
|
+
// A measure pass stopped the motion: start again now
|
|
524
|
+
['resize', () => control.isPlaying() && !timer && run()],
|
|
525
|
+
// A drag, a wheel step or a goToSnap() stops the auto scroll, or makes it wait until the next "settle"
|
|
526
|
+
['interact', () => {
|
|
527
|
+
if (control.isPlaying()) {
|
|
528
|
+
wait(-1);
|
|
529
|
+
if (options.stopOnInteraction) {
|
|
530
|
+
control.stop();
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}]
|
|
534
|
+
]
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* Start the auto scroll after its delay.
|
|
539
|
+
*
|
|
540
|
+
* @param {number} [cancel] With -1, only stop the timer.
|
|
541
|
+
*/
|
|
542
|
+
function wait(cancel) {
|
|
543
|
+
clearTimeout(timer);
|
|
544
|
+
timer = cancel ? 0 : setTimeout(run, options.startDelay);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function run() {
|
|
548
|
+
timer = 0;
|
|
549
|
+
const geo = context.geo();
|
|
550
|
+
if (geo && !geo.fit && !context.dragging() && !control.paused()) {
|
|
551
|
+
context.scroll(options.direction === 'prev' ? -1 : 1, options.speed / 1000);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return control;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/*
|
|
559
|
+
* Loop math: the period, the clones and the place of each slide. This module does not use the DOM.
|
|
560
|
+
*
|
|
561
|
+
* The values and the slides are the same as in geometry.js. In loop mode, each slide is at start + k * period.
|
|
562
|
+
* The library writes k * period as the translate of the slide.
|
|
563
|
+
*/
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* Get the number of full copies of the slides that the loop needs. With 0, the slides can loop with no clones:
|
|
567
|
+
* no slide is necessary at two places at the same time.
|
|
568
|
+
*
|
|
569
|
+
* @param {number} length The loop period of the original slides.
|
|
570
|
+
* @param {number} view
|
|
571
|
+
* @param {number} max
|
|
572
|
+
* @returns {number}
|
|
573
|
+
*/
|
|
574
|
+
function cloneCount(length, view, max) {
|
|
575
|
+
return length > 0 ? Math.max(0, Math.ceil((view + max) / length) - 1) : 0;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Get the k of each slide for a motion from one location to another. With from = to, it is the placement at rest.
|
|
580
|
+
* The slide center goes into a window of one period. The window has the same center as the part of the content that shows during the motion.
|
|
581
|
+
*
|
|
582
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
583
|
+
* @param {number} from
|
|
584
|
+
* @param {number} to
|
|
585
|
+
* @param {number} view The size of the visible area.
|
|
586
|
+
* @param {number} length The loop period.
|
|
587
|
+
* @param {number} [offset] The start of the visible area, relative to the viewport start.
|
|
588
|
+
* @returns {number[]}
|
|
589
|
+
*/
|
|
590
|
+
function placement(slides, from, to, view, length, offset = 0) {
|
|
591
|
+
const center = offset + (view - from - to) / 2;
|
|
592
|
+
return slides.map((slide) => Math.round((center - (slide.start + slide.end) / 2) / length) || 0);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Find if one placement is correct for the full motion. If not, the motion must change the placement during the motion.
|
|
597
|
+
*
|
|
598
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
599
|
+
* @param {number} from
|
|
600
|
+
* @param {number} to
|
|
601
|
+
* @param {number} view
|
|
602
|
+
* @param {number} length
|
|
603
|
+
* @returns {boolean}
|
|
604
|
+
*/
|
|
605
|
+
function pathFits(slides, from, to, view, length) {
|
|
606
|
+
const path = view + Math.abs(to - from);
|
|
607
|
+
return slides.every((slide) => length >= path + slide.end - slide.start);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Get the steps of each slide for an auto scroll iteration. The container moves by one period, from `from` to `from - length` (forward)
|
|
612
|
+
* or to `from + length` (back). Each slide moves by one period at one time in the iteration.
|
|
613
|
+
*
|
|
614
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
615
|
+
* @param {number} from
|
|
616
|
+
* @param {number} view
|
|
617
|
+
* @param {number} length
|
|
618
|
+
* @param {number} direction 1 for forward, -1 for back.
|
|
619
|
+
* @param {number} [offset] The start of the visible area, relative to the viewport start.
|
|
620
|
+
* @returns {Array<{k: number, offset: number}>} k at the start of the iteration, and the time of the step, from 0 to 1.
|
|
621
|
+
*/
|
|
622
|
+
function steps(slides, from, view, length, direction, offset = 0) {
|
|
623
|
+
return slides.map((slide) => {
|
|
624
|
+
const value = (offset + view / 2 - from - (slide.start + slide.end) / 2) / length,
|
|
625
|
+
k = Math.round(value);
|
|
626
|
+
|
|
627
|
+
return { k, offset: direction > 0 ? k + 0.5 - value : value - k + 0.5 };
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Put a location into the range (-length, 0].
|
|
633
|
+
*
|
|
634
|
+
* @param {number} location
|
|
635
|
+
* @param {number} length
|
|
636
|
+
* @returns {number}
|
|
637
|
+
*/
|
|
638
|
+
function normalize(location, length) {
|
|
639
|
+
return location - Math.ceil(location / length) * length;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/*
|
|
643
|
+
* Snap math: the snaps, the active slide, the slides in view and the progress. This module does not use the DOM.
|
|
644
|
+
*
|
|
645
|
+
* All values are on the main axis, in px. A slide is { start, end }: its border box at location 0, relative to the viewport start.
|
|
646
|
+
* The location L is the translate of the container. A slide shows at start + L.
|
|
647
|
+
* In loop mode, the period is the length of one copy of the slides. Without loop, it is 0.
|
|
648
|
+
*/
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Keep a value between two limits.
|
|
653
|
+
*
|
|
654
|
+
* @param {number} value
|
|
655
|
+
* @param {number} min
|
|
656
|
+
* @param {number} max
|
|
657
|
+
* @returns {number}
|
|
658
|
+
*/
|
|
659
|
+
function clamp(value, min, max) {
|
|
660
|
+
return Math.min(max, Math.max(min, value));
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Get a valid snap index. In loop mode, the index goes around. Without loop, it stops at the first or the last snap.
|
|
665
|
+
*
|
|
666
|
+
* @param {number} index
|
|
667
|
+
* @param {number} count The number of snaps.
|
|
668
|
+
* @param {number} [period]
|
|
669
|
+
* @returns {number}
|
|
670
|
+
*/
|
|
671
|
+
function snapIndex(index, count, period) {
|
|
672
|
+
return period ? (index % count + count) % count : clamp(index, 0, count - 1);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Get the offset of a snap from the viewport start.
|
|
677
|
+
*
|
|
678
|
+
* @param {string|Function} align 'start', 'center', 'end' or (viewSize, snapSize, index) => offset.
|
|
679
|
+
* @param {number} view The viewport size.
|
|
680
|
+
* @param {number} size The snap size.
|
|
681
|
+
* @param {number} index The snap index.
|
|
682
|
+
* @returns {number}
|
|
683
|
+
*/
|
|
684
|
+
function alignOffset(align, view, size, index) {
|
|
685
|
+
if (typeof align === 'function') {
|
|
686
|
+
return align(view, size, index);
|
|
687
|
+
}
|
|
688
|
+
return align === 'center' ? (view - size) / 2 : align === 'end' ? view - size : 0;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Get the first start and the last end of the slides.
|
|
693
|
+
*
|
|
694
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
695
|
+
* @returns {{start: number, end: number, size: number, max: number}} max is the size of the largest slide.
|
|
696
|
+
*/
|
|
697
|
+
function bounds(slides) {
|
|
698
|
+
let start = Infinity,
|
|
699
|
+
end = -Infinity,
|
|
700
|
+
max = 0;
|
|
701
|
+
|
|
702
|
+
for (const slide of slides) {
|
|
703
|
+
start = Math.min(start, slide.start);
|
|
704
|
+
end = Math.max(end, slide.end);
|
|
705
|
+
max = Math.max(max, slide.end - slide.start);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return { start, end, size: end - start, max };
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Put the slides that start at the same position (1 px or less) into one column.
|
|
713
|
+
* In a flex row, one column has one slide. In a grid, a column can have more slides.
|
|
714
|
+
*
|
|
715
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
716
|
+
* @returns {Array<{start: number, end: number}>} The columns, sorted by start.
|
|
717
|
+
*/
|
|
718
|
+
function columns(slides) {
|
|
719
|
+
const order = slides.map((slide, index) => index).sort((a, b) => slides[a].start - slides[b].start || a - b),
|
|
720
|
+
list = [];
|
|
721
|
+
|
|
722
|
+
let column;
|
|
723
|
+
|
|
724
|
+
for (const index of order) {
|
|
725
|
+
const slide = slides[index];
|
|
726
|
+
if (column && slide.start - column.start <= 1) {
|
|
727
|
+
column.end = Math.max(column.end, slide.end);
|
|
728
|
+
} else {
|
|
729
|
+
column = { start: slide.start, end: slide.end };
|
|
730
|
+
list.push(column);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
return list;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Put the columns into groups. One group gives one snap.
|
|
739
|
+
*
|
|
740
|
+
* @param {Array<{start: number, end: number}>} list The columns.
|
|
741
|
+
* @param {number} view
|
|
742
|
+
* @param {number|string} count A number of columns, or 'auto' for as many as fit in the viewport.
|
|
743
|
+
* @returns {Array<{start: number, end: number}>}
|
|
744
|
+
*/
|
|
745
|
+
function groups(list, view, count) {
|
|
746
|
+
const result = [];
|
|
747
|
+
|
|
748
|
+
let group,
|
|
749
|
+
size = 0;
|
|
750
|
+
|
|
751
|
+
for (const column of list) {
|
|
752
|
+
const fit = count === 'auto' ? group && column.end - group.start <= view + 1 : size < count;
|
|
753
|
+
if (group && fit) {
|
|
754
|
+
group.end = Math.max(group.end, column.end);
|
|
755
|
+
size++;
|
|
756
|
+
} else {
|
|
757
|
+
group = { start: column.start, end: column.end };
|
|
758
|
+
result.push(group);
|
|
759
|
+
size = 1;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
return result;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Get the distance between two locations. In loop mode, use the shortest distance modulo the period.
|
|
768
|
+
*
|
|
769
|
+
* @param {number} a
|
|
770
|
+
* @param {number} b
|
|
771
|
+
* @param {number} [period] The loop period, or 0 if the loop is off.
|
|
772
|
+
* @returns {number} a - b
|
|
773
|
+
*/
|
|
774
|
+
function distance(a, b, period) {
|
|
775
|
+
const value = a - b;
|
|
776
|
+
return period ? value - Math.round(value / period) * period : value;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Compute the snaps.
|
|
781
|
+
*
|
|
782
|
+
* @param {object} args
|
|
783
|
+
* @param {Array<{start: number, end: number}>} args.slides
|
|
784
|
+
* @param {number} args.view The viewport size.
|
|
785
|
+
* @param {string|Function} args.align
|
|
786
|
+
* @param {number|string} args.slidesPerSnap
|
|
787
|
+
* @param {string|boolean} args.containScroll 'trimSnaps', 'keepSnaps' or false.
|
|
788
|
+
* @param {number} [args.period] The loop period, or 0 if the loop is off.
|
|
789
|
+
* @returns {{snaps: Array<{location: number, slide: number}>, min: number, max: number}}
|
|
790
|
+
* Each snap has its location and its active slide. min and max are the limits of the location if the loop is off.
|
|
791
|
+
* With the loop, max is the location of the first snap, where the progress is 0.
|
|
792
|
+
*/
|
|
793
|
+
function snaps({ slides, view, align, slidesPerSnap, containScroll, period = 0 }) {
|
|
794
|
+
const content = bounds(slides);
|
|
795
|
+
|
|
796
|
+
let max = -content.start || 0,
|
|
797
|
+
min = view - content.end,
|
|
798
|
+
list = groups(columns(slides), view, slidesPerSnap).map((group, index) => alignOffset(align, view, group.end - group.start, index) - group.start);
|
|
799
|
+
|
|
800
|
+
if (!period) {
|
|
801
|
+
if (containScroll) {
|
|
802
|
+
list = list.map((location) => clamp(location, min, max));
|
|
803
|
+
} else {
|
|
804
|
+
max = Math.max(...list);
|
|
805
|
+
min = Math.min(...list);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
if (period || containScroll !== 'keepSnaps') {
|
|
810
|
+
list = list.filter((location, index) => !index || Math.abs(distance(location, list[index - 1], period)) > 1);
|
|
811
|
+
if (period && list.length > 1 && Math.abs(distance(list[0], list[list.length - 1], period)) <= 1) {
|
|
812
|
+
list.pop();
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const result = list.map((location) => ({ location, slide: activeSlide(slides, location, view, align, period) }));
|
|
817
|
+
|
|
818
|
+
// Without the loop, a trimmed snap at an end can get the slide of the snap next to it. Then it takes the nearest slide on its own side.
|
|
819
|
+
const fix = (snap, from, to) => {
|
|
820
|
+
const slide = activeSlide(slides, snap.location, view, align, 0, from, to);
|
|
821
|
+
snap.slide = slide > -1 ? slide : snap.slide;
|
|
822
|
+
};
|
|
823
|
+
|
|
824
|
+
if (!period && result.length > 1) {
|
|
825
|
+
const first = result[0],
|
|
826
|
+
last = result[result.length - 1];
|
|
827
|
+
if (first.slide >= result[1].slide) {
|
|
828
|
+
fix(first, 0, result[1].slide);
|
|
829
|
+
}
|
|
830
|
+
if (last.slide <= result[result.length - 2].slide) {
|
|
831
|
+
fix(last, result[result.length - 2].slide + 1, slides.length);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
return {
|
|
836
|
+
snaps: result,
|
|
837
|
+
min,
|
|
838
|
+
max: period ? list[0] : max
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* Find the slide whose anchor is nearest to the align point at a location.
|
|
844
|
+
* The anchor is the start for 'start', the center for 'center' and the end for 'end'.
|
|
845
|
+
* If two slides have the same distance, the lower index wins.
|
|
846
|
+
*
|
|
847
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
848
|
+
* @param {number} location
|
|
849
|
+
* @param {number} view
|
|
850
|
+
* @param {string|Function} align
|
|
851
|
+
* @param {number} [period]
|
|
852
|
+
* @param {number} [from] The first slide to look at.
|
|
853
|
+
* @param {number} [to] The slide after the last slide to look at.
|
|
854
|
+
* @returns {number} The slide index, or -1 if the range is empty.
|
|
855
|
+
*/
|
|
856
|
+
function activeSlide(slides, location, view, align, period, from = 0, to = slides.length) {
|
|
857
|
+
let best = -1,
|
|
858
|
+
gap = Infinity;
|
|
859
|
+
|
|
860
|
+
slides.forEach((slide, index) => {
|
|
861
|
+
const value = Math.abs(distance(slide.start + location, alignOffset(align, view, slide.end - slide.start, index), period));
|
|
862
|
+
if (index >= from && index < to && value < gap - 0.5) {
|
|
863
|
+
gap = value;
|
|
864
|
+
best = index;
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
|
|
868
|
+
return best;
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* Find the snap of a slide: the snap whose active slide it is, or the snap nearest to the raw location of the slide.
|
|
873
|
+
*
|
|
874
|
+
* @param {Array<{location: number, slide: number}>} list The snaps.
|
|
875
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
876
|
+
* @param {number} index The slide index.
|
|
877
|
+
* @param {number} view
|
|
878
|
+
* @param {string|Function} align
|
|
879
|
+
* @param {number} [period]
|
|
880
|
+
* @returns {number} The snap index.
|
|
881
|
+
*/
|
|
882
|
+
function snapOfSlide(list, slides, index, view, align, period) {
|
|
883
|
+
const found = list.findIndex((snap) => snap.slide === index),
|
|
884
|
+
slide = slides[index];
|
|
885
|
+
|
|
886
|
+
if (found > -1 || !slide) {
|
|
887
|
+
return Math.max(found, 0);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
return nearestSnap(list, alignOffset(align, view, slide.end - slide.start, index) - slide.start, period);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* Find the snap nearest to a location.
|
|
895
|
+
*
|
|
896
|
+
* @param {Array<{location: number}>} list The snaps.
|
|
897
|
+
* @param {number} location
|
|
898
|
+
* @param {number} [period]
|
|
899
|
+
* @returns {number} The snap index.
|
|
900
|
+
*/
|
|
901
|
+
function nearestSnap(list, location, period) {
|
|
902
|
+
let best = 0,
|
|
903
|
+
gap = Infinity;
|
|
904
|
+
|
|
905
|
+
list.forEach((snap, index) => {
|
|
906
|
+
const value = Math.abs(distance(snap.location, location, period));
|
|
907
|
+
if (value < gap) {
|
|
908
|
+
gap = value;
|
|
909
|
+
best = index;
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
|
|
913
|
+
return best;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Get the location of a snap that is nearest to the current location. In loop mode, a snap has a location in each period.
|
|
918
|
+
*
|
|
919
|
+
* @param {number} target The snap location.
|
|
920
|
+
* @param {number} location The current location.
|
|
921
|
+
* @param {number} [period]
|
|
922
|
+
* @param {number} [direction] 1 to go forward (a smaller location), -1 to go back, 0 for the shortest path.
|
|
923
|
+
* @returns {number}
|
|
924
|
+
*/
|
|
925
|
+
function targetLocation(target, location, period, direction = 0) {
|
|
926
|
+
if (!period) {
|
|
927
|
+
return target;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
if (direction > 0) {
|
|
931
|
+
return target + (Math.ceil((location - 0.5 - target) / period) - 1) * period;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
if (direction < 0) {
|
|
935
|
+
return target + (Math.floor((location + 0.5 - target) / period) + 1) * period;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
return location + distance(target, location, period);
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Get the progress of a location, from 0 to 1.
|
|
943
|
+
*
|
|
944
|
+
* @param {number} location
|
|
945
|
+
* @param {{min: number, max: number, period: number}} limits The limits of the location and the loop period. With the loop, max is the location of the first snap.
|
|
946
|
+
* @returns {number}
|
|
947
|
+
*/
|
|
948
|
+
function progress(location, { min, max, period }) {
|
|
949
|
+
if (period) {
|
|
950
|
+
const value = (max - location) / period;
|
|
951
|
+
return value - Math.floor(value);
|
|
952
|
+
}
|
|
953
|
+
return max > min ? clamp((max - location) / (max - min), 0, 1) : 0;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Find the slides that show at a location.
|
|
958
|
+
*
|
|
959
|
+
* @param {Array<{start: number, end: number}>} slides
|
|
960
|
+
* @param {number} location
|
|
961
|
+
* @param {number} view
|
|
962
|
+
* @param {number} threshold The part of a slide that must show, from 0 to 1. With 0, any part is enough.
|
|
963
|
+
* @param {number} [period]
|
|
964
|
+
* @returns {number[]} The slide indexes.
|
|
965
|
+
*/
|
|
966
|
+
function inView(slides, location, view, threshold, period) {
|
|
967
|
+
const result = [];
|
|
968
|
+
|
|
969
|
+
slides.forEach((slide, index) => {
|
|
970
|
+
const size = slide.end - slide.start,
|
|
971
|
+
start = period ? distance(slide.start + location + size / 2, view / 2, period) + view / 2 - size / 2 : slide.start + location,
|
|
972
|
+
visible = Math.min(start + size, view) - Math.max(start, 0);
|
|
973
|
+
|
|
974
|
+
if (visible > 0 && visible >= threshold * size - 0.5) {
|
|
975
|
+
result.push(index);
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
|
|
979
|
+
return result;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* Get the position of a location between the snaps, as a fractional snap index: 2.4 is between snap 2 and snap 3.
|
|
984
|
+
* In loop mode, a value after the last snap goes to the first snap again.
|
|
985
|
+
*
|
|
986
|
+
* @param {Array<{location: number}>} list The snaps.
|
|
987
|
+
* @param {number} location
|
|
988
|
+
* @param {number} [period]
|
|
989
|
+
* @returns {number}
|
|
990
|
+
*/
|
|
991
|
+
function snapPosition(list, location, period) {
|
|
992
|
+
const last = list.length - 1,
|
|
993
|
+
first = list[0].location,
|
|
994
|
+
at = period ? first - ((first - location) % period + period) % period : clamp(location, list[last].location, first);
|
|
995
|
+
|
|
996
|
+
let index = 0;
|
|
997
|
+
|
|
998
|
+
while (index < last && list[index + 1].location >= at) {
|
|
999
|
+
index++;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
const from = list[index].location,
|
|
1003
|
+
to = index < last ? list[index + 1].location : first - period;
|
|
1004
|
+
|
|
1005
|
+
return index + (to < from ? (from - at) / (from - to) : 0);
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* Compute the geometry of a carousel from the layout reads: the loop period, the snaps, and the logical snaps.
|
|
1010
|
+
* With clones, a logical snap is a snap whose active slide is an original slide.
|
|
1011
|
+
*
|
|
1012
|
+
* @param {object} layout The result of readLayout().
|
|
1013
|
+
* @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.
|
|
1014
|
+
* @param {{start: number, size: number}} area The result of visibleArea().
|
|
1015
|
+
* @param {number} count The number of original slides.
|
|
1016
|
+
* @param {object} options The options of the carousel.
|
|
1017
|
+
* @returns {object} The geometry. If the carousel needs a different number of clones, only { copies }: the number of copies of all slides.
|
|
1018
|
+
* map gives the logical snap of each snap.
|
|
1019
|
+
*/
|
|
1020
|
+
function compute(layout, rects, area, count, options) {
|
|
1021
|
+
const content = bounds(rects.slides.slice(0, count)),
|
|
1022
|
+
fit = content.size <= rects.view + 1 && !(options.autoScroll && options.loop),
|
|
1023
|
+
loop = options.loop && !fit && count,
|
|
1024
|
+
// The loop period: the distance from the first slide start to the same point in the next copy of the slides
|
|
1025
|
+
period = loop ? bounds(rects.slides).size + rects.gap : 0,
|
|
1026
|
+
copies = loop && options.clones ? cloneCount(content.size + rects.gap, area.size, content.max) : 0;
|
|
1027
|
+
|
|
1028
|
+
if (copies * count !== rects.slides.length - count) {
|
|
1029
|
+
return { copies };
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const geo = { ...layout, ...rects, area, fit, count, period, min: 0, max: 0 };
|
|
1033
|
+
|
|
1034
|
+
if (fit) {
|
|
1035
|
+
geo.snaps = [{ location: 0, slide: activeSlide(rects.slides, 0, rects.view, layout.align) }];
|
|
1036
|
+
} else {
|
|
1037
|
+
Object.assign(geo, snaps({ ...rects, align: layout.align, slidesPerSnap: options.slidesPerSnap, containScroll: options.containScroll, period }));
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const list = geo.snaps.map((snap, index) => index).filter((index) => !copies || geo.snaps[index].slide < count);
|
|
1041
|
+
|
|
1042
|
+
geo.logical = list;
|
|
1043
|
+
geo.map = geo.snaps.map((snap, index) => copies ? Math.max(0, list.findIndex((item) => geo.snaps[item].slide % count === snap.slide % count)) : index);
|
|
1044
|
+
|
|
1045
|
+
return geo;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/**
|
|
1049
|
+
* Find the snap of a logical snap that is nearest to a location. With clones, a logical snap has more than one snap.
|
|
1050
|
+
*
|
|
1051
|
+
* @param {{snaps: Array<{location: number}>, map: number[], period: number}} geo The result of compute().
|
|
1052
|
+
* @param {number} index The logical snap.
|
|
1053
|
+
* @param {number} location
|
|
1054
|
+
* @returns {number} The snap index.
|
|
1055
|
+
*/
|
|
1056
|
+
function physicalSnap(geo, index, location) {
|
|
1057
|
+
let best = -1,
|
|
1058
|
+
gap = Infinity;
|
|
1059
|
+
|
|
1060
|
+
geo.snaps.forEach((snap, item) => {
|
|
1061
|
+
const value = Math.abs(distance(snap.location, location, geo.period));
|
|
1062
|
+
if (geo.map[item] === index && value < gap) {
|
|
1063
|
+
gap = value;
|
|
1064
|
+
best = item;
|
|
1065
|
+
}
|
|
1066
|
+
});
|
|
1067
|
+
|
|
1068
|
+
return best < 0 ? clamp(index, 0, geo.snaps.length - 1) : best;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/*
|
|
1072
|
+
* Layout: the layout reads, and the observers that all carousels share.
|
|
1073
|
+
*
|
|
1074
|
+
* The reads run in the ResizeObserver callback, when the layout is clean.
|
|
1075
|
+
*/
|
|
1076
|
+
|
|
1077
|
+
/**
|
|
1078
|
+
* Read the axis, the alignment, the direction and the gap from the computed style of the container.
|
|
1079
|
+
*
|
|
1080
|
+
* @param {HTMLElement} container
|
|
1081
|
+
* @param {object} options
|
|
1082
|
+
* @returns {{axis: string, align: string|Function, rtl: boolean, sign: number, gap: number}} sign is -1 for a right-to-left carousel, else 1.
|
|
1083
|
+
*/
|
|
1084
|
+
function readLayout(container, options) {
|
|
1085
|
+
const style = getComputedStyle(container),
|
|
1086
|
+
display = style.display,
|
|
1087
|
+
content = style.justifyContent;
|
|
1088
|
+
|
|
1089
|
+
let axis = options.axis;
|
|
1090
|
+
|
|
1091
|
+
if (axis === 'auto') {
|
|
1092
|
+
axis = 'x';
|
|
1093
|
+
if (display.includes('grid')) {
|
|
1094
|
+
axis = style.gridAutoFlow.startsWith('column') ? 'x' : 'y';
|
|
1095
|
+
} else if (display.includes('flex') && style.flexDirection.startsWith('column') && style.flexWrap === 'nowrap') {
|
|
1096
|
+
axis = 'y';
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
let align = options.align;
|
|
1101
|
+
|
|
1102
|
+
if (align === 'auto') {
|
|
1103
|
+
align = content === 'center' ? 'center' : content === 'flex-end' || content === 'end' || (axis === 'x' && content === 'right') ? 'end' : 'start';
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
const rtl = axis === 'x' && (options.dir === 'auto' ? style.direction === 'rtl' : options.dir === 'rtl');
|
|
1107
|
+
|
|
1108
|
+
return {
|
|
1109
|
+
axis,
|
|
1110
|
+
align,
|
|
1111
|
+
rtl,
|
|
1112
|
+
sign: rtl ? -1 : 1,
|
|
1113
|
+
gap: parseFloat(axis === 'x' ? style.columnGap : style.rowGap) || 0
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* Read the slide boxes on the main axis, relative to the viewport start at location 0.
|
|
1119
|
+
*
|
|
1120
|
+
* @param {HTMLElement} viewport
|
|
1121
|
+
* @param {HTMLElement[]} nodes All slides, clones included.
|
|
1122
|
+
* @param {object} layout The result of readLayout().
|
|
1123
|
+
* @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
|
|
1124
|
+
* @returns {{view: number, slides: Array<{start: number, end: number, cross: number}>, gap: number}}
|
|
1125
|
+
* gap is the loop gap: the space between the last slide and the next copy of the first slide.
|
|
1126
|
+
*/
|
|
1127
|
+
function readRects(viewport, nodes, layout, written) {
|
|
1128
|
+
const box = viewport.getBoundingClientRect(),
|
|
1129
|
+
x = layout.axis === 'x',
|
|
1130
|
+
sign = layout.sign,
|
|
1131
|
+
known = written.axis === layout.axis,
|
|
1132
|
+
shift = known ? written.container : 0;
|
|
1133
|
+
|
|
1134
|
+
let first = 0,
|
|
1135
|
+
last = 0;
|
|
1136
|
+
|
|
1137
|
+
const slides = nodes.map((node, index) => {
|
|
1138
|
+
const rect = node.getBoundingClientRect(),
|
|
1139
|
+
offset = sign * (shift + (known && written.slides[index] || 0)),
|
|
1140
|
+
start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) - offset,
|
|
1141
|
+
size = x ? rect.width : rect.height;
|
|
1142
|
+
|
|
1143
|
+
return { start, end: start + size, cross: x ? rect.height : rect.width };
|
|
1144
|
+
});
|
|
1145
|
+
|
|
1146
|
+
slides.forEach((slide, index) => {
|
|
1147
|
+
if (slide.start < slides[first].start) {
|
|
1148
|
+
first = index;
|
|
1149
|
+
}
|
|
1150
|
+
if (slide.end > slides[last].end) {
|
|
1151
|
+
last = index;
|
|
1152
|
+
}
|
|
1153
|
+
});
|
|
1154
|
+
|
|
1155
|
+
let gap = layout.gap;
|
|
1156
|
+
|
|
1157
|
+
if (slides.length) {
|
|
1158
|
+
const side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'];
|
|
1159
|
+
gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
return {
|
|
1163
|
+
view: x ? box.width : box.height,
|
|
1164
|
+
slides,
|
|
1165
|
+
gap
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
/**
|
|
1170
|
+
* Get the window size on the main axis.
|
|
1171
|
+
*
|
|
1172
|
+
* @param {string} axis 'x' or 'y'.
|
|
1173
|
+
* @returns {number}
|
|
1174
|
+
*/
|
|
1175
|
+
function windowSize(axis) {
|
|
1176
|
+
return axis === 'x' ? document.documentElement.clientWidth : innerHeight;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/**
|
|
1180
|
+
* Get the part of the main axis where the loop must show slides, relative to the viewport start.
|
|
1181
|
+
* It is the viewport. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
|
|
1182
|
+
*
|
|
1183
|
+
* @param {HTMLElement} viewport
|
|
1184
|
+
* @param {{axis: string, rtl: boolean}} layout
|
|
1185
|
+
* @param {number} view The viewport size.
|
|
1186
|
+
* @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
|
|
1187
|
+
* @returns {{start: number, size: number}}
|
|
1188
|
+
*/
|
|
1189
|
+
function visibleArea(viewport, layout, view, size) {
|
|
1190
|
+
if (!size) {
|
|
1191
|
+
return { start: 0, size: view };
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const box = viewport.getBoundingClientRect(),
|
|
1195
|
+
before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top));
|
|
1196
|
+
|
|
1197
|
+
return { start: -before, size: before + Math.max(view, Math.round(size - before)) };
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
// One ResizeObserver for all carousels. Each callback first reads the layout of all carousels, then writes. In this way, the reads of one carousel do not
|
|
1201
|
+
// come after the writes of another carousel, and the browser does one layout for all of them.
|
|
1202
|
+
const owners = new WeakMap();
|
|
1203
|
+
|
|
1204
|
+
let resizer;
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* Watch the size of elements. The ResizeObserver callback calls owner.read() for each owner, and then owner.write() for each owner whose read() returned true.
|
|
1208
|
+
* An entry for which owner.skip() returns true does not count.
|
|
1209
|
+
*
|
|
1210
|
+
* @param {Element[]} nodes
|
|
1211
|
+
* @param {{read: () => boolean, write: () => void, skip: (entry: ResizeObserverEntry) => boolean}} [owner] Without an owner, stop the watch.
|
|
1212
|
+
*/
|
|
1213
|
+
function observeSize(nodes, owner) {
|
|
1214
|
+
resizer ||= new ResizeObserver((entries) => {
|
|
1215
|
+
const list = new Set(entries.filter((entry) => !owners.get(entry.target)?.skip(entry)).map((entry) => owners.get(entry.target)));
|
|
1216
|
+
[...list].filter((item) => item && item.read()).forEach((item) => item.write());
|
|
1217
|
+
});
|
|
1218
|
+
|
|
1219
|
+
for (const node of nodes) {
|
|
1220
|
+
if (owner) {
|
|
1221
|
+
owners.set(node, owner);
|
|
1222
|
+
resizer.observe(node);
|
|
1223
|
+
} else {
|
|
1224
|
+
owners.delete(node);
|
|
1225
|
+
resizer.unobserve(node);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the boxes that readBoxes() read
|
|
1231
|
+
const watchers = new Map(),
|
|
1232
|
+
waiters = new WeakMap(),
|
|
1233
|
+
boxes = new WeakMap();
|
|
1234
|
+
|
|
1235
|
+
/**
|
|
1236
|
+
* 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.
|
|
1237
|
+
* waitNear() uses each box one time.
|
|
1238
|
+
*
|
|
1239
|
+
* @param {Element[]} elements
|
|
1240
|
+
*/
|
|
1241
|
+
function readBoxes(elements) {
|
|
1242
|
+
elements.forEach((element) => boxes.set(element, element.getBoundingClientRect()));
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* Wait until an element comes near the screen.
|
|
1247
|
+
*
|
|
1248
|
+
* @param {Element} node
|
|
1249
|
+
* @param {true|number} lazy The "lazy" option: true for one screen height, or a distance in px.
|
|
1250
|
+
* @param {Function} callback
|
|
1251
|
+
* @returns {Function|null} A function that stops the wait, or null if the element is near the screen now.
|
|
1252
|
+
*/
|
|
1253
|
+
function waitNear(node, lazy, callback) {
|
|
1254
|
+
const near = lazy === true ? innerHeight : lazy,
|
|
1255
|
+
rect = boxes.get(node) || node.getBoundingClientRect(),
|
|
1256
|
+
margin = lazy === true ? '100%' : lazy + 'px';
|
|
1257
|
+
|
|
1258
|
+
boxes.delete(node);
|
|
1259
|
+
|
|
1260
|
+
if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
|
|
1261
|
+
return null;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
let observer = watchers.get(margin);
|
|
1265
|
+
if (!observer) {
|
|
1266
|
+
observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
|
|
1267
|
+
watchers.set(margin, observer);
|
|
1268
|
+
}
|
|
1269
|
+
waiters.set(node, callback);
|
|
1270
|
+
observer.observe(node);
|
|
1271
|
+
return () => {
|
|
1272
|
+
observer.unobserve(node);
|
|
1273
|
+
waiters.delete(node);
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/*
|
|
1278
|
+
* Motion: the easing, the duration of a goToSnap() motion, and the motion engine.
|
|
1279
|
+
*/
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
// The easing of a goToSnap() motion
|
|
1283
|
+
const EASE = [0.25, 1, 0.5, 1];
|
|
1284
|
+
|
|
1285
|
+
// The easing of a glide after a free drag
|
|
1286
|
+
const GLIDE = [0.2, 0.6, 0.35, 1];
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* Make a cubic Bézier easing function, the same as the CSS cubic-bezier().
|
|
1290
|
+
*
|
|
1291
|
+
* @param {number[]} curve [x1, y1, x2, y2]
|
|
1292
|
+
* @returns {(t: number) => number}
|
|
1293
|
+
*/
|
|
1294
|
+
function bezier([x1, y1, x2, y2]) {
|
|
1295
|
+
const axis = (a, b, t) => ((1 + 3 * a - 3 * b) * t + 3 * b - 6 * a) * t * t + 3 * a * t;
|
|
1296
|
+
|
|
1297
|
+
return (x) => {
|
|
1298
|
+
if (x <= 0 || x >= 1) {
|
|
1299
|
+
return x <= 0 ? 0 : 1;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
let t = x;
|
|
1303
|
+
|
|
1304
|
+
// Newton steps, then bisection if the slope is too small
|
|
1305
|
+
for (let i = 0; i < 6; i++) {
|
|
1306
|
+
const error = axis(x1, x2, t) - x,
|
|
1307
|
+
slope = 3 * (1 + 3 * x1 - 3 * x2) * t * t + 2 * (3 * x2 - 6 * x1) * t + 3 * x1;
|
|
1308
|
+
if (Math.abs(error) < 1e-5) {
|
|
1309
|
+
return axis(y1, y2, t);
|
|
1310
|
+
}
|
|
1311
|
+
if (Math.abs(slope) < 1e-6) {
|
|
1312
|
+
break;
|
|
1313
|
+
}
|
|
1314
|
+
t -= error / slope;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
let low = 0,
|
|
1318
|
+
high = 1;
|
|
1319
|
+
|
|
1320
|
+
t = x;
|
|
1321
|
+
|
|
1322
|
+
while (high - low > 1e-5) {
|
|
1323
|
+
if (axis(x1, x2, t) < x) {
|
|
1324
|
+
low = t;
|
|
1325
|
+
} else {
|
|
1326
|
+
high = t;
|
|
1327
|
+
}
|
|
1328
|
+
t = (low + high) / 2;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
return axis(y1, y2, t);
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* Get the duration of a goToSnap() motion.
|
|
1337
|
+
*
|
|
1338
|
+
* @param {number} duration The duration for one snap, in ms.
|
|
1339
|
+
* @param {number} count The number of snaps to move.
|
|
1340
|
+
* @returns {number}
|
|
1341
|
+
*/
|
|
1342
|
+
function snapDuration(duration, count) {
|
|
1343
|
+
return count > 1 ? Math.min(2 * duration, duration * (1 + Math.log2(count))) : duration;
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
/**
|
|
1347
|
+
* Make the motion engine of a carousel. A motion runs as a Web Animations API animation of the container translate, on the compositor.
|
|
1348
|
+
* With raf set, it runs as a requestAnimationFrame loop instead, which calls frame() on each frame.
|
|
1349
|
+
* A loop motion moves the container and the slides of a loop carousel at a constant speed, on the compositor, until it stops.
|
|
1350
|
+
*
|
|
1351
|
+
* @param {HTMLElement} element The container.
|
|
1352
|
+
* @param {(location: number) => string} css Get the CSS translate value of a location.
|
|
1353
|
+
* @param {(location: number) => void} frame Write a location.
|
|
1354
|
+
* @param {() => void} done Called when a motion ends. A loop motion does not end.
|
|
1355
|
+
* @param {((location: number) => void)|null} [tick] Called on each frame of a motion on the compositor, because such a motion runs no script.
|
|
1356
|
+
* @returns {{run: Function, loop: Function, retarget: Function, stop: Function, current: Function, shifts: Function}}
|
|
1357
|
+
*/
|
|
1358
|
+
function animator(element, css, frame, done, tick) {
|
|
1359
|
+
let state = null;
|
|
1360
|
+
|
|
1361
|
+
const time = () => state.animations ? state.animations[0].currentTime || 0 : performance.now() - state.start,
|
|
1362
|
+
current = () => state && state.from + (state.to - state.from) * state.ease(time() / state.duration);
|
|
1363
|
+
|
|
1364
|
+
// The frame loop: a requestAnimationFrame motion writes the location, and a motion on the compositor calls tick().
|
|
1365
|
+
// The next frame starts before the callback, so that a callback that stops the motion also stops the loop.
|
|
1366
|
+
function step() {
|
|
1367
|
+
if (!state.animations && time() >= state.duration) {
|
|
1368
|
+
return finish();
|
|
1369
|
+
}
|
|
1370
|
+
state.raf = requestAnimationFrame(step);
|
|
1371
|
+
(state.animations ? tick : frame)(current());
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function finish() {
|
|
1375
|
+
const to = state.to;
|
|
1376
|
+
stop();
|
|
1377
|
+
frame(to);
|
|
1378
|
+
done();
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/**
|
|
1382
|
+
* Stop the motion.
|
|
1383
|
+
*
|
|
1384
|
+
* @returns {number|null} The location at the stop, or null if no motion runs.
|
|
1385
|
+
*/
|
|
1386
|
+
function stop() {
|
|
1387
|
+
const at = current();
|
|
1388
|
+
if (state) {
|
|
1389
|
+
state.animations?.forEach((animation) => animation.cancel());
|
|
1390
|
+
cancelAnimationFrame(state.raf);
|
|
1391
|
+
state = null;
|
|
1392
|
+
}
|
|
1393
|
+
return at;
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
function animate(at) {
|
|
1397
|
+
const animation = element.animate([{ translate: css(state.from) }, { translate: css(state.to) }], { duration: state.duration, easing: 'cubic-bezier(' + state.curve + ')', fill: 'forwards' });
|
|
1398
|
+
animation.currentTime = at;
|
|
1399
|
+
animation.onfinish = finish;
|
|
1400
|
+
state.animations = [animation];
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
/**
|
|
1404
|
+
* Start a motion. It stops the motion that runs.
|
|
1405
|
+
*
|
|
1406
|
+
* @param {object} next The state of the new motion. script: true runs it as a requestAnimationFrame loop.
|
|
1407
|
+
* @param {HTMLElement[]} [nodes] The slides of a loop motion.
|
|
1408
|
+
*/
|
|
1409
|
+
function start(next, nodes) {
|
|
1410
|
+
stop();
|
|
1411
|
+
state = next;
|
|
1412
|
+
if (next.list) {
|
|
1413
|
+
const timing = { duration: next.duration, iterations: Infinity },
|
|
1414
|
+
begin = document.timeline.currentTime,
|
|
1415
|
+
{ from, to, length, direction } = next;
|
|
1416
|
+
next.animations = [
|
|
1417
|
+
element.animate([{ translate: css(from) }, { translate: css(to) }], timing),
|
|
1418
|
+
...nodes.map((node, index) => {
|
|
1419
|
+
const { k, offset } = next.list[index],
|
|
1420
|
+
before = css(k * length),
|
|
1421
|
+
after = css((k + direction) * length);
|
|
1422
|
+
return node.animate([{ translate: before }, { translate: before, offset }, { translate: after, offset }, { translate: after }], timing);
|
|
1423
|
+
})
|
|
1424
|
+
];
|
|
1425
|
+
next.animations.forEach((animation) => animation.startTime = begin);
|
|
1426
|
+
} else if (next.script) {
|
|
1427
|
+
next.start = performance.now();
|
|
1428
|
+
} else {
|
|
1429
|
+
animate(0);
|
|
1430
|
+
}
|
|
1431
|
+
if (next.script || tick) {
|
|
1432
|
+
next.raf = requestAnimationFrame(step);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
return {
|
|
1437
|
+
/**
|
|
1438
|
+
* Start a motion to a location.
|
|
1439
|
+
*
|
|
1440
|
+
* @param {number} from
|
|
1441
|
+
* @param {number} to
|
|
1442
|
+
* @param {number} duration ms
|
|
1443
|
+
* @param {number[]} curve The cubic Bézier easing.
|
|
1444
|
+
* @param {boolean} raf Use a requestAnimationFrame loop.
|
|
1445
|
+
*/
|
|
1446
|
+
run: (from, to, duration, curve, raf) => start({ from, to, duration, curve, script: raf, ease: bezier(curve) }),
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* Start a loop motion. The container moves by one period in each iteration, and each slide moves by one period
|
|
1450
|
+
* at the time when it leaves the visible area.
|
|
1451
|
+
*
|
|
1452
|
+
* @param {number} from
|
|
1453
|
+
* @param {number} direction 1 for forward, -1 for back.
|
|
1454
|
+
* @param {number} duration The time of one iteration, in ms.
|
|
1455
|
+
* @param {{slides: Array<{start: number, end: number}>, area: {start: number, size: number}, period: number}} geo
|
|
1456
|
+
* @param {HTMLElement[]} nodes All slides, clones included.
|
|
1457
|
+
*/
|
|
1458
|
+
loop: (from, direction, duration, geo, nodes) => start({
|
|
1459
|
+
from,
|
|
1460
|
+
to: from - direction * geo.period,
|
|
1461
|
+
duration,
|
|
1462
|
+
direction,
|
|
1463
|
+
length: geo.period,
|
|
1464
|
+
list: steps(geo.slides, from, geo.area.size, geo.period, direction, geo.area.start),
|
|
1465
|
+
// The time in the iteration, from 0 to 1
|
|
1466
|
+
ease: (value) => value % 1
|
|
1467
|
+
}, nodes),
|
|
1468
|
+
|
|
1469
|
+
/**
|
|
1470
|
+
* Change the end of the motion that runs. The start, the time and the easing stay, so the motion does not jump.
|
|
1471
|
+
*
|
|
1472
|
+
* @param {number} to
|
|
1473
|
+
* @returns {boolean} false if no motion runs, or if a loop motion runs: it has no end.
|
|
1474
|
+
*/
|
|
1475
|
+
retarget(to) {
|
|
1476
|
+
if (!state || state.list) {
|
|
1477
|
+
return false;
|
|
1478
|
+
}
|
|
1479
|
+
if (to !== state.to) {
|
|
1480
|
+
state.to = to;
|
|
1481
|
+
if (state.animations) {
|
|
1482
|
+
const at = time();
|
|
1483
|
+
state.animations[0].cancel();
|
|
1484
|
+
animate(at);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
return true;
|
|
1488
|
+
},
|
|
1489
|
+
|
|
1490
|
+
stop,
|
|
1491
|
+
current,
|
|
1492
|
+
|
|
1493
|
+
/**
|
|
1494
|
+
* Get the translate values of the slides during a loop motion.
|
|
1495
|
+
*
|
|
1496
|
+
* @param {number} sign -1 for a right-to-left carousel.
|
|
1497
|
+
* @returns {number[]|null} The values in px, or null if no loop motion runs.
|
|
1498
|
+
*/
|
|
1499
|
+
shifts(sign) {
|
|
1500
|
+
if (!state?.list) {
|
|
1501
|
+
return null;
|
|
1502
|
+
}
|
|
1503
|
+
const phase = time() / state.duration % 1;
|
|
1504
|
+
return state.list.map(({ k, offset }) => sign * (phase >= offset ? k + state.direction : k) * state.length);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/*
|
|
1510
|
+
* Options: the defaults, the class names, the merge of the option sources, and the breakpoints.
|
|
1511
|
+
*/
|
|
1512
|
+
|
|
1513
|
+
const defaults = {
|
|
1514
|
+
axis: 'auto',
|
|
1515
|
+
align: 'auto',
|
|
1516
|
+
dir: 'auto',
|
|
1517
|
+
loop: false,
|
|
1518
|
+
dragFree: false,
|
|
1519
|
+
dragFriction: 1,
|
|
1520
|
+
containScroll: 'trimSnaps',
|
|
1521
|
+
slidesPerSnap: 1,
|
|
1522
|
+
skipSnaps: true,
|
|
1523
|
+
dragThreshold: 10,
|
|
1524
|
+
duration: 400,
|
|
1525
|
+
startSnap: 0,
|
|
1526
|
+
lazy: false,
|
|
1527
|
+
drag: true,
|
|
1528
|
+
wheel: true,
|
|
1529
|
+
keys: true,
|
|
1530
|
+
resize: true,
|
|
1531
|
+
slideChanges: true,
|
|
1532
|
+
focus: true,
|
|
1533
|
+
inViewThreshold: 0,
|
|
1534
|
+
active: true,
|
|
1535
|
+
breakpoints: {},
|
|
1536
|
+
container: null,
|
|
1537
|
+
slides: null,
|
|
1538
|
+
wrapper: true,
|
|
1539
|
+
arrows: true,
|
|
1540
|
+
dots: true,
|
|
1541
|
+
dotsStyle: 'zoom',
|
|
1542
|
+
labels: { carousel: 'Carousel', slide: '%d of %n', prev: 'Previous slide', next: 'Next slide', dot: 'Go to slide %d', play: 'Start the slide show', pause: 'Stop the slide show' },
|
|
1543
|
+
classes: null,
|
|
1544
|
+
state: '',
|
|
1545
|
+
sync: null,
|
|
1546
|
+
clones: 'auto',
|
|
1547
|
+
autoplay: false,
|
|
1548
|
+
autoScroll: false,
|
|
1549
|
+
autoHeight: false,
|
|
1550
|
+
progress: false,
|
|
1551
|
+
offset: false
|
|
1552
|
+
};
|
|
1553
|
+
|
|
1554
|
+
// The class names of a prefix. The root class is the prefix, such as "better" or "embla".
|
|
1555
|
+
const names = (prefix) => ({
|
|
1556
|
+
root: prefix,
|
|
1557
|
+
viewport: prefix + '_viewport',
|
|
1558
|
+
container: prefix + '_container',
|
|
1559
|
+
fit: prefix + '_fit',
|
|
1560
|
+
horizontal: prefix + '_horizontal',
|
|
1561
|
+
vertical: prefix + '_vertical',
|
|
1562
|
+
autoHeight: prefix + '_auto_height',
|
|
1563
|
+
button: prefix + '_button',
|
|
1564
|
+
prevButton: prefix + '_prev',
|
|
1565
|
+
nextButton: prefix + '_next',
|
|
1566
|
+
dots: prefix + '_dots',
|
|
1567
|
+
dotsTrack: prefix + '_dots_track',
|
|
1568
|
+
dotsMarker: prefix + '_dots_marker',
|
|
1569
|
+
dotsAll: prefix + '_dots_all',
|
|
1570
|
+
dot: prefix + '_dot',
|
|
1571
|
+
playButton: prefix + '_play',
|
|
1572
|
+
clone: 'clone',
|
|
1573
|
+
selected: 'selected',
|
|
1574
|
+
inView: '',
|
|
1575
|
+
dragging: 'dragging',
|
|
1576
|
+
playing: 'playing',
|
|
1577
|
+
first: 'first',
|
|
1578
|
+
prev: 'prev',
|
|
1579
|
+
current: 'current',
|
|
1580
|
+
next: 'next',
|
|
1581
|
+
last: 'last'
|
|
1582
|
+
});
|
|
1583
|
+
|
|
1584
|
+
// The state classes get the "state" prefix
|
|
1585
|
+
const states = ['selected', 'inView', 'dragging', 'playing', 'first', 'prev', 'current', 'next', 'last'];
|
|
1586
|
+
|
|
1587
|
+
/**
|
|
1588
|
+
* Get the class names from the "classes" and "state" options.
|
|
1589
|
+
*
|
|
1590
|
+
* @param {string|object|null} classes A prefix, such as 'embla', or an object with the names to change. The default prefix is 'better'.
|
|
1591
|
+
* The object can have a "prefix" key for the names that it does not change: { prefix: 'embla', selected: 'snapped' }.
|
|
1592
|
+
* @param {string} state The prefix of the state classes.
|
|
1593
|
+
* @returns {object}
|
|
1594
|
+
*/
|
|
1595
|
+
function classNames(classes, state) {
|
|
1596
|
+
const result = typeof classes === 'string' ? names(classes) : { ...names(classes?.prefix || 'better'), ...classes };
|
|
1597
|
+
|
|
1598
|
+
for (const key of states) {
|
|
1599
|
+
if (result[key]) {
|
|
1600
|
+
result[key] = state + result[key];
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
return result;
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
/**
|
|
1608
|
+
* Merge the option sources. A later source wins. Objects such as "labels" merge one level deep.
|
|
1609
|
+
*
|
|
1610
|
+
* @param {...object} sources
|
|
1611
|
+
* @returns {object}
|
|
1612
|
+
*/
|
|
1613
|
+
function merge(...sources) {
|
|
1614
|
+
const result = {};
|
|
1615
|
+
|
|
1616
|
+
for (const source of sources) {
|
|
1617
|
+
for (const key in source) {
|
|
1618
|
+
const value = source[key],
|
|
1619
|
+
old = result[key];
|
|
1620
|
+
result[key] = value && old && typeof value === 'object' && typeof old === 'object' && value.constructor === Object && old.constructor === Object ? { ...old, ...value } : value;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
return result;
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
/**
|
|
1628
|
+
* Get the options of an element: the library defaults, then the sources, then the JSON options of the data-carousel attribute.
|
|
1629
|
+
*
|
|
1630
|
+
* @param {HTMLElement} element
|
|
1631
|
+
* @param {...object} sources The site defaults and the options of the call.
|
|
1632
|
+
* @returns {object}
|
|
1633
|
+
*/
|
|
1634
|
+
function resolve(element, ...sources) {
|
|
1635
|
+
let data = {};
|
|
1636
|
+
try {
|
|
1637
|
+
data = JSON.parse(element.dataset.carousel || '{}');
|
|
1638
|
+
} catch {
|
|
1639
|
+
// The library ignores an attribute that is not valid JSON
|
|
1640
|
+
}
|
|
1641
|
+
return merge(defaults, ...sources, data);
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* Merge the options of the breakpoints whose media query matches, and watch the media queries.
|
|
1646
|
+
*
|
|
1647
|
+
* @param {object} base The options, with the "breakpoints" option.
|
|
1648
|
+
* @param {() => void} change Called when a media query starts or stops to match.
|
|
1649
|
+
* @returns {{options: object, remove: () => void}} The options, and a function that stops the watch.
|
|
1650
|
+
*/
|
|
1651
|
+
function breakpoints(base, change) {
|
|
1652
|
+
// Keep the key of each query: the browser can write MediaQueryList.media in a different form.
|
|
1653
|
+
const list = Object.entries(base.breakpoints || {}).map(([query, value]) => [matchMedia(query), value]);
|
|
1654
|
+
|
|
1655
|
+
list.forEach(([query]) => query.addEventListener('change', change));
|
|
1656
|
+
|
|
1657
|
+
return {
|
|
1658
|
+
options: merge(base, ...list.filter(([query]) => query.matches).map(([, value]) => value)),
|
|
1659
|
+
remove: () => list.forEach(([query]) => query.removeEventListener('change', change))
|
|
1660
|
+
};
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
/*
|
|
1664
|
+
* Carousel: its state, its API, the setup, the measure pass, the render and the motion.
|
|
1665
|
+
*
|
|
1666
|
+
* The features get their part of the carousel through the context object. Each feature is a function that takes the context.
|
|
1667
|
+
* It returns nothing if its option is off, or an object with remove(). remove() removes all that the feature added.
|
|
1668
|
+
*/
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
// The instance of each root, viewport and container
|
|
1672
|
+
const registry = new WeakMap();
|
|
1673
|
+
|
|
1674
|
+
/**
|
|
1675
|
+
* Get the carousel of a root, a viewport or a container.
|
|
1676
|
+
*
|
|
1677
|
+
* @param {Element} element
|
|
1678
|
+
* @returns {object|undefined}
|
|
1679
|
+
*/
|
|
1680
|
+
const find = (element) => registry.get(element);
|
|
1681
|
+
|
|
1682
|
+
/**
|
|
1683
|
+
* Make an event emitter. A handler gets (api, name), as in Embla.
|
|
1684
|
+
* The handlers of the features run before the handlers of the page, and clear() removes them.
|
|
1685
|
+
*
|
|
1686
|
+
* @param {object} api
|
|
1687
|
+
* @returns {{on: Function, off: Function, listen: Function, clear: Function, emit: Function, has: Function}}
|
|
1688
|
+
*/
|
|
1689
|
+
function emitter(api) {
|
|
1690
|
+
const user = {},
|
|
1691
|
+
own = {},
|
|
1692
|
+
add = (map, name, handler) => (map[name] ||= new Set()).add(handler);
|
|
1693
|
+
|
|
1694
|
+
return {
|
|
1695
|
+
on(name, handler) {
|
|
1696
|
+
add(user, name, handler);
|
|
1697
|
+
return api;
|
|
1698
|
+
},
|
|
1699
|
+
off(name, handler) {
|
|
1700
|
+
user[name]?.delete(handler);
|
|
1701
|
+
return api;
|
|
1702
|
+
},
|
|
1703
|
+
listen: (name, handler) => add(own, name, handler),
|
|
1704
|
+
clear: () => Object.values(own).forEach((set) => set.clear()),
|
|
1705
|
+
emit(name) {
|
|
1706
|
+
own[name]?.forEach((handler) => handler(api, name));
|
|
1707
|
+
user[name]?.forEach((handler) => handler(api, name));
|
|
1708
|
+
},
|
|
1709
|
+
has: (name) => !!user[name]?.size
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
|
|
1713
|
+
/**
|
|
1714
|
+
* Make a carousel.
|
|
1715
|
+
*
|
|
1716
|
+
* @param {HTMLElement} element The container of the slides, or its viewport.
|
|
1717
|
+
* @param {object} userOptions
|
|
1718
|
+
* @param {object} defaults The site defaults.
|
|
1719
|
+
* @param {Array<(context: object) => ({remove: () => void}|undefined)>} features
|
|
1720
|
+
* @returns {object} The carousel API.
|
|
1721
|
+
*/
|
|
1722
|
+
function carousel(element, userOptions, defaults, features) {
|
|
1723
|
+
const found = registry.get(element);
|
|
1724
|
+
|
|
1725
|
+
if (found) {
|
|
1726
|
+
return found;
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
// The options and the markup
|
|
1730
|
+
let options,
|
|
1731
|
+
cls,
|
|
1732
|
+
root,
|
|
1733
|
+
viewport,
|
|
1734
|
+
container,
|
|
1735
|
+
slides = [],
|
|
1736
|
+
clones = [],
|
|
1737
|
+
nodes = [],
|
|
1738
|
+
// The features that are on
|
|
1739
|
+
parts = [];
|
|
1740
|
+
|
|
1741
|
+
// The observers and the measure state
|
|
1742
|
+
let observed = [],
|
|
1743
|
+
mutationObserver,
|
|
1744
|
+
media = null,
|
|
1745
|
+
ready = false,
|
|
1746
|
+
started = false,
|
|
1747
|
+
changed = false,
|
|
1748
|
+
signature = [],
|
|
1749
|
+
viewWidth = 0,
|
|
1750
|
+
pending = -1,
|
|
1751
|
+
lastWindow = 0;
|
|
1752
|
+
|
|
1753
|
+
// The geometry, the location and the selection
|
|
1754
|
+
let geo = null,
|
|
1755
|
+
location = 0,
|
|
1756
|
+
selected = 0,
|
|
1757
|
+
previous = 0,
|
|
1758
|
+
requested = -1,
|
|
1759
|
+
followed = -1,
|
|
1760
|
+
visible = [],
|
|
1761
|
+
written = { axis: '', container: 0, slides: [] };
|
|
1762
|
+
|
|
1763
|
+
// The motion and the drag. A free motion, such as the auto scroll, has no snap: it selects the nearest snap when it stops.
|
|
1764
|
+
let motion,
|
|
1765
|
+
dragging = false,
|
|
1766
|
+
free = false;
|
|
1767
|
+
|
|
1768
|
+
const api = {
|
|
1769
|
+
goToSnap: (index, instant) => go(physical(index), instant),
|
|
1770
|
+
goToNext: (instant) => api.canGoToNext() && step(selected, 1, instant),
|
|
1771
|
+
goToPrev: (instant) => api.canGoToPrev() && step(selected, -1, instant),
|
|
1772
|
+
goToSlide: (index, instant) => go(physical(api.snapOfSlide(index)), instant, index),
|
|
1773
|
+
canGoToNext: () => !!geo && !geo.fit && (!!geo.period || selected < geo.snaps.length - 1),
|
|
1774
|
+
canGoToPrev: () => !!geo && !geo.fit && (!!geo.period || selected > 0),
|
|
1775
|
+
selectedSnap: () => logical(selected),
|
|
1776
|
+
previousSnap: () => logical(previous),
|
|
1777
|
+
selectedSlide,
|
|
1778
|
+
snapOfSlide: (index) => geo ? logical(snapOfSlide(geo.snaps, geo.slides, index, geo.view, geo.align, geo.period)) : index,
|
|
1779
|
+
snapProgress: () => geo ? geo.logical.map((index) => progress(geo.snaps[index].location, geo)) : [],
|
|
1780
|
+
progress: () => geo ? progress(current(), geo) : 0,
|
|
1781
|
+
slideNodes: () => slides.slice(),
|
|
1782
|
+
slidesInView: () => visible.slice(),
|
|
1783
|
+
rootNode: () => root,
|
|
1784
|
+
viewportNode: () => viewport,
|
|
1785
|
+
containerNode: () => container,
|
|
1786
|
+
isFit: () => !geo || geo.fit,
|
|
1787
|
+
options: () => options,
|
|
1788
|
+
reinit,
|
|
1789
|
+
destroy: () => {
|
|
1790
|
+
teardown(false);
|
|
1791
|
+
events.emit('destroy');
|
|
1792
|
+
}
|
|
1793
|
+
};
|
|
1794
|
+
|
|
1795
|
+
const events = emitter(api),
|
|
1796
|
+
owner = { read: measure, write: measured, skip: heightOnly },
|
|
1797
|
+
// The states that the "progress" and the "offset" callbacks get. Each call gets the same object, so a frame makes no garbage.
|
|
1798
|
+
whole = { progress: 0, snap: 0 },
|
|
1799
|
+
each = { node: null, index: 0, offset: 0, distance: 0, size: 0, visible: 0 },
|
|
1800
|
+
/**
|
|
1801
|
+
* What the features share: the API, the events, and the state and the actions of the carousel.
|
|
1802
|
+
* setup() adds root, viewport, container, cls and options.
|
|
1803
|
+
*/
|
|
1804
|
+
context = {
|
|
1805
|
+
api,
|
|
1806
|
+
emit: events.emit,
|
|
1807
|
+
// Listen to an event until the teardown
|
|
1808
|
+
on: events.listen,
|
|
1809
|
+
|
|
1810
|
+
// The state
|
|
1811
|
+
geo: () => geo,
|
|
1812
|
+
nodes: () => nodes,
|
|
1813
|
+
selected: () => selected,
|
|
1814
|
+
dragging: () => dragging,
|
|
1815
|
+
// The location at rest or at the end of the motion. During a free motion, the location now.
|
|
1816
|
+
location: () => free ? current() : location,
|
|
1817
|
+
current,
|
|
1818
|
+
|
|
1819
|
+
// The actions
|
|
1820
|
+
hold,
|
|
1821
|
+
halt,
|
|
1822
|
+
step,
|
|
1823
|
+
scroll,
|
|
1824
|
+
// Select a snap and move to a location
|
|
1825
|
+
move: (index, target, duration, curve) => {
|
|
1826
|
+
requested = -1;
|
|
1827
|
+
move(index, target, duration, curve);
|
|
1828
|
+
},
|
|
1829
|
+
// Start or end a drag, and set the "dragging" class. The start is an interaction, as goToSnap() is.
|
|
1830
|
+
drag: (on) => {
|
|
1831
|
+
dragging = on;
|
|
1832
|
+
setClass(root, cls.dragging, on);
|
|
1833
|
+
if (on) {
|
|
1834
|
+
events.emit('interact');
|
|
1835
|
+
events.emit('dragstart');
|
|
1836
|
+
} else {
|
|
1837
|
+
events.emit('dragend');
|
|
1838
|
+
}
|
|
1839
|
+
},
|
|
1840
|
+
// Set the slide that the sync option follows
|
|
1841
|
+
follow: (index) => {
|
|
1842
|
+
followed = index;
|
|
1843
|
+
}
|
|
1844
|
+
};
|
|
1845
|
+
|
|
1846
|
+
api.on = events.on;
|
|
1847
|
+
api.off = events.off;
|
|
1848
|
+
|
|
1849
|
+
// 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:
|
|
1850
|
+
// a start after the first paint adds the arrows and the dots in view, and this moves the page (CLS).
|
|
1851
|
+
let resolved = resolve(element, defaults, userOptions),
|
|
1852
|
+
waiting = resolved.lazy ? waitNear(element, resolved.lazy, reinit) : null;
|
|
1853
|
+
|
|
1854
|
+
if (waiting) {
|
|
1855
|
+
registry.set(element, api);
|
|
1856
|
+
} else {
|
|
1857
|
+
setup();
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
return api;
|
|
1861
|
+
|
|
1862
|
+
/**
|
|
1863
|
+
* Read the options, add the markup, start the features and the observers. The first ResizeObserver callback measures the layout.
|
|
1864
|
+
*/
|
|
1865
|
+
function setup() {
|
|
1866
|
+
media = breakpoints(resolved || resolve(element, defaults, userOptions), () => reinit());
|
|
1867
|
+
resolved = null;
|
|
1868
|
+
options = media.options;
|
|
1869
|
+
|
|
1870
|
+
if (!options.active) {
|
|
1871
|
+
return;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
cls = classNames(options.classes, options.state);
|
|
1875
|
+
({ root, viewport, container } = build(element, options, cls));
|
|
1876
|
+
|
|
1877
|
+
for (const node of [root, viewport, container]) {
|
|
1878
|
+
registry.set(node, api);
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
slides = readSlides(container, options.slides);
|
|
1882
|
+
nodes = slides;
|
|
1883
|
+
selected = options.startSnap;
|
|
1884
|
+
|
|
1885
|
+
observe(true);
|
|
1886
|
+
|
|
1887
|
+
Object.assign(context, { root, viewport, container, cls, options });
|
|
1888
|
+
|
|
1889
|
+
parts = features.map((feature) => feature(context)).filter(Boolean);
|
|
1890
|
+
motion = animator(container, css, frame, settle, (options.progress || options.offset) && ((at) => track(at, motion.shifts(geo.sign) || written.slides)));
|
|
1891
|
+
|
|
1892
|
+
if (options.autoHeight) {
|
|
1893
|
+
addClass(root, cls.autoHeight);
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
viewport.addEventListener('scroll', onScroll);
|
|
1897
|
+
if (options.loop && options.clones === 'fill') {
|
|
1898
|
+
addEventListener('resize', onWindow);
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
if (options.slideChanges) {
|
|
1902
|
+
mutationObserver = new MutationObserver(onMutation);
|
|
1903
|
+
mutationObserver.observe(container, { childList: true });
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
/**
|
|
1908
|
+
* Remove what setup() added.
|
|
1909
|
+
*
|
|
1910
|
+
* @param {boolean} keep Keep the wrapper markup for a new setup().
|
|
1911
|
+
*/
|
|
1912
|
+
function teardown(keep) {
|
|
1913
|
+
waiting?.();
|
|
1914
|
+
waiting = null;
|
|
1915
|
+
registry.delete(element);
|
|
1916
|
+
observe(false);
|
|
1917
|
+
mutationObserver?.disconnect();
|
|
1918
|
+
media?.remove();
|
|
1919
|
+
media = null;
|
|
1920
|
+
|
|
1921
|
+
if (!cls) {
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
motion.stop();
|
|
1926
|
+
parts.forEach((part) => part.remove());
|
|
1927
|
+
events.clear();
|
|
1928
|
+
parts = [];
|
|
1929
|
+
followed = -1;
|
|
1930
|
+
dragging = free = false;
|
|
1931
|
+
setClones(0);
|
|
1932
|
+
viewport.removeEventListener('scroll', onScroll);
|
|
1933
|
+
removeEventListener('resize', onWindow);
|
|
1934
|
+
|
|
1935
|
+
for (const node of nodes) {
|
|
1936
|
+
setStyle(node, 'translate', '');
|
|
1937
|
+
node.style.removeProperty('--better-offset');
|
|
1938
|
+
setClass(node, cls.selected, false);
|
|
1939
|
+
setClass(node, cls.inView, false);
|
|
1940
|
+
cleanStyle(node);
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
setStyle(container, 'translate', '');
|
|
1944
|
+
setStyle(container, 'willChange', '');
|
|
1945
|
+
setStyle(viewport, 'touchAction', '');
|
|
1946
|
+
setStyle(viewport, 'height', '');
|
|
1947
|
+
root.style.removeProperty('--better-progress');
|
|
1948
|
+
|
|
1949
|
+
for (const name of ['horizontal', 'vertical', 'fit', 'dragging']) {
|
|
1950
|
+
setClass(root, cls[name], false);
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
for (const node of [root, viewport, container]) {
|
|
1954
|
+
cleanStyle(node);
|
|
1955
|
+
registry.delete(node);
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
restore(root, viewport, container, slides, keep);
|
|
1959
|
+
|
|
1960
|
+
cls = geo = null;
|
|
1961
|
+
ready = false;
|
|
1962
|
+
location = 0;
|
|
1963
|
+
visible = [];
|
|
1964
|
+
signature = [];
|
|
1965
|
+
viewWidth = 0;
|
|
1966
|
+
written = { axis: '', container: 0, slides: [] };
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
/**
|
|
1970
|
+
* Merge new options and set up the carousel again. The selected slide stays.
|
|
1971
|
+
*
|
|
1972
|
+
* @param {object} [newOptions]
|
|
1973
|
+
*/
|
|
1974
|
+
function reinit(newOptions) {
|
|
1975
|
+
if (newOptions) {
|
|
1976
|
+
userOptions = merge(userOptions, newOptions);
|
|
1977
|
+
resolved = null;
|
|
1978
|
+
}
|
|
1979
|
+
const keep = geo ? selectedSlide() : requested;
|
|
1980
|
+
teardown(true);
|
|
1981
|
+
setup();
|
|
1982
|
+
requested = keep;
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
/**
|
|
1986
|
+
* Put the clones after the last slide.
|
|
1987
|
+
*
|
|
1988
|
+
* @param {number} count The number of copies of all slides.
|
|
1989
|
+
*/
|
|
1990
|
+
function setClones(count) {
|
|
1991
|
+
if (clones.length === count * slides.length) {
|
|
1992
|
+
return;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
clones.forEach((node) => node.remove());
|
|
1996
|
+
clones = copySlides(slides, count, cls.clone);
|
|
1997
|
+
container.append(...clones);
|
|
1998
|
+
nodes = slides.concat(clones);
|
|
1999
|
+
written.slides.length = slides.length;
|
|
2000
|
+
mutationObserver?.takeRecords();
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
/**
|
|
2004
|
+
* Watch the size of the viewport, the container and the slides.
|
|
2005
|
+
*
|
|
2006
|
+
* @param {boolean} on false stops the watch.
|
|
2007
|
+
*/
|
|
2008
|
+
function observe(on) {
|
|
2009
|
+
observeSize(observed);
|
|
2010
|
+
observed = on ? [viewport, container, ...nodes] : [];
|
|
2011
|
+
observeSize(observed, owner);
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* Find a resize of the viewport that changed only its height in a horizontal carousel with autoHeight.
|
|
2016
|
+
* autoHeight sets this height, and its transition changes it on each frame, so it needs no measure pass.
|
|
2017
|
+
*
|
|
2018
|
+
* @param {ResizeObserverEntry} entry
|
|
2019
|
+
* @returns {boolean}
|
|
2020
|
+
*/
|
|
2021
|
+
function heightOnly({ target, contentRect: { width } }) {
|
|
2022
|
+
if (target !== viewport) {
|
|
2023
|
+
return false;
|
|
2024
|
+
}
|
|
2025
|
+
const same = width === viewWidth;
|
|
2026
|
+
viewWidth = width;
|
|
2027
|
+
return same && options.autoHeight && geo?.axis === 'x';
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
function onMutation() {
|
|
2031
|
+
slides = readSlides(container, options.slides);
|
|
2032
|
+
setClones(0);
|
|
2033
|
+
nodes = slides;
|
|
2034
|
+
changed = true;
|
|
2035
|
+
observe(true);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// The original slide index of a slide or a clone
|
|
2039
|
+
function original(index) {
|
|
2040
|
+
return index % slides.length;
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// The logical snap of a snap. They are different only when the carousel has clones.
|
|
2044
|
+
function logical(index) {
|
|
2045
|
+
return geo ? geo.map[index] ?? 0 : index;
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
// The snap of a logical snap that is nearest to the current location
|
|
2049
|
+
function physical(index) {
|
|
2050
|
+
return geo ? physicalSnap(geo, index, current()) : index;
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
function selectedSlide() {
|
|
2054
|
+
// A carousel with the sync option selects the slide of the other carousel, also after a drag
|
|
2055
|
+
if (followed > -1) {
|
|
2056
|
+
return followed;
|
|
2057
|
+
}
|
|
2058
|
+
if (!geo) {
|
|
2059
|
+
return Math.max(requested, 0);
|
|
2060
|
+
}
|
|
2061
|
+
return requested >= 0 && api.snapOfSlide(requested) === logical(selected) ? requested : original(geo.snaps[selected].slide);
|
|
2062
|
+
}
|
|
2063
|
+
|
|
2064
|
+
// The location now, also during a motion
|
|
2065
|
+
function current() {
|
|
2066
|
+
return motion.current() ?? location;
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Read the layout and compute the geometry. This function does not write to the DOM.
|
|
2071
|
+
*
|
|
2072
|
+
* @returns {boolean} false if nothing changed.
|
|
2073
|
+
*/
|
|
2074
|
+
function measure() {
|
|
2075
|
+
const sign = geo?.sign || 1,
|
|
2076
|
+
at = motion.current(),
|
|
2077
|
+
layout = readLayout(container, options),
|
|
2078
|
+
// The translate values that show now: the written values, or the values of a motion
|
|
2079
|
+
rects = readRects(viewport, nodes, layout, at === null ? written : { axis: written.axis, container: sign * at, slides: motion.shifts(sign) || written.slides });
|
|
2080
|
+
|
|
2081
|
+
// With clones: 'fill', the loop fills the window
|
|
2082
|
+
lastWindow = options.loop && options.clones === 'fill' ? windowSize(layout.axis) : 0;
|
|
2083
|
+
|
|
2084
|
+
const area = visibleArea(viewport, layout, rects.view, lastWindow),
|
|
2085
|
+
values = [layout.axis, layout.rtl, typeof layout.align === 'string' && layout.align, rects.view, rects.gap, area.start, area.size, ...rects.slides.flatMap((slide) => [slide.start, slide.end, slide.cross])];
|
|
2086
|
+
|
|
2087
|
+
// A change of less than 0.5 px is not a change. During a motion, the rects have small errors, because the browser and bezier() round the easing differently.
|
|
2088
|
+
if (ready && values.length === signature.length && values.every((value, index) => value === signature[index] || Math.abs(value - signature[index]) < 0.5)) {
|
|
2089
|
+
return false;
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
signature = values;
|
|
2093
|
+
|
|
2094
|
+
const keep = ready ? selectedSlide() : requested,
|
|
2095
|
+
next = compute(layout, rects, area, slides.length, options);
|
|
2096
|
+
|
|
2097
|
+
if (!next.snaps) {
|
|
2098
|
+
pending = next.copies;
|
|
2099
|
+
return true;
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
geo = next;
|
|
2103
|
+
|
|
2104
|
+
const total = geo.snaps.length;
|
|
2105
|
+
|
|
2106
|
+
// Before the first measure pass, selected is the logical snap of the startSnap option or of goToSnap()
|
|
2107
|
+
selected = keep >= 0 ? physical(api.snapOfSlide(keep)) : Math.min(total - 1, ready ? selected : physical(selected));
|
|
2108
|
+
previous = Math.min(previous, total - 1);
|
|
2109
|
+
requested = keep;
|
|
2110
|
+
if (!dragging) {
|
|
2111
|
+
location = targetLocation(geo.snaps[selected].location, location, geo.period);
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
return true;
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
// A change of the window size can change the visible area, and the viewport size can stay the same.
|
|
2118
|
+
// Mobile browsers send a resize when the address bar shows or hides. Measure only if the size on the main axis changes.
|
|
2119
|
+
function onWindow() {
|
|
2120
|
+
if (geo && windowSize(geo.axis) !== lastWindow && measure()) {
|
|
2121
|
+
measured();
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
/**
|
|
2126
|
+
* Write the result of a measure pass and emit the events.
|
|
2127
|
+
*/
|
|
2128
|
+
function measured() {
|
|
2129
|
+
if (pending >= 0) {
|
|
2130
|
+
setClones(pending);
|
|
2131
|
+
pending = -1;
|
|
2132
|
+
signature = [];
|
|
2133
|
+
observe(true);
|
|
2134
|
+
return;
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
// A free motion stops where it is, and its feature starts it again on "resize"
|
|
2138
|
+
if (free) {
|
|
2139
|
+
halt();
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
// A motion goes on to the new location of its snap, for example when the selected slide changes its width. A drag keeps its location.
|
|
2143
|
+
const at = motion.current();
|
|
2144
|
+
if (at !== null && written.axis === geo.axis && !geo.fit && motion.retarget(location)) {
|
|
2145
|
+
place(at, location);
|
|
2146
|
+
render(true);
|
|
2147
|
+
} else {
|
|
2148
|
+
motion.stop();
|
|
2149
|
+
render(dragging);
|
|
2150
|
+
}
|
|
2151
|
+
labelSlides(slides, options.labels.slide);
|
|
2152
|
+
|
|
2153
|
+
if (!options.resize) {
|
|
2154
|
+
observe(false);
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
if (!ready) {
|
|
2158
|
+
ready = true;
|
|
2159
|
+
events.emit(started ? 'reinit' : 'init');
|
|
2160
|
+
started = true;
|
|
2161
|
+
} else {
|
|
2162
|
+
events.emit('resize');
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
if (changed) {
|
|
2166
|
+
changed = false;
|
|
2167
|
+
events.emit('slideschanged');
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
/**
|
|
2172
|
+
* Write the location, the classes, the touch action and the auto height.
|
|
2173
|
+
*
|
|
2174
|
+
* @param {boolean} [keep] Do not write the location, because a motion or a drag writes it.
|
|
2175
|
+
*/
|
|
2176
|
+
function render(keep) {
|
|
2177
|
+
const x = geo.axis === 'x';
|
|
2178
|
+
|
|
2179
|
+
setClass(root, cls.horizontal, x);
|
|
2180
|
+
setClass(root, cls.vertical, !x);
|
|
2181
|
+
setClass(root, cls.fit, geo.fit);
|
|
2182
|
+
setStyle(viewport, 'touchAction', geo.fit ? '' : x ? 'pan-y pinch-zoom' : 'pan-x pinch-zoom');
|
|
2183
|
+
setStyle(container, 'willChange', geo.fit ? '' : 'translate');
|
|
2184
|
+
|
|
2185
|
+
if (!keep) {
|
|
2186
|
+
write(geo.fit ? 0 : location);
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
// Auto height: the height of the tallest slide in view at the target location
|
|
2190
|
+
if (options.autoHeight) {
|
|
2191
|
+
setStyle(viewport, 'height', x ? Math.max(...inView(geo.slides, location, geo.view, 0, geo.period).map((index) => geo.slides[index].cross)) + 'px' : '');
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
const chosen = selectedSlide(),
|
|
2195
|
+
list = [...new Set(inView(geo.slides, location, geo.view, options.inViewThreshold, geo.period).map(original))].sort((a, b) => a - b);
|
|
2196
|
+
|
|
2197
|
+
nodes.forEach((node, index) => setClass(node, cls.selected, original(index) === chosen));
|
|
2198
|
+
|
|
2199
|
+
if (list.join() !== visible.join()) {
|
|
2200
|
+
visible = list;
|
|
2201
|
+
nodes.forEach((node, index) => setClass(node, cls.inView, list.includes(original(index))));
|
|
2202
|
+
events.emit('slidesinview');
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
/**
|
|
2207
|
+
* Get the screen value of a location: rounded to device pixels, with the sign of the direction.
|
|
2208
|
+
*
|
|
2209
|
+
* @param {number} value
|
|
2210
|
+
* @returns {number}
|
|
2211
|
+
*/
|
|
2212
|
+
function screen(value) {
|
|
2213
|
+
const scale = devicePixelRatio || 1;
|
|
2214
|
+
return Math.round(value * scale) / scale * geo.sign;
|
|
2215
|
+
}
|
|
2216
|
+
|
|
2217
|
+
/**
|
|
2218
|
+
* Get the CSS translate value of a screen value.
|
|
2219
|
+
*
|
|
2220
|
+
* @param {number} value px
|
|
2221
|
+
* @returns {string}
|
|
2222
|
+
*/
|
|
2223
|
+
function translate(value) {
|
|
2224
|
+
return value ? (geo.axis === 'x' ? value + 'px' : '0 ' + value + 'px') : '';
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
/**
|
|
2228
|
+
* Write the location as the translate of the container, and give it to the "progress" and the "offset" options.
|
|
2229
|
+
*
|
|
2230
|
+
* @param {number} value
|
|
2231
|
+
*/
|
|
2232
|
+
function write(value) {
|
|
2233
|
+
if (written.axis !== geo.axis) {
|
|
2234
|
+
nodes.forEach((node) => setStyle(node, 'translate', ''));
|
|
2235
|
+
written = { axis: geo.axis, container: 0, slides: [] };
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
written.container = screen(value);
|
|
2239
|
+
setStyle(container, 'translate', translate(written.container));
|
|
2240
|
+
place(value, value);
|
|
2241
|
+
if (options.progress || options.offset) {
|
|
2242
|
+
track(value, written.slides);
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
/**
|
|
2247
|
+
* Write the "progress" and the "offset" options for a location: the CSS variables, or the calls of the callbacks.
|
|
2248
|
+
* The motion engine also calls this function on each frame of a motion on the compositor.
|
|
2249
|
+
*
|
|
2250
|
+
* @param {number} at The location.
|
|
2251
|
+
* @param {number[]} shifts The loop shift of each slide on the screen, in px.
|
|
2252
|
+
*/
|
|
2253
|
+
function track(at, shifts) {
|
|
2254
|
+
if (options.progress === true) {
|
|
2255
|
+
root.style.setProperty('--better-progress', progress(at, geo));
|
|
2256
|
+
} else if (options.progress) {
|
|
2257
|
+
const value = snapPosition(geo.snaps, at, geo.period),
|
|
2258
|
+
snap = Math.floor(value);
|
|
2259
|
+
whole.progress = progress(at, geo);
|
|
2260
|
+
whole.snap = logical(snap) + value - snap;
|
|
2261
|
+
options.progress(whole, api);
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
if (options.offset) {
|
|
2265
|
+
nodes.forEach((node, index) => {
|
|
2266
|
+
const box = geo.slides[index],
|
|
2267
|
+
size = box.end - box.start,
|
|
2268
|
+
// The slide start on the screen, and its distance from its snap position
|
|
2269
|
+
start = box.start + geo.sign * (shifts[index] || 0) + at,
|
|
2270
|
+
delta = start - alignOffset(geo.align, geo.view, size, index),
|
|
2271
|
+
offset = delta / (size + geo.gap);
|
|
2272
|
+
|
|
2273
|
+
if (options.offset === true) {
|
|
2274
|
+
node.style.setProperty('--better-offset', offset);
|
|
2275
|
+
} else {
|
|
2276
|
+
each.node = node;
|
|
2277
|
+
each.index = original(index);
|
|
2278
|
+
each.offset = offset;
|
|
2279
|
+
each.distance = geo.sign * delta;
|
|
2280
|
+
each.size = size;
|
|
2281
|
+
each.visible = clamp((Math.min(start + size, geo.view) - Math.max(start, 0)) / size, 0, 1) || 0;
|
|
2282
|
+
options.offset(each, api);
|
|
2283
|
+
}
|
|
2284
|
+
});
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
/**
|
|
2289
|
+
* Write the loop shift of each slide for a motion from one location to another.
|
|
2290
|
+
*
|
|
2291
|
+
* @param {number} from
|
|
2292
|
+
* @param {number} to
|
|
2293
|
+
*/
|
|
2294
|
+
function place(from, to) {
|
|
2295
|
+
const list = geo.period ? placement(geo.slides, from, to, geo.area.size, geo.period, geo.area.start) : [];
|
|
2296
|
+
|
|
2297
|
+
nodes.forEach((node, index) => {
|
|
2298
|
+
const value = list.length ? screen(list[index] * geo.period) : 0;
|
|
2299
|
+
if ((written.slides[index] || 0) !== value) {
|
|
2300
|
+
written.slides[index] = value;
|
|
2301
|
+
setStyle(node, 'translate', translate(value));
|
|
2302
|
+
}
|
|
2303
|
+
});
|
|
2304
|
+
}
|
|
2305
|
+
|
|
2306
|
+
// The CSS translate value of a location
|
|
2307
|
+
function css(value) {
|
|
2308
|
+
return translate(screen(value)) || '0px';
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
/**
|
|
2312
|
+
* Go to the snap after a snap in a direction. In loop mode, the first snap follows the last snap.
|
|
2313
|
+
*
|
|
2314
|
+
* @param {number} index The snap.
|
|
2315
|
+
* @param {number} direction 1, -1, or 0 for the snap itself.
|
|
2316
|
+
* @param {boolean} [instant]
|
|
2317
|
+
*/
|
|
2318
|
+
function step(index, direction, instant) {
|
|
2319
|
+
go(snapIndex(index + direction, geo.snaps.length, geo.period), instant, -1, direction);
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
/**
|
|
2323
|
+
* Go to a snap. This is an interaction: it stops the autoplay and the auto scroll, or makes them wait.
|
|
2324
|
+
*
|
|
2325
|
+
* @param {number} index The snap index. physical() and step() give a valid index.
|
|
2326
|
+
* @param {boolean} [instant]
|
|
2327
|
+
* @param {number} [slide] The slide index, for goToSlide().
|
|
2328
|
+
* @param {number} [direction] 1 to go forward, -1 to go back, 0 for the shortest path in a loop.
|
|
2329
|
+
*/
|
|
2330
|
+
function go(index, instant, slide = -1, direction = 0) {
|
|
2331
|
+
if (waiting) {
|
|
2332
|
+
reinit();
|
|
2333
|
+
}
|
|
2334
|
+
events.emit('interact');
|
|
2335
|
+
requested = slide;
|
|
2336
|
+
if (!geo) {
|
|
2337
|
+
selected = index;
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
|
|
2341
|
+
const target = targetLocation(geo.snaps[index].location, current(), geo.period, direction),
|
|
2342
|
+
span = Math.abs(index - selected),
|
|
2343
|
+
count = geo.period ? Math.min(span, geo.snaps.length - span) : span;
|
|
2344
|
+
|
|
2345
|
+
move(index, target, instant ? 0 : snapDuration(options.duration, count), EASE);
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
/**
|
|
2349
|
+
* Select a snap and move to a location.
|
|
2350
|
+
*
|
|
2351
|
+
* @param {number} index The snap index.
|
|
2352
|
+
* @param {number} target The location.
|
|
2353
|
+
* @param {number} duration ms. With 0, the carousel jumps.
|
|
2354
|
+
* @param {number[]} curve
|
|
2355
|
+
*/
|
|
2356
|
+
function move(index, target, duration, curve) {
|
|
2357
|
+
const from = halt(),
|
|
2358
|
+
picked = select(index),
|
|
2359
|
+
jump = !duration || geo.fit || Math.abs(target - from) < 0.5;
|
|
2360
|
+
|
|
2361
|
+
location = target;
|
|
2362
|
+
|
|
2363
|
+
if (jump) {
|
|
2364
|
+
render();
|
|
2365
|
+
} else {
|
|
2366
|
+
const raf = events.has('scroll') || !!geo.period && !pathFits(geo.slides, from, target, geo.area.size, geo.period);
|
|
2367
|
+
render(true);
|
|
2368
|
+
if (!raf) {
|
|
2369
|
+
place(from, target);
|
|
2370
|
+
}
|
|
2371
|
+
motion.run(from, target, duration, curve, raf);
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
if (picked) {
|
|
2375
|
+
events.emit('select');
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
if (jump) {
|
|
2379
|
+
settle();
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
/**
|
|
2384
|
+
* Move at a constant speed, as a free motion. With the loop, the motion goes on until it stops. Without the loop, it goes to the end.
|
|
2385
|
+
* A free motion changes the classes only when it stops.
|
|
2386
|
+
*
|
|
2387
|
+
* @param {number} direction 1 for forward, -1 for back.
|
|
2388
|
+
* @param {number} speed px/ms
|
|
2389
|
+
*/
|
|
2390
|
+
function scroll(direction, speed) {
|
|
2391
|
+
const from = halt(),
|
|
2392
|
+
to = direction > 0 ? geo.min : geo.max;
|
|
2393
|
+
|
|
2394
|
+
if (geo.period) {
|
|
2395
|
+
free = true;
|
|
2396
|
+
// Start in the first period, so that the location does not grow after each pause
|
|
2397
|
+
location = normalize(from, geo.period);
|
|
2398
|
+
motion.loop(location, direction, geo.period / speed, geo, nodes);
|
|
2399
|
+
} else if (Math.abs(to - from) > 1) {
|
|
2400
|
+
free = true;
|
|
2401
|
+
location = to;
|
|
2402
|
+
motion.run(from, to, Math.abs(to - from) / speed, [0, 0, 1, 1], events.has('scroll'));
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
|
|
2406
|
+
/**
|
|
2407
|
+
* Change the selected snap.
|
|
2408
|
+
*
|
|
2409
|
+
* @param {number} index
|
|
2410
|
+
* @returns {boolean} true if the snap changed.
|
|
2411
|
+
*/
|
|
2412
|
+
function select(index) {
|
|
2413
|
+
if (index === selected) {
|
|
2414
|
+
return false;
|
|
2415
|
+
}
|
|
2416
|
+
previous = selected;
|
|
2417
|
+
selected = index;
|
|
2418
|
+
return true;
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
// Select the snap that is nearest to the location
|
|
2422
|
+
function pick() {
|
|
2423
|
+
if (select(nearestSnap(geo.snaps, location, geo.period))) {
|
|
2424
|
+
render(true);
|
|
2425
|
+
events.emit('select');
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
/**
|
|
2430
|
+
* Write a location during a motion or a drag.
|
|
2431
|
+
*
|
|
2432
|
+
* @param {number} value
|
|
2433
|
+
*/
|
|
2434
|
+
function frame(value) {
|
|
2435
|
+
write(value);
|
|
2436
|
+
events.emit('scroll');
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
/**
|
|
2440
|
+
* End a motion.
|
|
2441
|
+
*/
|
|
2442
|
+
function settle() {
|
|
2443
|
+
if (free) {
|
|
2444
|
+
free = false;
|
|
2445
|
+
pick();
|
|
2446
|
+
}
|
|
2447
|
+
if (geo.period) {
|
|
2448
|
+
location = normalize(location, geo.period);
|
|
2449
|
+
}
|
|
2450
|
+
render();
|
|
2451
|
+
events.emit('settle');
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
/**
|
|
2455
|
+
* Stop the motion where it is, and write that location. A free motion also selects the nearest snap.
|
|
2456
|
+
*
|
|
2457
|
+
* @returns {number} The location.
|
|
2458
|
+
*/
|
|
2459
|
+
function halt() {
|
|
2460
|
+
const at = motion.stop();
|
|
2461
|
+
if (at !== null) {
|
|
2462
|
+
location = at;
|
|
2463
|
+
write(at);
|
|
2464
|
+
if (free) {
|
|
2465
|
+
pick();
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
free = false;
|
|
2469
|
+
return location;
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
/**
|
|
2473
|
+
* Write a location without a motion, and select the snap that is nearest to it.
|
|
2474
|
+
*
|
|
2475
|
+
* @param {number} value
|
|
2476
|
+
* @param {boolean} [moving] Emit "scroll", as during a motion.
|
|
2477
|
+
*/
|
|
2478
|
+
function hold(value, moving) {
|
|
2479
|
+
location = value;
|
|
2480
|
+
(moving ? frame : write)(value);
|
|
2481
|
+
pick();
|
|
2482
|
+
}
|
|
2483
|
+
|
|
2484
|
+
/**
|
|
2485
|
+
* The browser scrolls the viewport to a focused element, although its overflow is hidden. Scroll it back.
|
|
2486
|
+
*/
|
|
2487
|
+
function onScroll() {
|
|
2488
|
+
viewport.scrollLeft = viewport.scrollTop = 0;
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
/*
|
|
2493
|
+
* Input: the pointer drag, the mouse wheel, the arrow keys, the keyboard focus, and the target of the motion after a drag.
|
|
2494
|
+
*
|
|
2495
|
+
* Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
|
|
2496
|
+
*/
|
|
2497
|
+
|
|
2498
|
+
|
|
2499
|
+
// The targets that keep their own pointer behavior
|
|
2500
|
+
const fields = 'input,textarea,select,[contenteditable]';
|
|
2501
|
+
|
|
2502
|
+
// The duration of the motion for one wheel event, in ms
|
|
2503
|
+
const WHEEL = 180;
|
|
2504
|
+
|
|
2505
|
+
// The time constant of the glide, in ms: the glide distance is velocity * MOMENTUM
|
|
2506
|
+
const MOMENTUM = 325;
|
|
2507
|
+
|
|
2508
|
+
/**
|
|
2509
|
+
* Get the duration of a motion after a release, so that the motion starts at the release velocity.
|
|
2510
|
+
*
|
|
2511
|
+
* @param {number} path The distance of the motion: target - location.
|
|
2512
|
+
* @param {number} velocity The release velocity, in px/ms.
|
|
2513
|
+
* @param {number[]} curve The easing of the motion.
|
|
2514
|
+
* @param {number} fallback The duration if the velocity is too low or in the other direction.
|
|
2515
|
+
* @returns {number}
|
|
2516
|
+
*/
|
|
2517
|
+
function releaseDuration(path, velocity, curve, fallback) {
|
|
2518
|
+
if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
|
|
2519
|
+
return fallback;
|
|
2520
|
+
}
|
|
2521
|
+
return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
/**
|
|
2525
|
+
* Get the velocity from the last samples of a drag.
|
|
2526
|
+
*
|
|
2527
|
+
* @param {Array<number[]>} samples [location, time] pairs, the oldest first. A drag always has one sample or more.
|
|
2528
|
+
* @returns {number} px/ms
|
|
2529
|
+
*/
|
|
2530
|
+
function velocity(samples) {
|
|
2531
|
+
const last = samples[samples.length - 1];
|
|
2532
|
+
|
|
2533
|
+
// The last sample is always in its own window, so find() always finds a sample
|
|
2534
|
+
const first = samples.find((sample) => last[1] - sample[1] <= 100),
|
|
2535
|
+
time = last[1] - first[1];
|
|
2536
|
+
|
|
2537
|
+
return time > 0 ? (last[0] - first[0]) / time : 0;
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
/**
|
|
2541
|
+
* Find the target of the motion after a drag.
|
|
2542
|
+
*
|
|
2543
|
+
* @param {object} args
|
|
2544
|
+
* @param {number} args.location The location at the release.
|
|
2545
|
+
* @param {number} args.from The location at the drag start.
|
|
2546
|
+
* @param {number} args.velocity The release velocity, in px/ms.
|
|
2547
|
+
* @param {number} args.current The selected snap at the drag start.
|
|
2548
|
+
* @param {Array<{location: number}>} args.snaps
|
|
2549
|
+
* @param {number} args.min
|
|
2550
|
+
* @param {number} args.max
|
|
2551
|
+
* @param {number} [args.period]
|
|
2552
|
+
* @param {boolean|number} [args.skipSnaps] true: go to the snap nearest to the projected location. A number: the same, but go at most this number of snaps.
|
|
2553
|
+
* false: go at most one snap.
|
|
2554
|
+
* @param {boolean|string} [args.dragFree]
|
|
2555
|
+
* @param {number} [args.dragFriction] The glide distance is divided by this number.
|
|
2556
|
+
* @returns {{location: number, snap: number}}
|
|
2557
|
+
*/
|
|
2558
|
+
function releaseTarget({ location, from, velocity, current, snaps, min, max, period, skipSnaps, dragFree, dragFriction = 1 }) {
|
|
2559
|
+
const count = snaps.length;
|
|
2560
|
+
|
|
2561
|
+
let projected = location + velocity * MOMENTUM / dragFriction;
|
|
2562
|
+
|
|
2563
|
+
if (!period) {
|
|
2564
|
+
projected = clamp(projected, min, max);
|
|
2565
|
+
}
|
|
2566
|
+
|
|
2567
|
+
// A number in skipSnaps: keep the projected location between the snaps that are skipSnaps snaps before and after the start snap
|
|
2568
|
+
if (typeof skipSnaps === 'number' && skipSnaps > 0 && skipSnaps < count - 1 + !period) {
|
|
2569
|
+
const limit = (direction) => targetLocation(snaps[snapIndex(current + direction * skipSnaps, count, period)].location, from, period, direction);
|
|
2570
|
+
projected = clamp(projected, limit(1), limit(-1));
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
if (dragFree === true) {
|
|
2574
|
+
return { location: projected, snap: nearestSnap(snaps, projected, period) };
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
if (dragFree || skipSnaps) {
|
|
2578
|
+
const snap = nearestSnap(snaps, projected, period);
|
|
2579
|
+
return { location: targetLocation(snaps[snap].location, projected, period), snap };
|
|
2580
|
+
}
|
|
2581
|
+
|
|
2582
|
+
const moved = location - from;
|
|
2583
|
+
|
|
2584
|
+
let direction = 0;
|
|
2585
|
+
|
|
2586
|
+
if (Math.abs(velocity) > 0.3) {
|
|
2587
|
+
direction = velocity < 0 ? 1 : -1;
|
|
2588
|
+
} else if (Math.abs(moved) > 20) {
|
|
2589
|
+
direction = moved < 0 ? 1 : -1;
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
const snap = snapIndex(current + direction, count, period),
|
|
2593
|
+
target = snaps[snap].location;
|
|
2594
|
+
|
|
2595
|
+
return {
|
|
2596
|
+
location: period ? targetLocation(target, direction ? from : location, period, snap === current ? 0 : direction) : target,
|
|
2597
|
+
snap
|
|
2598
|
+
};
|
|
2599
|
+
}
|
|
2600
|
+
|
|
2601
|
+
/**
|
|
2602
|
+
* Make the drag input of a carousel. The carousel follows the pointer. At the release, it goes to a snap, or with dragFree, it glides.
|
|
2603
|
+
*
|
|
2604
|
+
* @param {object} context What the features share. See carousel.js.
|
|
2605
|
+
* @returns {{remove: () => void}|undefined}
|
|
2606
|
+
*/
|
|
2607
|
+
function drag(context) {
|
|
2608
|
+
const { viewport, options } = context;
|
|
2609
|
+
|
|
2610
|
+
if (!options.drag) {
|
|
2611
|
+
return;
|
|
2612
|
+
}
|
|
2613
|
+
|
|
2614
|
+
let pointer = null,
|
|
2615
|
+
start,
|
|
2616
|
+
base,
|
|
2617
|
+
axis,
|
|
2618
|
+
block = false,
|
|
2619
|
+
samples = [],
|
|
2620
|
+
// The selected snap at the drag start
|
|
2621
|
+
snap = 0;
|
|
2622
|
+
|
|
2623
|
+
const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
|
|
2624
|
+
|
|
2625
|
+
function down(event) {
|
|
2626
|
+
block = false;
|
|
2627
|
+
|
|
2628
|
+
const geo = context.geo();
|
|
2629
|
+
|
|
2630
|
+
if (pointer !== null || event.button || !geo || geo.fit || event.target.closest(fields)) {
|
|
2631
|
+
return;
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
// Stop the text selection and the native image drag
|
|
2635
|
+
if (event.pointerType === 'mouse') {
|
|
2636
|
+
event.preventDefault();
|
|
2637
|
+
}
|
|
2638
|
+
|
|
2639
|
+
pointer = event.pointerId;
|
|
2640
|
+
axis = { x: geo.axis === 'x', sign: geo.sign };
|
|
2641
|
+
start = [event.clientX, event.clientY];
|
|
2642
|
+
samples = [];
|
|
2643
|
+
listen('addEventListener');
|
|
2644
|
+
}
|
|
2645
|
+
|
|
2646
|
+
function handle(event) {
|
|
2647
|
+
if (event.pointerId !== pointer) {
|
|
2648
|
+
return;
|
|
2649
|
+
}
|
|
2650
|
+
|
|
2651
|
+
if (event.type !== 'pointermove') {
|
|
2652
|
+
// A stop before the release gives a low velocity
|
|
2653
|
+
if (samples.length) {
|
|
2654
|
+
samples.push([samples[samples.length - 1][0], event.timeStamp]);
|
|
2655
|
+
}
|
|
2656
|
+
return end(event.type === 'pointerup');
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
const dx = event.clientX - start[0],
|
|
2660
|
+
dy = event.clientY - start[1],
|
|
2661
|
+
main = axis.x ? dx * axis.sign : dy,
|
|
2662
|
+
cross = axis.x ? dy : dx;
|
|
2663
|
+
|
|
2664
|
+
if (!context.dragging()) {
|
|
2665
|
+
// A touch move across the axis scrolls the page
|
|
2666
|
+
if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
|
|
2667
|
+
return end();
|
|
2668
|
+
}
|
|
2669
|
+
if (Math.abs(main) < options.dragThreshold) {
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
// Stop the motion, and start the drag at the location where the carousel is now
|
|
2673
|
+
base = context.halt();
|
|
2674
|
+
snap = context.selected();
|
|
2675
|
+
context.drag(true);
|
|
2676
|
+
// Capture only now: with capture, a link in a slide does not get the click
|
|
2677
|
+
viewport.setPointerCapture(pointer);
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
const geo = context.geo(),
|
|
2681
|
+
value = base + main,
|
|
2682
|
+
edge = clamp(value, geo.min, geo.max);
|
|
2683
|
+
|
|
2684
|
+
// Out of the limits, the carousel moves at a quarter of the pointer speed
|
|
2685
|
+
context.hold(geo.period ? value : edge + (value - edge) / 4, true);
|
|
2686
|
+
samples.push([main, event.timeStamp]);
|
|
2687
|
+
|
|
2688
|
+
if (samples.length > 10) {
|
|
2689
|
+
samples.shift();
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
/**
|
|
2694
|
+
* End the drag.
|
|
2695
|
+
*
|
|
2696
|
+
* @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
|
|
2697
|
+
*/
|
|
2698
|
+
function end(up) {
|
|
2699
|
+
listen('removeEventListener');
|
|
2700
|
+
pointer = null;
|
|
2701
|
+
|
|
2702
|
+
if (!context.dragging()) {
|
|
2703
|
+
return;
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
const geo = context.geo(),
|
|
2707
|
+
location = context.location(),
|
|
2708
|
+
speed = up ? velocity(samples) : 0,
|
|
2709
|
+
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 }),
|
|
2710
|
+
curve = options.dragFree === true ? GLIDE : EASE;
|
|
2711
|
+
|
|
2712
|
+
block = true;
|
|
2713
|
+
context.drag(false);
|
|
2714
|
+
context.move(target.snap, target.location, releaseDuration(target.location - location, speed, curve, options.duration), curve);
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
function click(event) {
|
|
2718
|
+
if (block) {
|
|
2719
|
+
block = false;
|
|
2720
|
+
event.preventDefault();
|
|
2721
|
+
event.stopPropagation();
|
|
2722
|
+
}
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
const prevent = (event) => event.preventDefault();
|
|
2726
|
+
|
|
2727
|
+
// Stop a text selection during a drag. A "user-select" rule on the dragging class does the same, but its change paints all layers of the carousel.
|
|
2728
|
+
const select = (event) => context.dragging() && event.preventDefault();
|
|
2729
|
+
|
|
2730
|
+
viewport.addEventListener('pointerdown', down);
|
|
2731
|
+
viewport.addEventListener('click', click, true);
|
|
2732
|
+
viewport.addEventListener('dragstart', prevent);
|
|
2733
|
+
viewport.addEventListener('selectstart', select);
|
|
2734
|
+
|
|
2735
|
+
return {
|
|
2736
|
+
remove() {
|
|
2737
|
+
listen('removeEventListener');
|
|
2738
|
+
viewport.removeEventListener('pointerdown', down);
|
|
2739
|
+
viewport.removeEventListener('click', click, true);
|
|
2740
|
+
viewport.removeEventListener('dragstart', prevent);
|
|
2741
|
+
viewport.removeEventListener('selectstart', select);
|
|
2742
|
+
}
|
|
2743
|
+
};
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
/**
|
|
2747
|
+
* Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
|
|
2748
|
+
* 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
|
|
2749
|
+
* location, the page scrolls.
|
|
2750
|
+
*
|
|
2751
|
+
* @param {object} context What the features share. See carousel.js.
|
|
2752
|
+
* @returns {{remove: () => void}|undefined}
|
|
2753
|
+
*/
|
|
2754
|
+
function wheel(context) {
|
|
2755
|
+
const { viewport, options } = context,
|
|
2756
|
+
// With dragFree: true, the carousel stays where the wheel stops
|
|
2757
|
+
free = options.dragFree === true;
|
|
2758
|
+
|
|
2759
|
+
if (!options.wheel) {
|
|
2760
|
+
return;
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
// The time of the last wheel event, and of the last event that moved the carousel
|
|
2764
|
+
let time = 0,
|
|
2765
|
+
moved = 0,
|
|
2766
|
+
// The timer that finds the end of a gesture
|
|
2767
|
+
timer = 0,
|
|
2768
|
+
// The selected snap at the gesture start, and the direction of the last step
|
|
2769
|
+
snap = 0,
|
|
2770
|
+
direction = 0;
|
|
2771
|
+
|
|
2772
|
+
function onWheel(event) {
|
|
2773
|
+
const geo = context.geo(),
|
|
2774
|
+
side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
|
|
2775
|
+
delta = side ? event.deltaX * geo.sign : event.deltaY;
|
|
2776
|
+
|
|
2777
|
+
if (event.ctrlKey || !delta || context.dragging()) {
|
|
2778
|
+
return;
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
const now = event.timeStamp,
|
|
2782
|
+
gesture = now - time < 200,
|
|
2783
|
+
base = context.location(),
|
|
2784
|
+
path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
|
|
2785
|
+
|
|
2786
|
+
let target = base - path;
|
|
2787
|
+
if (!geo.period) {
|
|
2788
|
+
target = clamp(target, geo.min, geo.max);
|
|
2789
|
+
}
|
|
2790
|
+
|
|
2791
|
+
time = now;
|
|
2792
|
+
|
|
2793
|
+
// At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
|
|
2794
|
+
if (Math.abs(target - base) < 0.5) {
|
|
2795
|
+
if (gesture && now - moved < 1000) {
|
|
2796
|
+
event.preventDefault();
|
|
2797
|
+
}
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
event.preventDefault();
|
|
2802
|
+
context.emit('interact');
|
|
2803
|
+
|
|
2804
|
+
if (!timer) {
|
|
2805
|
+
snap = context.selected();
|
|
2806
|
+
}
|
|
2807
|
+
moved = now;
|
|
2808
|
+
direction = path > 0 ? 1 : -1;
|
|
2809
|
+
context.move(nearestSnap(geo.snaps, target, geo.period), target, WHEEL, EASE);
|
|
2810
|
+
|
|
2811
|
+
clearTimeout(timer);
|
|
2812
|
+
if (!free) {
|
|
2813
|
+
timer = setTimeout(end, 150);
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
// Go to a snap when the wheel stops. A short wheel motion goes to the next snap in its direction, so that one wheel step always changes the slide.
|
|
2818
|
+
function end() {
|
|
2819
|
+
timer = 0;
|
|
2820
|
+
const geo = context.geo(),
|
|
2821
|
+
at = context.current(),
|
|
2822
|
+
index = nearestSnap(geo.snaps, at, geo.period),
|
|
2823
|
+
away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
|
|
2824
|
+
|
|
2825
|
+
context.step(index, index === snap && away ? direction : 0);
|
|
2826
|
+
}
|
|
2827
|
+
|
|
2828
|
+
// A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
|
|
2829
|
+
// Add it only where the wheel moves the carousel.
|
|
2830
|
+
function listen() {
|
|
2831
|
+
const geo = context.geo();
|
|
2832
|
+
viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
|
|
2836
|
+
|
|
2837
|
+
return {
|
|
2838
|
+
remove() {
|
|
2839
|
+
viewport.removeEventListener('wheel', onWheel);
|
|
2840
|
+
clearTimeout(timer);
|
|
2841
|
+
}
|
|
2842
|
+
};
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
/**
|
|
2846
|
+
* Make the arrow keys move the carousel while the keyboard focus is in its root: left and right in a horizontal carousel, up and down
|
|
2847
|
+
* in a vertical carousel. In a right-to-left carousel, the left arrow goes to the next slide. A key in a form field does not move the carousel.
|
|
2848
|
+
*
|
|
2849
|
+
* @param {object} context What the features share. See carousel.js.
|
|
2850
|
+
* @returns {{remove: () => void}|undefined}
|
|
2851
|
+
*/
|
|
2852
|
+
function keys(context) {
|
|
2853
|
+
const { api, root, options } = context;
|
|
2854
|
+
|
|
2855
|
+
if (!options.keys) {
|
|
2856
|
+
return;
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
function onKey(event) {
|
|
2860
|
+
const geo = context.geo(),
|
|
2861
|
+
{ key, target } = event,
|
|
2862
|
+
// -1 for the previous slide, 1 for the next slide. A right-to-left carousel has the next slide at the left.
|
|
2863
|
+
direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
|
|
2864
|
+
name = direction > 0 ? 'Next' : 'Prev';
|
|
2865
|
+
// At the first and the last slide, the key scrolls the page
|
|
2866
|
+
if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) && api['canGoTo' + name]()) {
|
|
2867
|
+
event.preventDefault();
|
|
2868
|
+
api['goTo' + name]();
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
root.addEventListener('keydown', onKey);
|
|
2873
|
+
|
|
2874
|
+
return {
|
|
2875
|
+
remove() {
|
|
2876
|
+
root.removeEventListener('keydown', onKey);
|
|
2877
|
+
}
|
|
2878
|
+
};
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
/**
|
|
2882
|
+
* Go to a slide that gets the keyboard focus, if it does not show fully. A focus soon after a pointer press does not move the carousel.
|
|
2883
|
+
*
|
|
2884
|
+
* @param {object} context What the features share. See carousel.js.
|
|
2885
|
+
* @returns {{remove: () => void}}
|
|
2886
|
+
*/
|
|
2887
|
+
function focus(context) {
|
|
2888
|
+
const { api, container, options } = context;
|
|
2889
|
+
|
|
2890
|
+
// The time of the last pointer press
|
|
2891
|
+
let pressed = -1e4;
|
|
2892
|
+
|
|
2893
|
+
function press(event) {
|
|
2894
|
+
if (!event.target.closest(fields)) {
|
|
2895
|
+
pressed = event.timeStamp;
|
|
2896
|
+
}
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
function onFocus(event) {
|
|
2900
|
+
const geo = context.geo(),
|
|
2901
|
+
index = api.slideNodes().findIndex((node) => node.contains(event.target));
|
|
2902
|
+
|
|
2903
|
+
if (!geo || index < 0 || event.timeStamp - pressed < 600) {
|
|
2904
|
+
return;
|
|
2905
|
+
}
|
|
2906
|
+
if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
|
|
2907
|
+
api.goToSlide(index);
|
|
2908
|
+
}
|
|
2909
|
+
context.emit('slidefocus');
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
container.addEventListener('pointerdown', press);
|
|
2913
|
+
container.addEventListener('focusin', onFocus);
|
|
2914
|
+
|
|
2915
|
+
return {
|
|
2916
|
+
remove() {
|
|
2917
|
+
container.removeEventListener('pointerdown', press);
|
|
2918
|
+
container.removeEventListener('focusin', onFocus);
|
|
2919
|
+
}
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
/*
|
|
2924
|
+
* Navigation: the arrows, the dots, and the link to another carousel (the sync option).
|
|
2925
|
+
*
|
|
2926
|
+
* Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
|
|
2927
|
+
*/
|
|
2928
|
+
|
|
2929
|
+
|
|
2930
|
+
/**
|
|
2931
|
+
* Make the arrows and the dots of a carousel. They update on the carousel events.
|
|
2932
|
+
*
|
|
2933
|
+
* @param {object} context What the features share. See carousel.js.
|
|
2934
|
+
* @returns {{remove: () => void}|undefined} remove() removes the arrows and the dots.
|
|
2935
|
+
*/
|
|
2936
|
+
function nav(context) {
|
|
2937
|
+
const { api, root, cls, options } = context,
|
|
2938
|
+
labels = options.labels,
|
|
2939
|
+
arrows = optionElement(options.arrows, root),
|
|
2940
|
+
box = optionElement(options.dots, root),
|
|
2941
|
+
buttons = [],
|
|
2942
|
+
dots = [],
|
|
2943
|
+
// The window of 5 dots, or all dots with dotsStyle: 'all'
|
|
2944
|
+
windowed = options.dotsStyle !== 'all',
|
|
2945
|
+
// The window of the dots, the track that slides in it, and the marker of the selected dot
|
|
2946
|
+
list = box && create('div', windowed ? cls.dots : cls.dots + ' ' + cls.dotsAll),
|
|
2947
|
+
track = list && create('div', cls.dotsTrack);
|
|
2948
|
+
|
|
2949
|
+
let marks = new Map();
|
|
2950
|
+
|
|
2951
|
+
if (!arrows && !box) {
|
|
2952
|
+
return;
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
// Add the window of the dots now: its CSS height is fixed, so the dots that the first measure adds do not shift the page
|
|
2956
|
+
if (list) {
|
|
2957
|
+
track.append(create('span', cls.dotsMarker));
|
|
2958
|
+
list.append(track);
|
|
2959
|
+
box.append(list);
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
if (arrows) {
|
|
2963
|
+
[['prev', 'goToPrev'], ['next', 'goToNext']].forEach(([key, method]) => {
|
|
2964
|
+
const button = create('button', cls.button + ' ' + cls[key + 'Button']);
|
|
2965
|
+
button.type = 'button';
|
|
2966
|
+
button.setAttribute('aria-label', labels[key]);
|
|
2967
|
+
button.setAttribute('aria-controls', context.container.id);
|
|
2968
|
+
button.addEventListener('click', () => api[method]());
|
|
2969
|
+
buttons.push(button);
|
|
2970
|
+
});
|
|
2971
|
+
}
|
|
2972
|
+
|
|
2973
|
+
function update() {
|
|
2974
|
+
const fit = api.isFit(),
|
|
2975
|
+
count = fit ? 0 : api.snapProgress().length,
|
|
2976
|
+
selected = api.selectedSnap();
|
|
2977
|
+
|
|
2978
|
+
buttons.forEach((button, index) => {
|
|
2979
|
+
if (fit) {
|
|
2980
|
+
button.remove();
|
|
2981
|
+
} else {
|
|
2982
|
+
if (!button.isConnected) {
|
|
2983
|
+
// Before the dots, for the tab order
|
|
2984
|
+
list?.parentNode === arrows ? list.before(button) : arrows.append(button);
|
|
2985
|
+
}
|
|
2986
|
+
const disabled = !(index ? api.canGoToNext() : api.canGoToPrev());
|
|
2987
|
+
if (button.disabled !== disabled) {
|
|
2988
|
+
button.disabled = disabled;
|
|
2989
|
+
}
|
|
2990
|
+
}
|
|
2991
|
+
});
|
|
2992
|
+
|
|
2993
|
+
if (!list) {
|
|
2994
|
+
return;
|
|
2995
|
+
}
|
|
2996
|
+
|
|
2997
|
+
if (count < 2) {
|
|
2998
|
+
list.remove();
|
|
2999
|
+
return;
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
while (dots.length > count) {
|
|
3003
|
+
dots.pop().remove();
|
|
3004
|
+
marks.delete(dots.length);
|
|
3005
|
+
}
|
|
3006
|
+
|
|
3007
|
+
while (dots.length < count) {
|
|
3008
|
+
const dot = create('button', cls.dot),
|
|
3009
|
+
index = dots.length;
|
|
3010
|
+
dot.type = 'button';
|
|
3011
|
+
dot.setAttribute('aria-label', labels.dot.replace('%d', index + 1));
|
|
3012
|
+
dot.setAttribute('aria-controls', context.container.id);
|
|
3013
|
+
// The window of the dots hides the dots out of the zoom: keep them out of the tab order
|
|
3014
|
+
if (windowed) {
|
|
3015
|
+
dot.tabIndex = -1;
|
|
3016
|
+
}
|
|
3017
|
+
dot.addEventListener('click', () => api.goToSnap(index));
|
|
3018
|
+
dots.push(dot);
|
|
3019
|
+
track.append(dot);
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
if (!list.isConnected) {
|
|
3023
|
+
box.append(list);
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
// The zoom effect: the 5 dots around the selected dot get state classes
|
|
3027
|
+
const next = new Map();
|
|
3028
|
+
|
|
3029
|
+
['first', 'prev', 'current', 'next', 'last'].forEach((key, offset) => {
|
|
3030
|
+
if (dots[selected + offset - 2]) {
|
|
3031
|
+
next.set(selected + offset - 2, cls[key]);
|
|
3032
|
+
}
|
|
3033
|
+
});
|
|
3034
|
+
|
|
3035
|
+
marks.forEach((name, index) => {
|
|
3036
|
+
if (next.get(index) !== name) {
|
|
3037
|
+
setClass(dots[index], name, false);
|
|
3038
|
+
setAttribute(dots[index], 'aria-current', false);
|
|
3039
|
+
dots[index].tabIndex = windowed ? -1 : 0;
|
|
3040
|
+
}
|
|
3041
|
+
});
|
|
3042
|
+
|
|
3043
|
+
next.forEach((name, index) => {
|
|
3044
|
+
setClass(dots[index], name, true);
|
|
3045
|
+
setAttribute(dots[index], 'aria-current', index === selected && 'true');
|
|
3046
|
+
dots[index].tabIndex = 0;
|
|
3047
|
+
});
|
|
3048
|
+
|
|
3049
|
+
marks = next;
|
|
3050
|
+
|
|
3051
|
+
// Center the group of up to 5 dots in the window of the dots, and move the marker to the selected dot. The CSS moves the track and the marker with "translate".
|
|
3052
|
+
if (windowed) {
|
|
3053
|
+
variable('--better-shift', 2 - (Math.max(0, selected - 2) + Math.min(count - 1, selected + 2)) / 2);
|
|
3054
|
+
}
|
|
3055
|
+
variable('--better-dot', selected);
|
|
3056
|
+
}
|
|
3057
|
+
|
|
3058
|
+
// Set a CSS variable on the window of the dots, if its value changes
|
|
3059
|
+
function variable(name, value) {
|
|
3060
|
+
if (list.style.getPropertyValue(name) !== String(value)) {
|
|
3061
|
+
list.style.setProperty(name, value);
|
|
3062
|
+
}
|
|
3063
|
+
}
|
|
3064
|
+
|
|
3065
|
+
['init', 'reinit', 'resize', 'select', 'slideschanged'].forEach((name) => context.on(name, update));
|
|
3066
|
+
|
|
3067
|
+
return {
|
|
3068
|
+
remove() {
|
|
3069
|
+
buttons.forEach((button) => button.remove());
|
|
3070
|
+
list?.remove();
|
|
3071
|
+
}
|
|
3072
|
+
};
|
|
3073
|
+
}
|
|
3074
|
+
|
|
3075
|
+
/**
|
|
3076
|
+
* Connect a carousel to another carousel with the same slides, such as thumbnails to a main gallery. This carousel follows the slide
|
|
3077
|
+
* that the other carousel selects. Only a click on a slide of this carousel selects that slide in the other carousel: a drag does not.
|
|
3078
|
+
*
|
|
3079
|
+
* @param {object} context What the features share. See carousel.js. The "sync" option is the other carousel, its container or a selector.
|
|
3080
|
+
* @returns {{remove: () => void}|undefined} remove() disconnects the carousels.
|
|
3081
|
+
*/
|
|
3082
|
+
function sync(context) {
|
|
3083
|
+
const { api, container } = context,
|
|
3084
|
+
target = context.options.sync;
|
|
3085
|
+
|
|
3086
|
+
let other = null;
|
|
3087
|
+
|
|
3088
|
+
if (!target) {
|
|
3089
|
+
return;
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
// Show the slide that the other carousel selects
|
|
3093
|
+
function show(instant) {
|
|
3094
|
+
const index = other.selectedSlide();
|
|
3095
|
+
context.follow(index);
|
|
3096
|
+
api.goToSlide(index, instant === true);
|
|
3097
|
+
}
|
|
3098
|
+
|
|
3099
|
+
function click(event) {
|
|
3100
|
+
// The slide or the clone that gets the click, and then its original slide
|
|
3101
|
+
const index = context.nodes().findIndex((node) => node.contains(event.target));
|
|
3102
|
+
if (other && index > -1) {
|
|
3103
|
+
other.goToSlide(index % api.slideNodes().length);
|
|
3104
|
+
}
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
// The other carousel can come later than this one, so find it at the init
|
|
3108
|
+
function connect() {
|
|
3109
|
+
if (other) {
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
other = target.goToSnap ? target : find(typeof target === 'string' ? optionElement(target, context.root) : target);
|
|
3113
|
+
if (other) {
|
|
3114
|
+
other.on('select', show);
|
|
3115
|
+
show(true);
|
|
3116
|
+
}
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
context.on('init', connect);
|
|
3120
|
+
context.on('reinit', connect);
|
|
3121
|
+
container.addEventListener('click', click);
|
|
3122
|
+
|
|
3123
|
+
return {
|
|
3124
|
+
remove() {
|
|
3125
|
+
other?.off('select', show);
|
|
3126
|
+
container.removeEventListener('click', click);
|
|
3127
|
+
}
|
|
3128
|
+
};
|
|
3129
|
+
}
|
|
3130
|
+
|
|
3131
|
+
/*
|
|
3132
|
+
* Entry point: the BetterCarousel function, its features, and its static members defaults, get() and initAll().
|
|
3133
|
+
*/
|
|
3134
|
+
|
|
3135
|
+
|
|
3136
|
+
// The features. Their event handlers run in this order.
|
|
3137
|
+
const features = [drag, wheel, keys, focus, nav, autoplay, autoScroll, sync];
|
|
3138
|
+
|
|
3139
|
+
/**
|
|
3140
|
+
* Make a carousel, or get the carousel of an element that has one.
|
|
3141
|
+
*
|
|
3142
|
+
* @param {HTMLElement} element The container of the slides, or its viewport.
|
|
3143
|
+
* @param {object} [options]
|
|
3144
|
+
* @returns {object} The carousel API.
|
|
3145
|
+
*/
|
|
3146
|
+
function BetterCarousel(element, options = {}) {
|
|
3147
|
+
return carousel(element, options, BetterCarousel.defaults, features);
|
|
3148
|
+
}
|
|
3149
|
+
|
|
3150
|
+
// The site defaults. They merge over the library defaults.
|
|
3151
|
+
BetterCarousel.defaults = {};
|
|
3152
|
+
|
|
3153
|
+
/**
|
|
3154
|
+
* Get the instance of a root, a viewport or a container.
|
|
3155
|
+
*
|
|
3156
|
+
* @param {Element} element
|
|
3157
|
+
* @returns {object|undefined}
|
|
3158
|
+
*/
|
|
3159
|
+
BetterCarousel.get = find;
|
|
3160
|
+
|
|
3161
|
+
/**
|
|
3162
|
+
* Make a carousel for each element that matches a selector and has no carousel.
|
|
3163
|
+
*
|
|
3164
|
+
* @param {string} selector
|
|
3165
|
+
* @param {object} [options]
|
|
3166
|
+
* @returns {object[]}
|
|
3167
|
+
*/
|
|
3168
|
+
BetterCarousel.initAll = (selector, options) => {
|
|
3169
|
+
const elements = [...document.querySelectorAll(selector)];
|
|
3170
|
+
// Read the boxes of the lazy carousels before the first setup() writes. Then the reads cause one layout, not one for each carousel.
|
|
3171
|
+
readBoxes(elements.filter((element) => !find(element) && resolve(element, BetterCarousel.defaults, options).lazy));
|
|
3172
|
+
return elements.map((element) => BetterCarousel(element, options));
|
|
3173
|
+
};
|
|
3174
|
+
|
|
3175
|
+
export { BetterCarousel as default };
|