-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathCarousel.js
668 lines (627 loc) · 17.6 KB
/
Carousel.js
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
import Vue from 'vue';
import { getInRange, now, Timer, normalizeSlideIndex, cloneNode, normalizeChildren, sign, assign } from './utils';
import './styles/carousel.css';
let EMITTER = new Vue();
export default {
name: 'Hooper',
provide() {
return {
$hooper: this
};
},
props: {
// count of items to showed per view
itemsToShow: {
default: 1,
type: Number
},
// count of items to slide when use navigation buttons
itemsToSlide: {
default: 1,
type: Number
},
// index number of initial slide
initialSlide: {
default: 0,
type: Number
},
// control infinite scrolling mode
infiniteScroll: {
default: false,
type: Boolean
},
// control center mode
centerMode: {
default: false,
type: Boolean
},
// vertical sliding mode
vertical: {
default: false,
type: Boolean
},
// enable rtl mode
rtl: {
default: null,
type: Boolean
},
// enable auto sliding to carousel
autoPlay: {
default: false,
type: Boolean
},
// speed of auto play to trigger slide
playSpeed: {
default: 2000,
type: Number
},
// toggle mouse dragging
mouseDrag: {
default: true,
type: Boolean
},
// toggle touch dragging
touchDrag: {
default: true,
type: Boolean
},
// toggle mouse wheel sliding
wheelControl: {
default: true,
type: Boolean
},
// toggle keyboard control
keysControl: {
default: true,
type: Boolean
},
// enable any move to commit a slide
shortDrag: {
default: true,
type: Boolean
},
// sliding transition time in ms
transition: {
default: 300,
type: Number
},
// pause autoPlay on mousehover
hoverPause: {
default: true,
type: Boolean
},
// remove empty space around slides
trimWhiteSpace: {
default: false,
type: Boolean
},
// an object to pass all settings
settings: {
default() {
return {};
},
type: Object
},
group: {
type: String,
default: null
}
},
data() {
return {
isDragging: false,
isSliding: false,
isTouch: false,
isHover: false,
isFocus: false,
initialized: false,
slideWidth: 0,
slideHeight: 0,
slidesCount: 0,
trimStart: 0,
trimEnd: 1,
currentSlide: null,
timer: null,
defaults: {},
breakpoints: {},
delta: { x: 0, y: 0 },
config: {}
};
},
computed: {
slideBounds() {
const { config, currentSlide } = this;
// Because the "isActive" depends on the slides shown, not the number of slidable ones.
// but upper and lower bounds for Next,Prev depend on whatever is smaller.
const siblings = config.itemsToShow;
const lower = config.centerMode ? Math.ceil(currentSlide - siblings / 2) : currentSlide;
const upper = config.centerMode
? Math.floor(currentSlide + siblings / 2)
: Math.floor(currentSlide + siblings - 1);
return {
lower,
upper
};
},
trackTransform() {
const { infiniteScroll, vertical, rtl, centerMode } = this.config;
const direction = rtl ? -1 : 1;
const slideLength = vertical ? this.slideHeight : this.slideWidth;
const containerLength = vertical ? this.containerHeight : this.containerWidth;
const dragDelta = vertical ? this.delta.y : this.delta.x;
const clonesSpace = infiniteScroll ? slideLength * this.slidesCount : 0;
const centeringSpace = centerMode ? (containerLength - slideLength) / 2 : 0;
// calculate track translate
const translate = dragDelta + direction * (centeringSpace - clonesSpace - this.currentSlide * slideLength);
if (vertical) {
return `transform: translate(0, ${translate}px);`;
}
return `transform: translate(${translate}px, 0);`;
},
trackTransition() {
if (this.initialized && this.isSliding) {
return `transition: ${this.config.transition}ms`;
}
return '';
}
},
watch: {
group(val, oldVal) {
if (val === oldVal) {
return;
}
EMITTER.$off(`slideGroup:${oldVal}`, this._groupSlideHandler);
this.addGroupListeners();
},
autoPlay(val, oldVal) {
if (val === oldVal) {
return;
}
this.restartTimer();
}
},
methods: {
// controlling methods
slideTo(slideIndex, isSource = true) {
if (this.isSliding || slideIndex === this.currentSlide) {
return;
}
this.$emit('beforeSlide', {
currentSlide: this.currentSlide,
slideTo: index
});
const { infiniteScroll, transition } = this.config;
const previousSlide = this.currentSlide;
const index = infiniteScroll
? slideIndex
: getInRange(slideIndex, this.trimStart, this.slidesCount - this.trimEnd);
// Notify others if in a group and is the slide event initiator.
if (this.group && isSource) {
EMITTER.$emit(`slideGroup:${this.group}`, slideIndex);
}
this.currentSlide = index;
this.isSliding = true;
window.setTimeout(() => {
this.isSliding = false;
this.currentSlide = normalizeSlideIndex(index, this.slidesCount);
}, transition);
this.$emit('slide', {
currentSlide: this.currentSlide,
slideFrom: previousSlide
});
},
slideNext() {
this.slideTo(this.currentSlide + this.config.itemsToSlide);
},
slidePrev() {
this.slideTo(this.currentSlide - this.config.itemsToSlide);
},
initEvents() {
// get the element direction if not explicitly set
if (this.defaults.rtl === null) {
this.defaults.rtl = getComputedStyle(this.$el).direction === 'rtl';
}
if (this.$props.autoPlay) {
this.initAutoPlay();
}
if (this.config.mouseDrag) {
this.$refs.list.addEventListener('mousedown', this.onDragStart);
}
if (this.config.touchDrag) {
this.$refs.list.addEventListener('touchstart', this.onDragStart, {
passive: true
});
}
if (this.config.keysControl) {
this.$el.addEventListener('keydown', this.onKeypress);
}
if (this.config.wheelControl) {
this.lastScrollTime = now();
this.$el.addEventListener('wheel', this.onWheel, { passive: false });
}
window.addEventListener('resize', this.update);
},
getCurrentSlideTimeout() {
const curIdx = normalizeSlideIndex(this.currentSlide, this.slidesCount);
const children = normalizeChildren(this);
return children[curIdx].componentOptions.propsData.duration;
}, // switched to using a timeout which defaults to the prop set on this component, but can be overridden on a per slide basis.
initAutoPlay() {
this.timer = new Timer(() => {
if (
this.isSliding ||
this.isDragging ||
(this.isHover && this.config.hoverPause) ||
this.isFocus ||
!this.$props.autoPlay
) {
this.timer.set(this.getCurrentSlideTimeout());
return;
}
if (this.currentSlide === this.slidesCount - 1 && !this.config.infiniteScroll) {
this.slideTo(0);
this.timer.set(this.getCurrentSlideTimeout());
return;
}
this.slideNext();
this.timer.set(this.getCurrentSlideTimeout());
}, this.getCurrentSlideTimeout());
},
initDefaults() {
this.breakpoints = this.settings.breakpoints;
this.defaults = assign({}, this.$props, this.settings);
this.config = assign({}, this.defaults);
},
// updating methods
update() {
if (this.breakpoints) {
this.updateConfig();
}
this.updateWidth();
this.updateTrim();
this.$emit('updated', {
containerWidth: this.containerWidth,
containerHeight: this.containerHeight,
slideWidth: this.slideWidth,
slideHeight: this.slideHeight,
settings: this.config
});
},
updateTrim() {
const { trimWhiteSpace, itemsToShow, centerMode, infiniteScroll } = this.config;
if (!trimWhiteSpace || infiniteScroll) {
this.trimStart = 0;
this.trimEnd = 1;
return;
}
this.trimStart = centerMode ? Math.floor((itemsToShow - 1) / 2) : 0;
this.trimEnd = centerMode ? Math.ceil(itemsToShow / 2) : itemsToShow;
},
updateWidth() {
const rect = this.$el.getBoundingClientRect();
this.containerWidth = rect.width;
this.containerHeight = rect.height;
if (this.config.vertical) {
this.slideHeight = this.containerHeight / this.config.itemsToShow;
return;
}
this.slideWidth = this.containerWidth / this.config.itemsToShow;
},
updateConfig() {
const breakpoints = Object.keys(this.breakpoints).sort((a, b) => b - a);
let matched;
breakpoints.some(breakpoint => {
matched = window.matchMedia(`(min-width: ${breakpoint}px)`).matches;
if (matched) {
this.config = assign({}, this.config, this.defaults, this.breakpoints[breakpoint]);
return true;
}
});
if (!matched) {
this.config = assign(this.config, this.defaults);
}
},
restartTimer() {
this.$nextTick(() => {
if (this.timer === null && this.$props.autoPlay) {
this.initAutoPlay();
return;
}
if (this.timer) {
this.timer.stop();
if (this.$props.autoPlay) {
this.timer.set(this.getCurrentSlideTimeout());
this.timer.start();
}
}
});
},
restart() {
this.$nextTick(() => {
this.update();
});
},
// events handlers
onDragStart(event) {
this.isTouch = event.type === 'touchstart';
if (!this.isTouch && event.button !== 0) {
return;
}
this.startPosition = { x: 0, y: 0 };
this.endPosition = { x: 0, y: 0 };
this.isDragging = true;
this.startPosition.x = this.isTouch ? event.touches[0].clientX : event.clientX;
this.startPosition.y = this.isTouch ? event.touches[0].clientY : event.clientY;
document.addEventListener(this.isTouch ? 'touchmove' : 'mousemove', this.onDrag);
document.addEventListener(this.isTouch ? 'touchend' : 'mouseup', this.onDragEnd);
},
isInvalidDirection(deltaX, deltaY) {
if (!this.config.vertical) {
return Math.abs(deltaX) <= Math.abs(deltaY);
}
if (this.config.vertical) {
return Math.abs(deltaY) <= Math.abs(deltaX);
}
return false;
},
onDrag(event) {
if (this.isSliding) {
return;
}
this.endPosition.x = this.isTouch ? event.touches[0].clientX : event.clientX;
this.endPosition.y = this.isTouch ? event.touches[0].clientY : event.clientY;
const deltaX = this.endPosition.x - this.startPosition.x;
const deltaY = this.endPosition.y - this.startPosition.y;
// Maybe scrolling.
if (this.isInvalidDirection(deltaX, deltaY)) {
return;
}
this.delta.y = deltaY;
this.delta.x = deltaX;
if (!this.isTouch) {
event.preventDefault();
}
},
onDragEnd() {
const tolerance = this.config.shortDrag ? 0.5 : 0.15;
this.isDragging = false;
if (this.config.vertical) {
const draggedSlides = Math.round(Math.abs(this.delta.y / this.slideHeight) + tolerance);
this.slideTo(this.currentSlide - sign(this.delta.y) * draggedSlides);
}
if (!this.config.vertical) {
const direction = (this.config.rtl ? -1 : 1) * sign(this.delta.x);
const draggedSlides = Math.round(Math.abs(this.delta.x / this.slideWidth) + tolerance);
this.slideTo(this.currentSlide - direction * draggedSlides);
}
this.delta.x = 0;
this.delta.y = 0;
document.removeEventListener(this.isTouch ? 'touchmove' : 'mousemove', this.onDrag);
document.removeEventListener(this.isTouch ? 'touchend' : 'mouseup', this.onDragEnd);
this.restartTimer();
},
onTransitionend() {
this.isSliding = false;
this.$emit('afterSlide', {
currentSlide: this.currentSlide
});
},
onKeypress(event) {
const key = event.key;
if (key.startsWith('Arrow')) {
event.preventDefault();
}
if (this.config.vertical) {
if (key === 'ArrowUp') {
this.slidePrev();
}
if (key === 'ArrowDown') {
this.slideNext();
}
return;
}
if (this.config.rtl) {
if (key === 'ArrowRight') {
this.slidePrev();
}
if (key === 'ArrowLeft') {
this.slideNext();
}
return;
}
if (key === 'ArrowRight') {
this.slideNext();
}
if (key === 'ArrowLeft') {
this.slidePrev();
}
},
onWheel(event) {
event.preventDefault();
if (now() - this.lastScrollTime < 200) {
return;
}
// get wheel direction
this.lastScrollTime = now();
const value = event.wheelDelta || -event.deltaY;
const delta = sign(value);
if (delta === -1) {
this.slideNext();
}
if (delta === 1) {
this.slidePrev();
}
},
addGroupListeners() {
if (!this.group) {
return;
}
this._groupSlideHandler = slideIndex => {
// set the isSource to false to prevent infinite emitting loop.
this.slideTo(slideIndex, false);
};
EMITTER.$on(`slideGroup:${this.group}`, this._groupSlideHandler);
}
},
created() {
this.initDefaults();
},
mounted() {
this.initEvents();
this.addGroupListeners();
this.$nextTick(() => {
this.update();
this.slideTo(this.config.initialSlide || 0);
setTimeout(() => {
this.$emit('loaded');
this.initialized = true;
}, this.transition);
});
},
beforeDestroy() {
window.removeEventListener('resize', this.update);
if (this.group) {
EMITTER.$off(`slideGroup:${this.group}`, this._groupSlideHandler);
}
if (this.timer) {
this.timer.stop();
}
},
render(h) {
const body = renderBody.call(this, h);
return h(
'section',
{
class: {
hooper: true,
'is-vertical': this.config.vertical,
'is-rtl': this.config.rtl
},
attrs: {
tabindex: '0'
},
on: {
focusin: () => (this.isFocus = true),
focusout: () => (this.isFocus = false),
mouseover: () => (this.isHover = true),
mouseleave: () => (this.isHover = false)
}
},
body
);
}
};
/**
* Renders additional slides for infinite slides mode.
* By cloning Slides VNodes before and after either edges.
*/
function renderBufferSlides(h, slides) {
const before = [];
const after = [];
// reduce prop access
const slidesCount = slides.length;
for (let i = 0; i < slidesCount; i++) {
const slide = slides[i];
const clonedBefore = cloneNode(h, slide);
let slideIndex = i - slidesCount;
clonedBefore.data.key = `before_${i}`;
clonedBefore.key = clonedBefore.data.key;
clonedBefore.componentOptions.propsData.index = slideIndex;
clonedBefore.data.props = {
index: slideIndex,
isClone: true
};
before.push(clonedBefore);
const clonedAfter = cloneNode(h, slide);
slideIndex = i + slidesCount;
clonedAfter.data.key = `after_${slideIndex}`;
clonedAfter.componentOptions.propsData.index = slideIndex;
clonedAfter.key = clonedAfter.data.key;
clonedAfter.data.props = {
index: slideIndex,
isClone: true
};
after.push(clonedAfter);
}
return [...before, ...slides, ...after];
}
/**
* Produces the VNodes for the Slides.
* requires {this} to be bound to hooper.
* So use with .call or .bind
*/
function renderSlides(h) {
const children = normalizeChildren(this);
const childrenCount = children.length;
let idx = 0;
let slides = [];
for (let i = 0; i < childrenCount; i++) {
const child = children[i];
const ctor = child.componentOptions && child.componentOptions.Ctor;
if (!ctor || ctor.options.name !== 'HooperSlide') {
continue;
}
// give slide an index behind the scenes
child.componentOptions.propsData.index = idx;
child.data.key = idx;
child.key = idx;
child.data.props = {
...(child.data.props || {}),
isClone: false,
index: idx++
};
slides.push(child);
}
// update hooper's information of the slide count.
this.slidesCount = slides.length;
if (this.config.infiniteScroll) {
slides = renderBufferSlides(h, slides);
}
return h(
'ul',
{
class: {
'hooper-track': true,
'is-dragging': this.isDragging
},
style: this.trackTransform + this.trackTransition,
ref: 'track',
on: {
transitionend: this.onTransitionend
}
},
slides
);
}
/**
* Builds the VNodes for the hooper body.
* Which is the slides, addons if available, and a11y stuff.
* REQUIRES {this} to be bound to the hooper instance.
* use with .call or .bind
*/
function renderBody(h) {
const slides = renderSlides.call(this, h);
const addons = this.$slots['hooper-addons'] || [];
const a11y = h(
'div',
{
class: 'hooper-liveregion hooper-sr-only',
attrs: {
'aria-live': 'polite',
'aria-atomic': 'true'
}
},
`Item ${this.currentSlide + 1} of ${this.slidesCount}`
);
const children = [slides, ...addons, a11y];
return [
h(
'div',
{
class: 'hooper-list',
ref: 'list'
},
children
)
];
}