@angular/material
Version:
Angular Material
1,459 lines (1,444 loc) • 117 kB
JavaScript
import { Version, InjectionToken, isDevMode, NgModule, Optional, Inject, inject, LOCALE_ID, Injectable, ɵɵdefineInjectable, Directive, ElementRef, NgZone, Input, Component, ViewEncapsulation, ChangeDetectionStrategy, EventEmitter, ChangeDetectorRef, Output } from '@angular/core';
import { HighContrastModeDetector, isFakeMousedownFromScreenReader } from '@angular/cdk/a11y';
import { BidiModule } from '@angular/cdk/bidi';
import { VERSION as VERSION$2 } from '@angular/cdk';
import { coerceBooleanProperty, coerceElement } from '@angular/cdk/coercion';
import { Subject, Observable } from 'rxjs';
import { Platform, PlatformModule, normalizePassiveListenerOptions } from '@angular/cdk/platform';
import { HammerGestureConfig } from '@angular/platform-browser';
import { startWith } from 'rxjs/operators';
import { CommonModule } from '@angular/common';
import { ANIMATION_MODULE_TYPE } from '@angular/platform-browser/animations';
import { ENTER, SPACE, hasModifierKey } from '@angular/cdk/keycodes';
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/version.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Current version of Angular Material.
* @type {?}
*/
const VERSION = new Version('9.0.1');
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/animation/animation.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @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
*/
/**
* \@docs-private
*/
class AnimationCurves {
}
AnimationCurves.STANDARD_CURVE = 'cubic-bezier(0.4,0.0,0.2,1)';
AnimationCurves.DECELERATION_CURVE = 'cubic-bezier(0.0,0.0,0.2,1)';
AnimationCurves.ACCELERATION_CURVE = 'cubic-bezier(0.4,0.0,1,1)';
AnimationCurves.SHARP_CURVE = 'cubic-bezier(0.4,0.0,0.6,1)';
if (false) {
/** @type {?} */
AnimationCurves.STANDARD_CURVE;
/** @type {?} */
AnimationCurves.DECELERATION_CURVE;
/** @type {?} */
AnimationCurves.ACCELERATION_CURVE;
/** @type {?} */
AnimationCurves.SHARP_CURVE;
}
/**
* \@docs-private
*/
class AnimationDurations {
}
AnimationDurations.COMPLEX = '375ms';
AnimationDurations.ENTERING = '225ms';
AnimationDurations.EXITING = '195ms';
if (false) {
/** @type {?} */
AnimationDurations.COMPLEX;
/** @type {?} */
AnimationDurations.ENTERING;
/** @type {?} */
AnimationDurations.EXITING;
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/common-module.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// Private version constant to circumvent test/build issues,
// i.e. avoid core to depend on the @angular/material primary entry-point
// Can be removed once the Material primary entry-point no longer
// re-exports all secondary entry-points
/** @type {?} */
const VERSION$1 = new Version('9.0.1');
/**
* \@docs-private
* @return {?}
*/
function MATERIAL_SANITY_CHECKS_FACTORY() {
return true;
}
/**
* Injection token that configures whether the Material sanity checks are enabled.
* @type {?}
*/
const MATERIAL_SANITY_CHECKS = new InjectionToken('mat-sanity-checks', {
providedIn: 'root',
factory: MATERIAL_SANITY_CHECKS_FACTORY,
});
/**
* Object that can be used to configure the sanity checks granularly.
* @record
*/
function GranularSanityChecks() { }
if (false) {
/** @type {?} */
GranularSanityChecks.prototype.doctype;
/** @type {?} */
GranularSanityChecks.prototype.theme;
/** @type {?} */
GranularSanityChecks.prototype.version;
/**
* @deprecated No longer being used.
* \@breaking-change 10.0.0
* @type {?}
*/
GranularSanityChecks.prototype.hammer;
}
/**
* Module that captures anything that should be loaded and/or run for *all* Angular Material
* components. This includes Bidi, etc.
*
* This module should be imported to each top-level component module (e.g., MatTabsModule).
*/
class MatCommonModule {
/**
* @param {?} highContrastModeDetector
* @param {?} sanityChecks
*/
constructor(highContrastModeDetector, sanityChecks) {
/**
* Whether we've done the global sanity checks (e.g. a theme is loaded, there is a doctype).
*/
this._hasDoneGlobalChecks = false;
/**
* Reference to the global `document` object.
*/
this._document = typeof document === 'object' && document ? document : null;
/**
* Reference to the global 'window' object.
*/
this._window = typeof window === 'object' && window ? window : null;
// While A11yModule also does this, we repeat it here to avoid importing A11yModule
// in MatCommonModule.
highContrastModeDetector._applyBodyHighContrastModeCssClasses();
// Note that `_sanityChecks` is typed to `any`, because AoT
// throws an error if we use the `SanityChecks` type directly.
this._sanityChecks = sanityChecks;
if (!this._hasDoneGlobalChecks) {
this._checkDoctypeIsDefined();
this._checkThemeIsPresent();
this._checkCdkVersionMatch();
this._hasDoneGlobalChecks = true;
}
}
/**
* Whether any sanity checks are enabled.
* @private
* @return {?}
*/
_checksAreEnabled() {
return isDevMode() && !this._isTestEnv();
}
/**
* Whether the code is running in tests.
* @private
* @return {?}
*/
_isTestEnv() {
/** @type {?} */
const window = (/** @type {?} */ (this._window));
return window && (window.__karma__ || window.jasmine);
}
/**
* @private
* @return {?}
*/
_checkDoctypeIsDefined() {
/** @type {?} */
const isEnabled = this._checksAreEnabled() &&
(this._sanityChecks === true || ((/** @type {?} */ (this._sanityChecks))).doctype);
if (isEnabled && this._document && !this._document.doctype) {
console.warn('Current document does not have a doctype. This may cause ' +
'some Angular Material components not to behave as expected.');
}
}
/**
* @private
* @return {?}
*/
_checkThemeIsPresent() {
// We need to assert that the `body` is defined, because these checks run very early
// and the `body` won't be defined if the consumer put their scripts in the `head`.
/** @type {?} */
const isDisabled = !this._checksAreEnabled() ||
(this._sanityChecks === false || !((/** @type {?} */ (this._sanityChecks))).theme);
if (isDisabled || !this._document || !this._document.body ||
typeof getComputedStyle !== 'function') {
return;
}
/** @type {?} */
const testElement = this._document.createElement('div');
testElement.classList.add('mat-theme-loaded-marker');
this._document.body.appendChild(testElement);
/** @type {?} */
const computedStyle = getComputedStyle(testElement);
// In some situations the computed style of the test element can be null. For example in
// Firefox, the computed style is null if an application is running inside of a hidden iframe.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=548397
if (computedStyle && computedStyle.display !== 'none') {
console.warn('Could not find Angular Material core theme. Most Material ' +
'components may not work as expected. For more info refer ' +
'to the theming guide: https://material.angular.io/guide/theming');
}
this._document.body.removeChild(testElement);
}
/**
* Checks whether the material version matches the cdk version
* @private
* @return {?}
*/
_checkCdkVersionMatch() {
/** @type {?} */
const isEnabled = this._checksAreEnabled() &&
(this._sanityChecks === true || ((/** @type {?} */ (this._sanityChecks))).version);
if (isEnabled && VERSION$1.full !== VERSION$2.full) {
console.warn('The Angular Material version (' + VERSION$1.full + ') does not match ' +
'the Angular CDK version (' + VERSION$2.full + ').\n' +
'Please ensure the versions of these two packages exactly match.');
}
}
}
MatCommonModule.decorators = [
{ type: NgModule, args: [{
imports: [BidiModule],
exports: [BidiModule],
},] }
];
/** @nocollapse */
MatCommonModule.ctorParameters = () => [
{ type: HighContrastModeDetector },
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MATERIAL_SANITY_CHECKS,] }] }
];
if (false) {
/**
* Whether we've done the global sanity checks (e.g. a theme is loaded, there is a doctype).
* @type {?}
* @private
*/
MatCommonModule.prototype._hasDoneGlobalChecks;
/**
* Reference to the global `document` object.
* @type {?}
* @private
*/
MatCommonModule.prototype._document;
/**
* Reference to the global 'window' object.
* @type {?}
* @private
*/
MatCommonModule.prototype._window;
/**
* Configured sanity checks.
* @type {?}
* @private
*/
MatCommonModule.prototype._sanityChecks;
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/disabled.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@docs-private
* @record
*/
function CanDisable() { }
if (false) {
/**
* Whether the component is disabled.
* @type {?}
*/
CanDisable.prototype.disabled;
}
/**
* Mixin to augment a directive with a `disabled` property.
* @template T
* @param {?} base
* @return {?}
*/
function mixinDisabled(base) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
this._disabled = false;
}
/**
* @return {?}
*/
get disabled() { return this._disabled; }
/**
* @param {?} value
* @return {?}
*/
set disabled(value) { this._disabled = coerceBooleanProperty(value); }
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/color.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @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
*/
/**
* \@docs-private
* @record
*/
function CanColor() { }
if (false) {
/**
* Theme color palette for the component.
* @type {?}
*/
CanColor.prototype.color;
}
/**
* \@docs-private
* @record
*/
function HasElementRef() { }
if (false) {
/** @type {?} */
HasElementRef.prototype._elementRef;
}
/**
* Mixin to augment a directive with a `color` property.
* @template T
* @param {?} base
* @param {?=} defaultColor
* @return {?}
*/
function mixinColor(base, defaultColor) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
// Set the default color that can be specified from the mixin.
this.color = defaultColor;
}
/**
* @return {?}
*/
get color() { return this._color; }
/**
* @param {?} value
* @return {?}
*/
set color(value) {
/** @type {?} */
const colorPalette = value || defaultColor;
if (colorPalette !== this._color) {
if (this._color) {
this._elementRef.nativeElement.classList.remove(`mat-${this._color}`);
}
if (colorPalette) {
this._elementRef.nativeElement.classList.add(`mat-${colorPalette}`);
}
this._color = colorPalette;
}
}
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/disable-ripple.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@docs-private
* @record
*/
function CanDisableRipple() { }
if (false) {
/**
* Whether ripples are disabled.
* @type {?}
*/
CanDisableRipple.prototype.disableRipple;
}
/**
* Mixin to augment a directive with a `disableRipple` property.
* @template T
* @param {?} base
* @return {?}
*/
function mixinDisableRipple(base) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
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); }
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/tabindex.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @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
*/
/**
* \@docs-private
* @record
*/
function HasTabIndex() { }
if (false) {
/**
* Tabindex of the component.
* @type {?}
*/
HasTabIndex.prototype.tabIndex;
}
/**
* Mixin to augment a directive with a `tabIndex` property.
* @template T
* @param {?} base
* @param {?=} defaultTabIndex
* @return {?}
*/
function mixinTabIndex(base, defaultTabIndex = 0) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
this._tabIndex = defaultTabIndex;
}
/**
* @return {?}
*/
get tabIndex() { return this.disabled ? -1 : this._tabIndex; }
/**
* @param {?} value
* @return {?}
*/
set tabIndex(value) {
// If the specified tabIndex value is null or undefined, fall back to the default value.
this._tabIndex = value != null ? value : defaultTabIndex;
}
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/error-state.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* \@docs-private
* @record
*/
function CanUpdateErrorState() { }
if (false) {
/** @type {?} */
CanUpdateErrorState.prototype.stateChanges;
/** @type {?} */
CanUpdateErrorState.prototype.errorState;
/** @type {?} */
CanUpdateErrorState.prototype.errorStateMatcher;
/**
* @return {?}
*/
CanUpdateErrorState.prototype.updateErrorState = function () { };
}
/**
* \@docs-private
* @record
*/
function HasErrorState() { }
if (false) {
/** @type {?} */
HasErrorState.prototype._parentFormGroup;
/** @type {?} */
HasErrorState.prototype._parentForm;
/** @type {?} */
HasErrorState.prototype._defaultErrorStateMatcher;
/** @type {?} */
HasErrorState.prototype.ngControl;
}
/**
* Mixin to augment a directive with updateErrorState method.
* For component with `errorState` and need to update `errorState`.
* @template T
* @param {?} base
* @return {?}
*/
function mixinErrorState(base) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
/**
* Whether the component is in an error state.
*/
this.errorState = false;
/**
* Stream that emits whenever the state of the input changes such that the wrapping
* `MatFormField` needs to run change detection.
*/
this.stateChanges = new Subject();
}
/**
* @return {?}
*/
updateErrorState() {
/** @type {?} */
const oldState = this.errorState;
/** @type {?} */
const parent = this._parentFormGroup || this._parentForm;
/** @type {?} */
const matcher = this.errorStateMatcher || this._defaultErrorStateMatcher;
/** @type {?} */
const control = this.ngControl ? (/** @type {?} */ (this.ngControl.control)) : null;
/** @type {?} */
const newState = matcher.isErrorState(control, parent);
if (newState !== oldState) {
this.errorState = newState;
this.stateChanges.next();
}
}
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/initialized.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* Mixin that adds an initialized property to a directive which, when subscribed to, will emit a
* value once markInitialized has been called, which should be done during the ngOnInit function.
* If the subscription is made after it has already been marked as initialized, then it will trigger
* an emit immediately.
* \@docs-private
* @record
*/
function HasInitialized() { }
if (false) {
/**
* Stream that emits once during the directive/component's ngOnInit.
* @type {?}
*/
HasInitialized.prototype.initialized;
/**
* Sets the state as initialized and must be called during ngOnInit to notify subscribers that
* the directive has been initialized.
* \@docs-private
* @type {?}
*/
HasInitialized.prototype._markInitialized;
}
/**
* Mixin to augment a directive with an initialized property that will emits when ngOnInit ends.
* @template T
* @param {?} base
* @return {?}
*/
function mixinInitialized(base) {
return class extends base {
/**
* @param {...?} args
*/
constructor(...args) {
super(...args);
/**
* Whether this directive has been marked as initialized.
*/
this._isInitialized = false;
/**
* List of subscribers that subscribed before the directive was initialized. Should be notified
* during _markInitialized. Set to null after pending subscribers are notified, and should
* not expect to be populated after.
*/
this._pendingSubscribers = [];
/**
* Observable stream that emits when the directive initializes. If already initialized, the
* subscriber is stored to be notified once _markInitialized is called.
*/
this.initialized = new Observable((/**
* @param {?} subscriber
* @return {?}
*/
subscriber => {
// If initialized, immediately notify the subscriber. Otherwise store the subscriber to notify
// when _markInitialized is called.
if (this._isInitialized) {
this._notifySubscriber(subscriber);
}
else {
(/** @type {?} */ (this._pendingSubscribers)).push(subscriber);
}
}));
}
/**
* Marks the state as initialized and notifies pending subscribers. Should be called at the end
* of ngOnInit.
* \@docs-private
* @return {?}
*/
_markInitialized() {
if (this._isInitialized) {
throw Error('This directive has already been marked as initialized and ' +
'should not be called twice.');
}
this._isInitialized = true;
(/** @type {?} */ (this._pendingSubscribers)).forEach(this._notifySubscriber);
this._pendingSubscribers = null;
}
/**
* Emits and completes the subscriber stream (should only emit once).
* @param {?} subscriber
* @return {?}
*/
_notifySubscriber(subscriber) {
subscriber.next();
subscriber.complete();
}
};
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/common-behaviors/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/datetime/date-adapter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* InjectionToken for datepicker that can be used to override default locale code.
* @type {?}
*/
const MAT_DATE_LOCALE = new InjectionToken('MAT_DATE_LOCALE', {
providedIn: 'root',
factory: MAT_DATE_LOCALE_FACTORY,
});
/**
* \@docs-private
* @return {?}
*/
function MAT_DATE_LOCALE_FACTORY() {
return inject(LOCALE_ID);
}
/**
* No longer needed since MAT_DATE_LOCALE has been changed to a scoped injectable.
* If you are importing and providing this in your code you can simply remove it.
* @deprecated
* \@breaking-change 8.0.0
* @type {?}
*/
const MAT_DATE_LOCALE_PROVIDER = { provide: MAT_DATE_LOCALE, useExisting: LOCALE_ID };
/**
* Adapts type `D` to be usable as a date by cdk-based components that work with dates.
* @abstract
* @template D
*/
class DateAdapter {
constructor() {
this._localeChanges = new Subject();
}
/**
* A stream that emits when the locale changes.
* @return {?}
*/
get localeChanges() { return this._localeChanges; }
/**
* Attempts to deserialize a value to a valid date object. This is different from parsing in that
* deserialize should only accept non-ambiguous, locale-independent formats (e.g. a ISO 8601
* string). The default implementation does not allow any deserialization, it simply checks that
* the given value is already a valid date object or null. The `<mat-datepicker>` will call this
* method on all of its `\@Input()` properties that accept dates. It is therefore possible to
* support passing values from your backend directly to these properties by overriding this method
* to also deserialize the format used by your backend.
* @param {?} value The value to be deserialized into a date object.
* @return {?} The deserialized date object, either a valid date, null if the value can be
* deserialized into a null date (e.g. the empty string), or an invalid date.
*/
deserialize(value) {
if (value == null || this.isDateInstance(value) && this.isValid(value)) {
return value;
}
return this.invalid();
}
/**
* Sets the locale used for all dates.
* @param {?} locale The new locale.
* @return {?}
*/
setLocale(locale) {
this.locale = locale;
this._localeChanges.next();
}
/**
* Compares two dates.
* @param {?} first The first date to compare.
* @param {?} second The second date to compare.
* @return {?} 0 if the dates are equal, a number less than 0 if the first date is earlier,
* a number greater than 0 if the first date is later.
*/
compareDate(first, second) {
return this.getYear(first) - this.getYear(second) ||
this.getMonth(first) - this.getMonth(second) ||
this.getDate(first) - this.getDate(second);
}
/**
* Checks if two dates are equal.
* @param {?} first The first date to check.
* @param {?} second The second date to check.
* @return {?} Whether the two dates are equal.
* Null dates are considered equal to other null dates.
*/
sameDate(first, second) {
if (first && second) {
/** @type {?} */
let firstValid = this.isValid(first);
/** @type {?} */
let secondValid = this.isValid(second);
if (firstValid && secondValid) {
return !this.compareDate(first, second);
}
return firstValid == secondValid;
}
return first == second;
}
/**
* Clamp the given date between min and max dates.
* @param {?} date The date to clamp.
* @param {?=} min The minimum value to allow. If null or omitted no min is enforced.
* @param {?=} max The maximum value to allow. If null or omitted no max is enforced.
* @return {?} `min` if `date` is less than `min`, `max` if date is greater than `max`,
* otherwise `date`.
*/
clampDate(date, min, max) {
if (min && this.compareDate(date, min) < 0) {
return min;
}
if (max && this.compareDate(date, max) > 0) {
return max;
}
return date;
}
}
if (false) {
/**
* The locale to use for all dates.
* @type {?}
* @protected
*/
DateAdapter.prototype.locale;
/**
* @type {?}
* @protected
*/
DateAdapter.prototype._localeChanges;
/**
* Gets the year component of the given date.
* @abstract
* @param {?} date The date to extract the year from.
* @return {?} The year component.
*/
DateAdapter.prototype.getYear = function (date) { };
/**
* Gets the month component of the given date.
* @abstract
* @param {?} date The date to extract the month from.
* @return {?} The month component (0-indexed, 0 = January).
*/
DateAdapter.prototype.getMonth = function (date) { };
/**
* Gets the date of the month component of the given date.
* @abstract
* @param {?} date The date to extract the date of the month from.
* @return {?} The month component (1-indexed, 1 = first of month).
*/
DateAdapter.prototype.getDate = function (date) { };
/**
* Gets the day of the week component of the given date.
* @abstract
* @param {?} date The date to extract the day of the week from.
* @return {?} The month component (0-indexed, 0 = Sunday).
*/
DateAdapter.prototype.getDayOfWeek = function (date) { };
/**
* Gets a list of names for the months.
* @abstract
* @param {?} style The naming style (e.g. long = 'January', short = 'Jan', narrow = 'J').
* @return {?} An ordered list of all month names, starting with January.
*/
DateAdapter.prototype.getMonthNames = function (style) { };
/**
* Gets a list of names for the dates of the month.
* @abstract
* @return {?} An ordered list of all date of the month names, starting with '1'.
*/
DateAdapter.prototype.getDateNames = function () { };
/**
* Gets a list of names for the days of the week.
* @abstract
* @param {?} style The naming style (e.g. long = 'Sunday', short = 'Sun', narrow = 'S').
* @return {?} An ordered list of all weekday names, starting with Sunday.
*/
DateAdapter.prototype.getDayOfWeekNames = function (style) { };
/**
* Gets the name for the year of the given date.
* @abstract
* @param {?} date The date to get the year name for.
* @return {?} The name of the given year (e.g. '2017').
*/
DateAdapter.prototype.getYearName = function (date) { };
/**
* Gets the first day of the week.
* @abstract
* @return {?} The first day of the week (0-indexed, 0 = Sunday).
*/
DateAdapter.prototype.getFirstDayOfWeek = function () { };
/**
* Gets the number of days in the month of the given date.
* @abstract
* @param {?} date The date whose month should be checked.
* @return {?} The number of days in the month of the given date.
*/
DateAdapter.prototype.getNumDaysInMonth = function (date) { };
/**
* Clones the given date.
* @abstract
* @param {?} date The date to clone
* @return {?} A new date equal to the given date.
*/
DateAdapter.prototype.clone = function (date) { };
/**
* Creates a date with the given year, month, and date. Does not allow over/under-flow of the
* month and date.
* @abstract
* @param {?} year The full year of the date. (e.g. 89 means the year 89, not the year 1989).
* @param {?} month The month of the date (0-indexed, 0 = January). Must be an integer 0 - 11.
* @param {?} date The date of month of the date. Must be an integer 1 - length of the given month.
* @return {?} The new date, or null if invalid.
*/
DateAdapter.prototype.createDate = function (year, month, date) { };
/**
* Gets today's date.
* @abstract
* @return {?} Today's date.
*/
DateAdapter.prototype.today = function () { };
/**
* Parses a date from a user-provided value.
* @abstract
* @param {?} value The value to parse.
* @param {?} parseFormat The expected format of the value being parsed
* (type is implementation-dependent).
* @return {?} The parsed date.
*/
DateAdapter.prototype.parse = function (value, parseFormat) { };
/**
* Formats a date as a string according to the given format.
* @abstract
* @param {?} date The value to format.
* @param {?} displayFormat The format to use to display the date as a string.
* @return {?} The formatted date string.
*/
DateAdapter.prototype.format = function (date, displayFormat) { };
/**
* Adds the given number of years to the date. Years are counted as if flipping 12 pages on the
* calendar for each year and then finding the closest date in the new month. For example when
* adding 1 year to Feb 29, 2016, the resulting date will be Feb 28, 2017.
* @abstract
* @param {?} date The date to add years to.
* @param {?} years The number of years to add (may be negative).
* @return {?} A new date equal to the given one with the specified number of years added.
*/
DateAdapter.prototype.addCalendarYears = function (date, years) { };
/**
* Adds the given number of months to the date. Months are counted as if flipping a page on the
* calendar for each month and then finding the closest date in the new month. For example when
* adding 1 month to Jan 31, 2017, the resulting date will be Feb 28, 2017.
* @abstract
* @param {?} date The date to add months to.
* @param {?} months The number of months to add (may be negative).
* @return {?} A new date equal to the given one with the specified number of months added.
*/
DateAdapter.prototype.addCalendarMonths = function (date, months) { };
/**
* Adds the given number of days to the date. Days are counted as if moving one cell on the
* calendar for each day.
* @abstract
* @param {?} date The date to add days to.
* @param {?} days The number of days to add (may be negative).
* @return {?} A new date equal to the given one with the specified number of days added.
*/
DateAdapter.prototype.addCalendarDays = function (date, days) { };
/**
* Gets the RFC 3339 compatible string (https://tools.ietf.org/html/rfc3339) for the given date.
* This method is used to generate date strings that are compatible with native HTML attributes
* such as the `min` or `max` attribute of an `<input>`.
* @abstract
* @param {?} date The date to get the ISO date string for.
* @return {?} The ISO date string date string.
*/
DateAdapter.prototype.toIso8601 = function (date) { };
/**
* Checks whether the given object is considered a date instance by this DateAdapter.
* @abstract
* @param {?} obj The object to check
* @return {?} Whether the object is a date instance.
*/
DateAdapter.prototype.isDateInstance = function (obj) { };
/**
* Checks whether the given date is valid.
* @abstract
* @param {?} date The date to check.
* @return {?} Whether the date is valid.
*/
DateAdapter.prototype.isValid = function (date) { };
/**
* Gets date instance that is not valid.
* @abstract
* @return {?} An invalid date.
*/
DateAdapter.prototype.invalid = function () { };
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/datetime/date-formats.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/** @type {?} */
const MAT_DATE_FORMATS = new InjectionToken('mat-date-formats');
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/datetime/native-date-adapter.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// TODO(mmalerba): Remove when we no longer support safari 9.
/**
* Whether the browser supports the Intl API.
* @type {?}
*/
let SUPPORTS_INTL_API;
// We need a try/catch around the reference to `Intl`, because accessing it in some cases can
// cause IE to throw. These cases are tied to particular versions of Windows and can happen if
// the consumer is providing a polyfilled `Map`. See:
// https://github.com/Microsoft/ChakraCore/issues/3189
// https://github.com/angular/components/issues/15687
try {
SUPPORTS_INTL_API = typeof Intl != 'undefined';
}
catch (_a) {
SUPPORTS_INTL_API = false;
}
/**
* The default month names to use if Intl API is not available.
* @type {?}
*/
const DEFAULT_MONTH_NAMES = {
'long': [
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
],
'short': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
'narrow': ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D']
};
const ɵ0 = /**
* @param {?} i
* @return {?}
*/
i => String(i + 1);
/**
* The default date names to use if Intl API is not available.
* @type {?}
*/
const DEFAULT_DATE_NAMES = range(31, (ɵ0));
/**
* The default day of the week names to use if Intl API is not available.
* @type {?}
*/
const DEFAULT_DAY_OF_WEEK_NAMES = {
'long': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
'short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
'narrow': ['S', 'M', 'T', 'W', 'T', 'F', 'S']
};
/**
* Matches strings that have the form of a valid RFC 3339 string
* (https://tools.ietf.org/html/rfc3339). Note that the string may not actually be a valid date
* because the regex will match strings an with out of bounds month, date, etc.
* @type {?}
*/
const ISO_8601_REGEX = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|(?:(?:\+|-)\d{2}:\d{2}))?)?$/;
/**
* Creates an array and fills it with values.
* @template T
* @param {?} length
* @param {?} valueFunction
* @return {?}
*/
function range(length, valueFunction) {
/** @type {?} */
const valuesArray = Array(length);
for (let i = 0; i < length; i++) {
valuesArray[i] = valueFunction(i);
}
return valuesArray;
}
/**
* Adapts the native JS Date for use with cdk-based components that work with dates.
*/
class NativeDateAdapter extends DateAdapter {
/**
* @param {?} matDateLocale
* @param {?} platform
*/
constructor(matDateLocale, platform) {
super();
/**
* Whether to use `timeZone: 'utc'` with `Intl.DateTimeFormat` when formatting dates.
* Without this `Intl.DateTimeFormat` sometimes chooses the wrong timeZone, which can throw off
* the result. (e.g. in the en-US locale `new Date(1800, 7, 14).toLocaleDateString()`
* will produce `'8/13/1800'`.
*
* TODO(mmalerba): drop this variable. It's not being used in the code right now. We're now
* getting the string representation of a Date object from its utc representation. We're keeping
* it here for sometime, just for precaution, in case we decide to revert some of these changes
* though.
*/
this.useUtcForDisplay = true;
super.setLocale(matDateLocale);
// IE does its own time zone correction, so we disable this on IE.
this.useUtcForDisplay = !platform.TRIDENT;
this._clampDate = platform.TRIDENT || platform.EDGE;
}
/**
* @param {?} date
* @return {?}
*/
getYear(date) {
return date.getFullYear();
}
/**
* @param {?} date
* @return {?}
*/
getMonth(date) {
return date.getMonth();
}
/**
* @param {?} date
* @return {?}
*/
getDate(date) {
return date.getDate();
}
/**
* @param {?} date
* @return {?}
*/
getDayOfWeek(date) {
return date.getDay();
}
/**
* @param {?} style
* @return {?}
*/
getMonthNames(style) {
if (SUPPORTS_INTL_API) {
/** @type {?} */
const dtf = new Intl.DateTimeFormat(this.locale, { month: style, timeZone: 'utc' });
return range(12, (/**
* @param {?} i
* @return {?}
*/
i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, i, 1)))));
}
return DEFAULT_MONTH_NAMES[style];
}
/**
* @return {?}
*/
getDateNames() {
if (SUPPORTS_INTL_API) {
/** @type {?} */
const dtf = new Intl.DateTimeFormat(this.locale, { day: 'numeric', timeZone: 'utc' });
return range(31, (/**
* @param {?} i
* @return {?}
*/
i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, 0, i + 1)))));
}
return DEFAULT_DATE_NAMES;
}
/**
* @param {?} style
* @return {?}
*/
getDayOfWeekNames(style) {
if (SUPPORTS_INTL_API) {
/** @type {?} */
const dtf = new Intl.DateTimeFormat(this.locale, { weekday: style, timeZone: 'utc' });
return range(7, (/**
* @param {?} i
* @return {?}
*/
i => this._stripDirectionalityCharacters(this._format(dtf, new Date(2017, 0, i + 1)))));
}
return DEFAULT_DAY_OF_WEEK_NAMES[style];
}
/**
* @param {?} date
* @return {?}
*/
getYearName(date) {
if (SUPPORTS_INTL_API) {
/** @type {?} */
const dtf = new Intl.DateTimeFormat(this.locale, { year: 'numeric', timeZone: 'utc' });
return this._stripDirectionalityCharacters(this._format(dtf, date));
}
return String(this.getYear(date));
}
/**
* @return {?}
*/
getFirstDayOfWeek() {
// We can't tell using native JS Date what the first day of the week is, we default to Sunday.
return 0;
}
/**
* @param {?} date
* @return {?}
*/
getNumDaysInMonth(date) {
return this.getDate(this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0));
}
/**
* @param {?} date
* @return {?}
*/
clone(date) {
return new Date(date.getTime());
}
/**
* @param {?} year
* @param {?} month
* @param {?} date
* @return {?}
*/
createDate(year, month, date) {
// Check for invalid month and date (except upper bound on date which we have to check after
// creating the Date).
if (month < 0 || month > 11) {
throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
}
if (date < 1) {
throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
}
/** @type {?} */
let result = this._createDateWithOverflow(year, month, date);
// Check that the date wasn't above the upper bound for the month, causing the month to overflow
if (result.getMonth() != month) {
throw Error(`Invalid date "${date}" for month with index "${month}".`);
}
return result;
}
/**
* @return {?}
*/
today() {
return new Date();
}
/**
* @param {?} value
* @return {?}
*/
parse(value) {
// We have no way using the native JS Date to set the parse format or locale, so we ignore these
// parameters.
if (typeof value == 'number') {
return new Date(value);
}
return value ? new Date(Date.parse(value)) : null;
}
/**
* @param {?} date
* @param {?} displayFormat
* @return {?}
*/
format(date, displayFormat) {
if (!this.isValid(date)) {
throw Error('NativeDateAdapter: Cannot format invalid date.');
}
if (SUPPORTS_INTL_API) {
// On IE and Edge the i18n API will throw a hard error that can crash the entire app
// if we attempt to format a date whose year is less than 1 or greater than 9999.
if (this._clampDate && (date.getFullYear() < 1 || date.getFullYear() > 9999)) {
date = this.clone(date);
date.setFullYear(Math.max(1, Math.min(9999, date.getFullYear())));
}
displayFormat = Object.assign(Object.assign({}, displayFormat), { timeZone: 'utc' });
/** @type {?} */
const dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
return this._stripDirectionalityCharacters(this._format(dtf, date));
}
return this._stripDirectionalityCharacters(date.toDateString());
}
/**
* @param {?} date
* @param {?} years
* @return {?}
*/
addCalendarYears(date, years) {
return this.addCalendarMonths(date, years * 12);
}
/**
* @param {?} date
* @param {?} months
* @return {?}
*/
addCalendarMonths(date, months) {
/** @type {?} */
let newDate = this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + months, this.getDate(date));
// It's possible to wind up in the wrong month if the original month has more days than the new
// month. In this case we want to go to the last day of the desired month.
// Note: the additional + 12 % 12 ensures we end up with a positive number, since JS % doesn't
// guarantee this.
if (this.getMonth(newDate) != ((this.getMonth(date) + months) % 12 + 12) % 12) {
newDate = this._createDateWithOverflow(this.getYear(newDate), this.getMonth(newDate), 0);
}
return newDate;
}
/**
* @param {?} date
* @param {?} days
* @return {?}
*/
addCalendarDays(date, days) {
return this._createDateWithOverflow(this.getYear(date), this.getMonth(date), this.getDate(date) + days);
}
/**
* @param {?} date
* @return {?}
*/
toIso8601(date) {
return [
date.getUTCFullYear(),
this._2digit(date.getUTCMonth() + 1),
this._2digit(date.getUTCDate())
].join('-');
}
/**
* Returns the given value if given a valid Date or null. Deserializes valid ISO 8601 strings
* (https://www.ietf.org/rfc/rfc3339.txt) into valid Dates and empty string into null. Returns an
* invalid date for all other values.
* @param {?} value
* @return {?}
*/
deserialize(value) {
if (typeof value === 'string') {
if (!value) {
return null;
}
// The `Date` constructor accepts formats other than ISO 8601, so we need to make sure the
// string is the right format first.
if (ISO_8601_REGEX.test(value)) {
/** @type {?} */
let date = new Date(value);
if (this.isValid(date)) {
return date;
}
}
}
return super.deserialize(value);
}
/**
* @param {?} obj
* @return {?}
*/
isDateInstance(obj) {
return obj instanceof Date;
}
/**
* @param {?} date
* @return {?}
*/
isValid(date) {
return !isNaN(date.getTime());
}
/**
* @return {?}
*/
invalid() {
return new Date(NaN);
}
/**
* Creates a date but allows the month and date to overflow.
* @private
* @param {?} year
* @param {?} month
* @param {?} date
* @return {?}
*/
_createDateWithOverflow(year, month, date) {
/** @type {?} */
const result = new Date(year, month, date);
// We need to correct for the fact that JS native Date treats years in range [0, 99] as
// abbreviations for 19xx.
if (year >= 0 && year < 100) {
result.setFullYear(this.getYear(result) - 1900);
}
return result;
}
/**
* Pads a number to make it two digits.
* @private
* @param {?} n The number to pad.
* @return {?} The padded number.
*/
_2digit(n) {
return ('00' + n).slice(-2);
}
/**
* Strip out unicode LTR and RTL characters. Edge and IE insert these into formatted dates while
* other browsers do not. We remove them to make output consistent and because they interfere with
* date parsing.
* @private
* @param {?} str The string to strip direction characters from.
* @return {?} The stripped string.
*/
_stripDirectionalityCharacters(str) {
return str.replace(/[\u200e\u200f]/g, '');
}
/**
* When converting Date object to string, javascript built-in functions may return wrong
* results because it applies its internal DST rules. The DST rules around the world change
* very frequently, and the current valid rule is not always valid in previous years though.
* We work around this problem building a new Date object which has its internal UTC
* representation with the local date and time.
* @private
* @param {?} dtf Intl.DateTimeFormat object, containg the desired string format. It must have
* timeZone set to 'utc' to work fine.
* @param {?} date Date from which we want to get the string representation according to dtf
* @return {?} A Date object with its UTC representation based on the passed in date info
*/
_format(dtf, date) {
/** @type {?} */
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
return dtf.format(d);
}
}
NativeDateAdapter.decorators = [
{ type: Injectable }
];
/** @nocollapse */
NativeDateAdapter.ctorParameters = () => [
{ type: String, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_LOCALE,] }] },
{ type: Platform }
];
if (false) {
/**
* Whether to clamp the date between 1 and 9999 to avoid IE and Edge errors.
* @type {?}
* @private
*/
NativeDateAdapter.prototype._clampDate;
/**
* Whether to use `timeZone: 'utc'` with `Intl.DateTimeFormat` when formatting dates.
* Without this `Intl.DateTimeFormat` sometimes chooses the wrong timeZone, which can throw off
* the result. (e.g. in the en-US locale `new Date(1800, 7, 14).toLocaleDateString()`
* will produce `'8/13/1800'`.
*
* TODO(mmalerba): drop this variable. It's not being used in the code right now. We're now
* getting the string representation of a Date object from its utc representation. We're keeping
* it here for sometime, just for precaution, in case we decide to revert some of these changes
* though.
* @type {?}
*/
NativeDateAdapter.prototype.useUtcForDisplay;
}
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/datetime/native-date-formats.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
/**
* @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
*/
/** @type {?} */
const MAT_NATIVE_DATE_FORMATS = {
parse: {
dateInput: null,
},
display: {
dateInput: { year: 'numeric', month: 'numeric', day: 'numeric' },
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
/**
* @fileoverview added by tsickle
* Generated from: src/material/core/datetime/index.ts
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
class NativeDate