@twistedandy/better-carousel 0.0.0-stage → 1.1.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.
@@ -0,0 +1,484 @@
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 pointerdown events that a carousel took for a drag
14
+ const claimed = new WeakSet();
15
+
16
+ // The duration of the motion for one wheel event, in ms
17
+ const WHEEL = 180;
18
+
19
+ // The time constant of the glide, in ms: the glide distance is velocity * MOMENTUM
20
+ const MOMENTUM = 325;
21
+
22
+ /**
23
+ * Get the duration of a motion after a release, so that the motion starts at the release velocity.
24
+ *
25
+ * @param {number} path The distance of the motion: target - location.
26
+ * @param {number} velocity The release velocity, in px/ms.
27
+ * @param {number[]} curve The easing of the motion.
28
+ * @param {number} fallback The duration if the velocity is too low or in the other direction.
29
+ * @returns {number}
30
+ */
31
+ export function releaseDuration(path, velocity, curve, fallback) {
32
+ if (Math.sign(path) !== Math.sign(velocity) || Math.abs(velocity) < 0.05) {
33
+ return fallback;
34
+ }
35
+ return clamp(Math.abs(path) * curve[1] / curve[0] / Math.abs(velocity), 200, 1200);
36
+ }
37
+
38
+ /**
39
+ * Get the velocity from the last samples of a drag.
40
+ *
41
+ * @param {Array<number[]>} samples [location, time] pairs, the oldest first. A drag always has one sample or more.
42
+ * @returns {number} px/ms
43
+ */
44
+ export function velocity(samples) {
45
+ const last = samples[samples.length - 1];
46
+
47
+ // The last sample is always in its own window, so find() always finds a sample
48
+ const first = samples.find((sample) => last[1] - sample[1] <= 100),
49
+ time = last[1] - first[1];
50
+
51
+ return time > 0 ? (last[0] - first[0]) / time : 0;
52
+ }
53
+
54
+ /**
55
+ * Find the target of the motion after a drag.
56
+ *
57
+ * @param {object} args
58
+ * @param {number} args.location The location at the release.
59
+ * @param {number} args.from The location at the drag start.
60
+ * @param {number} args.velocity The release velocity, in px/ms.
61
+ * @param {number} args.current The selected snap at the drag start.
62
+ * @param {Array<{location: number}>} args.snaps
63
+ * @param {number} args.min
64
+ * @param {number} args.max
65
+ * @param {number} [args.period]
66
+ * @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.
67
+ * false: go at most one snap.
68
+ * @param {boolean|string} [args.dragFree]
69
+ * @param {number} [args.dragFriction] The glide distance is divided by this number.
70
+ * @returns {{location: number, snap: number}}
71
+ */
72
+ export function releaseTarget({ location, from, velocity, current, snaps, min, max, period, skipSnaps, dragFree, dragFriction = 1 }) {
73
+ const count = snaps.length;
74
+
75
+ let projected = location + velocity * MOMENTUM / dragFriction;
76
+
77
+ if (!period) {
78
+ projected = clamp(projected, min, max);
79
+ }
80
+
81
+ // A number in skipSnaps: keep the projected location between the snaps that are skipSnaps snaps before and after the start snap
82
+ if (typeof skipSnaps === 'number' && skipSnaps > 0 && skipSnaps < count - 1 + !period) {
83
+ const limit = (direction) => targetLocation(snaps[snapIndex(current + direction * skipSnaps, count, period)].location, from, period, direction);
84
+ projected = clamp(projected, limit(1), limit(-1));
85
+ }
86
+
87
+ if (dragFree === true) {
88
+ return { location: projected, snap: nearestSnap(snaps, projected, period) };
89
+ }
90
+
91
+ if (dragFree || skipSnaps) {
92
+ const snap = nearestSnap(snaps, projected, period);
93
+ return { location: targetLocation(snaps[snap].location, projected, period), snap };
94
+ }
95
+
96
+ const moved = location - from;
97
+
98
+ let direction = 0;
99
+
100
+ if (Math.abs(velocity) > 0.3) {
101
+ direction = velocity < 0 ? 1 : -1;
102
+ } else if (Math.abs(moved) > 20) {
103
+ direction = moved < 0 ? 1 : -1;
104
+ }
105
+
106
+ const snap = snapIndex(current + direction, count, period),
107
+ target = snaps[snap].location;
108
+
109
+ return {
110
+ location: period ? targetLocation(target, direction ? from : location, period, snap === current ? 0 : direction) : target,
111
+ snap
112
+ };
113
+ }
114
+
115
+ /**
116
+ * 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.
117
+ *
118
+ * @param {object} context What the features share. See carousel.js.
119
+ * @returns {{remove: () => void}|undefined}
120
+ */
121
+ export function drag(context) {
122
+ const { viewport, options } = context;
123
+
124
+ if (!options.drag) {
125
+ return;
126
+ }
127
+
128
+ let pointer = null,
129
+ start,
130
+ base,
131
+ axis,
132
+ block = false,
133
+ samples = [],
134
+ // The selected snap at the drag start
135
+ snap = 0;
136
+
137
+ const listen = (method) => ['pointermove', 'pointerup', 'pointercancel'].forEach((name) => window[method](name, handle));
138
+
139
+ function down(event) {
140
+ block = false;
141
+
142
+ const geo = context.geo();
143
+
144
+ // In nested carousels, the inner carousel gets the press first and claims it
145
+ if (pointer !== null || event.button || !geo || geo.fit || claimed.has(event) || event.target.closest(fields)) {
146
+ return;
147
+ }
148
+
149
+ claimed.add(event);
150
+
151
+ // Stop the text selection and the native image drag
152
+ if (event.pointerType === 'mouse') {
153
+ event.preventDefault();
154
+ }
155
+
156
+ pointer = event.pointerId;
157
+ // In a parent with a CSS scale, one px of the pointer is not one px of the carousel
158
+ axis = { x: geo.axis === 'x', sign: geo.sign, scale: geo.scale };
159
+ start = [event.clientX, event.clientY];
160
+ samples = [];
161
+ listen('addEventListener');
162
+ }
163
+
164
+ function handle(event) {
165
+ if (event.pointerId !== pointer) {
166
+ return;
167
+ }
168
+
169
+ if (event.type !== 'pointermove') {
170
+ // A stop before the release gives a low velocity
171
+ if (samples.length) {
172
+ samples.push([samples[samples.length - 1][0], event.timeStamp]);
173
+ }
174
+ return end(event.type === 'pointerup');
175
+ }
176
+
177
+ const dx = (event.clientX - start[0]) / axis.scale,
178
+ dy = (event.clientY - start[1]) / axis.scale,
179
+ main = axis.x ? dx * axis.sign : dy,
180
+ cross = axis.x ? dy : dx;
181
+
182
+ if (!context.dragging()) {
183
+ // A touch move across the axis scrolls the page
184
+ if (event.pointerType !== 'mouse' && Math.abs(cross) > Math.abs(main)) {
185
+ return end();
186
+ }
187
+ if (Math.abs(main) < options.dragThreshold) {
188
+ return;
189
+ }
190
+ // Stop the motion, and start the drag at the location where the carousel is now
191
+ base = context.halt();
192
+ snap = context.selected();
193
+ context.drag(true);
194
+ // Capture only now: with capture, a link in a slide does not get the click
195
+ viewport.setPointerCapture(pointer);
196
+ }
197
+
198
+ const geo = context.geo(),
199
+ value = base + main,
200
+ edge = clamp(value, geo.min, geo.max);
201
+
202
+ // Out of the limits, the carousel moves at a quarter of the pointer speed
203
+ context.hold(geo.period ? value : edge + (value - edge) / 4, true);
204
+ samples.push([main, event.timeStamp]);
205
+
206
+ if (samples.length > 10) {
207
+ samples.shift();
208
+ }
209
+ }
210
+
211
+ /**
212
+ * End the drag.
213
+ *
214
+ * @param {boolean} [up] true for a pointerup. A pointercancel releases with no velocity.
215
+ */
216
+ function end(up) {
217
+ listen('removeEventListener');
218
+ pointer = null;
219
+
220
+ if (!context.dragging()) {
221
+ return;
222
+ }
223
+
224
+ const geo = context.geo(),
225
+ location = context.location(),
226
+ speed = up ? velocity(samples) : 0,
227
+ target = releaseTarget({ location, from: base, velocity: speed, current: snap, snaps: geo.snaps, min: geo.min, max: geo.max, period: geo.period, skipSnaps: options.skipSnaps, dragFree: options.dragFree, dragFriction: options.dragFriction }),
228
+ curve = options.dragFree === true ? GLIDE : EASE;
229
+
230
+ block = true;
231
+ context.drag(false);
232
+ context.move(target.snap, target.location, releaseDuration(target.location - location, speed, curve, options.duration), curve);
233
+ }
234
+
235
+ function click(event) {
236
+ if (block) {
237
+ block = false;
238
+ event.preventDefault();
239
+ event.stopPropagation();
240
+ }
241
+ }
242
+
243
+ const prevent = (event) => event.preventDefault();
244
+
245
+ // Stop a text selection during a drag. A "user-select" rule on the dragging class does the same, but its change paints all layers of the carousel.
246
+ const select = (event) => context.dragging() && event.preventDefault();
247
+
248
+ viewport.addEventListener('pointerdown', down);
249
+ viewport.addEventListener('click', click, true);
250
+ viewport.addEventListener('dragstart', prevent);
251
+ viewport.addEventListener('selectstart', select);
252
+
253
+ return {
254
+ remove() {
255
+ listen('removeEventListener');
256
+ viewport.removeEventListener('pointerdown', down);
257
+ viewport.removeEventListener('click', click, true);
258
+ viewport.removeEventListener('dragstart', prevent);
259
+ viewport.removeEventListener('selectstart', select);
260
+ }
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Find an element between a node and the viewport that can scroll in a direction.
266
+ *
267
+ * @param {Element} node The target of the wheel event.
268
+ * @param {Element} viewport
269
+ * @param {string} axis 'x' or 'y'.
270
+ * @param {number} delta The wheel delta on the axis.
271
+ * @returns {boolean}
272
+ */
273
+ function scrolls(node, viewport, axis, delta) {
274
+ const [size, client, position, overflow] = axis === 'x' ? ['scrollWidth', 'clientWidth', 'scrollLeft', 'overflowX'] : ['scrollHeight', 'clientHeight', 'scrollTop', 'overflowY'];
275
+
276
+ for (; node && node !== viewport; node = node.parentElement) {
277
+ // Read the style only for an element with more content than space
278
+ if (node[size] > node[client] && /auto|scroll/.test(getComputedStyle(node)[overflow])) {
279
+ const at = Math.abs(node[position]);
280
+ if (delta > 0 ? at + node[client] < node[size] - 1 : at > 0) {
281
+ return true;
282
+ }
283
+ }
284
+ }
285
+
286
+ return false;
287
+ }
288
+
289
+ /**
290
+ * Make the wheel input of a viewport: in a vertical carousel, and with wheel: 'both' also in a horizontal carousel. The carousel follows
291
+ * the wheel distance with a short motion on the compositor. When the wheel stops, the carousel goes to a snap. At the first and the last
292
+ * location, the page scrolls.
293
+ *
294
+ * @param {object} context What the features share. See carousel.js.
295
+ * @returns {{remove: () => void}|undefined}
296
+ */
297
+ export function wheel(context) {
298
+ const { viewport, options } = context,
299
+ // With dragFree: true, the carousel stays where the wheel stops
300
+ free = options.dragFree === true;
301
+
302
+ if (!options.wheel) {
303
+ return;
304
+ }
305
+
306
+ // The time and the delta size of the last wheel event, and true if the gesture moved the carousel
307
+ let time = 0,
308
+ last = 0,
309
+ held = false,
310
+ // true while a gesture scrolls an element in a slide
311
+ inner = false,
312
+ // The timer that finds the end of a gesture
313
+ timer = 0,
314
+ // The selected snap at the gesture start, and the direction of the last step
315
+ snap = 0,
316
+ direction = 0;
317
+
318
+ function onWheel(event) {
319
+ const geo = context.geo(),
320
+ side = geo.axis === 'x' && Math.abs(event.deltaX) > Math.abs(event.deltaY),
321
+ delta = side ? event.deltaX * geo.sign : event.deltaY;
322
+
323
+ if (event.ctrlKey || !delta || context.dragging()) {
324
+ return;
325
+ }
326
+
327
+ const now = event.timeStamp,
328
+ gesture = now - time < 200,
329
+ size = Math.abs(delta),
330
+ // A delta that does not grow is the inertia of the gesture, not a new push
331
+ inertia = gesture && size <= last;
332
+
333
+ last = size;
334
+ if (!gesture) {
335
+ held = false;
336
+ }
337
+
338
+ // An element in a slide that can scroll in the wheel direction scrolls, also for the rest of its gesture
339
+ if ((gesture && inner) || scrolls(event.target, viewport, side ? 'x' : 'y', side ? event.deltaX : delta)) {
340
+ inner = true;
341
+ time = now;
342
+ return;
343
+ }
344
+ inner = false;
345
+
346
+ const base = context.location(),
347
+ path = delta * (event.deltaMode === 1 ? 40 : event.deltaMode ? geo.view : 1);
348
+
349
+ let target = base - path;
350
+ if (!geo.period) {
351
+ target = clamp(target, geo.min, geo.max);
352
+ }
353
+
354
+ time = now;
355
+
356
+ // At the end, the page scrolls. The inertia of a gesture that moved the carousel does not scroll the page.
357
+ if (Math.abs(target - base) < 0.5) {
358
+ if (held && inertia) {
359
+ event.preventDefault();
360
+ }
361
+ return;
362
+ }
363
+
364
+ event.preventDefault();
365
+ context.emit('interact');
366
+
367
+ if (!timer) {
368
+ snap = context.selected();
369
+ }
370
+ held = true;
371
+ direction = path > 0 ? 1 : -1;
372
+ context.move(nearestSnap(geo.snaps, target, geo.period), target, WHEEL, EASE);
373
+
374
+ clearTimeout(timer);
375
+ if (!free) {
376
+ timer = setTimeout(end, 150);
377
+ }
378
+ }
379
+
380
+ // 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.
381
+ function end() {
382
+ timer = 0;
383
+ const geo = context.geo(),
384
+ at = context.current(),
385
+ index = nearestSnap(geo.snaps, at, geo.period),
386
+ away = Math.abs(targetLocation(geo.snaps[index].location, at, geo.period) - at) > 10;
387
+
388
+ context.step(index, index === snap && away ? direction : 0);
389
+ }
390
+
391
+ // A wheel listener that is not passive makes the browser wait for the main thread before it scrolls the page.
392
+ // Add it only where the wheel moves the carousel.
393
+ function listen() {
394
+ const geo = context.geo();
395
+ viewport[!geo.fit && (geo.axis === 'y' || options.wheel === 'both') ? 'addEventListener' : 'removeEventListener']('wheel', onWheel, { passive: false });
396
+ }
397
+
398
+ ['init', 'reinit', 'resize'].forEach((name) => context.on(name, listen));
399
+
400
+ return {
401
+ remove() {
402
+ viewport.removeEventListener('wheel', onWheel);
403
+ clearTimeout(timer);
404
+ }
405
+ };
406
+ }
407
+
408
+ /**
409
+ * 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
410
+ * 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.
411
+ *
412
+ * @param {object} context What the features share. See carousel.js.
413
+ * @returns {{remove: () => void}|undefined}
414
+ */
415
+ export function keys(context) {
416
+ const { api, root, options } = context;
417
+
418
+ if (!options.keys) {
419
+ return;
420
+ }
421
+
422
+ function onKey(event) {
423
+ const geo = context.geo(),
424
+ { key, target } = event,
425
+ // -1 for the previous slide, 1 for the next slide. A right-to-left carousel has the next slide at the left.
426
+ direction = geo && !geo.fit && (geo.axis === 'y' ? { ArrowUp: -1, ArrowDown: 1 } : { ArrowLeft: -geo.sign, ArrowRight: geo.sign })[key],
427
+ name = direction > 0 ? 'Next' : 'Prev';
428
+ // At the first and the last slide, the key scrolls the page
429
+ if (direction && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) && api['canGoTo' + name]()) {
430
+ event.preventDefault();
431
+ api['goTo' + name]();
432
+ }
433
+ }
434
+
435
+ root.addEventListener('keydown', onKey);
436
+
437
+ return {
438
+ remove() {
439
+ root.removeEventListener('keydown', onKey);
440
+ }
441
+ };
442
+ }
443
+
444
+ /**
445
+ * 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.
446
+ *
447
+ * @param {object} context What the features share. See carousel.js.
448
+ * @returns {{remove: () => void}}
449
+ */
450
+ export function focus(context) {
451
+ const { api, container, options } = context;
452
+
453
+ // The time of the last pointer press
454
+ let pressed = -1e4;
455
+
456
+ function press(event) {
457
+ if (!event.target.closest(fields)) {
458
+ pressed = event.timeStamp;
459
+ }
460
+ }
461
+
462
+ function onFocus(event) {
463
+ const geo = context.geo(),
464
+ index = api.slideNodes().findIndex((node) => node.contains(event.target));
465
+
466
+ if (!geo || index < 0 || event.timeStamp - pressed < 600) {
467
+ return;
468
+ }
469
+ if (options.focus && !inView(geo.slides, context.location(), geo.view, 1, geo.period).map((item) => item % geo.count).includes(index)) {
470
+ api.goToSlide(index);
471
+ }
472
+ context.emit('slidefocus');
473
+ }
474
+
475
+ container.addEventListener('pointerdown', press);
476
+ container.addEventListener('focusin', onFocus);
477
+
478
+ return {
479
+ remove() {
480
+ container.removeEventListener('pointerdown', press);
481
+ container.removeEventListener('focusin', onFocus);
482
+ }
483
+ };
484
+ }