-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
carousel.js
1344 lines (1207 loc) · 41.7 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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2019 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ActionSource} from './action-source';
import {
Alignment,
Axis,
findOverlappingIndex,
getDimension,
getPercentageOffsetFromAlignment,
scrollContainerToElement,
setTransformTranslateStyle,
updateLengthStyle,
updateScrollPosition,
} from './dimensions.js';
import {AutoAdvance} from './auto-advance';
import {CarouselAccessibility} from './carousel-accessibility';
import {CarouselEvents} from './carousel-events';
import {backwardWrappingDistance, forwardWrappingDistance} from './array-util';
import {clamp, mod} from '../../../src/utils/math';
import {createCustomEvent, listen, listenOnce} from '../../../src/event-helper';
import {debounce} from '../../../src/utils/rate-limit';
import {dict} from '../../../src/utils/object';
import {
getStyle,
setImportantStyles,
setStyle,
setStyles,
} from '../../../src/style';
import {iterateCursor} from '../../../src/dom';
/**
* How long to wait prior to resetting the scrolling position after the last
* scroll event. Ideally this should be low, so that once the user stops
* scrolling, things are immediately centered again. Since there can be some
* delay between scroll events, and we do not want to move things during a
* scroll, it cannot be too small. 200ms seems to be around the lower limit for
* this value on Android / iOS.
*/
const RESET_SCROLL_REFERENCE_POINT_WAIT_MS = 200;
/**
* Runs a callback while disabling smooth scrolling by temporarily setting
* the `scrollBehavior` to `auto`.
* @param {!Element} el
* @param {Function} cb
*/
function runDisablingSmoothScroll(el, cb) {
const scrollBehavior = getStyle(el, 'scrollBehavior');
setStyle(el, 'scrollBehavior', 'auto');
cb();
setStyle(el, 'scrollBehavior', scrollBehavior);
}
/**
* @param {!Array<number>} arr
* @return {number}
*/
function sum(arr) {
return arr.reduce((p, c) => p + c, 0);
}
/**
* How the carousel works when looping:
*
* We want to make sure that the user can scroll all the way to the opposite
* end (either forwards or backwards) of the carousel, but no further (no
* looping back past where you started). We use spacer elements to adjust the
* scroll width of the scrolling area to allow the browser to scroll as well as
* providing targets for the browser to snap on. This is important as these
* targets need to be present before the scroll starts for things to work
* correctly.
*
* The spacers come in 3 types:
*
* - beforeSpacers: These provide scroll/snap before the first slide
* - replacementSpacers: These take up the spot of the slides as they are
* translated around
* - afterSpacers: These provide scroll/snap targets after the last slide
*
* The spacers are then hidden/shown depending on the reference point, called
* the restingIndex to allow full movement forwards and backwards. You can
* imagine this looks like the following if you have 5 slides:
*
* [r][r][r][r][r]
* [b][b][b][b][b][1][2][3][4][5][a][a][a][a][a]
*
* b = beforeSpacer, r = replacementSpacer, a = afterSpacer
*
* The replacement spacers are stacked on top of the slides.
* When the restingIndex is the first index, we should translate slides and
* hide the spacers as follows:
*
* [h][ ][ ][4][5][1][2][3][ ][ ][h][h][h][h][h]
*
* h = hidden
*
* This ensures that if you move left or right, there is a slide to show. Note
* that we have two empty slots at the start, where slides '2' and '3' will
* be moved as the user scrolls. Likewise, we have two slots at the end, where
* slides '4' and '5' will move. Since the other spacers are hidden, the
* browser cannot scroll into that area.
*
* When the user stops scrolling, we update the restingIndex and show/hide the
* appropriate spacers. For example, if the user started at slide '1' and moved
* left to slide '4', the UI would update to the following as they scrolled:
*
* [h][2][3][4][5][1][ ][ ][ ][ ][h][h][h][h][h]
*
* Once scrolling stopped, the reference point would be reset and this would
* update to:
*
* [h][h][h][h][ ][ ][2][3][4][5][1][ ][ ][h][h]
*
* Moving slides:
*
* Slides are moved around using `transform: translate` relative to their
* original resting spot. Slides are moved to be before or after the current
* slide as the user scrolls. Currently, half the slides are moved before and
* half the slides are moved after. This could be a bit smarter and only move
* as many as are necessary to have a sufficient amount of buffer. When slides
* are moved, they are positioned on top of an existing spacer.
*
* Initial index:
*
* The initial index can be specified, which will make the carousel scroll to
* the desired index when it first renders. Since the layout of the slides is
* asynchronous, this should be used instead of calling `goToSlide` after
* creating the carousel.
*/
export class Carousel {
/**
* @param {{
* win: !Window,
* element: !Element,
* scrollContainer: !Element,
* runMutate: function(function()),
* }} config
*/
constructor(config) {
const {win, element, scrollContainer, runMutate} = config;
/** @private @const */
this.win_ = win;
/** @private @const */
this.runMutate_ = runMutate;
/** @private @const */
this.element_ = element;
/** @private @const */
this.scrollContainer_ = scrollContainer;
/** @private @const */
this.autoAdvance_ = new AutoAdvance({
win,
element,
scrollContainer,
advanceable: this,
});
/** @private @const */
this.carouselAccessibility_ = new CarouselAccessibility({
win,
element,
scrollContainer,
runMutate,
stoppable: this.autoAdvance_,
});
/** @private @const */
this.debouncedResetScrollReferencePoint_ = debounce(
win,
() => this.resetScrollReferencePoint_(),
RESET_SCROLL_REFERENCE_POINT_WAIT_MS
);
/** @private {number} */
this.advanceCount_ = 1;
/** @private {number} */
this.autoAdvanceLoops_ = Number.POSITIVE_INFINITY;
/** @private {boolean} */
this.mixedLength_ = false;
/** @private {!Array<!Element>} */
this.slides_ = [];
/** @private {boolean} */
this.userScrollable_ = true;
/** @private {boolean} */
this.updating_ = false;
/**@private {!Array<!Element>} */
this.beforeSpacers_ = [];
/** @private {!Array<!Element>} */
this.replacementSpacers_ = [];
/** @private {!Array<!Element>} */
this.afterSpacers_ = [];
/** @protected {!Array<!Element>} */
this.allSpacers_ = [];
/**
* @private {boolean}
*/
this.layoutPaused_ = false;
/**
* Set from sources of programmatic scrolls to avoid doing work associated
* with regular scrolling.
* @private {boolean}
*/
this.ignoreNextScroll_ = false;
/**
* The offset for the current element, based on the alignment and axis. This
* is a percentage of the Element's length along the current axis. This is
* used to preserve relative scroll position when updating the UI after
* things have moved (e.g. on rotate).
* @private {number}
*/
this.currentElementOffset_ = 0;
/**
* Keeps track of an index that was requested to be scrolled to
* programmatically. This is used to make sure that the carousel ends on
* the right slide if a UI update was requested during a programmatic
* scroll. This is cleared when the user manually scrolls.
* @private {number?}
*/
this.requestedIndex_ = null;
/**
* The reference index where the the scrollable area last stopped
* scrolling. This slide is not translated and other slides are translated
* to move before or after as needed. This is also used when looping to
* prevent a single swipe from wrapping past the starting point.
* @private {number}
*/
this.restingIndex_ = NaN;
/**
* Whether or not the user is currently touching the scrollable area. This
* is used to avoid resetting the resting point while the user is touching
* (e.g. they have dragged part way to the next slide, but have not yet
* released their finger).
* @private {boolean}
*/
this.touching_ = false;
/**
* Whether or not there is a scroll in progress. This is tracked from the
* first scroll event, until RESET_SCROLL_REFERENCE_POINT_WAIT_MS after the
* last scroll event is received. This is used to prevent programmatic
* scroll requests while a scroll is in progress.
* @private {boolean}
*/
this.scrolling_ = false;
/**
* Tracks the source of what cause the carousel to change index. This can
* be provided when moving the carousel programmatically, and the value
* will be propagated.
* @private {!ActionSource|undefined}
*/
this.actionSource_ = undefined;
/** @private {!Alignment} */
this.alignment_ = Alignment.START;
/** @private {!Axis} */
this.axis_ = Axis.X;
/**
* Whether slides are laid out in the forwards or reverse direction. When
* using rtl (right to left), this should be false. This is used to set the
* transforms for slides and spacers correctly when the flex direction is
* reversed due to a rtl direction. TODO(sparhami) is there some way we
* could get this to work without needing to be explicitly told what the
* direction is?
* @private {boolean}
*/
this.forwards_ = true;
/** @private {boolean} */
this.hideScrollbar_ = true;
/**
* TODO(sparhami) Rename this to `activeIndex`. We do not want to expose
* this as it changes, only when the user stops scrolling. Also change
* restingIndex to currentIndex.
* @private {number}
*/
this.currentIndex_ = 0;
/**
* Whether or not looping is requested. Do not use directly, but rather use
* `isLooping` instead.
* @private {boolean}
*/
this.loop_ = false;
/** @private {boolean} */
this.snap_ = true;
/** @private {number} */
this.snapBy_ = 1;
/** @private {number} */
this.visibleCount_ = 1;
this.scrollContainer_.addEventListener(
'scroll',
() => this.handleScroll_(),
true
);
this.scrollContainer_.addEventListener(
'scrollend',
() => this.handleScrollEnd_(),
true
);
listen(
this.scrollContainer_,
'touchstart',
() => this.handleTouchStart_(),
{capture: true, passive: true}
);
listen(this.scrollContainer_, 'wheel', () => this.handleWheel_(), {
capture: true,
passive: true,
});
}
/**
* Moves forward by the current advance count.
* @param {!ActionSource=} actionSource
*/
next(actionSource) {
this.advance(this.advanceCount_, {actionSource});
}
/**
* Moves backwards by the current advance count.
* @param {!ActionSource=} actionSource
*/
prev(actionSource) {
this.advance(-this.advanceCount_, {actionSource});
}
/**
* Moves the current index forward/backwards by a given delta and scrolls
* the new index into view. There are a few cases where this behaves
* differently than might be expected when not looping:
*
* 1. The current index is in the last group, then the new index will be the
* zeroth index. For example, say you have four slides, 'a', 'b', 'c' and 'd',
* you are showing two at a time, start aligning slides and are advancing one
* slide at a time. If you are on slide 'c', advancing will move back to 'a'
* instead of moving to 'd', which would cause no scrolling since 'd' is
* already visible and cannot start align itself.
* 2. The delta would go past the start or the end and the the current index
* is not at the start or end, then the advancement is capped to the start
* or end respectively.
* 3. The delta would go past the start or the end and the current index is
* at the start or end, then the next index will be the opposite end of the
* carousel.
*
* TODO(sparhami) How can we make this work well for accessibility?
* @param {number} delta
* @param {{
* actionSource: (!ActionSource|undefined),
* allowWrap: (boolean|undefined),
* }=} options
*/
advance(delta, options = {}) {
const {slides_, currentIndex_, requestedIndex_} = this;
const {actionSource, allowWrap = false} = options;
// If we have a requested index, use that as the reference point. The
// current index may not be updated yet.This allows calling `advance`
// multiple times in a row and ending on the correct slide.
const index = requestedIndex_ !== null ? requestedIndex_ : currentIndex_;
const newIndex = index + delta;
const endIndex = slides_.length - 1;
const atStart = index === 0;
const atEnd = index === endIndex;
const passingStart = newIndex < 0;
const passingEnd = newIndex > endIndex;
let slideIndex;
if (this.isLooping()) {
slideIndex = mod(newIndex, endIndex + 1);
} else if (!allowWrap) {
slideIndex = clamp(newIndex, 0, endIndex);
} else if (
delta > 0 &&
this.inLastWindow_(index) &&
this.inLastWindow_(newIndex)
) {
slideIndex = 0;
} else if ((passingStart && atStart) || (passingEnd && !atEnd)) {
slideIndex = endIndex;
} else if ((passingStart && !atStart) || (passingEnd && atEnd)) {
slideIndex = 0;
} else {
slideIndex = newIndex;
}
this.goToSlide(slideIndex, {actionSource});
}
/**
* Pauses the layout temporarily. This can be resumed by calling
* `resumseLayout`.
*/
pauseLayout() {
this.layoutPaused_ = true;
this.autoAdvance_.pause();
}
/**
* Resumes layout of the component. This will update the UI to the correct
* state if there were changes since pausing layout.
*/
resumeLayout() {
this.layoutPaused_ = false;
this.updateUi();
this.autoAdvance_.resume();
}
/**
* @return {number} The current index of the carousel.
*/
getCurrentIndex() {
return this.currentIndex_;
}
/**
* @return {number} The number of items visible at a time.
*/
getVisibleCount() {
return this.visibleCount_;
}
/**
* Checks whether or not looping is enabled. This requires that looping is
* configured and that there are enough slides to do looping.
* @return {boolean} Whether or not looping is enabled.
*/
isLooping() {
return this.loop_ && this.slides_.length / this.visibleCount_ >= 3;
}
/**
* Moves the carousel to a given index. If the index is out of range, the
* carousel is not moved.
* @param {number} index
* @param {{
* smoothScroll: (boolean|undefined),
* actionSource: (!ActionSource|undefined),
* }=} options
*/
goToSlide(index, options = {}) {
const {smoothScroll = true, actionSource} = options;
if (index < 0 || index > this.slides_.length - 1 || isNaN(index)) {
return;
}
if (index === this.currentIndex_) {
return;
}
// If the user is interacting with the carousel, either by touching or by
// a momentum scroll, ignore programmatic requests as the user's
// interaction is much more important.
if (this.touching_ || this.isUserScrolling_()) {
return;
}
this.ignoreNextScroll_ = false;
this.requestedIndex_ = index;
this.actionSource_ = actionSource;
this.scrollSlideIntoView_(this.slides_[index], {smoothScroll});
}
/**
* @param {number} advanceCount How many slides to advance by. This is the
* number of slides moved forwards/backwards when calling prev/next.
*/
updateAdvanceCount(advanceCount) {
this.advanceCount_ = advanceCount;
}
/**
* @param {string} alignment How to align slides when snapping or scrolling
* to the propgramatticaly (auto advance or next/prev). This should be
* either "start" or "cemter".
*/
updateAlignment(alignment) {
this.alignment_ =
alignment === 'start' ? Alignment.START : Alignment.CENTER;
this.updateUi();
}
/**
* @param {boolean} autoAdvance Whether or not to autoadvance. Changing this
* will start or stop autoadvance.
*/
updateAutoAdvance(autoAdvance) {
this.autoAdvance_.updateAutoAdvance(autoAdvance);
}
/**
* @param {number} autoAdvanceCount How many items to advance by. A positive
* number advances forwards, a negative number advances backwards.
*/
updateAutoAdvanceCount(autoAdvanceCount) {
this.autoAdvance_.updateAutoAdvanceCount(autoAdvanceCount);
}
/**
* @param {number} autoAdvanceInterval How much time between auto advances.
* This time starts counting from when scrolling has stopped.
*/
updateAutoAdvanceInterval(autoAdvanceInterval) {
this.autoAdvance_.updateAutoAdvanceInterval(autoAdvanceInterval);
}
/**
* @param {number} autoAdvanceLoops The number of loops through the carousel
* that should be autoadvanced before stopping. This defaults to infinite
* loops.
*/
updateAutoAdvanceLoops(autoAdvanceLoops) {
this.autoAdvanceLoops_ = autoAdvanceLoops;
this.updateUi();
}
/**
* @param {boolean} forwards Whether or not the advancement direction is
* forwards (e.g. ltr) or reverse (e.g. rtl).
*/
updateForwards(forwards) {
this.forwards_ = forwards;
this.updateUi();
}
/**
* @param {boolean} hideScrollbar Whether or not the scrollbar should be
* hidden.
*/
updateHideScrollbar(hideScrollbar) {
this.hideScrollbar_ = hideScrollbar;
this.updateUi();
}
/**
* @param {boolean} horizontal Whether the scrollable should lay out
* horizontally or vertically.
*/
updateHorizontal(horizontal) {
this.axis_ = horizontal ? Axis.X : Axis.Y;
this.updateUi();
}
/**
* @param {boolean} loop Whether or not the scrollable should loop when
* reaching the last slide.
*/
updateLoop(loop) {
this.loop_ = loop;
this.updateUi();
}
/**
* @param {boolean} mixedLength Whether the slides used mixed lengths or they
* should be have a length assigned in accordance to the visible count.
*/
updateMixedLength(mixedLength) {
this.mixedLength_ = mixedLength;
this.carouselAccessibility_.updateMixedLength(mixedLength);
this.updateUi();
}
/**
* Lets the scrollable know that the slides have changed. This is needed for
* various internal calculations.
* @param {!Array<!Element>} slides
*/
updateSlides(slides) {
this.slides_ = slides;
this.carouselAccessibility_.updateSlides(slides);
// TODO(sparhami) Should need to call `this.updateUi()` here.
}
/**
* @param {boolean} snap Whether or not to snap.
*/
updateSnap(snap) {
this.snap_ = snap;
this.updateUi();
}
/**
* @param {number} snapBy Snaps on every nth slide, including the zeroth
* slide.
*/
updateSnapBy(snapBy) {
this.snapBy_ = Math.max(1, snapBy);
this.updateUi();
}
/**
*
* @param {boolean} userScrollable Whether or not the carousel can be
* scrolled (e.g. via touch). If false, then the carousel can only be
* advanced via next, prev, goToSlide or autoAdvance.
*/
updateUserScrollable(userScrollable) {
this.userScrollable_ = userScrollable;
this.updateUi();
}
/**
* Updates the UI of the carousel. Since screen rotation can change scroll
* position, this should be called to restore the scroll position (i.e. which
* slide is at the start / center of the scrollable, depending on alignment).
*/
updateUi() {
if (this.updating_ || this.layoutPaused_) {
return;
}
this.updating_ = true;
this.runMutate_(() => {
this.updating_ = false;
this.scrollContainer_.setAttribute('mixed-length', this.mixedLength_);
this.scrollContainer_.setAttribute(
'user-scrollable',
this.userScrollable_
);
this.scrollContainer_.setAttribute('hide-scrollbar', this.hideScrollbar_);
this.scrollContainer_.setAttribute('horizontal', this.axis_ === Axis.X);
this.scrollContainer_.setAttribute('loop', this.isLooping());
this.scrollContainer_.setAttribute('snap', this.snap_);
// TODO(sparhami) Do not use CSS custom property
setImportantStyles(this.scrollContainer_, {
'--visible-count': this.visibleCount_,
});
if (!this.slides_.length) {
return;
}
this.autoAdvance_.updateMaxAdvances(
this.autoAdvanceLoops_ * this.slides_.length - 1
);
this.updateSpacers_();
this.setChildrenSnapAlign_();
this.hideSpacersAndSlides_();
this.resetScrollReferencePoint_(/* force */ true);
});
}
/**
* @param {number} visibleCount How many slides to show at a time within the
* scrollable. This option is ignored if mixed lengths is set.
*/
updateVisibleCount(visibleCount) {
this.visibleCount_ = Math.max(1, visibleCount);
this.carouselAccessibility_.updateVisibleCount(visibleCount);
this.updateUi();
}
/**
* Updates the resting index as well as firing an event, if it actually
* changed.
* @param {number} restingIndex The new resting index.
* @param {ActionSource=} actionSource The actionSource associated with this
* change.
* @private
*/
updateRestingIndex_(restingIndex, actionSource) {
if (this.restingIndex_ === restingIndex) {
return;
}
this.restingIndex_ = restingIndex;
this.element_.dispatchEvent(
createCustomEvent(
this.win_,
CarouselEvents.INDEX_CHANGE,
dict({
'index': restingIndex,
'total': this.slides_.length,
'actionSource': actionSource,
'slides': this.slides_,
}),
{
bubbles: true,
}
)
);
}
/**
* Updates the current offset within the current Element as well as firing an
* event.
* @param {number} index The index of the Element.
* @param {number} offset The offset, as a percentage of the Element's width.
*/
updateCurrentElementOffset_(index, offset) {
this.currentIndex_ = index;
this.currentElementOffset_ = offset;
this.element_.dispatchEvent(
createCustomEvent(
this.win_,
CarouselEvents.OFFSET_CHANGE,
dict({
'index': index,
'total': this.slides_.length,
'offset': this.forwards_ ? -offset : offset,
'slides': this.slides_,
}),
{
bubbles: true,
}
)
);
}
/**
* Fires an event when the scroll position has changed, once scrolling has
* settled. In some situations, the index may not change, but you still want
* to react to the scroll position changing.
*/
notifyScrollStart() {
this.element_.dispatchEvent(
createCustomEvent(this.win_, CarouselEvents.SCROLL_START, null)
);
}
/**
* Fires an event when the scroll position has changed, once scrolling has
* settled. In some situations, the index may not change, but you still want
* to react to the scroll position changing.
*/
notifyScrollPositionChanged_() {
this.element_.dispatchEvent(
createCustomEvent(this.win_, CarouselEvents.SCROLL_POSITION_CHANGED, null)
);
}
/**
* Handles a touch start, preventing `resetScrollReferencePoint_` from
* running until the user stops touching.
* @private
*/
handleTouchStart_() {
this.touching_ = true;
this.actionSource_ = ActionSource.TOUCH;
this.requestedIndex_ = null;
this.ignoreNextScroll_ = false;
listenOnce(
window,
'touchend',
() => {
this.touching_ = false;
this.debouncedResetScrollReferencePoint_();
},
{
capture: true,
passive: true,
}
);
}
/**
* Handles a wheel event.
* @private
*/
handleWheel_() {
this.actionSource_ = ActionSource.WHEEL;
this.requestedIndex_ = null;
this.ignoreNextScroll_ = false;
}
/**
* Handles a scroll event, updating the the current index as well as moving
* slides around as needed.
* @private
*/
handleScroll_() {
if (this.ignoreNextScroll_) {
this.ignoreNextScroll_ = false;
return;
}
this.scrolling_ = true;
this.updateCurrent_();
this.notifyScrollStart();
this.debouncedResetScrollReferencePoint_();
}
/**
* For browsers that support the scrollend event, reset the reference point
* immediately. This prevents users from hitting the wrapping point while
* scrolling continually.
*/
handleScrollEnd_() {
// For now, do not handle scrollend when requestedIndex_ is set (e.g.
// from a call to advance, via arrow buttons). This is because updating
// the scroll position causes a scrollend, so if you advance while a
// smooth scroll is in progress, the resetScrollReferencePoint_ would cause
// it to jump to the final slide.
// The scrollend is likely triggered due to what causes
// https://bugs.chromium.org/p/chromium/issues/detail?id=1018842, though it
// is unclear if this will ever be changed.
// TODO(https://bugs.chromium.org/p/chromium/issues/detail?id=1018842):
// Remove this if/when scrollend stops firing when adjusting the scroll
// position. We will want to make sure that this works if/when Safari
// impelemnts scrollend as well.
if (this.requestedIndex_ !== null) {
return;
}
this.resetScrollReferencePoint_();
}
/**
* @return {boolean} Whether or not the user is scrolling. For example, the
* user flicked the carousel and there is a momentum scroll in progress.
*/
isUserScrolling_() {
return (
this.scrolling_ &&
(this.actionSource_ === ActionSource.TOUCH ||
this.actionSource_ === ActionSource.WHEEL)
);
}
/**
* @param {!Element} el The slide or spacer to move.
* @param {number} revolutions How many revolutions forwards (or backwards)
* the slide or spacer should move.
* @param {number} revolutionLength The length of a single revolution around
* the scrollable area.
* @private
*/
setElementTransform_(el, revolutions, revolutionLength) {
const dir = this.forwards_ ? 1 : -1;
const delta = revolutions * revolutionLength * dir;
setTransformTranslateStyle(this.axis_, el, delta);
el._revolutions = revolutions;
}
/**
* Resets the transforms for all the slides, putting them back in their
* natural position.
* @param {number} totalLength The total length of all the slides.
* @private
*/
resetSlideTransforms_(totalLength) {
const revolutions = 0; // Sets the slide back to the initial position.
this.slides_.forEach((slide) => {
this.setElementTransform_(slide, revolutions, totalLength);
});
}
/**
* @return {!Array<number>}} An array of the lengths of the slides.
* @private
*/
getSlideLengths_() {
return this.slides_.map((s) => getDimension(this.axis_, s).length);
}
/**
* @return {boolean} True if the carousel is not looping, and is at the
* start, false otherwise.
*/
isAtEnd() {
if (this.isLooping()) {
return false;
}
return this.forwards_
? this.isScrollAtRightEdge()
: this.isScrollAtLeftEdge();
}
/**
* @return {boolean} True if the carousel is not looping, and is at the
* end, false otherwise.
*/
isAtStart() {
if (this.isLooping()) {
return false;
}
return this.forwards_
? this.isScrollAtLeftEdge()
: this.isScrollAtRightEdge();
}
/**
* @return {boolean} True if the scrolling is at the right edge of the
* carousel. Note that this ignores RTL, and only checks for the right
* edge.
*/
isScrollAtRightEdge() {
const el = this.scrollContainer_;
const {width} = el./*OK*/ getBoundingClientRect();
return el./*OK*/ scrollLeft + Math.ceil(width) >= el./*OK*/ scrollWidth;
}
/**
* @return {boolean} True if the scrolling is at the left edge of the
* carousel. Note that this ignores RTL, and only checks for the left
* edge.
*/
isScrollAtLeftEdge() {
return this.scrollContainer_./*OK*/ scrollLeft <= 0;
}
/**
* @param {number} count The number of spacers to create
* @return {!Array<!Element>} An array of spacers.
* @private
*/
createSpacers_(count) {
const spacers = [];
for (let i = 0; i < count; i++) {
const spacer = document.createElement('div');
spacer.className = 'i-amphtml-carousel-spacer';
spacers.push(spacer);
}
return spacers;
}
/**
* Updates the spacers, removing the old ones and creating new ones.
* @private
*/
updateSpacers_() {
const {axis_, slides_} = this;
const slideLengths = this.getSlideLengths_();
const totalLength = sum(slideLengths);
const count = this.isLooping() ? slides_.length : 0;
// Replace the before spacers.
this.beforeSpacers_.forEach((spacer) => {
this.scrollContainer_.removeChild(spacer);
});
this.beforeSpacers_ = this.createSpacers_(count);
this.beforeSpacers_.forEach((spacer, i) => {
updateLengthStyle(axis_, spacer, slideLengths[i]);
this.scrollContainer_.insertBefore(spacer, slides_[0]);
});
// Replace the replacement spacers.
this.replacementSpacers_.forEach((spacer) => {
this.scrollContainer_.removeChild(spacer);
});
this.replacementSpacers_ = this.createSpacers_(count);
this.replacementSpacers_.forEach((spacer, i) => {
updateLengthStyle(axis_, spacer, slideLengths[i]);
// Translate these 1 revolution up, so they end up on top of the slides.
this.setElementTransform_(spacer, -1, totalLength);
this.scrollContainer_.appendChild(spacer);
});
// Replace the after spacers.
this.afterSpacers_.forEach((spacer) => {
this.scrollContainer_.removeChild(spacer);
});
this.afterSpacers_ = this.createSpacers_(count);
this.afterSpacers_.forEach((spacer, i) => {
updateLengthStyle(axis_, spacer, slideLengths[i]);
// Translate these 1 revolution up, so they end up right after the