-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
carousel.ts
519 lines (447 loc) · 16.7 KB
/
carousel.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
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
NgZone,
OnDestroy,
Output,
PLATFORM_ID,
QueryList,
TemplateRef,
ViewEncapsulation,
AfterViewInit
} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import {NgbCarouselConfig} from './carousel-config';
import {BehaviorSubject, combineLatest, NEVER, Observable, Subject, timer, zip} from 'rxjs';
import {distinctUntilChanged, map, startWith, switchMap, take, takeUntil} from 'rxjs/operators';
import {ngbCompleteTransition, ngbRunTransition, NgbTransitionOptions} from '../util/transition/ngbTransition';
import {
ngbCarouselTransitionIn,
ngbCarouselTransitionOut,
NgbSlideEventDirection,
NgbCarouselCtx
} from './carousel-transition';
let nextId = 0;
/**
* A directive that wraps the individual carousel slide.
*/
@Directive({selector: 'ng-template[ngbSlide]'})
export class NgbSlide {
/**
* Slide id that must be unique for the entire document.
*
* If not provided, will be generated in the `ngb-slide-xx` format.
*/
@Input() id = `ngb-slide-${nextId++}`;
/**
* An event emitted when the slide transition is finished
*
* @since 8.0.0
*/
@Output() slid = new EventEmitter<NgbSingleSlideEvent>();
constructor(public tplRef: TemplateRef<any>) {}
}
/**
* Carousel is a component to easily create and control slideshows.
*
* Allows to set intervals, change the way user interacts with the slides and provides a programmatic API.
*/
@Component({
selector: 'ngb-carousel',
exportAs: 'ngbCarousel',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: {
'class': 'carousel slide',
'[style.display]': '"block"',
'tabIndex': '0',
'(keydown.arrowLeft)': 'keyboard && arrowLeft()',
'(keydown.arrowRight)': 'keyboard && arrowRight()',
'(mouseenter)': 'mouseHover = true',
'(mouseleave)': 'mouseHover = false',
'(focusin)': 'focused = true',
'(focusout)': 'focused = false',
'[attr.aria-activedescendant]': `'slide-' + activeId`
},
template: `
<div class="carousel-indicators" [class.visually-hidden]="!showNavigationIndicators" role="tablist">
<button type="button" data-bs-target *ngFor="let slide of slides" [class.active]="slide.id === activeId"
role="tab" [attr.aria-labelledby]="'slide-' + slide.id" [attr.aria-controls]="'slide-' + slide.id"
[attr.aria-selected]="slide.id === activeId"
(click)="focus();select(slide.id, NgbSlideEventSource.INDICATOR);"></button>
</div>
<div class="carousel-inner">
<div *ngFor="let slide of slides; index as i; count as c" class="carousel-item" [id]="'slide-' + slide.id" role="tabpanel">
<span class="visually-hidden" i18n="Currently selected slide number read by screen reader@@ngb.carousel.slide-number">
Slide {{i + 1}} of {{c}}
</span>
<ng-template [ngTemplateOutlet]="slide.tplRef"></ng-template>
</div>
</div>
<button class="carousel-control-prev" type="button" (click)="arrowLeft()" *ngIf="showNavigationArrows">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden" i18n="@@ngb.carousel.previous">Previous</span>
</button>
<button class="carousel-control-next" type="button" (click)="arrowRight()" *ngIf="showNavigationArrows">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden" i18n="@@ngb.carousel.next">Next</span>
</button>
`
})
export class NgbCarousel implements AfterContentChecked,
AfterContentInit, AfterViewInit, OnDestroy {
@ContentChildren(NgbSlide) slides: QueryList<NgbSlide>;
public NgbSlideEventSource = NgbSlideEventSource;
private _destroy$ = new Subject<void>();
private _interval$ = new BehaviorSubject(0);
private _mouseHover$ = new BehaviorSubject(false);
private _focused$ = new BehaviorSubject(false);
private _pauseOnHover$ = new BehaviorSubject(false);
private _pauseOnFocus$ = new BehaviorSubject(false);
private _pause$ = new BehaviorSubject(false);
private _wrap$ = new BehaviorSubject(false);
/**
* A flag to enable/disable the animations.
*
* @since 8.0.0
*/
@Input() animation: boolean;
/**
* The slide id that should be displayed **initially**.
*
* For subsequent interactions use methods `select()`, `next()`, etc. and the `(slide)` output.
*/
@Input() activeId: string;
/**
* Time in milliseconds before the next slide is shown.
*/
@Input()
set interval(value: number) {
this._interval$.next(value);
}
get interval() { return this._interval$.value; }
/**
* If `true`, will 'wrap' the carousel by switching from the last slide back to the first.
*/
@Input()
set wrap(value: boolean) {
this._wrap$.next(value);
}
get wrap() { return this._wrap$.value; }
/**
* If `true`, allows to interact with carousel using keyboard 'arrow left' and 'arrow right'.
*/
@Input() keyboard: boolean;
/**
* If `true`, will pause slide switching when mouse cursor hovers the slide.
*
* @since 2.2.0
*/
@Input()
set pauseOnHover(value: boolean) {
this._pauseOnHover$.next(value);
}
get pauseOnHover() { return this._pauseOnHover$.value; }
/**
* If `true`, will pause slide switching when the focus is inside the carousel.
*/
@Input()
set pauseOnFocus(value: boolean) {
this._pauseOnFocus$.next(value);
}
get pauseOnFocus() { return this._pauseOnFocus$.value; }
/**
* If `true`, 'previous' and 'next' navigation arrows will be visible on the slide.
*
* @since 2.2.0
*/
@Input() showNavigationArrows: boolean;
/**
* If `true`, navigation indicators at the bottom of the slide will be visible.
*
* @since 2.2.0
*/
@Input() showNavigationIndicators: boolean;
/**
* An event emitted just before the slide transition starts.
*
* See [`NgbSlideEvent`](#/components/carousel/api#NgbSlideEvent) for payload details.
*/
@Output() slide = new EventEmitter<NgbSlideEvent>();
/**
* An event emitted right after the slide transition is completed.
*
* See [`NgbSlideEvent`](#/components/carousel/api#NgbSlideEvent) for payload details.
*
* @since 8.0.0
*/
@Output() slid = new EventEmitter<NgbSlideEvent>();
/*
* Keep the ids of the panels currently transitionning
* in order to allow only the transition revertion
*/
private _transitionIds: [string, string] | null = null;
set mouseHover(value: boolean) { this._mouseHover$.next(value); }
get mouseHover() { return this._mouseHover$.value; }
set focused(value: boolean) { this._focused$.next(value); }
get focused() { return this._focused$.value; }
constructor(
config: NgbCarouselConfig, @Inject(PLATFORM_ID) private _platformId, private _ngZone: NgZone,
private _cd: ChangeDetectorRef, private _container: ElementRef) {
this.animation = config.animation;
this.interval = config.interval;
this.wrap = config.wrap;
this.keyboard = config.keyboard;
this.pauseOnHover = config.pauseOnHover;
this.pauseOnFocus = config.pauseOnFocus;
this.showNavigationArrows = config.showNavigationArrows;
this.showNavigationIndicators = config.showNavigationIndicators;
}
arrowLeft() {
this.focus();
this.prev(NgbSlideEventSource.ARROW_LEFT);
}
arrowRight() {
this.focus();
this.next(NgbSlideEventSource.ARROW_RIGHT);
}
ngAfterContentInit() {
// setInterval() doesn't play well with SSR and protractor,
// so we should run it in the browser and outside Angular
if (isPlatformBrowser(this._platformId)) {
this._ngZone.runOutsideAngular(() => {
const hasNextSlide$ = combineLatest([
this.slide.pipe(map(slideEvent => slideEvent.current), startWith(this.activeId)),
this._wrap$, this.slides.changes.pipe(startWith(null))
])
.pipe(
map(([currentSlideId, wrap]) => {
const slideArr = this.slides.toArray();
const currentSlideIdx = this._getSlideIdxById(currentSlideId);
return wrap ? slideArr.length > 1 : currentSlideIdx < slideArr.length - 1;
}),
distinctUntilChanged());
combineLatest([
this._pause$, this._pauseOnHover$, this._mouseHover$, this._pauseOnFocus$, this._focused$, this._interval$,
hasNextSlide$
])
.pipe(
map(([pause, pauseOnHover, mouseHover, pauseOnFocus, focused, interval,
hasNextSlide]: [boolean, boolean, boolean, boolean, boolean, number, boolean]) =>
((pause || (pauseOnHover && mouseHover) || (pauseOnFocus && focused) || !hasNextSlide) ?
0 :
interval)),
distinctUntilChanged(), switchMap(interval => interval > 0 ? timer(interval, interval) : NEVER),
takeUntil(this._destroy$))
.subscribe(() => this._ngZone.run(() => this.next(NgbSlideEventSource.TIMER)));
});
}
this.slides.changes.pipe(takeUntil(this._destroy$)).subscribe(() => {
this._transitionIds ?.forEach(id => ngbCompleteTransition(this._getSlideElement(id)));
this._transitionIds = null;
this._cd.markForCheck();
// The following code need to be done asynchronously, after the dom becomes stable,
// otherwise all changes will be undone.
this._ngZone.onStable.pipe(take(1)).subscribe(() => {
for (const { id } of this.slides) {
const element = this._getSlideElement(id);
if (id === this.activeId) {
element.classList.add('active');
} else {
element.classList.remove('active');
}
}
});
});
}
ngAfterContentChecked() {
let activeSlide = this._getSlideById(this.activeId);
this.activeId = activeSlide ? activeSlide.id : (this.slides.length ? this.slides.first.id : '');
}
ngAfterViewInit() {
// Initialize the 'active' class (not managed by the template)
if (this.activeId) {
const element = this._getSlideElement(this.activeId);
if (element) {
element.classList.add('active');
}
}
}
ngOnDestroy() { this._destroy$.next(); }
/**
* Navigates to a slide with the specified identifier.
*/
select(slideId: string, source?: NgbSlideEventSource) {
this._cycleToSelected(slideId, this._getSlideEventDirection(this.activeId, slideId), source);
}
/**
* Navigates to the previous slide.
*/
prev(source?: NgbSlideEventSource) {
this._cycleToSelected(this._getPrevSlide(this.activeId), NgbSlideEventDirection.END, source);
}
/**
* Navigates to the next slide.
*/
next(source?: NgbSlideEventSource) {
this._cycleToSelected(this._getNextSlide(this.activeId), NgbSlideEventDirection.START, source);
}
/**
* Pauses cycling through the slides.
*/
pause() { this._pause$.next(true); }
/**
* Restarts cycling through the slides from start to end.
*/
cycle() { this._pause$.next(false); }
/**
* Set the focus on the carousel.
*/
focus() { this._container.nativeElement.focus(); }
private _cycleToSelected(slideIdx: string, direction: NgbSlideEventDirection, source?: NgbSlideEventSource) {
const transitionIds = this._transitionIds;
if (transitionIds && (transitionIds[0] !== slideIdx || transitionIds[1] !== this.activeId)) {
// Revert prevented
return;
}
let selectedSlide = this._getSlideById(slideIdx);
if (selectedSlide && selectedSlide.id !== this.activeId) {
this._transitionIds = [this.activeId, slideIdx];
this.slide.emit(
{prev: this.activeId, current: selectedSlide.id, direction: direction, paused: this._pause$.value, source});
const options: NgbTransitionOptions<NgbCarouselCtx> = {
animation: this.animation,
runningTransition: 'stop',
context: {direction},
};
const transitions: Array<Observable<any>> = [];
const activeSlide = this._getSlideById(this.activeId);
if (activeSlide) {
const activeSlideTransition =
ngbRunTransition(this._ngZone, this._getSlideElement(activeSlide.id), ngbCarouselTransitionOut, options);
activeSlideTransition.subscribe(() => { activeSlide.slid.emit({isShown: false, direction, source}); });
transitions.push(activeSlideTransition);
}
const previousId = this.activeId;
this.activeId = selectedSlide.id;
const nextSlide = this._getSlideById(this.activeId);
const transition =
ngbRunTransition(this._ngZone, this._getSlideElement(selectedSlide.id), ngbCarouselTransitionIn, options);
transition.subscribe(() => { nextSlide ?.slid.emit({isShown: true, direction, source}); });
transitions.push(transition);
zip(...transitions).pipe(take(1)).subscribe(() => {
this._transitionIds = null;
this.slid.emit(
{prev: previousId, current: selectedSlide !.id, direction: direction, paused: this._pause$.value, source});
});
}
// we get here after the interval fires or any external API call like next(), prev() or select()
this._cd.markForCheck();
}
private _getSlideEventDirection(currentActiveSlideId: string, nextActiveSlideId: string): NgbSlideEventDirection {
const currentActiveSlideIdx = this._getSlideIdxById(currentActiveSlideId);
const nextActiveSlideIdx = this._getSlideIdxById(nextActiveSlideId);
return currentActiveSlideIdx > nextActiveSlideIdx ? NgbSlideEventDirection.END : NgbSlideEventDirection.START;
}
private _getSlideById(slideId: string): NgbSlide | null {
return this.slides.find(slide => slide.id === slideId) || null;
}
private _getSlideIdxById(slideId: string): number {
const slide = this._getSlideById(slideId);
return slide != null ? this.slides.toArray().indexOf(slide) : -1;
}
private _getNextSlide(currentSlideId: string): string {
const slideArr = this.slides.toArray();
const currentSlideIdx = this._getSlideIdxById(currentSlideId);
const isLastSlide = currentSlideIdx === slideArr.length - 1;
return isLastSlide ? (this.wrap ? slideArr[0].id : slideArr[slideArr.length - 1].id) :
slideArr[currentSlideIdx + 1].id;
}
private _getPrevSlide(currentSlideId: string): string {
const slideArr = this.slides.toArray();
const currentSlideIdx = this._getSlideIdxById(currentSlideId);
const isFirstSlide = currentSlideIdx === 0;
return isFirstSlide ? (this.wrap ? slideArr[slideArr.length - 1].id : slideArr[0].id) :
slideArr[currentSlideIdx - 1].id;
}
private _getSlideElement(slideId: string): HTMLElement {
return this._container.nativeElement.querySelector(`#slide-${slideId}`);
}
}
/**
* A slide change event emitted right after the slide transition is completed.
*/
export interface NgbSlideEvent {
/**
* The previous slide id.
*/
prev: string;
/**
* The current slide id.
*/
current: string;
/**
* The slide event direction.
*
* <span class="badge bg-info text-dark">since 12.0.0</span> Possible values are `'start' | 'end'`.
*
* <span class="badge bg-secondary">before 12.0.0</span> Possible values were `'left' | 'right'`.
*/
direction: NgbSlideEventDirection;
/**
* Whether the pause() method was called (and no cycle() call was done afterwards).
*
* @since 5.1.0
*/
paused: boolean;
/**
* Source triggering the slide change event.
*
* Possible values are `'timer' | 'arrowLeft' | 'arrowRight' | 'indicator'`
*
* @since 5.1.0
*/
source?: NgbSlideEventSource;
}
/**
* A slide change event emitted right after the slide transition is completed.
*
* @since 8.0.0
*/
export interface NgbSingleSlideEvent {
/**
* true if the slide is shown, false otherwise
*/
isShown: boolean;
/**
* The slide event direction.
*
* <span class="badge bg-info text-dark">since 12.0.0</span> Possible values are `'start' | 'end'`.
*
* <span class="badge bg-secondary">before 12.0.0</span> Possible values were `'left' | 'right'`.
*/
direction: NgbSlideEventDirection;
/**
* Source triggering the slide change event.
*
* Possible values are `'timer' | 'arrowLeft' | 'arrowRight' | 'indicator'`
*
*/
source?: NgbSlideEventSource;
}
export enum NgbSlideEventSource {
TIMER = 'timer',
ARROW_LEFT = 'arrowLeft',
ARROW_RIGHT = 'arrowRight',
INDICATOR = 'indicator'
}
export const NGB_CAROUSEL_DIRECTIVES = [NgbCarousel, NgbSlide];