@angular/material
Version:
Angular Material
1,279 lines (1,270 loc) • 82.7 kB
JavaScript
/**
* @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 { Directive, ElementRef, Inject, InjectionToken, NgZone, Optional, TemplateRef, ChangeDetectionStrategy, Component, ContentChild, Input, ViewChild, ViewContainerRef, ViewEncapsulation, ChangeDetectorRef, Output, EventEmitter, ComponentFactoryResolver, forwardRef, ContentChildren, Attribute, NgModule } from '@angular/core';
import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations';
import { CdkPortal, TemplatePortal, CdkPortalOutlet, PortalHostDirective, PortalModule } from '@angular/cdk/portal';
import { mixinDisabled, mixinColor, mixinDisableRipple, MAT_RIPPLE_GLOBAL_OPTIONS, mixinTabIndex, RippleRenderer, MatCommonModule, MatRippleModule } from '@angular/material/core';
import { Subject, Subscription, merge, of, timer, fromEvent } from 'rxjs';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { Directionality } from '@angular/cdk/bidi';
import { startWith, distinctUntilChanged, takeUntil } from 'rxjs/operators';
import { coerceNumberProperty, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { FocusKeyManager, FocusMonitor, A11yModule } from '@angular/cdk/a11y';
import { END, ENTER, HOME, SPACE, hasModifierKey } from '@angular/cdk/keycodes';
import { Platform, normalizePassiveListenerOptions } from '@angular/cdk/platform';
import { ObserversModule } from '@angular/cdk/observers';
import { CommonModule } from '@angular/common';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Injection token for the MatInkBar's Positioner.
* @type {?}
*/
const _MAT_INK_BAR_POSITIONER = new InjectionToken('MatInkBarPositioner', {
providedIn: 'root',
factory: _MAT_INK_BAR_POSITIONER_FACTORY
});
/**
* The default positioner function for the MatInkBar.
* \@docs-private
* @return {?}
*/
function _MAT_INK_BAR_POSITIONER_FACTORY() {
/** @type {?} */
const method = (/**
* @param {?} element
* @return {?}
*/
(element) => ({
left: element ? (element.offsetLeft || 0) + 'px' : '0',
width: element ? (element.offsetWidth || 0) + 'px' : '0',
}));
return method;
}
/**
* The ink-bar is used to display and animate the line underneath the current active tab label.
* \@docs-private
*/
class MatInkBar {
/**
* @param {?} _elementRef
* @param {?} _ngZone
* @param {?} _inkBarPositioner
* @param {?=} _animationMode
*/
constructor(_elementRef, _ngZone, _inkBarPositioner, _animationMode) {
this._elementRef = _elementRef;
this._ngZone = _ngZone;
this._inkBarPositioner = _inkBarPositioner;
this._animationMode = _animationMode;
}
/**
* Calculates the styles from the provided element in order to align the ink-bar to that element.
* Shows the ink bar if previously set as hidden.
* @param {?} element
* @return {?}
*/
alignToElement(element) {
this.show();
if (typeof requestAnimationFrame !== 'undefined') {
this._ngZone.runOutsideAngular((/**
* @return {?}
*/
() => {
requestAnimationFrame((/**
* @return {?}
*/
() => this._setStyles(element)));
}));
}
else {
this._setStyles(element);
}
}
/**
* Shows the ink bar.
* @return {?}
*/
show() {
this._elementRef.nativeElement.style.visibility = 'visible';
}
/**
* Hides the ink bar.
* @return {?}
*/
hide() {
this._elementRef.nativeElement.style.visibility = 'hidden';
}
/**
* Sets the proper styles to the ink bar element.
* @private
* @param {?} element
* @return {?}
*/
_setStyles(element) {
/** @type {?} */
const positions = this._inkBarPositioner(element);
/** @type {?} */
const inkBar = this._elementRef.nativeElement;
inkBar.style.left = positions.left;
inkBar.style.width = positions.width;
}
}
MatInkBar.decorators = [
{ type: Directive, args: [{
selector: 'mat-ink-bar',
host: {
'class': 'mat-ink-bar',
'[class._mat-animation-noopable]': `_animationMode === 'NoopAnimations'`,
},
},] },
];
/** @nocollapse */
MatInkBar.ctorParameters = () => [
{ type: ElementRef },
{ type: NgZone },
{ type: undefined, decorators: [{ type: Inject, args: [_MAT_INK_BAR_POSITIONER,] }] },
{ type: String, decorators: [{ type: Optional }, { type: Inject, args: [ANIMATION_MODULE_TYPE,] }] }
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Decorates the `ng-template` tags and reads out the template from it.
*/
class MatTabContent {
/**
* @param {?} template
*/
constructor(template) {
this.template = template;
}
}
MatTabContent.decorators = [
{ type: Directive, args: [{ selector: '[matTabContent]' },] },
];
/** @nocollapse */
MatTabContent.ctorParameters = () => [
{ type: TemplateRef }
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Used to flag tab labels for use with the portal directive
*/
class MatTabLabel extends CdkPortal {
}
MatTabLabel.decorators = [
{ type: Directive, args: [{
selector: '[mat-tab-label], [matTabLabel]',
},] },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// Boilerplate for applying mixins to MatTab.
/**
* \@docs-private
*/
class MatTabBase {
}
/** @type {?} */
const _MatTabMixinBase = mixinDisabled(MatTabBase);
class MatTab extends _MatTabMixinBase {
/**
* @param {?} _viewContainerRef
*/
constructor(_viewContainerRef) {
super();
this._viewContainerRef = _viewContainerRef;
/**
* Plain text label for the tab, used when there is no template label.
*/
this.textLabel = '';
/**
* Portal that will be the hosted content of the tab
*/
this._contentPortal = null;
/**
* Emits whenever the internal state of the tab changes.
*/
this._stateChanges = new Subject();
/**
* The relatively indexed position where 0 represents the center, negative is left, and positive
* represents the right.
*/
this.position = null;
/**
* The initial relatively index origin of the tab if it was created and selected after there
* was already a selected tab. Provides context of what position the tab should originate from.
*/
this.origin = null;
/**
* Whether the tab is currently active.
*/
this.isActive = false;
}
/**
* \@docs-private
* @return {?}
*/
get content() {
return this._contentPortal;
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes.hasOwnProperty('textLabel') || changes.hasOwnProperty('disabled')) {
this._stateChanges.next();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
this._stateChanges.complete();
}
/**
* @return {?}
*/
ngOnInit() {
this._contentPortal = new TemplatePortal(this._explicitContent || this._implicitContent, this._viewContainerRef);
}
}
MatTab.decorators = [
{ type: Component, args: [{selector: 'mat-tab',
template: "<ng-template><ng-content></ng-content></ng-template>",
inputs: ['disabled'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'matTab',
},] },
];
/** @nocollapse */
MatTab.ctorParameters = () => [
{ type: ViewContainerRef }
];
MatTab.propDecorators = {
templateLabel: [{ type: ContentChild, args: [MatTabLabel, { static: false },] }],
_explicitContent: [{ type: ContentChild, args: [MatTabContent, { read: TemplateRef, static: true },] }],
_implicitContent: [{ type: ViewChild, args: [TemplateRef, { static: true },] }],
textLabel: [{ type: Input, args: ['label',] }],
ariaLabel: [{ type: Input, args: ['aria-label',] }],
ariaLabelledby: [{ type: Input, args: ['aria-labelledby',] }]
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Animations used by the Material tabs.
* \@docs-private
* @type {?}
*/
const matTabsAnimations = {
/**
* Animation translates a tab along the X axis.
*/
translateTab: trigger('translateTab', [
// Note: transitions to `none` instead of 0, because some browsers might blur the content.
state('center, void, left-origin-center, right-origin-center', style({ transform: 'none' })),
// If the tab is either on the left or right, we additionally add a `min-height` of 1px
// in order to ensure that the element has a height before its state changes. This is
// necessary because Chrome does seem to skip the transition in RTL mode if the element does
// not have a static height and is not rendered. See related issue: #9465
state('left', style({ transform: 'translate3d(-100%, 0, 0)', minHeight: '1px' })),
state('right', style({ transform: 'translate3d(100%, 0, 0)', minHeight: '1px' })),
transition('* => left, * => right, left => center, right => center', animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')),
transition('void => left-origin-center', [
style({ transform: 'translate3d(-100%, 0, 0)' }),
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')
]),
transition('void => right-origin-center', [
style({ transform: 'translate3d(100%, 0, 0)' }),
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')
])
])
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The portal host directive for the contents of the tab.
* \@docs-private
*/
class MatTabBodyPortal extends CdkPortalOutlet {
/**
* @param {?} componentFactoryResolver
* @param {?} viewContainerRef
* @param {?} _host
*/
constructor(componentFactoryResolver, viewContainerRef, _host) {
super(componentFactoryResolver, viewContainerRef);
this._host = _host;
/**
* Subscription to events for when the tab body begins centering.
*/
this._centeringSub = Subscription.EMPTY;
/**
* Subscription to events for when the tab body finishes leaving from center position.
*/
this._leavingSub = Subscription.EMPTY;
}
/**
* Set initial visibility or set up subscription for changing visibility.
* @return {?}
*/
ngOnInit() {
super.ngOnInit();
this._centeringSub = this._host._beforeCentering
.pipe(startWith(this._host._isCenterPosition(this._host._position)))
.subscribe((/**
* @param {?} isCentering
* @return {?}
*/
(isCentering) => {
if (isCentering && !this.hasAttached()) {
this.attach(this._host._content);
}
}));
this._leavingSub = this._host._afterLeavingCenter.subscribe((/**
* @return {?}
*/
() => {
this.detach();
}));
}
/**
* Clean up centering subscription.
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
this._centeringSub.unsubscribe();
this._leavingSub.unsubscribe();
}
}
MatTabBodyPortal.decorators = [
{ type: Directive, args: [{
selector: '[matTabBodyHost]'
},] },
];
/** @nocollapse */
MatTabBodyPortal.ctorParameters = () => [
{ type: ComponentFactoryResolver },
{ type: ViewContainerRef },
{ type: MatTabBody, decorators: [{ type: Inject, args: [forwardRef((/**
* @return {?}
*/
() => MatTabBody)),] }] }
];
/**
* Wrapper for the contents of a tab.
* \@docs-private
*/
class MatTabBody {
/**
* @param {?} _elementRef
* @param {?} _dir
* @param {?} changeDetectorRef
*/
constructor(_elementRef, _dir, changeDetectorRef) {
this._elementRef = _elementRef;
this._dir = _dir;
/**
* Subscription to the directionality change observable.
*/
this._dirChangeSubscription = Subscription.EMPTY;
/**
* Emits when an animation on the tab is complete.
*/
this._translateTabComplete = new Subject();
/**
* Event emitted when the tab begins to animate towards the center as the active tab.
*/
this._onCentering = new EventEmitter();
/**
* Event emitted before the centering of the tab begins.
*/
this._beforeCentering = new EventEmitter();
/**
* Event emitted before the centering of the tab begins.
*/
this._afterLeavingCenter = new EventEmitter();
/**
* Event emitted when the tab completes its animation towards the center.
*/
this._onCentered = new EventEmitter(true);
// Note that the default value will always be overwritten by `MatTabBody`, but we need one
// anyway to prevent the animations module from throwing an error if the body is used on its own.
/**
* Duration for the tab's animation.
*/
this.animationDuration = '500ms';
if (_dir) {
this._dirChangeSubscription = _dir.change.subscribe((/**
* @param {?} dir
* @return {?}
*/
(dir) => {
this._computePositionAnimationState(dir);
changeDetectorRef.markForCheck();
}));
}
// Ensure that we get unique animation events, because the `.done` callback can get
// invoked twice in some browsers. See https://github.com/angular/angular/issues/24084.
this._translateTabComplete.pipe(distinctUntilChanged((/**
* @param {?} x
* @param {?} y
* @return {?}
*/
(x, y) => {
return x.fromState === y.fromState && x.toState === y.toState;
}))).subscribe((/**
* @param {?} event
* @return {?}
*/
event => {
// If the transition to the center is complete, emit an event.
if (this._isCenterPosition(event.toState) && this._isCenterPosition(this._position)) {
this._onCentered.emit();
}
if (this._isCenterPosition(event.fromState) && !this._isCenterPosition(this._position)) {
this._afterLeavingCenter.emit();
}
}));
}
/**
* The shifted index position of the tab body, where zero represents the active center tab.
* @param {?} position
* @return {?}
*/
set position(position) {
this._positionIndex = position;
this._computePositionAnimationState();
}
/**
* After initialized, check if the content is centered and has an origin. If so, set the
* special position states that transition the tab from the left or right before centering.
* @return {?}
*/
ngOnInit() {
if (this._position == 'center' && this.origin != null) {
this._position = this._computePositionFromOrigin();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
this._dirChangeSubscription.unsubscribe();
this._translateTabComplete.complete();
}
/**
* @param {?} event
* @return {?}
*/
_onTranslateTabStarted(event) {
/** @type {?} */
const isCentering = this._isCenterPosition(event.toState);
this._beforeCentering.emit(isCentering);
if (isCentering) {
this._onCentering.emit(this._elementRef.nativeElement.clientHeight);
}
}
/**
* The text direction of the containing app.
* @return {?}
*/
_getLayoutDirection() {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/**
* Whether the provided position state is considered center, regardless of origin.
* @param {?} position
* @return {?}
*/
_isCenterPosition(position) {
return position == 'center' ||
position == 'left-origin-center' ||
position == 'right-origin-center';
}
/**
* Computes the position state that will be used for the tab-body animation trigger.
* @private
* @param {?=} dir
* @return {?}
*/
_computePositionAnimationState(dir = this._getLayoutDirection()) {
if (this._positionIndex < 0) {
this._position = dir == 'ltr' ? 'left' : 'right';
}
else if (this._positionIndex > 0) {
this._position = dir == 'ltr' ? 'right' : 'left';
}
else {
this._position = 'center';
}
}
/**
* Computes the position state based on the specified origin position. This is used if the
* tab is becoming visible immediately after creation.
* @private
* @return {?}
*/
_computePositionFromOrigin() {
/** @type {?} */
const dir = this._getLayoutDirection();
if ((dir == 'ltr' && this.origin <= 0) || (dir == 'rtl' && this.origin > 0)) {
return 'left-origin-center';
}
return 'right-origin-center';
}
}
MatTabBody.decorators = [
{ type: Component, args: [{selector: 'mat-tab-body',
template: "<div class=\"mat-tab-body-content\" #content [@translateTab]=\"{ value: _position, params: {animationDuration: animationDuration} }\" (@translateTab.start)=\"_onTranslateTabStarted($event)\" (@translateTab.done)=\"_translateTabComplete.next($event)\"><ng-template matTabBodyHost></ng-template></div>",
styles: [".mat-tab-body-content{height:100%;overflow:auto}.mat-tab-group-dynamic-height .mat-tab-body-content{overflow:hidden}"],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [matTabsAnimations.translateTab],
host: {
'class': 'mat-tab-body',
},
},] },
];
/** @nocollapse */
MatTabBody.ctorParameters = () => [
{ type: ElementRef },
{ type: Directionality, decorators: [{ type: Optional }] },
{ type: ChangeDetectorRef }
];
MatTabBody.propDecorators = {
_onCentering: [{ type: Output }],
_beforeCentering: [{ type: Output }],
_afterLeavingCenter: [{ type: Output }],
_onCentered: [{ type: Output }],
_portalHost: [{ type: ViewChild, args: [PortalHostDirective, { static: false },] }],
_content: [{ type: Input, args: ['content',] }],
origin: [{ type: Input }],
animationDuration: [{ type: Input }],
position: [{ type: Input }]
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// Boilerplate for applying mixins to MatTabLabelWrapper.
/**
* \@docs-private
*/
class MatTabLabelWrapperBase {
}
/** @type {?} */
const _MatTabLabelWrapperMixinBase = mixinDisabled(MatTabLabelWrapperBase);
/**
* Used in the `mat-tab-group` view to display tab labels.
* \@docs-private
*/
class MatTabLabelWrapper extends _MatTabLabelWrapperMixinBase {
/**
* @param {?} elementRef
*/
constructor(elementRef) {
super();
this.elementRef = elementRef;
}
/**
* Sets focus on the wrapper element
* @return {?}
*/
focus() {
this.elementRef.nativeElement.focus();
}
/**
* @return {?}
*/
getOffsetLeft() {
return this.elementRef.nativeElement.offsetLeft;
}
/**
* @return {?}
*/
getOffsetWidth() {
return this.elementRef.nativeElement.offsetWidth;
}
}
MatTabLabelWrapper.decorators = [
{ type: Directive, args: [{
selector: '[matTabLabelWrapper]',
inputs: ['disabled'],
host: {
'[class.mat-tab-disabled]': 'disabled',
'[attr.aria-disabled]': '!!disabled',
}
},] },
];
/** @nocollapse */
MatTabLabelWrapper.ctorParameters = () => [
{ type: ElementRef }
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Config used to bind passive event listeners
* @type {?}
*/
const passiveEventListenerOptions = (/** @type {?} */ (normalizePassiveListenerOptions({ passive: true })));
/**
* The distance in pixels that will be overshot when scrolling a tab label into view. This helps
* provide a small affordance to the label next to it.
* @type {?}
*/
const EXAGGERATED_OVERSCROLL = 60;
/**
* Amount of milliseconds to wait before starting to scroll the header automatically.
* Set a little conservatively in order to handle fake events dispatched on touch devices.
* @type {?}
*/
const HEADER_SCROLL_DELAY = 650;
/**
* Interval in milliseconds at which to scroll the header
* while the user is holding their pointer.
* @type {?}
*/
const HEADER_SCROLL_INTERVAL = 100;
/**
* Base class for a tab header that supported pagination.
* @abstract
*/
class MatPaginatedTabHeader {
/**
* @param {?} _elementRef
* @param {?} _changeDetectorRef
* @param {?} _viewportRuler
* @param {?} _dir
* @param {?} _ngZone
* @param {?=} _platform
* @param {?=} _animationMode
*/
constructor(_elementRef, _changeDetectorRef, _viewportRuler, _dir, _ngZone, _platform, _animationMode) {
this._elementRef = _elementRef;
this._changeDetectorRef = _changeDetectorRef;
this._viewportRuler = _viewportRuler;
this._dir = _dir;
this._ngZone = _ngZone;
this._platform = _platform;
this._animationMode = _animationMode;
/**
* The distance in pixels that the tab labels should be translated to the left.
*/
this._scrollDistance = 0;
/**
* Whether the header should scroll to the selected index after the view has been checked.
*/
this._selectedIndexChanged = false;
/**
* Emits when the component is destroyed.
*/
this._destroyed = new Subject();
/**
* Whether the controls for pagination should be displayed
*/
this._showPaginationControls = false;
/**
* Whether the tab list can be scrolled more towards the end of the tab label list.
*/
this._disableScrollAfter = true;
/**
* Whether the tab list can be scrolled more towards the beginning of the tab label list.
*/
this._disableScrollBefore = true;
/**
* Stream that will stop the automated scrolling.
*/
this._stopScrolling = new Subject();
this._selectedIndex = 0;
/**
* Event emitted when the option is selected.
*/
this.selectFocusedIndex = new EventEmitter();
/**
* Event emitted when a label is focused.
*/
this.indexFocused = new EventEmitter();
// Bind the `mouseleave` event on the outside since it doesn't change anything in the view.
_ngZone.runOutsideAngular((/**
* @return {?}
*/
() => {
fromEvent(_elementRef.nativeElement, 'mouseleave')
.pipe(takeUntil(this._destroyed))
.subscribe((/**
* @return {?}
*/
() => {
this._stopInterval();
}));
}));
}
/**
* The index of the active tab.
* @return {?}
*/
get selectedIndex() { return this._selectedIndex; }
/**
* @param {?} value
* @return {?}
*/
set selectedIndex(value) {
value = coerceNumberProperty(value);
if (this._selectedIndex != value) {
this._selectedIndexChanged = true;
this._selectedIndex = value;
if (this._keyManager) {
this._keyManager.updateActiveItemIndex(value);
}
}
}
/**
* @return {?}
*/
ngAfterViewInit() {
// We need to handle these events manually, because we want to bind passive event listeners.
fromEvent(this._previousPaginator.nativeElement, 'touchstart', passiveEventListenerOptions)
.pipe(takeUntil(this._destroyed))
.subscribe((/**
* @return {?}
*/
() => {
this._handlePaginatorPress('before');
}));
fromEvent(this._nextPaginator.nativeElement, 'touchstart', passiveEventListenerOptions)
.pipe(takeUntil(this._destroyed))
.subscribe((/**
* @return {?}
*/
() => {
this._handlePaginatorPress('after');
}));
}
/**
* @return {?}
*/
ngAfterContentInit() {
/** @type {?} */
const dirChange = this._dir ? this._dir.change : of(null);
/** @type {?} */
const resize = this._viewportRuler.change(150);
/** @type {?} */
const realign = (/**
* @return {?}
*/
() => {
this.updatePagination();
this._alignInkBarToSelectedTab();
});
this._keyManager = new FocusKeyManager(this._items)
.withHorizontalOrientation(this._getLayoutDirection())
.withWrap();
this._keyManager.updateActiveItem(0);
// Defer the first call in order to allow for slower browsers to lay out the elements.
// This helps in cases where the user lands directly on a page with paginated tabs.
typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame(realign) : realign();
// On dir change or window resize, realign the ink bar and update the orientation of
// the key manager if the direction has changed.
merge(dirChange, resize, this._items.changes).pipe(takeUntil(this._destroyed)).subscribe((/**
* @return {?}
*/
() => {
realign();
this._keyManager.withHorizontalOrientation(this._getLayoutDirection());
}));
// If there is a change in the focus key manager we need to emit the `indexFocused`
// event in order to provide a public event that notifies about focus changes. Also we realign
// the tabs container by scrolling the new focused tab into the visible section.
this._keyManager.change.pipe(takeUntil(this._destroyed)).subscribe((/**
* @param {?} newFocusIndex
* @return {?}
*/
newFocusIndex => {
this.indexFocused.emit(newFocusIndex);
this._setTabFocus(newFocusIndex);
}));
}
/**
* @return {?}
*/
ngAfterContentChecked() {
// If the number of tab labels have changed, check if scrolling should be enabled
if (this._tabLabelCount != this._items.length) {
this.updatePagination();
this._tabLabelCount = this._items.length;
this._changeDetectorRef.markForCheck();
}
// If the selected index has changed, scroll to the label and check if the scrolling controls
// should be disabled.
if (this._selectedIndexChanged) {
this._scrollToLabel(this._selectedIndex);
this._checkScrollingControls();
this._alignInkBarToSelectedTab();
this._selectedIndexChanged = false;
this._changeDetectorRef.markForCheck();
}
// If the scroll distance has been changed (tab selected, focused, scroll controls activated),
// then translate the header to reflect this.
if (this._scrollDistanceChanged) {
this._updateTabScrollPosition();
this._scrollDistanceChanged = false;
this._changeDetectorRef.markForCheck();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
this._stopScrolling.complete();
}
/**
* Handles keyboard events on the header.
* @param {?} event
* @return {?}
*/
_handleKeydown(event) {
// We don't handle any key bindings with a modifier key.
if (hasModifierKey(event)) {
return;
}
switch (event.keyCode) {
case HOME:
this._keyManager.setFirstItemActive();
event.preventDefault();
break;
case END:
this._keyManager.setLastItemActive();
event.preventDefault();
break;
case ENTER:
case SPACE:
this.selectFocusedIndex.emit(this.focusIndex);
this._itemSelected(event);
break;
default:
this._keyManager.onKeydown(event);
}
}
/**
* Callback for when the MutationObserver detects that the content has changed.
* @return {?}
*/
_onContentChanges() {
/** @type {?} */
const textContent = this._elementRef.nativeElement.textContent;
// We need to diff the text content of the header, because the MutationObserver callback
// will fire even if the text content didn't change which is inefficient and is prone
// to infinite loops if a poorly constructed expression is passed in (see #14249).
if (textContent !== this._currentTextContent) {
this._currentTextContent = textContent || '';
// The content observer runs outside the `NgZone` by default, which
// means that we need to bring the callback back in ourselves.
this._ngZone.run((/**
* @return {?}
*/
() => {
this.updatePagination();
this._alignInkBarToSelectedTab();
this._changeDetectorRef.markForCheck();
}));
}
}
/**
* Updates the view whether pagination should be enabled or not.
*
* 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.
* @return {?}
*/
updatePagination() {
this._checkPaginationEnabled();
this._checkScrollingControls();
this._updateTabScrollPosition();
}
/**
* Tracks which element has focus; used for keyboard navigation
* @return {?}
*/
get focusIndex() {
return this._keyManager ? (/** @type {?} */ (this._keyManager.activeItemIndex)) : 0;
}
/**
* When the focus index is set, we must manually send focus to the correct label
* @param {?} value
* @return {?}
*/
set focusIndex(value) {
if (!this._isValidIndex(value) || this.focusIndex === value || !this._keyManager) {
return;
}
this._keyManager.setActiveItem(value);
}
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the user is
* providing a valid index and return true.
* @param {?} index
* @return {?}
*/
_isValidIndex(index) {
if (!this._items) {
return true;
}
/** @type {?} */
const tab = this._items ? this._items.toArray()[index] : null;
return !!tab && !tab.disabled;
}
/**
* Sets focus on the HTML element for the label wrapper and scrolls it into the view if
* scrolling is enabled.
* @param {?} tabIndex
* @return {?}
*/
_setTabFocus(tabIndex) {
if (this._showPaginationControls) {
this._scrollToLabel(tabIndex);
}
if (this._items && this._items.length) {
this._items.toArray()[tabIndex].focus();
// Do not let the browser manage scrolling to focus the element, this will be handled
// by using translation. In LTR, the scroll left should be 0. In RTL, the scroll width
// should be the full width minus the offset width.
/** @type {?} */
const containerEl = this._tabListContainer.nativeElement;
/** @type {?} */
const dir = this._getLayoutDirection();
if (dir == 'ltr') {
containerEl.scrollLeft = 0;
}
else {
containerEl.scrollLeft = containerEl.scrollWidth - containerEl.offsetWidth;
}
}
}
/**
* The layout direction of the containing app.
* @return {?}
*/
_getLayoutDirection() {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/**
* Performs the CSS transformation on the tab list that will cause the list to scroll.
* @return {?}
*/
_updateTabScrollPosition() {
/** @type {?} */
const scrollDistance = this.scrollDistance;
/** @type {?} */
const platform = this._platform;
/** @type {?} */
const translateX = this._getLayoutDirection() === 'ltr' ? -scrollDistance : scrollDistance;
// Don't use `translate3d` here because we don't want to create a new layer. A new layer
// seems to cause flickering and overflow in Internet Explorer. For example, the ink bar
// and ripples will exceed the boundaries of the visible tab bar.
// See: https://github.com/angular/components/issues/10276
// We round the `transform` here, because transforms with sub-pixel precision cause some
// browsers to blur the content of the element.
this._tabList.nativeElement.style.transform = `translateX(${Math.round(translateX)}px)`;
// Setting the `transform` on IE will change the scroll offset of the parent, causing the
// position to be thrown off in some cases. We have to reset it ourselves to ensure that
// it doesn't get thrown off. Note that we scope it only to IE and Edge, because messing
// with the scroll position throws off Chrome 71+ in RTL mode (see #14689).
// @breaking-change 9.0.0 Remove null check for `platform` after it can no longer be undefined.
if (platform && (platform.TRIDENT || platform.EDGE)) {
this._tabListContainer.nativeElement.scrollLeft = 0;
}
}
/**
* Sets the distance in pixels that the tab header should be transformed in the X-axis.
* @return {?}
*/
get scrollDistance() { return this._scrollDistance; }
/**
* @param {?} value
* @return {?}
*/
set scrollDistance(value) {
this._scrollTo(value);
}
/**
* Moves the tab list in the 'before' or 'after' direction (towards the beginning of the list or
* the end of the list, respectively). The distance to scroll is computed to be a third of the
* length of the tab list view window.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
* @param {?} direction
* @return {?}
*/
_scrollHeader(direction) {
/** @type {?} */
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
// Move the scroll distance one-third the length of the tab list's viewport.
/** @type {?} */
const scrollAmount = (direction == 'before' ? -1 : 1) * viewLength / 3;
return this._scrollTo(this._scrollDistance + scrollAmount);
}
/**
* Handles click events on the pagination arrows.
* @param {?} direction
* @return {?}
*/
_handlePaginatorClick(direction) {
this._stopInterval();
this._scrollHeader(direction);
}
/**
* Moves the tab list such that the desired tab label (marked by index) is moved into view.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
* @param {?} labelIndex
* @return {?}
*/
_scrollToLabel(labelIndex) {
/** @type {?} */
const selectedLabel = this._items ? this._items.toArray()[labelIndex] : null;
if (!selectedLabel) {
return;
}
// The view length is the visible width of the tab labels.
/** @type {?} */
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
const { offsetLeft, offsetWidth } = selectedLabel.elementRef.nativeElement;
/** @type {?} */
let labelBeforePos;
/** @type {?} */
let labelAfterPos;
if (this._getLayoutDirection() == 'ltr') {
labelBeforePos = offsetLeft;
labelAfterPos = labelBeforePos + offsetWidth;
}
else {
labelAfterPos = this._tabList.nativeElement.offsetWidth - offsetLeft;
labelBeforePos = labelAfterPos - offsetWidth;
}
/** @type {?} */
const beforeVisiblePos = this.scrollDistance;
/** @type {?} */
const afterVisiblePos = this.scrollDistance + viewLength;
if (labelBeforePos < beforeVisiblePos) {
// Scroll header to move label to the before direction
this.scrollDistance -= beforeVisiblePos - labelBeforePos + EXAGGERATED_OVERSCROLL;
}
else if (labelAfterPos > afterVisiblePos) {
// Scroll header to move label to the after direction
this.scrollDistance += labelAfterPos - afterVisiblePos + EXAGGERATED_OVERSCROLL;
}
}
/**
* Evaluate whether the pagination controls should be displayed. If the scroll width of the
* tab list is wider than the size of the header container, then the pagination controls should
* be shown.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
* @return {?}
*/
_checkPaginationEnabled() {
/** @type {?} */
const isEnabled = this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;
if (!isEnabled) {
this.scrollDistance = 0;
}
if (isEnabled !== this._showPaginationControls) {
this._changeDetectorRef.markForCheck();
}
this._showPaginationControls = isEnabled;
}
/**
* Evaluate whether the before and after controls should be enabled or disabled.
* If the header is at the beginning of the list (scroll distance is equal to 0) then disable the
* before button. If the header is at the end of the list (scroll distance is equal to the
* maximum distance we can scroll), then disable the after button.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
* @return {?}
*/
_checkScrollingControls() {
// Check if the pagination arrows should be activated.
this._disableScrollBefore = this.scrollDistance == 0;
this._disableScrollAfter = this.scrollDistance == this._getMaxScrollDistance();
this._changeDetectorRef.markForCheck();
}
/**
* Determines what is the maximum length in pixels that can be set for the scroll distance. This
* is equal to the difference in width between the tab list container and tab header container.
*
* This is an expensive call that forces a layout reflow to compute box and scroll metrics and
* should be called sparingly.
* @return {?}
*/
_getMaxScrollDistance() {
/** @type {?} */
const lengthOfTabList = this._tabList.nativeElement.scrollWidth;
/** @type {?} */
const viewLength = this._tabListContainer.nativeElement.offsetWidth;
return (lengthOfTabList - viewLength) || 0;
}
/**
* Tells the ink-bar to align itself to the current label wrapper
* @return {?}
*/
_alignInkBarToSelectedTab() {
/** @type {?} */
const selectedItem = this._items && this._items.length ?
this._items.toArray()[this.selectedIndex] : null;
/** @type {?} */
const selectedLabelWrapper = selectedItem ? selectedItem.elementRef.nativeElement : null;
if (selectedLabelWrapper) {
this._inkBar.alignToElement(selectedLabelWrapper);
}
else {
this._inkBar.hide();
}
}
/**
* Stops the currently-running paginator interval.
* @return {?}
*/
_stopInterval() {
this._stopScrolling.next();
}
/**
* Handles the user pressing down on one of the paginators.
* Starts scrolling the header after a certain amount of time.
* @param {?} direction In which direction the paginator should be scrolled.
* @return {?}
*/
_handlePaginatorPress(direction) {
// Avoid overlapping timers.
this._stopInterval();
// Start a timer after the delay and keep firing based on the interval.
timer(HEADER_SCROLL_DELAY, HEADER_SCROLL_INTERVAL)
// Keep the timer going until something tells it to stop or the component is destroyed.
.pipe(takeUntil(merge(this._stopScrolling, this._destroyed)))
.subscribe((/**
* @return {?}
*/
() => {
const { maxScrollDistance, distance } = this._scrollHeader(direction);
// Stop the timer if we've reached the start or the end.
if (distance === 0 || distance >= maxScrollDistance) {
this._stopInterval();
}
}));
}
/**
* Scrolls the header to a given position.
* @private
* @param {?} position Position to which to scroll.
* @return {?} Information on the current scroll distance and the maximum.
*/
_scrollTo(position) {
/** @type {?} */
const maxScrollDistance = this._getMaxScrollDistance();
this._scrollDistance = Math.max(0, Math.min(maxScrollDistance, position));
// Mark that the scroll distance has changed so that after the view is checked, the CSS
// transformation can move the header.
this._scrollDistanceChanged = true;
this._checkScrollingControls();
return { maxScrollDistance, distance: this._scrollDistance };
}
}
/** @nocollapse */
MatPaginatedTabHeader.ctorParameters = () => [
{ type: ElementRef },
{ type: ChangeDetectorRef },
{ type: ViewportRuler },
{ type: Directionality, decorators: [{ type: Optional }] },
{ type: NgZone },
{ type: Platform },
{ type: String }
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* The header of the tab group which displays a list of all the tabs in the tab group. Includes
* an ink bar that follows the currently selected tab. When the tabs list's width exceeds the
* width of the header container, then arrows will be displayed to allow the user to scroll
* left and right across the header.
* \@docs-private
*/
class MatTabHeader extends MatPaginatedTabHeader {
/**
* @param {?} elementRef
* @param {?} changeDetectorRef
* @param {?} viewportRuler
* @param {?} dir
* @param {?} ngZone
* @param {?} platform
* @param {?=} animationMode
*/
constructor(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform,
// @breaking-change 9.0.0 `_animationMode` parameter to be made required.
animationMode) {
super(elementRef, changeDetectorRef, viewportRuler, dir, ngZone, platform, animationMode);
this._disableRipple = false;
}
/**
* Whether the ripple effect is disabled or not.
* @return {?}
*/
get disableRipple() { return this._disableRipple; }
/**
* @param {?} value
* @return {?}
*/
set disableRipple(value) { this._disableRipple = coerceBooleanProperty(value); }
/**
* @protected
* @param {?} event
* @return {?}
*/
_itemSelected(event) {
event.preventDefault();
}
}
MatTabHeader.decorators = [
{ type: Component, args: [{selector: 'mat-tab-header',
template: "<div class=\"mat-tab-header-pagination mat-tab-header-pagination-before mat-elevation-z4\" #previousPaginator aria-hidden=\"true\" mat-ripple [matRippleDisabled]=\"_disableScrollBefore || disableRipple\" [class.mat-tab-header-pagination-disabled]=\"_disableScrollBefore\" (click)=\"_handlePaginatorClick('before')\" (mousedown)=\"_handlePaginatorPress('before')\" (touchend)=\"_stopInterval()\"><div class=\"mat-tab-header-pagination-chevron\"></div></div><div class=\"mat-tab-label-container\" #tabListContainer (keydown)=\"_handleKeydown($event)\"><div #tabList class=\"mat-tab-list\" [class._mat-animation-noopable]=\"_animationMode === 'NoopAnimations'\" role=\"tablist\" (cdkObserveContent)=\"_onContentChanges()\"><div class=\"mat-tab-labels\"><ng-content></ng-content></div><mat-ink-bar></mat-ink-bar></div></div><div class=\"mat-tab-header-pagination mat-tab-header-pagination-after mat-elevation-z4\" #nextPaginator aria-hidden=\"true\" mat-ripple [matRippleDisabled]=\"_disableScrollAfter || disableRipple\" [class.mat-tab-header-pagination-disabled]=\"_disableScrollAfter\" (mousedown)=\"_handlePaginatorPress('after')\" (click)=\"_handlePaginatorClick('after')\" (touchend)=\"_stopInterval()\"><div class=\"mat-tab-header-pagination-chevron\"></div></div>",
styles: [".mat-tab-header{display:flex;overflow:hidden;position:relative;flex-shrink:0}.mat-tab-header-pagination{-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;position:relative;display:none;justify-content:center;align-items:center;min-width:32px;cursor:pointer;z-index:2;-webkit-tap-highlight-color:transparent;touch-action:none}.mat-tab-header-pagination-controls-enabled .mat-tab-header-pagination{display:flex}.mat-tab-header-pagination-before,.mat-tab-header-rtl .mat-tab-header-pagination-after{padding-left:4px}.mat-tab-header-pagination-before .mat-tab-header-pagination-chevron,.mat-tab-header-rtl .mat-tab-header-pagination-after .mat-tab-header-pagination-chevron{transform:rotate(-135deg)}.mat-tab-header-pagination-after,.mat-tab-header-rtl .mat-tab-header-pagination-before{padding-right:4px}.mat-tab-header-pagination-after .mat-tab-header-pagination-chevron,.mat-tab-header-rtl .mat-tab-header-pagination-before .mat-tab-header-pagination-chevron{transform:rotate(45deg)}.mat-tab-header-pagination-chevron{border-style:solid;border-width:2px 2px 0 0;content:'';height:8px;width:8px}.mat-tab-header-pagination-disabled{box-shadow:none;cursor:default}.mat-tab-list{flex-grow:1;position:relative;transition:transform .5s cubic-bezier(.35,0,.25,1)}.mat-ink-bar{position:absolute;bottom:0;height:2px;transition:.5s cubic-bezier(.35,0,.25,1)}._mat-animation-noopable.mat-ink-bar{transition:none;animation:none}.mat-tab-group-inverted-header .mat-ink-bar{bottom:auto;top:0}@media (-ms-high-contrast:active){.mat-ink-bar{outline:solid 2px;height:0}}.mat-tab-labels{display:flex}[mat-align-tabs=center] .mat-tab-labels{justify-content:center}[mat-align-tabs=end] .mat-tab-labels{justify-content:flex-end}.mat-tab-label-container{display:flex;flex-grow:1;overflow:hidden;z-index:1}._mat-animation-noopable.mat-tab-list{transition:none;animation:none}.mat-tab-label{height:48px;padding:0 24px;cursor:pointer;box-sizing:border-box;opacity:.6;min-width:160px;text-align:center;display:inline-flex;justify-content:center;align-items:center;white-space:nowrap;position:relative}.mat-tab-label:focus{outline:0}.mat-tab-label:focus:not(.mat-tab-disabled){opacity:1}@media (-ms-high-contrast:active){.mat-tab-label:focus{outline:dotted 2px}}.mat-tab-label.mat-tab-disabled{cursor:default}@media (-ms-high-contrast:active){.mat-tab-label.mat-tab-disabled{opacity:.5}}.mat-tab-label .mat-tab-label-content{display:inline-flex;justify-content:center;align-items:center;white-space:nowrap}@media (-ms-high-contrast:active){.mat-tab-label{opacity:1}}@media (max-width:599px){.mat-tab-label{min-width:72px}}"],
inputs: ['selectedIndex'],
outputs: ['selectFocusedIndex', 'indexFocused'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'mat-tab-header',
'[class.mat-tab-header-pagination-controls-enabled]': '_showPaginationControls',
'[class.mat-tab-header-rtl]': "_getLayoutDire