-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarousel.js
More file actions
574 lines (516 loc) · 18.9 KB
/
Copy pathcarousel.js
File metadata and controls
574 lines (516 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// ==================== Carousel plugin ====================
const carouselClass = "ff-carousel";
const carouselIndicatorClass = "ff-carousel-indicator";
// Defines default options for the carousel plugin.
let carouselDefaults = {
// The index of the initially active item.
active: 0,
// The number of items concurrently visible.
items: 1,
// Show an indicator dot each x items. -1 means the same value as items.
dotsEach: -1,
// The margin between two items, in pixels.
gutter: 0,
// Shows the indicator dots for the active item.
indicator: true,
// Starts looping through all items automatically.
autoPlay: false,
// Autoplay item switch interval, in milliseconds.
autoPlayInterval: 4000,
// Pauses autoplay while the carousel is hovered with the mouse.
pauseOnHover: true,
// The mouse cursor to show during dragging.
dragCursor: undefined,
// The animation between items.
// Possible values: slide-all, slide-in, slide-out, fade, slide-fade
// For more than one visible item, only slide-all is supported and automatically used.
animation: "slide-all",
// Loops all items at the end instead of rewinding/restricting.
// TODO
//loop: false
};
// Converts each selected element into a carousel.
function carousel(options) {
return this.forEach(carousel => {
if (carousel.querySelector("." + carouselClass)) return; // Already done
let opt = F.initOptions("carousel", carousel, {}, options);
if (opt.items > 1 || opt.gutter > 0)
opt.animation = "slide-all";
let stage = F.c("div");
stage.classList.add(carouselClass);
opt._gutterWidth = (opt.items - 1) / opt.items * opt.gutter;
opt._gutterOffset = 1 / opt.items * opt.gutter;
opt._itemWidthPercent = 100 / opt.items;
opt._layout = layout;
let itemIndex = 0;
let maxItemHeight = 0;
let items = carousel.F.children;
let autoPlayTimeout;
let itemOffset, startItemOffset, prevItemOffset, dragDirection, itemOffsetMin, itemOffsetMax, itemWidth;
let currentTransition = "";
let clickLock = false;
let clickUnlockTimeout;
if (opt.dotsEach === -1)
opt.dotsEach = opt.items;
opt.dotsEach = F.clamp(opt.dotsEach, 0, opt.items);
// Set up items positioning
items.forEach(obj => {
obj.style.width = "calc(" + opt._itemWidthPercent + "% - " + opt._gutterWidth + "px)";
maxItemHeight = Math.max(maxItemHeight, obj.F.borderHeight);
stage.append(obj);
itemIndex++;
if (obj.getAttribute("href")) {
obj.style.cursor = "pointer";
obj.setAttribute("tabindex", "-1");
obj.F.on("click", () => {
if (!clickLock) {
location.href = obj.getAttribute("href");
}
});
}
});
carousel.append(stage);
stage.style.height = maxItemHeight + "px";
stage.setAttribute("tabindex", "-1"); // Would be tab-focusable otherwise (not sure why)
// Add controls
if (opt.indicator) {
let indicator = F.c("div");
indicator.classList.add(carouselIndicatorClass);
carousel.append(indicator);
let indicatorCount = Math.ceil(items.length / opt.dotsEach) - (opt.items - opt.dotsEach);
for (let i = 0; i < indicatorCount; i++) {
let dot = F("<span tabindex='0'><span></span></span>").appendTo(indicator).first;
let fn = () => {
carousel.F.carousel.activeItemIndex = i * opt.dotsEach;
suspendAutoplay();
resumeAutoplay();
};
dot.F.on("click", fn);
dot.F.on("keydown", event => {
if (event.key === "Enter") {
event.preventDefault();
fn();
}
});
}
}
carousel.F.carousel.activeItemIndex = opt.active;
stage.F.draggable({
axis: "x",
dragCursor: opt.dragCursor,
cancel: stage.querySelectorAll("input, button, textarea, label")
});
stage.F.on("draggablestart", event => {
let dx = Math.abs(event.dragPoint.left - event.newPoint.left);
let dy = Math.abs(event.dragPoint.top - event.newPoint.top);
if (dy > dx) {
// Movement was mostly vertical, don't drag in that direction but leave scrolling intact
event.preventDefault();
return;
}
itemWidth = stage.F.width / opt.items;
prevItemOffset = startItemOffset = layout();
let lastPageFirstItem = Math.max(0, items.length - opt.items);
itemOffsetMin = -opt.active;
itemOffsetMax = lastPageFirstItem - opt.active;
opt._isDragging = true;
if (clickUnlockTimeout)
clearTimeout(clickUnlockTimeout);
clickLock = true;
// Disable transition and autoplay while dragging
removeTransition();
suspendAutoplay();
});
stage.F.on("draggablemove", event => {
itemOffset = startItemOffset - (event.newPoint.left - event.elemRect.left) / itemWidth;
dragDirection = itemOffset - prevItemOffset;
prevItemOffset = itemOffset;
// Don't move the stage anywhere! Just tell me how far the pointer is dragged and we'll
// move something else (the items within the stage) to provide the expected visual feedback.
event.newPoint = event.elemRect;
// Restrict dragging at start/end
if (itemOffset < itemOffsetMin)
itemOffset = itemOffsetMin - elastic(itemOffsetMin - itemOffset);
if (itemOffset > itemOffsetMax)
itemOffset = itemOffsetMax + elastic(itemOffset - itemOffsetMax);
function elastic(exceeding) {
var max = 0.25;
// This function has a slope of 1 for x = 0 and slowly approaches (but never reaches) max
return -max / (exceeding / max + 1) + max;
}
layout(itemOffset);
});
stage.F.on("draggableend", () => {
// Restore transition and autoplay
addTransition();
resumeAutoplay();
opt._isDragging = false;
clickUnlockTimeout = setTimeout(() => clickLock = false, 100);
// Snap to item, consider last drag direction
let itemIndex = opt.active + itemOffset;
if (itemIndex < 0)
itemIndex = 0;
let newDot = itemIndex / opt.dotsEach;
if (dragDirection > 0)
newDot = Math.ceil(newDot);
else
newDot = Math.floor(newDot);
carousel.F.carousel.activeItemIndex = newDot * opt.dotsEach;
});
// Add transition after setting position of every item
F.forceReflow();
addTransition();
let autoplaySuspendLevel = 0;
if (opt.autoPlay) {
if (opt.pauseOnHover) {
stage.F.on("pointerenter", suspendAutoplay);
stage.F.on("pointerleave", resumeAutoplay);
}
autoPlayTimeout = setTimeout(next, opt.autoPlayInterval);
}
function suspendAutoplay() {
autoPlayTimeout && clearTimeout(autoPlayTimeout);
autoplaySuspendLevel++;
}
function resumeAutoplay() {
autoplaySuspendLevel--;
if (opt.autoPlay && !autoplaySuspendLevel) {
autoPlayTimeout = setTimeout(next, opt.autoPlayInterval * 2);
}
}
function next() {
let index = opt.active;
index += opt.dotsEach;
if (index > items.length - opt.items)
index = 0;
carousel.F.carousel.activeItemIndex = index;
autoPlayTimeout = setTimeout(next, opt.autoPlayInterval);
}
function removeTransition() {
currentTransition = "";
items.style.transition = currentTransition;
}
function addTransition() {
let opacityTime = "0.4s";
if (opt.animation === "fade")
opacityTime = "0.8s";
currentTransition = "left 0.4s ease-in-out, opacity " + opacityTime + " ease-in-out";
items.style.transition = currentTransition;
}
// Item layouts for each animation type:
// slide-all
// All items are positioned next to each other and moved simultaneously
// No z-index or opacity is used
// slide-out
// There are two stacks next to each other
// The right stack is at left: 0 (visible in the stage), the left stack is directly next to it
// The active item and all following items are on the right (visible) stack, with z-index from front to back
// The previous items are on the left (invisible) stack
// Only one item can be moved to the other stack at a time
// slide-in
// There are two stacks next to each other
// The left stack is at left: 0 (visible in the stage), the right stack is directly next to it
// The active item and all previous items are on the left (visible) stack, with z-index from back to front
// The following items are on the right (invisible) stack
// Only one item can be moved to the other stack at a time
// fade
// All items are stacked above one another, at the same position (left: 0, in the stage)
// The visible item or the item that is becoming visible is on z-index 1, opacity is 1.
// The previously visible item or the item that is becoming invisible is on z-index 2, opacity is (becoming) 0, pointer-events is none.
// All other items are on z-index 0 with opacity 0.
// slide-fade
// Based on slide-all but moving items by 1/10th of the stage width.
// The active/visible item has opacity 1, gradually changing to 0 for the adjacent and all other items.
// Translates between an item offset and the current layout.
// The getter is used to initialise the item offset when starting to drag during an ongoing transition.
// The setter is used everywhere the items need to be laid out for a new active item or item offset.
function layout(itemOffset) {
// Getter
if (itemOffset === undefined) {
let pos = [];
let allSame = true;
switch (opt.animation) {
case "fade":
let z1, z2, z2Opacity;
items.forEach((obj, index) => {
let style = obj.F.computedStyle;
if (style.zIndex == 1)
z1 = index;
if (style.zIndex == 2) {
z2 = index;
z2Opacity = parseFloat(style.opacity);
}
});
//console.log("get layout: z1=" + z1 + " z2=" + z2 + " z2Opacity=" + z2Opacity + " active=" + opt.active);
if (z2 !== undefined) {
if (z1 > z2) // Moving forward (a higher item index is in layer 1, becoming visible)
return z1 + (1 - z2Opacity) - opt.active - 1;
else // Moving backward
return z1 + z2Opacity - opt.active;
}
if (z1 !== undefined)
return z1 - opt.active;
return 0;
case "slide-in":
let anyZero = false;
let firstGtZero = -1;
items.forEach((obj, index) => {
let style = obj.F.computedStyle;
let left = parseFloat(style.left);
pos.push(left);
if (left !== pos[0])
allSame = false;
if (left === 0)
anyZero = true;
if (left > 0 && firstGtZero === -1)
firstGtZero = index;
});
if (allSame && pos[0] < 0)
return items.length - 1 - pos[0] / itemWidth - opt.active;
if (!anyZero)
return -pos[0] / itemWidth - opt.active;
if (firstGtZero > 0)
return firstGtZero - pos[firstGtZero] / itemWidth - opt.active;
return 0;
case "slide-out":
let anyPositive = false;
let firstZero = -1;
items.forEach((obj, index) => {
let style = obj.F.computedStyle;
let left = parseFloat(style.left);
pos.push(left);
if (left !== pos[0])
allSame = false;
if (left >= 0)
anyPositive = true;
if (left === 0 && firstZero === -1)
firstZero = index;
});
if (allSame && pos[0] > 0)
return -pos[0] / itemWidth - opt.active;
if (!anyPositive)
return items.length - 1 + -pos[pos.length - 1] / itemWidth - opt.active;
if (firstZero > 0)
return firstZero - 1 + -pos[firstZero - 1] / itemWidth - opt.active;
return 0;
case "slide-fade":
let activeItemLeft2 = parseFloat(items.get(opt.active).F.computedStyle.left);
return -activeItemLeft2 / (itemWidth / 10);
case "slide-all":
default:
let activeItemLeft = parseFloat(items.get(opt.active).F.computedStyle.left);
return -activeItemLeft / itemWidth;
}
}
// Setter
switch (opt.animation) {
case "fade":
if (itemOffset !== 0) {
let fullyVisible = opt.active + Math.trunc(itemOffset);
let partiallyVisible = opt.active + Math.trunc(itemOffset) + Math.sign(itemOffset);
//console.log(fullyVisible, partiallyVisible);
items.forEach((obj, index) => {
if (index === fullyVisible) {
obj.style.zIndex = "1";
obj.style.opacity = "1";
}
else if (index === partiallyVisible) {
obj.style.zIndex = "2";
obj.style.opacity = Math.abs(itemOffset) - Math.trunc(Math.abs(itemOffset));
}
else {
obj.style.zIndex = "0";
obj.style.opacity = "0";
}
});
}
else {
let z1, z2, z2Opacity;
items.forEach((obj, index) => {
let style = obj.F.computedStyle;
if (style.zIndex == 1)
z1 = index;
if (style.zIndex == 2) {
z2 = index;
z2Opacity = parseFloat(style.opacity);
}
});
//console.log("set layout: z1=" + z1 + " z2=" + z2 + " z2Opacity=" + z2Opacity + " active=" + opt.active);
if (opt.active === z1) {
items.get(z2).style.opacity = "0";
items.get(z2).style.pointerEvents = "none";
}
else if (opt.active === z2) {
removeTransition();
items.get(z1).style.zIndex = "2";
items.get(z1).style.opacity = 1 - z2Opacity;
items.get(z2).style.zIndex = "1";
items.get(z2).style.opacity = "1";
items.get(z2).style.pointerEvents = "";
F.forceReflow();
if (!opt._isDragging)
addTransition();
items.get(z1).style.opacity = "0";
items.get(z1).style.pointerEvents = "none";
}
else {
let currentVisible;
items.forEach((obj, index) => {
let style = obj.F.computedStyle;
if (style.zIndex == 1)
currentVisible = index;
});
removeTransition();
items.get(opt.active).style.zIndex = "1";
items.get(opt.active).style.opacity = "1";
items.get(opt.active).style.pointerEvents = "";
F.forceReflow();
if (!opt._isDragging)
addTransition();
items.forEach((obj, index) => {
if (index === opt.active) {
}
else if (index === currentVisible) {
obj.style.zIndex = "2";
obj.style.opacity = "0";
obj.style.pointerEvents = "none";
}
else {
obj.style.zIndex = "0";
obj.style.opacity = "0";
obj.style.pointerEvents = "";
}
});
}
}
//let status = "";
//items.forEach((obj, index) => {
// let style = obj.F.computedStyle;
// status += index + ": z=" + style.zIndex + " op=" + style.opacity + (index === opt.active ? " active" : "") + "\n";
//});
//console.log(status);
break;
case "slide-in":
items.forEach((obj, index) => {
let left = opt.active + itemOffset <= items.length - 1 ?
F.clamp((index - opt.active - itemOffset) * 100, 0, 100) :
(items.length - 1 - opt.active - itemOffset) * 100;
obj.style.left = left + "%";
obj.style.zIndex = index;
});
break;
case "slide-out":
items.forEach((obj, index) => {
let left = opt.active + itemOffset >= 0 ?
F.clamp((index - opt.active - itemOffset) * 100, -100, 0) :
(-opt.active - itemOffset) * 100;
obj.style.left = left + "%";
obj.style.zIndex = items.length - 1 - index;
});
break;
case "slide-fade":
items.forEach((obj, index) => {
let percent = (index - opt.active) * 100 / 10;
let left = (index - opt.active) * opt._gutterOffset - itemOffset * stage.F.width / 10;
obj.style.left = "calc(" + percent + "% + " + left + "px)";
let opacity = 1 - F.clamp(Math.abs(index - (opt.active + itemOffset)), 0, 1);
obj.style.opacity = opacity;
});
break;
case "slide-all":
default:
items.forEach((obj, index) => {
let percent = (index - opt.active) * opt._itemWidthPercent;
let left = (index - opt.active) * opt._gutterOffset - itemOffset * stage.F.width / opt.items;
obj.style.left = "calc(" + percent + "% + " + left + "px)";
});
break;
}
}
});
}
// Gets the active item in a carousel.
function getActiveItem() {
let carousel = this.first;
if (!carousel) return; // Nothing to do
let opt = F.loadOptions("carousel", carousel);
if (!opt) return;
let items = carousel.F.querySelector("." + carouselClass).children;
return items.array[opt.active];
}
// Sets the active item in a carousel.
//
// item: The new active item element in each selected carousel.
function setActiveItem(item) {
let carousel = this.first;
if (!carousel) return; // Nothing to do
let opt = F.loadOptions("carousel", carousel);
if (!opt || opt._isDragging) return; // Ignore request while dragging
let items = carousel.F.querySelector("." + carouselClass).children;
let index = item.F.index;
index = F.clamp(index, 0, items.length - opt.items);
opt.active = index;
opt._layout(0);
if (opt.indicator) {
let dots = carousel.F.querySelector("." + carouselIndicatorClass).children;
dots.classList.remove("active");
dots.get(Math.ceil(index / opt.dotsEach)).classList.add("active");
}
carousel.F.trigger("activeItemChange");
}
// Gets the index of the active item in a carousel.
function getActiveItemIndex() {
let carousel = this.first;
if (!carousel) return; // Nothing to do
let opt = F.loadOptions("carousel", carousel);
return opt?.active;
}
// Sets the active item in a carousel by its index.
//
// index: The index of the new active item in each selected carousel.
function setActiveItemIndex(index) {
return this.forEach(carousel => {
let opt = F.loadOptions("carousel", carousel);
if (!opt || opt._isDragging) return; // Ignore request while dragging
let items = carousel.F.querySelector("." + carouselClass).children;
if (index === Infinity)
index = items.length; // Infinity can't be handled by Math.min
else if (index < 0)
index += items.length; // Negative count from the end
index = F.clamp(index, 0, items.length - opt.items);
opt.active = index;
opt._layout(0);
if (opt.indicator) {
let dots = carousel.F.querySelector("." + carouselIndicatorClass).children;
dots.classList.remove("active");
dots.get(Math.ceil(index / opt.dotsEach)).classList.add("active");
}
carousel.F.trigger("activeItemChange");
});
}
// Gets the number of items in a carousel.
function getItemCount() {
let carousel = this.first;
if (!carousel) return; // Nothing to do
let opt = F.loadOptions("carousel", carousel);
if (!opt) return;
let items = carousel.F.querySelector("." + carouselClass).children;
return items.array.length;
}
F.registerPlugin("carousel", carousel, {
defaultOptions: carouselDefaults,
methods: {
activeItem: {
get: getActiveItem,
set: setActiveItem
},
activeItemIndex: {
get: getActiveItemIndex,
set: setActiveItemIndex
},
length: {
get: getItemCount
}
},
selectors: [".carousel"]
});