-
Notifications
You must be signed in to change notification settings - Fork 77
/
slideshow.component.ts
629 lines (564 loc) · 19.7 KB
/
slideshow.component.ts
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
import { Component, ElementRef, EventEmitter, Inject, Input, Output, PLATFORM_ID, Renderer2, ViewChild, DoCheck, NgZone, OnInit, OnDestroy, ChangeDetectionStrategy, ChangeDetectorRef, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';
// import { SwipeService } from './swipe.service';
import { isPlatformServer, DOCUMENT } from '@angular/common';
import { ISlide } from './ISlide';
import { IImage } from './IImage';
import { DomSanitizer, TransferState, makeStateKey, SafeStyle } from '@angular/platform-browser';
import { PointerService } from './pointer.service';
import { Subscription } from 'rxjs';
const FIRST_SLIDE_KEY = makeStateKey<any>('firstSlide');
@Component({
selector: 'slideshow',
templateUrl: './slideshow.component.html',
styleUrls: ['./slideshow.component.scss'],
providers: [PointerService],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SlideshowComponent implements OnInit, AfterViewInit, DoCheck, OnChanges, OnDestroy {
slideIndex: number = -1;
slides: ISlide[] = [];
hideLeftArrow: boolean = false;
hideRightArrow: boolean = false;
private _urlCache: (string | IImage)[];
private _autoplayIntervalId: any;
private _initial: boolean = true;
private _isHidden: boolean = false;
private _slideSub: Subscription;
private _clickSub: Subscription;
@Input() imageUrls: (string | IImage)[] = [];
@Input() height: string = '100%';
@Input() minHeight: string;
@Input() arrowSize: string;
@Input() showArrows: boolean = true;
@Input() disableSwiping: boolean = false;
@Input() autoPlay: boolean = false;
@Input() autoPlayInterval: number = 3333;
@Input() stopAutoPlayOnSlide: boolean = true;
@Input() autoPlayWaitForLazyLoad: boolean = true;
@Input() debug: boolean;
@Input() backgroundSize: string = 'cover';
@Input() backgroundPosition: string = 'center center';
@Input() backgroundRepeat: string = 'no-repeat';
@Input() showDots: boolean = false;
@Input() dotColor: string = '#FFF';
@Input() showCaptions: boolean = true;
@Input() captionColor: string = '#FFF';
@Input() captionBackground: string = 'rgba(0, 0, 0, .35)';
@Input() lazyLoad: boolean = false;
@Input() hideOnNoSlides: boolean = false;
@Input() fullscreen: boolean = false;
@Input() enableZoom: boolean = false;
@Input() enablePan: boolean = false;
@Input() noLoop: boolean = false;
@Output() onSlideLeft = new EventEmitter<number>();
@Output() onSlideRight = new EventEmitter<number>();
@Output() onSwipeLeft = new EventEmitter<number>();
@Output() onSwipeRight = new EventEmitter<number>();
@Output() onFullscreenExit = new EventEmitter<boolean>();
@Output() onIndexChanged = new EventEmitter<number>();
@Output() onImageLazyLoad = new EventEmitter<ISlide>();
@Output() onClick = new EventEmitter<{ slide: ISlide, index: number }>();
@ViewChild('container') container: ElementRef;
@ViewChild('prevArrow') prevArrow: ElementRef;
@ViewChild('nextArrow') nextArrow: ElementRef;
get safeStyleDotColor(): SafeStyle {
return this.sanitizer.bypassSecurityTrustStyle(`--dot-color: ${ this.dotColor }`);
}
constructor(
private _pointerService: PointerService,
private _renderer: Renderer2,
private _transferState: TransferState,
private _ngZone: NgZone,
private _cdRef: ChangeDetectorRef,
public sanitizer: DomSanitizer,
@Inject(PLATFORM_ID) private platform_id: any,
@Inject(DOCUMENT) private document: any
) { }
ngOnInit() {
if (this.debug !== undefined) {
console.warn('[Deprecation Warning]: The debug input will be removed from ng-simple-slideshow in 1.3.0');
}
this._slideSub = this._pointerService.slideEvent.subscribe((indexDirection: number) => {
this.onSlide(indexDirection, true);
});
this._clickSub = this._pointerService.clickEvent.subscribe(() => {
this._onClick();
});
if (this.noLoop) {
this.hideLeftArrow = true;
}
}
ngAfterViewInit(): void {
this._pointerService.bind(this.container);
}
ngOnDestroy() {
try {
if (this._slideSub && !this._slideSub.closed) {
this._slideSub.unsubscribe();
}
}
catch (error) {
console.warn('Slide Subscription error caught in ng-simple-slideshow OnDestroy:', error);
}
try {
if (this._clickSub && !this._clickSub.closed) {
this._clickSub.unsubscribe();
}
}
catch (error) {
console.warn('Click Subscription error caught in ng-simple-slideshow OnDestroy:', error);
}
try {
this._pointerService.unbind(this.container);
}
catch (error) {
console.warn('Pointer Service unbind error caught in ng-simple-slideshow OnDestroy:', error);
}
try {
if (this._autoplayIntervalId) {
this._ngZone.runOutsideAngular(() => clearInterval(this._autoplayIntervalId));
this._autoplayIntervalId = null;
}
}
catch (error) {
console.warn('Autoplay cancel error caught in ng-simple-slideshow OnDestroy:', error);
}
}
ngOnChanges(changes: SimpleChanges) {
if (changes['noLoop']) {
if (changes['noLoop'].currentValue) {
this.hideLeftArrow = this.slideIndex <= 0;
this.hideRightArrow = this.slideIndex === this.slides.length - 1;
}
else {
this.hideLeftArrow = false;
this.hideRightArrow = false;
}
this._cdRef.detectChanges();
}
}
ngDoCheck() {
// if this is the first being called, create a copy of the input
if (this.imageUrls && this.imageUrls.length > 0) {
if (this._initial === true) {
this._urlCache = Array.from(this.imageUrls);
}
if (this._isHidden === true) {
this._renderer.removeStyle(this.container.nativeElement, 'display');
this._isHidden = false;
}
this.setSlides();
}
else if (this.hideOnNoSlides === true) {
this._renderer.setStyle(this.container.nativeElement, 'display', 'none');
this._isHidden = true;
}
this.setStyles();
this.handleAutoPlay();
this._pointerService.disableSwiping = this.disableSwiping;
this._pointerService.enableZoom = this.enableZoom;
this._pointerService.enablePan = this.enablePan;
}
/**
* @param {number} indexDirection
* @param {boolean} isSwipe
* @description this is the function that should be called to make the slides change.
* indexDirection to move back is -1, to move forward is 1, and to stay in place is 0.
* 0 is taken into account for failed swipes
*/
onSlide(indexDirection: number, isSwipe?: boolean): void {
this.handleAutoPlay(this.stopAutoPlayOnSlide);
this.slide(indexDirection, isSwipe);
}
// /**
// * @param {TouchEvent} e
// * @param {string} when
// * @description Use the swipe service to detect swipe events from phone and tablets
// */
// onSwipe(e: TouchEvent, when: string): void {
// if (this.disableSwiping === true) {
// return;
// }
// const indexDirection = this._swipeService.swipe(e, when);
// // handle a failed swipe
// if (indexDirection === 0) {
// return;
// }
// else {
// this.onSlide(indexDirection, true);
// }
// }
/**
* @description Redirect to current slide "href" if defined
*/
private _onClick(): void {
const currentSlide = this.slides.length > 0 && this.slides[this.slideIndex];
this.onClick.emit({ slide: currentSlide, index: this.slideIndex });
if (currentSlide && currentSlide.image.clickAction) {
currentSlide.image.clickAction();
}
else if (currentSlide && currentSlide.image.href) {
this.document.location.href = currentSlide.image.href;
}
}
/**
* @param {number} index
* @description set the index to the desired index - 1 and simulate a right slide
*/
goToSlide(index: number) {
const beforeClickIndex = this.slideIndex;
this.slideIndex = index - 1;
this.setSlideIndex(1);
if (this.slides[this.slideIndex] && !this.slides[this.slideIndex].loaded) {
this.loadRemainingSlides();
}
this.handleAutoPlay(this.stopAutoPlayOnSlide);
this.slideRight(beforeClickIndex);
this.slides[beforeClickIndex].selected = false;
this.slides[this.slideIndex].selected = true;
this._cdRef.detectChanges();
}
/**
* @param {number} index
* @description set the index to the desired index - 1 and simulate a right slide
*/
getSlideStyle(index: number) {
const slide = this.slides[index];
if (slide && slide.loaded) {
return {
"background-image": 'url(' + slide.image.url + ')',
"background-size": slide.image.backgroundSize || this.backgroundSize,
"background-position": slide.image.backgroundPosition || this.backgroundPosition,
"background-repeat": slide.image.backgroundRepeat || this.backgroundRepeat
};
}
else {
// doesn't compile correctly if returning an empty object, sooooo.....
return {
"background-image": undefined,
"background-size": undefined,
"background-position": undefined,
"background-repeat": undefined
};
}
}
exitFullScreen(e: Event) {
e.preventDefault();
this.fullscreen = false;
this.onFullscreenExit.emit(true);
}
/**
* @param {number} indexDirection
* @param {boolean} isSwipe
* @description Set the new slide index, then make the transition happen.
*/
private slide(indexDirection: number, isSwipe?: boolean): void {
const oldIndex = this.slideIndex;
if (this.setSlideIndex(indexDirection)) {
if (this.slides[this.slideIndex] && !this.slides[this.slideIndex].loaded) {
this.loadRemainingSlides();
}
if (indexDirection === 1) {
this.slideRight(oldIndex, isSwipe);
}
else {
this.slideLeft(oldIndex, isSwipe);
}
this.slides[oldIndex].selected = false;
this.slides[this.slideIndex].selected = true;
}
this._cdRef.detectChanges();
}
/**
* @param {number} indexDirection
* @description This is just treating the url array like a circular list.
*/
private setSlideIndex(indexDirection: number): boolean {
let willChange = true;
this.slideIndex += indexDirection;
if (this.noLoop) {
this.hideRightArrow = this.slideIndex === this.slides.length - 1;
this.hideLeftArrow = false;
}
if (this.slideIndex < 0) {
if (this.noLoop) {
this.slideIndex -= indexDirection;
willChange = false;
this.hideLeftArrow = true;
}
else {
this.slideIndex = this.slides.length - 1;
}
}
else if (this.slideIndex >= this.slides.length) {
if (this.noLoop) {
this.slideIndex -= indexDirection;
willChange = false;
this.hideRightArrow = true;
}
else {
this.slideIndex = 0;
}
}
if (willChange) {
this.onIndexChanged.emit(this.slideIndex);
}
return willChange;
}
/**
* @param {number} oldIndex
* @param {boolean} isSwipe
* @description This function handles the variables to move the CSS classes around accordingly.
* In order to correctly handle animations, the new slide as well as the slides to
* the left and right are assigned classes.
*/
private slideLeft(oldIndex: number, isSwipe?: boolean): void {
if (isSwipe === true) {
this.onSwipeLeft.emit(this.slideIndex);
}
else {
this.onSlideLeft.emit(this.slideIndex);
}
this.slides[this.getLeftSideIndex(oldIndex)].leftSide = false;
this.slides[oldIndex].leftSide = true;
this.slides[oldIndex].action = 'slideOutLeft';
this.slides[this.slideIndex].rightSide = false;
this.slides[this.getRightSideIndex()].rightSide = true;
this.slides[this.slideIndex].action = 'slideInRight';
}
/**
* @param {number} oldIndex
* @param {boolean} isSwipe
* @description This function handles the variables to move the CSS classes around accordingly.
* In order to correctly handle animations, the new slide as well as the slides to
* the left and right are assigned classes.
*/
private slideRight(oldIndex: number, isSwipe?: boolean): void {
if (isSwipe === true) {
this.onSwipeRight.emit(this.slideIndex);
}
else {
this.onSlideRight.emit(this.slideIndex);
}
this.slides[this.getRightSideIndex(oldIndex)].rightSide = false;
this.slides[oldIndex].rightSide = true;
this.slides[oldIndex].action = 'slideOutRight';
this.slides[this.slideIndex].leftSide = false;
this.slides[this.getLeftSideIndex()].leftSide = true;
this.slides[this.slideIndex].action = 'slideInLeft';
}
/**
* @description Check to make sure slide images have been set or haven't changed
*/
private setSlides(): void {
if (this.imageUrls) {
if (this.checkCache() || this._initial === true) {
this._initial = false;
this._urlCache = Array.from(this.imageUrls);
this.slides = [];
if (this.lazyLoad === true) {
this.buildLazyLoadSlideArray();
}
else {
this.buildSlideArray();
}
this._cdRef.detectChanges();
}
}
}
/**
* @description create the slides without background urls, which will be added in
* for the "lazy load," then load only the first slide
*/
private buildLazyLoadSlideArray(): void {
for (let image of this.imageUrls) {
this.slides.push({
image: (typeof image === 'string' ? { url: null } : { url: null, href: image.href || '' }),
action: '',
leftSide: false,
rightSide: false,
selected: false,
loaded: false
});
}
if (this.slideIndex === -1) {
this.slideIndex = 0;
}
this.slides[this.slideIndex].selected = true;
this.loadFirstSlide();
this.onIndexChanged.emit(this.slideIndex);
}
/**
* @description create the slides with background urls all at once
*/
private buildSlideArray(): void {
for (let image of this.imageUrls) {
this.slides.push({
image: (typeof image === 'string' ? { url: image } : image),
action: '',
leftSide: false,
rightSide: false,
selected: false,
loaded: true
});
}
if (this.slideIndex === -1) {
this.slideIndex = 0;
}
this.slides[this.slideIndex].selected = true;
this.onIndexChanged.emit(this.slideIndex);
}
/**
* @description load the first slide image if lazy loading
* this takes server side and browser side into account
*/
private loadFirstSlide(): void {
const tmpIndex = this.slideIndex;
const tmpImage = this.imageUrls[tmpIndex];
// if server side, we don't need to worry about the rest of the slides
if (isPlatformServer(this.platform_id)) {
this.slides[tmpIndex].image = (typeof tmpImage === 'string' ? { url: tmpImage } : tmpImage);
this.slides[tmpIndex].loaded = true;
this._transferState.set(FIRST_SLIDE_KEY, this.slides[tmpIndex]);
}
else {
const firstSlideFromTransferState = this._transferState.get(FIRST_SLIDE_KEY, null as any);
// if the first slide didn't finish loading on the server side, we need to load it
if (firstSlideFromTransferState === null) {
let loadImage = new Image();
loadImage.src = (typeof tmpImage === 'string' ? tmpImage : tmpImage.url);
loadImage.addEventListener('load', () => {
this.slides[tmpIndex].image = (typeof tmpImage === 'string' ? { url: tmpImage } : tmpImage);
this.slides[tmpIndex].loaded = true;
this.onImageLazyLoad.emit(this.slides[tmpIndex]);
this._cdRef.detectChanges();
});
}
else {
this.slides[tmpIndex] = firstSlideFromTransferState;
this._transferState.remove(FIRST_SLIDE_KEY);
}
}
}
/**
* @description if lazy loading in browser, start loading remaining slides
* @todo: figure out how to not show the spinner if images are loading fast enough
*/
private loadRemainingSlides(): void {
for (let i = 0; i < this.slides.length; i++) {
if (!this.slides[i].loaded) {
new Promise((resolve) => {
const tmpImage = this.imageUrls[i];
let loadImage = new Image();
loadImage.addEventListener('load', () => {
this.slides[i].image = (typeof tmpImage === 'string' ? { url: tmpImage } : tmpImage);
this.slides[i].loaded = true;
this._cdRef.detectChanges();
this.onImageLazyLoad.emit(this.slides[i]);
resolve();
});
loadImage.src = (typeof tmpImage === 'string' ? tmpImage : tmpImage.url);
});
}
}
}
/**
* @param {boolean} stopAutoPlay
* @description Start or stop autoPlay, don't do it at all server side
*/
private handleAutoPlay(stopAutoPlay?: boolean): void {
if (isPlatformServer(this.platform_id)) {
return;
}
if (stopAutoPlay === true || this.autoPlay === false) {
if (this._autoplayIntervalId) {
this._ngZone.runOutsideAngular(() => clearInterval(this._autoplayIntervalId));
this._autoplayIntervalId = null;
}
}
else if (!this._autoplayIntervalId) {
this._ngZone.runOutsideAngular(() => {
this._autoplayIntervalId = setInterval(() => {
if (!this.autoPlayWaitForLazyLoad || (this.autoPlayWaitForLazyLoad && this.slides[this.slideIndex] && this.slides[this.slideIndex].loaded)) {
this._ngZone.run(() => this.slide(1));
}
}, this.autoPlayInterval);
});
}
}
/**
* @description Keep the styles up to date with the input
*/
private setStyles(): void {
if (this.fullscreen) {
this._renderer.setStyle(this.container.nativeElement, 'height', '100%');
// Would be nice to make it configurable
this._renderer.setStyle(this.container.nativeElement, 'background-color', 'white');
}
else {
// Would be nice to make it configurable
this._renderer.removeStyle(this.container.nativeElement, 'background-color');
if (this.height) {
this._renderer.setStyle(this.container.nativeElement, 'height', this.height);
}
if (this.minHeight) {
this._renderer.setStyle(this.container.nativeElement, 'min-height', this.minHeight);
}
}
if (this.arrowSize) {
this._renderer.setStyle(this.prevArrow.nativeElement, 'height', this.arrowSize);
this._renderer.setStyle(this.prevArrow.nativeElement, 'width', this.arrowSize);
this._renderer.setStyle(this.nextArrow.nativeElement, 'height', this.arrowSize);
this._renderer.setStyle(this.nextArrow.nativeElement, 'width', this.arrowSize);
}
}
/**
* @description compare image array to the cache, returns false if no changes
*/
private checkCache(): boolean {
return !(this._urlCache.length === this.imageUrls.length && this._urlCache.every((cacheElement, i) => cacheElement === this.imageUrls[i]));
}
/**
* @param {number} i
* @returns {number}
* @description get the index for the slide to the left of the new slide
*/
private getLeftSideIndex(i?: number): number {
if (i === undefined) {
i = this.slideIndex;
}
if (--i < 0) {
i = this.slides.length - 1;
}
return i;
}
/**
* @param {number} i
* @returns {number}
* @description get the index for the slide to the right of the new slide
*/
private getRightSideIndex(i?: number): number {
if (i === undefined) {
i = this.slideIndex;
}
if (++i >= this.slides.length) {
i = 0;
}
return i;
}
/**
* @param {number} index
* @param {ISlide} slide
* @returns {any}
* @description a trackBy function for the ngFor loops
*/
trackByFn(index: number, slide: ISlide): any {
return slide.image;
}
/**
* @description don't let click events fire, handle in pointer service instead
*/
handleClick(event) {
event.preventDefault();
}
}