forked from angular/components
/
tab-group.ts
579 lines (496 loc) · 19.1 KB
/
tab-group.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
AfterContentChecked,
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
OnDestroy,
Optional,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
import {MAT_TAB_GROUP, MatTab} from './tab';
import {MatTabHeader} from './tab-header';
import {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput,
} from '@angular/cdk/coercion';
import {
CanColor,
CanDisableRipple,
mixinColor,
mixinDisableRipple,
ThemePalette,
} from '@angular/material/core';
import {merge, Subscription} from 'rxjs';
import {MAT_TABS_CONFIG, MatTabsConfig} from './tab-config';
import {startWith} from 'rxjs/operators';
import {FocusOrigin} from '@angular/cdk/a11y';
/** Used to generate unique ID's for each tab component */
let nextId = 0;
// Boilerplate for applying mixins to MatTabGroup.
/** @docs-private */
const _MatTabGroupMixinBase = mixinColor(
mixinDisableRipple(
class {
constructor(public _elementRef: ElementRef) {}
},
),
'primary',
);
/** @docs-private */
export interface MatTabGroupBaseHeader {
_alignInkBarToSelectedTab(): void;
updatePagination(): void;
focusIndex: number;
}
/** Possible positions for the tab header. */
export type MatTabHeaderPosition = 'above' | 'below';
/**
* Base class with all of the `MatTabGroupBase` functionality.
* @docs-private
*/
@Directive()
export abstract class _MatTabGroupBase
extends _MatTabGroupMixinBase
implements AfterContentInit, AfterContentChecked, OnDestroy, CanColor, CanDisableRipple
{
/**
* All tabs inside the tab group. This includes tabs that belong to groups that are nested
* inside the current one. We filter out only the tabs that belong to this group in `_tabs`.
*/
abstract _allTabs: QueryList<MatTab>;
abstract _tabBodyWrapper: ElementRef;
abstract _tabHeader: MatTabGroupBaseHeader;
/** All of the tabs that belong to the group. */
_tabs: QueryList<MatTab> = new QueryList<MatTab>();
/** The tab index that should be selected after the content has been checked. */
private _indexToSelect: number | null = 0;
/** Index of the tab that was focused last. */
private _lastFocusedTabIndex: number | null = null;
/** Snapshot of the height of the tab body wrapper before another tab is activated. */
private _tabBodyWrapperHeight: number = 0;
/** Subscription to tabs being added/removed. */
private _tabsSubscription = Subscription.EMPTY;
/** Subscription to changes in the tab labels. */
private _tabLabelSubscription = Subscription.EMPTY;
/** Whether the tab group should grow to the size of the active tab. */
@Input()
get dynamicHeight(): boolean {
return this._dynamicHeight;
}
set dynamicHeight(value: BooleanInput) {
this._dynamicHeight = coerceBooleanProperty(value);
}
private _dynamicHeight: boolean = false;
/** The index of the active tab. */
@Input()
get selectedIndex(): number | null {
return this._selectedIndex;
}
set selectedIndex(value: NumberInput) {
this._indexToSelect = coerceNumberProperty(value, null);
}
private _selectedIndex: number | null = null;
/** Position of the tab header. */
@Input() headerPosition: MatTabHeaderPosition = 'above';
/** Duration for the tab animation. Will be normalized to milliseconds if no units are set. */
@Input()
get animationDuration(): string {
return this._animationDuration;
}
set animationDuration(value: NumberInput) {
this._animationDuration = /^\d+$/.test(value + '') ? value + 'ms' : (value as string);
}
private _animationDuration: string;
/**
* `tabindex` to be set on the inner element that wraps the tab content. Can be used for improved
* accessibility when the tab does not have focusable elements or if it has scrollable content.
* The `tabindex` will be removed automatically for inactive tabs.
* Read more at https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-2/tabs.html
*/
@Input()
get contentTabIndex(): number | null {
return this._contentTabIndex;
}
set contentTabIndex(value: NumberInput) {
this._contentTabIndex = coerceNumberProperty(value, null);
}
private _contentTabIndex: number | null;
/**
* Whether pagination should be disabled. This can be used to avoid unnecessary
* layout recalculations if it's known that pagination won't be required.
*/
@Input()
get disablePagination(): boolean {
return this._disablePagination;
}
set disablePagination(value: BooleanInput) {
this._disablePagination = coerceBooleanProperty(value);
}
private _disablePagination: boolean = false;
/**
* By default tabs remove their content from the DOM while it's off-screen.
* Setting this to `true` will keep it in the DOM which will prevent elements
* like iframes and videos from reloading next time it comes back into the view.
*/
@Input()
get preserveContent(): boolean {
return this._preserveContent;
}
set preserveContent(value: BooleanInput) {
this._preserveContent = coerceBooleanProperty(value);
}
private _preserveContent: boolean = false;
/** Background color of the tab group. */
@Input()
get backgroundColor(): ThemePalette {
return this._backgroundColor;
}
set backgroundColor(value: ThemePalette) {
const classList: DOMTokenList = this._elementRef.nativeElement.classList;
classList.remove('mat-tabs-with-background', `mat-background-${this.backgroundColor}`);
if (value) {
classList.add('mat-tabs-with-background', `mat-background-${value}`);
}
this._backgroundColor = value;
}
private _backgroundColor: ThemePalette;
/** Output to enable support for two-way binding on `[(selectedIndex)]` */
@Output() readonly selectedIndexChange: EventEmitter<number> = new EventEmitter<number>();
/** Event emitted when focus has changed within a tab group. */
@Output() readonly focusChange: EventEmitter<MatTabChangeEvent> =
new EventEmitter<MatTabChangeEvent>();
/** Event emitted when the body animation has completed */
@Output() readonly animationDone: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the tab selection has changed. */
@Output() readonly selectedTabChange: EventEmitter<MatTabChangeEvent> =
new EventEmitter<MatTabChangeEvent>(true);
private _groupId: number;
constructor(
elementRef: ElementRef,
protected _changeDetectorRef: ChangeDetectorRef,
@Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig,
@Optional() @Inject(ANIMATION_MODULE_TYPE) public _animationMode?: string,
) {
super(elementRef);
this._groupId = nextId++;
this.animationDuration =
defaultConfig && defaultConfig.animationDuration ? defaultConfig.animationDuration : '500ms';
this.disablePagination =
defaultConfig && defaultConfig.disablePagination != null
? defaultConfig.disablePagination
: false;
this.dynamicHeight =
defaultConfig && defaultConfig.dynamicHeight != null ? defaultConfig.dynamicHeight : false;
this.contentTabIndex = defaultConfig?.contentTabIndex ?? null;
this.preserveContent = !!defaultConfig?.preserveContent;
}
/**
* After the content is checked, this component knows what tabs have been defined
* and what the selected index should be. This is where we can know exactly what position
* each tab should be in according to the new selected index, and additionally we know how
* a new selected tab should transition in (from the left or right).
*/
ngAfterContentChecked() {
// Don't clamp the `indexToSelect` immediately in the setter because it can happen that
// the amount of tabs changes before the actual change detection runs.
const indexToSelect = (this._indexToSelect = this._clampTabIndex(this._indexToSelect));
// If there is a change in selected index, emit a change event. Should not trigger if
// the selected index has not yet been initialized.
if (this._selectedIndex != indexToSelect) {
const isFirstRun = this._selectedIndex == null;
if (!isFirstRun) {
this.selectedTabChange.emit(this._createChangeEvent(indexToSelect));
// Preserve the height so page doesn't scroll up during tab change.
// Fixes https://stackblitz.com/edit/mat-tabs-scroll-page-top-on-tab-change
const wrapper = this._tabBodyWrapper.nativeElement;
wrapper.style.minHeight = wrapper.clientHeight + 'px';
}
// Changing these values after change detection has run
// since the checked content may contain references to them.
Promise.resolve().then(() => {
this._tabs.forEach((tab, index) => (tab.isActive = index === indexToSelect));
if (!isFirstRun) {
this.selectedIndexChange.emit(indexToSelect);
// Clear the min-height, this was needed during tab change to avoid
// unnecessary scrolling.
this._tabBodyWrapper.nativeElement.style.minHeight = '';
}
});
}
// Setup the position for each tab and optionally setup an origin on the next selected tab.
this._tabs.forEach((tab: MatTab, index: number) => {
tab.position = index - indexToSelect;
// If there is already a selected tab, then set up an origin for the next selected tab
// if it doesn't have one already.
if (this._selectedIndex != null && tab.position == 0 && !tab.origin) {
tab.origin = indexToSelect - this._selectedIndex;
}
});
if (this._selectedIndex !== indexToSelect) {
this._selectedIndex = indexToSelect;
this._lastFocusedTabIndex = null;
this._changeDetectorRef.markForCheck();
}
}
ngAfterContentInit() {
this._subscribeToAllTabChanges();
this._subscribeToTabLabels();
// Subscribe to changes in the amount of tabs, in order to be
// able to re-render the content as new tabs are added or removed.
this._tabsSubscription = this._tabs.changes.subscribe(() => {
const indexToSelect = this._clampTabIndex(this._indexToSelect);
// Maintain the previously-selected tab if a new tab is added or removed and there is no
// explicit change that selects a different tab.
if (indexToSelect === this._selectedIndex) {
const tabs = this._tabs.toArray();
let selectedTab: MatTab | undefined;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].isActive) {
// Assign both to the `_indexToSelect` and `_selectedIndex` so we don't fire a changed
// event, otherwise the consumer may end up in an infinite loop in some edge cases like
// adding a tab within the `selectedIndexChange` event.
this._indexToSelect = this._selectedIndex = i;
this._lastFocusedTabIndex = null;
selectedTab = tabs[i];
break;
}
}
// If we haven't found an active tab and a tab exists at the selected index, it means
// that the active tab was swapped out. Since this won't be picked up by the rendering
// loop in `ngAfterContentChecked`, we need to sync it up manually.
if (!selectedTab && tabs[indexToSelect]) {
Promise.resolve().then(() => {
tabs[indexToSelect].isActive = true;
this.selectedTabChange.emit(this._createChangeEvent(indexToSelect));
});
}
}
this._changeDetectorRef.markForCheck();
});
}
/** Listens to changes in all of the tabs. */
private _subscribeToAllTabChanges() {
// Since we use a query with `descendants: true` to pick up the tabs, we may end up catching
// some that are inside of nested tab groups. We filter them out manually by checking that
// the closest group to the tab is the current one.
this._allTabs.changes.pipe(startWith(this._allTabs)).subscribe((tabs: QueryList<MatTab>) => {
this._tabs.reset(
tabs.filter(tab => {
return tab._closestTabGroup === this || !tab._closestTabGroup;
}),
);
this._tabs.notifyOnChanges();
});
}
ngOnDestroy() {
this._tabs.destroy();
this._tabsSubscription.unsubscribe();
this._tabLabelSubscription.unsubscribe();
}
/** Re-aligns the ink bar to the selected tab element. */
realignInkBar() {
if (this._tabHeader) {
this._tabHeader._alignInkBarToSelectedTab();
}
}
/**
* Recalculates the tab group's pagination dimensions.
*
* WARNING: Calling this method can be very costly in terms of performance. It should be called
* as infrequently as possible from outside of the Tabs component as it causes a reflow of the
* page.
*/
updatePagination() {
if (this._tabHeader) {
this._tabHeader.updatePagination();
}
}
/**
* Sets focus to a particular tab.
* @param index Index of the tab to be focused.
*/
focusTab(index: number) {
const header = this._tabHeader;
if (header) {
header.focusIndex = index;
}
}
_focusChanged(index: number) {
this._lastFocusedTabIndex = index;
this.focusChange.emit(this._createChangeEvent(index));
}
private _createChangeEvent(index: number): MatTabChangeEvent {
const event = new MatTabChangeEvent();
event.index = index;
if (this._tabs && this._tabs.length) {
event.tab = this._tabs.toArray()[index];
}
return event;
}
/**
* Subscribes to changes in the tab labels. This is needed, because the @Input for the label is
* on the MatTab component, whereas the data binding is inside the MatTabGroup. In order for the
* binding to be updated, we need to subscribe to changes in it and trigger change detection
* manually.
*/
private _subscribeToTabLabels() {
if (this._tabLabelSubscription) {
this._tabLabelSubscription.unsubscribe();
}
this._tabLabelSubscription = merge(...this._tabs.map(tab => tab._stateChanges)).subscribe(() =>
this._changeDetectorRef.markForCheck(),
);
}
/** Clamps the given index to the bounds of 0 and the tabs length. */
private _clampTabIndex(index: number | null): number {
// Note the `|| 0`, which ensures that values like NaN can't get through
// and which would otherwise throw the component into an infinite loop
// (since Math.max(NaN, 0) === NaN).
return Math.min(this._tabs.length - 1, Math.max(index || 0, 0));
}
/** Returns a unique id for each tab label element */
_getTabLabelId(i: number): string {
return `mat-tab-label-${this._groupId}-${i}`;
}
/** Returns a unique id for each tab content element */
_getTabContentId(i: number): string {
return `mat-tab-content-${this._groupId}-${i}`;
}
/**
* Sets the height of the body wrapper to the height of the activating tab if dynamic
* height property is true.
*/
_setTabBodyWrapperHeight(tabHeight: number): void {
if (!this._dynamicHeight || !this._tabBodyWrapperHeight) {
return;
}
const wrapper: HTMLElement = this._tabBodyWrapper.nativeElement;
wrapper.style.height = this._tabBodyWrapperHeight + 'px';
// This conditional forces the browser to paint the height so that
// the animation to the new height can have an origin.
if (this._tabBodyWrapper.nativeElement.offsetHeight) {
wrapper.style.height = tabHeight + 'px';
}
}
/** Removes the height of the tab body wrapper. */
_removeTabBodyWrapperHeight(): void {
const wrapper = this._tabBodyWrapper.nativeElement;
this._tabBodyWrapperHeight = wrapper.clientHeight;
wrapper.style.height = '';
this.animationDone.emit();
}
/** Handle click events, setting new selected index if appropriate. */
_handleClick(tab: MatTab, tabHeader: MatTabGroupBaseHeader, index: number) {
if (!tab.disabled) {
this.selectedIndex = tabHeader.focusIndex = index;
}
}
/** Retrieves the tabindex for the tab. */
_getTabIndex(tab: MatTab, index: number): number | null {
if (tab.disabled) {
return null;
}
const targetIndex = this._lastFocusedTabIndex ?? this.selectedIndex;
return index === targetIndex ? 0 : -1;
}
/** Callback for when the focused state of a tab has changed. */
_tabFocusChanged(focusOrigin: FocusOrigin, index: number) {
// Mouse/touch focus happens during the `mousedown`/`touchstart` phase which
// can cause the tab to be moved out from under the pointer, interrupting the
// click sequence (see #21898). We don't need to scroll the tab into view for
// such cases anyway, because it will be done when the tab becomes selected.
if (focusOrigin && focusOrigin !== 'mouse' && focusOrigin !== 'touch') {
this._tabHeader.focusIndex = index;
}
}
}
/**
* Material design tab-group component. Supports basic tab pairs (label + content) and includes
* animated ink-bar, keyboard navigation, and screen reader.
* See: https://material.io/design/components/tabs.html
*/
@Component({
selector: 'mat-tab-group',
exportAs: 'matTabGroup',
templateUrl: 'tab-group.html',
styleUrls: ['tab-group.css'],
encapsulation: ViewEncapsulation.None,
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
inputs: ['color', 'disableRipple'],
providers: [
{
provide: MAT_TAB_GROUP,
useExisting: MatTabGroup,
},
],
host: {
'class': 'mat-mdc-tab-group',
'[class.mat-mdc-tab-group-dynamic-height]': 'dynamicHeight',
'[class.mat-mdc-tab-group-inverted-header]': 'headerPosition === "below"',
'[class.mat-mdc-tab-group-stretch-tabs]': 'stretchTabs',
},
})
export class MatTabGroup extends _MatTabGroupBase {
@ContentChildren(MatTab, {descendants: true}) _allTabs: QueryList<MatTab>;
@ViewChild('tabBodyWrapper') _tabBodyWrapper: ElementRef;
@ViewChild('tabHeader') _tabHeader: MatTabHeader;
/** Whether the ink bar should fit its width to the size of the tab label content. */
@Input()
get fitInkBarToContent(): boolean {
return this._fitInkBarToContent;
}
set fitInkBarToContent(v: BooleanInput) {
this._fitInkBarToContent = coerceBooleanProperty(v);
this._changeDetectorRef.markForCheck();
}
private _fitInkBarToContent = false;
/** Whether tabs should be stretched to fill the header. */
@Input('mat-stretch-tabs')
get stretchTabs(): boolean {
return this._stretchTabs;
}
set stretchTabs(v: BooleanInput) {
this._stretchTabs = coerceBooleanProperty(v);
}
private _stretchTabs = true;
constructor(
elementRef: ElementRef,
changeDetectorRef: ChangeDetectorRef,
@Inject(MAT_TABS_CONFIG) @Optional() defaultConfig?: MatTabsConfig,
@Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string,
) {
super(elementRef, changeDetectorRef, defaultConfig, animationMode);
this.fitInkBarToContent =
defaultConfig && defaultConfig.fitInkBarToContent != null
? defaultConfig.fitInkBarToContent
: false;
}
}
/** A simple change event emitted on focus or selection changes. */
export class MatTabChangeEvent {
/** Index of the currently-selected tab. */
index: number;
/** Reference to the currently-selected tab. */
tab: MatTab;
}