@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,432 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Input: the pointer drag, the mouse wheel, the arrow keys, the keyboard focus, and the target of the motion after a drag.
|
|
3
|
+
*
|
|
4
|
+
* Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { clamp, inView, nearestSnap, snapIndex, targetLocation } from './geometry.js';
|
|
8
|
+
import { EASE, GLIDE } from './motion.js';
|
|
9
|
+
|
|
10
|
+
// The targets that keep their own pointer behavior
|
|
11
|
+
const fields = 'input,textarea,select,[contenteditable]';
|
|
12
|
+
|
|
13
|
+
// The duration of the motion for one wheel event, in ms
|
|
14
|
+
const WHEEL = 180;
|
|
15
|
+
|
|
16
|
+
// The time constant of the glide, in ms: the glide distance is velocity * MOMENTUM
|
|
17
|
+
const MOMENTUM = 325;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Get the duration of a motion after a release, so that the motion starts at the release velocity.
|
|
21
|
+
*
|
|
22
|
+
* @param {number} path The distance of the motion: target - location.
|
|
23
|
+
* @param {number} velocity The release velocity, in px/ms.
|
|
24
|
+
* @param {number[]} curve The easing of the motion.
|
|
25
|
+
* @param {number} fallback The duration if the velocity is too low or in the other direction.
|
|
26
|
+
* @returns {number}
|
|
27
|
+
*/
|
|
28
|
+
export function releaseDuration(path, velocity, curve, fallback) {
|
|
29
|
+
if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
|
|
30
|
+
return fallback;
|
|
31
|
+
}
|
|
32
|
+
return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Get the velocity from the last samples of a drag.
|
|
37
|
+
*
|
|
38
|
+
* @param {Array<number[]>} samples [location, time] pairs, the oldest first. A drag always has one sample or more.
|
|
39
|
+
* @returns {number} px/ms
|
|
40
|
+
*/
|
|
41
|
+
export function velocity(samples) {
|
|
42
|
+
const last = samples[samples.length - 1];
|
|
43
|
+
|
|
44
|
+
// The last sample is always in its own window, so find() always finds a sample
|
|
45
|
+
const first = samples.find((sample) => last[1] - sample[1] <= 100),
|
|
46
|
+
time = last[1] - first[1];
|
|
47
|
+
|
|
48
|
+
return time > 0 ? (last[0] - first[0]) / time : 0;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Find the target of the motion after a drag.
|
|
53
|
+
*
|
|
54
|
+
* @param {object} args
|
|
55
|
+
* @param {number} args.location The location at the release.
|
|
56
|
+
* @param {number} args.from The location at the drag start.
|
|
57
|
+
* @param {number} args.velocity The release velocity, in px/ms.
|
|
58
|
+
* @param {number} args.current The selected snap at the drag start.
|
|
59
|
+
* @param {Array<{location: number}>} args.snaps
|
|
60
|
+
* @param {number} args.min
|
|
61
|
+
* @param {number} args.max
|
|
62
|
+
* @param {number} [args.period]
|
|
63
|
+
* @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.
|
|
64
|
+
* false: go at most one snap.
|
|
65
|
+
* @param {boolean|string} [args.dragFree]
|
|
66
|
+
* @param {number} [args.dragFriction] The glide distance is divided by this number.
|
|
67
|
+
* @returns {{location: number, snap: number}}
|
|
68
|
+
*/
|
|
69
|
+
export function releaseTarget({ location, from, velocity, current, snaps, min, max, period, skipSnaps, dragFree, dragFriction = 1 }) {
|
|
70
|
+
const count = snaps.length;
|
|
71
|
+
|
|
72
|
+
let projected = location + velocity * MOMENTUM / dragFriction;
|
|
73
|
+
|
|
74
|
+
if (!period) {
|
|
75
|
+
projected = clamp(projected, min, max);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A number in skipSnaps: keep the projected location between the snaps that are skipSnaps snaps before and after the start snap
|
|
79
|
+
if (typeof skipSnaps === 'number' && skipSnaps > 0 && skipSnaps < count - 1 + !period) {
|
|
80
|
+
const limit = (direction) => targetLocation(snaps[snapIndex(current + direction * skipSnaps, count, period)].location, from, period, direction);
|
|
81
|
+
projected = clamp(projected, limit(1), limit(-1));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (dragFree === true) {
|
|
85
|
+
return { location: projected, snap: nearestSnap(snaps, projected, period) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (dragFree || skipSnaps) {
|
|
89
|
+
const snap = nearestSnap(snaps, projected, period);
|
|
90
|
+
return { location: targetLocation(snaps[snap].location, projected, period), snap };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const moved = location - from;
|
|
94
|
+
|
|
95
|
+
let direction = 0;
|
|
96
|
+
|
|
97
|
+
if (Math.abs(velocity) > 0.3) {
|
|
98
|
+
direction = velocity < 0 ? 1 : -1;
|
|
99
|
+
} else if (Math.abs(moved) > 20) {
|
|
100
|
+
direction = moved < 0 ? 1 : -1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const snap = snapIndex(current + direction, count, period),
|
|
104
|
+
target = snaps[snap].location;
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
location: period ? targetLocation(target, direction ? from : location, period, snap === current ? 0 : direction) : target,
|
|
108
|
+
snap
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 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.
|
|
114
|
+
*
|
|
115
|
+
* @param {object} context What the features share. See carousel.js.
|
|
116
|
+
* @returns {{remove: () => void}|undefined}
|
|
117
|
+
*/
|
|
118
|
+
export function drag(context) {
|
|
119
|
+
const { viewport, options } = context;
|
|
120
|
+
|
|
121
|
+
if (!options.drag) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let pointer = null,
|
|
126
|
+
start,
|
|
127
|
+
base,
|
|
128
|
+
axis,
|
|
129
|
+
block = false,
|
|
130
|
+
samples = [],
|
|
131
|
+
// The selected snap at the drag start
|
|
132
|
+
snap = 0;
|
|
133
|
+
|
|
134
|
+
const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
|
|
135
|
+
|
|
136
|
+
function down(event) {
|
|
137
|
+
block = false;
|
|
138
|
+
|
|
139
|
+
const geo = context.geo();
|
|
140
|
+
|
|
141
|
+
if (pointer !== null || event.button || !geo || geo.fit || event.target.closest(fields)) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Stop the text selection and the native image drag
|
|
146
|
+
if (event.pointerType === 'mouse') {
|
|
147
|
+
event.preventDefault();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
pointer = event.pointerId;
|
|
151
|
+
axis = { x: geo.axis === 'x', sign: geo.sign };
|
|
152
|
+
start = [event.clientX, event.clientY];
|
|
153
|
+
samples = [];
|
|
154
|
+
listen('addEventListener');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function handle(event) {
|
|
158
|
+
if (event.pointerId !== pointer) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (event.type !== 'pointermove') {
|
|
163
|
+
// A stop before the release gives a low velocity
|
|
164
|
+
if (samples.length) {
|
|
165
|
+
samples.push([samples[samples.length - 1][0], event.timeStamp]);
|
|
166
|
+
}
|
|
167
|
+
return end(event.type === 'pointerup');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const dx = event.clientX - start[0],
|
|
171
|
+
dy = event.clientY - start[1],
|
|
172
|
+
main = axis.x ? dx * axis.sign : dy,
|
|
173
|
+
cross = axis.x ? dy : dx;
|
|
174
|
+
|
|
175
|
+
if (!context.dragging()) {
|
|
176
|
+
// A touch move across the axis scrolls the page
|
|
177
|
+
if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
|
|
178
|
+
return end();
|
|
179
|
+
}
|
|
180
|
+
if (Math.abs(main) < options.dragThreshold) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
// Stop the motion, and start the drag at the location where the carousel is now
|
|
184
|
+
base = context.halt();
|
|
185
|
+
snap = context.selected();
|
|
186
|
+
context.drag(true);
|
|
187
|
+
// Capture only now: with capture, a link in a slide does not get the click
|
|
188
|
+
viewport.setPointerCapture(pointer);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const geo = context.geo(),
|
|
192
|
+
value = base + main,
|
|
193
|
+
edge = clamp(value, geo.min, geo.max);
|
|
194
|
+
|
|
195
|
+
// Out of the limits, the carousel moves at a quarter of the pointer speed
|
|
196
|
+
context.hold(geo.period ? value : edge + (value - edge) / 4, true);
|
|
197
|
+
samples.push([main, event.timeStamp]);
|
|
198
|
+
|
|
199
|
+
if (samples.length > 10) {
|
|
200
|
+
samples.shift();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* End the drag.
|
|
206
|
+
*
|
|
207
|
+
* @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
|
|
208
|
+
*/
|
|
209
|
+
function end(up) {
|
|
210
|
+
listen('removeEventListener');
|
|
211
|
+
pointer = null;
|
|
212
|
+
|
|
213
|
+
if (!context.dragging()) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const geo = context.geo(),
|
|
218
|
+
location = context.location(),
|
|
219
|
+
speed = up ? velocity(samples) : 0,
|
|
220
|
+
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 }),
|
|
221
|
+
curve = options.dragFree === true ? GLIDE : EASE;
|
|
222
|
+
|
|
223
|
+
block = true;
|
|
224
|
+
context.drag(false);
|
|
225
|
+
context.move(target.snap, target.location, releaseDuration(target.location - location, speed, curve, options.duration), curve);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function click(event) {
|
|
229
|
+
if (block) {
|
|
230
|
+
block = false;
|
|
231
|
+
event.preventDefault();
|
|
232
|
+
event.stopPropagation();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const prevent = (event) => event.preventDefault();
|
|
237
|
+
|
|
238
|
+
// 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.
|
|
239
|
+
const select = (event) => context.dragging() && event.preventDefault();
|
|
240
|
+
|
|
241
|
+
viewport.addEventListener('pointerdown', down);
|
|
242
|
+
viewport.addEventListener('click', click, true);
|
|
243
|
+
viewport.addEventListener('dragstart', prevent);
|
|
244
|
+
viewport.addEventListener('selectstart', select);
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
remove() {
|
|
248
|
+
listen('removeEventListener');
|
|
249
|
+
viewport.removeEventListener('pointerdown', down);
|
|
250
|
+
viewport.removeEventListener('click', click, true);
|
|
251
|
+
viewport.removeEventListener('dragstart', prevent);
|
|
252
|
+
viewport.removeEventListener('selectstart', select);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
|
|
259
|
+
* 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
|
|
260
|
+
* location, the page scrolls.
|
|
261
|
+
*
|
|
262
|
+
* @param {object} context What the features share. See carousel.js.
|
|
263
|
+
* @returns {{remove: () => void}|undefined}
|
|
264
|
+
*/
|
|
265
|
+
export function wheel(context) {
|
|
266
|
+
const { viewport, options } = context,
|
|
267
|
+
// With dragFree: true, the carousel stays where the wheel stops
|
|
268
|
+
free = options.dragFree === true;
|
|
269
|
+
|
|
270
|
+
if (!options.wheel) {
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// The time of the last wheel event, and of the last event that moved the carousel
|
|
275
|
+
let time = 0,
|
|
276
|
+
moved = 0,
|
|
277
|
+
// The timer that finds the end of a gesture
|
|
278
|
+
timer = 0,
|
|
279
|
+
// The selected snap at the gesture start, and the direction of the last step
|
|
280
|
+
snap = 0,
|
|
281
|
+
direction = 0;
|
|
282
|
+
|
|
283
|
+
function onWheel(event) {
|
|
284
|
+
const geo = context.geo(),
|
|
285
|
+
side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
|
|
286
|
+
delta = side ? event.deltaX * geo.sign : event.deltaY;
|
|
287
|
+
|
|
288
|
+
if (event.ctrlKey || !delta || context.dragging()) {
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const now = event.timeStamp,
|
|
293
|
+
gesture = now - time < 200,
|
|
294
|
+
base = context.location(),
|
|
295
|
+
path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
|
|
296
|
+
|
|
297
|
+
let target = base - path;
|
|
298
|
+
if (!geo.period) {
|
|
299
|
+
target = clamp(target, geo.min, geo.max);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
time = now;
|
|
303
|
+
|
|
304
|
+
// At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
|
|
305
|
+
if (Math.abs(target - base) < 0.5) {
|
|
306
|
+
if (gesture && now - moved < 1000) {
|
|
307
|
+
event.preventDefault();
|
|
308
|
+
}
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
event.preventDefault();
|
|
313
|
+
context.emit('interact');
|
|
314
|
+
|
|
315
|
+
if (!timer) {
|
|
316
|
+
snap = context.selected();
|
|
317
|
+
}
|
|
318
|
+
moved = now;
|
|
319
|
+
direction = path > 0 ? 1 : -1;
|
|
320
|
+
context.move(nearestSnap(geo.snaps, target, geo.period), target, WHEEL, EASE);
|
|
321
|
+
|
|
322
|
+
clearTimeout(timer);
|
|
323
|
+
if (!free) {
|
|
324
|
+
timer = setTimeout(end, 150);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// 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.
|
|
329
|
+
function end() {
|
|
330
|
+
timer = 0;
|
|
331
|
+
const geo = context.geo(),
|
|
332
|
+
at = context.current(),
|
|
333
|
+
index = nearestSnap(geo.snaps, at, geo.period),
|
|
334
|
+
away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
|
|
335
|
+
|
|
336
|
+
context.step(index, index === snap && away ? direction : 0);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
|
|
340
|
+
// Add it only where the wheel moves the carousel.
|
|
341
|
+
function listen() {
|
|
342
|
+
const geo = context.geo();
|
|
343
|
+
viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
remove() {
|
|
350
|
+
viewport.removeEventListener('wheel', onWheel);
|
|
351
|
+
clearTimeout(timer);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 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
|
|
358
|
+
* 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.
|
|
359
|
+
*
|
|
360
|
+
* @param {object} context What the features share. See carousel.js.
|
|
361
|
+
* @returns {{remove: () => void}|undefined}
|
|
362
|
+
*/
|
|
363
|
+
export function keys(context) {
|
|
364
|
+
const { api, root, options } = context;
|
|
365
|
+
|
|
366
|
+
if (!options.keys) {
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function onKey(event) {
|
|
371
|
+
const geo = context.geo(),
|
|
372
|
+
{ key, target } = event,
|
|
373
|
+
// -1 for the previous slide, 1 for the next slide. A right-to-left carousel has the next slide at the left.
|
|
374
|
+
direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
|
|
375
|
+
name = direction > 0 ? 'Next' : 'Prev';
|
|
376
|
+
// At the first and the last slide, the key scrolls the page
|
|
377
|
+
if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) && api['canGoTo' + name]()) {
|
|
378
|
+
event.preventDefault();
|
|
379
|
+
api['goTo' + name]();
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
root.addEventListener('keydown', onKey);
|
|
384
|
+
|
|
385
|
+
return {
|
|
386
|
+
remove() {
|
|
387
|
+
root.removeEventListener('keydown', onKey);
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* 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.
|
|
394
|
+
*
|
|
395
|
+
* @param {object} context What the features share. See carousel.js.
|
|
396
|
+
* @returns {{remove: () => void}}
|
|
397
|
+
*/
|
|
398
|
+
export function focus(context) {
|
|
399
|
+
const { api, container, options } = context;
|
|
400
|
+
|
|
401
|
+
// The time of the last pointer press
|
|
402
|
+
let pressed = -1e4;
|
|
403
|
+
|
|
404
|
+
function press(event) {
|
|
405
|
+
if (!event.target.closest(fields)) {
|
|
406
|
+
pressed = event.timeStamp;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function onFocus(event) {
|
|
411
|
+
const geo = context.geo(),
|
|
412
|
+
index = api.slideNodes().findIndex((node) => node.contains(event.target));
|
|
413
|
+
|
|
414
|
+
if (!geo || index < 0 || event.timeStamp - pressed < 600) {
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
|
|
418
|
+
api.goToSlide(index);
|
|
419
|
+
}
|
|
420
|
+
context.emit('slidefocus');
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
container.addEventListener('pointerdown', press);
|
|
424
|
+
container.addEventListener('focusin', onFocus);
|
|
425
|
+
|
|
426
|
+
return {
|
|
427
|
+
remove() {
|
|
428
|
+
container.removeEventListener('pointerdown', press);
|
|
429
|
+
container.removeEventListener('focusin', onFocus);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Layout: the layout reads, and the observers that all carousels share.
|
|
3
|
+
*
|
|
4
|
+
* The reads run in the ResizeObserver callback, when the layout is clean.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Read the axis, the alignment, the direction and the gap from the computed style of the container.
|
|
9
|
+
*
|
|
10
|
+
* @param {HTMLElement} container
|
|
11
|
+
* @param {object} options
|
|
12
|
+
* @returns {{axis: string, align: string|Function, rtl: boolean, sign: number, gap: number}} sign is -1 for a right-to-left carousel, else 1.
|
|
13
|
+
*/
|
|
14
|
+
export function readLayout(container, options) {
|
|
15
|
+
const style = getComputedStyle(container),
|
|
16
|
+
display = style.display,
|
|
17
|
+
content = style.justifyContent;
|
|
18
|
+
|
|
19
|
+
let axis = options.axis;
|
|
20
|
+
|
|
21
|
+
if (axis === 'auto') {
|
|
22
|
+
axis = 'x';
|
|
23
|
+
if (display.includes('grid')) {
|
|
24
|
+
axis = style.gridAutoFlow.startsWith('column') ? 'x' : 'y';
|
|
25
|
+
} else if (display.includes('flex') && style.flexDirection.startsWith('column') && style.flexWrap === 'nowrap') {
|
|
26
|
+
axis = 'y';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let align = options.align;
|
|
31
|
+
|
|
32
|
+
if (align === 'auto') {
|
|
33
|
+
align = content === 'center' ? 'center' : content === 'flex-end' || content === 'end' || (axis === 'x' && content === 'right') ? 'end' : 'start';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const rtl = axis === 'x' && (options.dir === 'auto' ? style.direction === 'rtl' : options.dir === 'rtl');
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
axis,
|
|
40
|
+
align,
|
|
41
|
+
rtl,
|
|
42
|
+
sign: rtl ? -1 : 1,
|
|
43
|
+
gap: parseFloat(axis === 'x' ? style.columnGap : style.rowGap) || 0
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Read the slide boxes on the main axis, relative to the viewport start at location 0.
|
|
49
|
+
*
|
|
50
|
+
* @param {HTMLElement} viewport
|
|
51
|
+
* @param {HTMLElement[]} nodes All slides, clones included.
|
|
52
|
+
* @param {object} layout The result of readLayout().
|
|
53
|
+
* @param {{axis: string, container: number, slides: number[]}} written The translate values that the library wrote, in px on the screen.
|
|
54
|
+
* @returns {{view: number, slides: Array<{start: number, end: number, cross: number}>, gap: number}}
|
|
55
|
+
* gap is the loop gap: the space between the last slide and the next copy of the first slide.
|
|
56
|
+
*/
|
|
57
|
+
export function readRects(viewport, nodes, layout, written) {
|
|
58
|
+
const box = viewport.getBoundingClientRect(),
|
|
59
|
+
x = layout.axis === 'x',
|
|
60
|
+
sign = layout.sign,
|
|
61
|
+
known = written.axis === layout.axis,
|
|
62
|
+
shift = known ? written.container : 0;
|
|
63
|
+
|
|
64
|
+
let first = 0,
|
|
65
|
+
last = 0;
|
|
66
|
+
|
|
67
|
+
const slides = nodes.map((node, index) => {
|
|
68
|
+
const rect = node.getBoundingClientRect(),
|
|
69
|
+
offset = sign * (shift + (known && written.slides[index] || 0)),
|
|
70
|
+
start = (x ? (layout.rtl ? box.right - rect.right : rect.left - box.left) : rect.top - box.top) - offset,
|
|
71
|
+
size = x ? rect.width : rect.height;
|
|
72
|
+
|
|
73
|
+
return { start, end: start + size, cross: x ? rect.height : rect.width };
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
slides.forEach((slide, index) => {
|
|
77
|
+
if (slide.start < slides[first].start) {
|
|
78
|
+
first = index;
|
|
79
|
+
}
|
|
80
|
+
if (slide.end > slides[last].end) {
|
|
81
|
+
last = index;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
let gap = layout.gap;
|
|
86
|
+
|
|
87
|
+
if (slides.length) {
|
|
88
|
+
const side = x ? (layout.rtl ? ['Right', 'Left'] : ['Left', 'Right']) : ['Top', 'Bottom'];
|
|
89
|
+
gap += (parseFloat(getComputedStyle(nodes[first])['margin' + side[0]]) || 0) + (parseFloat(getComputedStyle(nodes[last])['margin' + side[1]]) || 0);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
view: x ? box.width : box.height,
|
|
94
|
+
slides,
|
|
95
|
+
gap
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Get the window size on the main axis.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} axis 'x' or 'y'.
|
|
103
|
+
* @returns {number}
|
|
104
|
+
*/
|
|
105
|
+
export function windowSize(axis) {
|
|
106
|
+
return axis === 'x' ? document.documentElement.clientWidth : innerHeight;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Get the part of the main axis where the loop must show slides, relative to the viewport start.
|
|
111
|
+
* It is the viewport. With clones: 'fill', it is the window, so that the slides fill it when the viewport overflow shows.
|
|
112
|
+
*
|
|
113
|
+
* @param {HTMLElement} viewport
|
|
114
|
+
* @param {{axis: string, rtl: boolean}} layout
|
|
115
|
+
* @param {number} view The viewport size.
|
|
116
|
+
* @param {number} [size] The window size on the main axis, for clones: 'fill'. Without it, the area is the viewport.
|
|
117
|
+
* @returns {{start: number, size: number}}
|
|
118
|
+
*/
|
|
119
|
+
export function visibleArea(viewport, layout, view, size) {
|
|
120
|
+
if (!size) {
|
|
121
|
+
return { start: 0, size: view };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const box = viewport.getBoundingClientRect(),
|
|
125
|
+
before = Math.max(0, Math.round(layout.axis === 'x' ? (layout.rtl ? size - box.right : box.left) : box.top));
|
|
126
|
+
|
|
127
|
+
return { start: -before, size: before + Math.max(view, Math.round(size - before)) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 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
|
|
131
|
+
// come after the writes of another carousel, and the browser does one layout for all of them.
|
|
132
|
+
const owners = new WeakMap();
|
|
133
|
+
|
|
134
|
+
let resizer;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 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.
|
|
138
|
+
* An entry for which owner.skip() returns true does not count.
|
|
139
|
+
*
|
|
140
|
+
* @param {Element[]} nodes
|
|
141
|
+
* @param {{read: () => boolean, write: () => void, skip: (entry: ResizeObserverEntry) => boolean}} [owner] Without an owner, stop the watch.
|
|
142
|
+
*/
|
|
143
|
+
export function observeSize(nodes, owner) {
|
|
144
|
+
resizer ||= new ResizeObserver((entries) => {
|
|
145
|
+
const list = new Set(entries.filter((entry) => !owners.get(entry.target)?.skip(entry)).map((entry) => owners.get(entry.target)));
|
|
146
|
+
[...list].filter((item) => item && item.read()).forEach((item) => item.write());
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
for (const node of nodes) {
|
|
150
|
+
if (owner) {
|
|
151
|
+
owners.set(node, owner);
|
|
152
|
+
resizer.observe(node);
|
|
153
|
+
} else {
|
|
154
|
+
owners.delete(node);
|
|
155
|
+
resizer.unobserve(node);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The lazy option: one IntersectionObserver for each margin, the callback of each element that waits, and the boxes that readBoxes() read
|
|
161
|
+
const watchers = new Map(),
|
|
162
|
+
waiters = new WeakMap(),
|
|
163
|
+
boxes = new WeakMap();
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 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.
|
|
167
|
+
* waitNear() uses each box one time.
|
|
168
|
+
*
|
|
169
|
+
* @param {Element[]} elements
|
|
170
|
+
*/
|
|
171
|
+
export function readBoxes(elements) {
|
|
172
|
+
elements.forEach((element) => boxes.set(element, element.getBoundingClientRect()));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Wait until an element comes near the screen.
|
|
177
|
+
*
|
|
178
|
+
* @param {Element} node
|
|
179
|
+
* @param {true|number} lazy The "lazy" option: true for one screen height, or a distance in px.
|
|
180
|
+
* @param {Function} callback
|
|
181
|
+
* @returns {Function|null} A function that stops the wait, or null if the element is near the screen now.
|
|
182
|
+
*/
|
|
183
|
+
export function waitNear(node, lazy, callback) {
|
|
184
|
+
const near = lazy === true ? innerHeight : lazy,
|
|
185
|
+
rect = boxes.get(node) || node.getBoundingClientRect(),
|
|
186
|
+
margin = lazy === true ? '100%' : lazy + 'px';
|
|
187
|
+
|
|
188
|
+
boxes.delete(node);
|
|
189
|
+
|
|
190
|
+
if (rect.height && rect.bottom >= -near && rect.top <= innerHeight + near) {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
let observer = watchers.get(margin);
|
|
195
|
+
if (!observer) {
|
|
196
|
+
observer = new IntersectionObserver((entries) => entries.forEach((entry) => entry.isIntersecting && waiters.get(entry.target)?.()), { rootMargin: margin });
|
|
197
|
+
watchers.set(margin, observer);
|
|
198
|
+
}
|
|
199
|
+
waiters.set(node, callback);
|
|
200
|
+
observer.observe(node);
|
|
201
|
+
return () => {
|
|
202
|
+
observer.unobserve(node);
|
|
203
|
+
waiters.delete(node);
|
|
204
|
+
};
|
|
205
|
+
}
|