UNPKG

@angular/material

Version:
1,508 lines (1,459 loc) 75.1 kB
/** * @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 { ChangeDetectionStrategy, ChangeDetectorRef, Component, Directive, ElementRef, EventEmitter, Inject, Injectable, InjectionToken, Input, LOCALE_ID, NgModule, NgZone, Optional, Output, ViewEncapsulation, isDevMode } from '@angular/core'; import { BidiModule } from '@angular/cdk/bidi'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import { HammerGestureConfig } from '@angular/platform-browser'; import { CommonModule } from '@angular/common'; import { Platform, PlatformModule, supportsPassiveEventListeners } from '@angular/cdk/platform'; import { ENTER, SPACE } from '@angular/cdk/keycodes'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * \@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)'; /** * \@docs-private */ class AnimationDurations { } AnimationDurations.COMPLEX = '375ms'; AnimationDurations.ENTERING = '225ms'; AnimationDurations.EXITING = '195ms'; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Injection token that configures whether the Material sanity checks are enabled. */ const MATERIAL_SANITY_CHECKS = new InjectionToken('mat-sanity-checks'); /** * 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 {?} _sanityChecksEnabled */ constructor(_sanityChecksEnabled) { this._sanityChecksEnabled = _sanityChecksEnabled; /** * Whether we've done the global sanity checks (e.g. a theme is loaded, there is a doctype). */ this._hasDoneGlobalChecks = false; /** * Whether we've already checked for HammerJs availability. */ this._hasCheckedHammer = 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; if (this._areChecksEnabled() && !this._hasDoneGlobalChecks) { this._checkDoctypeIsDefined(); this._checkThemeIsPresent(); this._hasDoneGlobalChecks = true; } } /** * Whether any sanity checks are enabled * @return {?} */ _areChecksEnabled() { return this._sanityChecksEnabled && isDevMode() && !this._isTestEnv(); } /** * Whether the code is running in tests. * @return {?} */ _isTestEnv() { return this._window && (this._window['__karma__'] || this._window['jasmine']); } /** * @return {?} */ _checkDoctypeIsDefined() { if (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.'); } } /** * @return {?} */ _checkThemeIsPresent() { if (this._document && typeof getComputedStyle === 'function') { const /** @type {?} */ testElement = this._document.createElement('div'); testElement.classList.add('mat-theme-loaded-marker'); this._document.body.appendChild(testElement); const /** @type {?} */ 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 HammerJS is available. * @return {?} */ _checkHammerIsAvailable() { if (this._hasCheckedHammer || !this._window) { return; } if (this._areChecksEnabled() && !this._window['Hammer']) { console.warn('Could not find HammerJS. Certain Angular Material components may not work correctly.'); } this._hasCheckedHammer = true; } } MatCommonModule.decorators = [ { type: NgModule, args: [{ imports: [BidiModule], exports: [BidiModule], providers: [{ provide: MATERIAL_SANITY_CHECKS, useValue: true, }], },] }, ]; /** @nocollapse */ MatCommonModule.ctorParameters = () => [ { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MATERIAL_SANITY_CHECKS,] },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * \@docs-private * @record */ /** * 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 * @suppress {checkTypes} checked by tsc */ /** * \@docs-private * @record */ /** * \@docs-private * @record */ /** * Mixin to augment a directive with a `color` property. * @template T * @param {?} base * @param {?=} defaultColor * @return {?} */ function mixinColor(base, defaultColor) { return class extends base { /** * @return {?} */ get color() { return this._color; } /** * @param {?} value * @return {?} */ set color(value) { const /** @type {?} */ 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; } } /** * @param {...?} args */ constructor(...args) { super(...args); // Set the default color that can be specified from the mixin. this.color = defaultColor; } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * \@docs-private * @record */ /** * 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 * @suppress {checkTypes} checked by tsc */ /** * \@docs-private * @record */ /** * 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 * @suppress {checkTypes} checked by tsc */ /** * \@docs-private * @record */ /** * \@docs-private * @record */ /** * 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() { const /** @type {?} */ oldState = this.errorState; const /** @type {?} */ parent = this._parentFormGroup || this._parentForm; const /** @type {?} */ matcher = this.errorStateMatcher || this._defaultErrorStateMatcher; const /** @type {?} */ control = this.ngControl ? /** @type {?} */ (this.ngControl.control) : null; const /** @type {?} */ newState = matcher.isErrorState(control, parent); if (newState !== oldState) { this.errorState = newState; this.stateChanges.next(); } } }; } /** * @fileoverview added by tsickle * @suppress {checkTypes} 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 */ /** * 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(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 * @suppress {checkTypes} checked by tsc */ /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * InjectionToken for datepicker that can be used to override default locale code. */ const MAT_DATE_LOCALE = new InjectionToken('MAT_DATE_LOCALE'); /** * Provider for MAT_DATE_LOCALE injection token. */ 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 */ 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 it's `\@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) { let /** @type {?} */ firstValid = this.isValid(first); let /** @type {?} */ 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; } } /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ const MAT_DATE_FORMATS = new InjectionToken('mat-date-formats'); /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Whether the browser supports the Intl API. */ const SUPPORTS_INTL_API = typeof Intl != 'undefined'; /** * The default month names to use if Intl API is not available. */ 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$1 = i => String(i + 1); /** * The default date names to use if Intl API is not available. */ const DEFAULT_DATE_NAMES = range(31, ɵ0$1); /** * The default day of the week names to use if Intl API is not available. */ 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. */ 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) { const /** @type {?} */ valuesArray = Array(length); for (let /** @type {?} */ 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 */ constructor(matDateLocale) { super(); super.setLocale(matDateLocale); // IE does its own time zone correction, so we disable this on IE. // TODO(mmalerba): replace with checks from PLATFORM, logic currently duplicated to avoid // breaking change from injecting the Platform. const /** @type {?} */ isBrowser = typeof document === 'object' && !!document; const /** @type {?} */ isIE = isBrowser && /(msie|trident)/i.test(navigator.userAgent); this.useUtcForDisplay = !isIE; this._clampDate = isIE || (isBrowser && /(edge)/i.test(navigator.userAgent)); } /** * @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) { let /** @type {?} */ dtf = new Intl.DateTimeFormat(this.locale, { month: style }); return range(12, i => this._stripDirectionalityCharacters(dtf.format(new Date(2017, i, 1)))); } return DEFAULT_MONTH_NAMES[style]; } /** * @return {?} */ getDateNames() { if (SUPPORTS_INTL_API) { let /** @type {?} */ dtf = new Intl.DateTimeFormat(this.locale, { day: 'numeric' }); return range(31, i => this._stripDirectionalityCharacters(dtf.format(new Date(2017, 0, i + 1)))); } return DEFAULT_DATE_NAMES; } /** * @param {?} style * @return {?} */ getDayOfWeekNames(style) { if (SUPPORTS_INTL_API) { let /** @type {?} */ dtf = new Intl.DateTimeFormat(this.locale, { weekday: style }); return range(7, i => this._stripDirectionalityCharacters(dtf.format(new Date(2017, 0, i + 1)))); } return DEFAULT_DAY_OF_WEEK_NAMES[style]; } /** * @param {?} date * @return {?} */ getYearName(date) { if (SUPPORTS_INTL_API) { let /** @type {?} */ dtf = new Intl.DateTimeFormat(this.locale, { year: 'numeric' }); return this._stripDirectionalityCharacters(dtf.format(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 this.createDate(this.getYear(date), this.getMonth(date), this.getDate(date)); } /** * @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.`); } let /** @type {?} */ 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()))); } if (this.useUtcForDisplay) { date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds())); displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' }); } const /** @type {?} */ dtf = new Intl.DateTimeFormat(this.locale, displayFormat); return this._stripDirectionalityCharacters(dtf.format(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) { let /** @type {?} */ 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)) { let /** @type {?} */ 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. * @param {?} year * @param {?} month * @param {?} date * @return {?} */ _createDateWithOverflow(year, month, date) { let /** @type {?} */ 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. * @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. * @param {?} str The string to strip direction characters from. * @return {?} The stripped string. */ _stripDirectionalityCharacters(str) { return str.replace(/[\u200e\u200f]/g, ''); } } NativeDateAdapter.decorators = [ { type: Injectable }, ]; /** @nocollapse */ NativeDateAdapter.ctorParameters = () => [ { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_LOCALE,] },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ 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 * @suppress {checkTypes} checked by tsc */ class NativeDateModule { } NativeDateModule.decorators = [ { type: NgModule, args: [{ providers: [ { provide: DateAdapter, useClass: NativeDateAdapter }, MAT_DATE_LOCALE_PROVIDER ], },] }, ]; /** @nocollapse */ NativeDateModule.ctorParameters = () => []; const ɵ0$$1 = MAT_NATIVE_DATE_FORMATS; class MatNativeDateModule { } MatNativeDateModule.decorators = [ { type: NgModule, args: [{ imports: [NativeDateModule], providers: [{ provide: MAT_DATE_FORMATS, useValue: ɵ0$$1 }], },] }, ]; /** @nocollapse */ MatNativeDateModule.ctorParameters = () => []; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Error state matcher that matches when a control is invalid and dirty. */ class ShowOnDirtyErrorStateMatcher { /** * @param {?} control * @param {?} form * @return {?} */ isErrorState(control, form) { return !!(control && control.invalid && (control.dirty || (form && form.submitted))); } } ShowOnDirtyErrorStateMatcher.decorators = [ { type: Injectable }, ]; /** @nocollapse */ ShowOnDirtyErrorStateMatcher.ctorParameters = () => []; /** * Provider that defines how form controls behave with regards to displaying error messages. */ class ErrorStateMatcher { /** * @param {?} control * @param {?} form * @return {?} */ isErrorState(control, form) { return !!(control && control.invalid && (control.touched || (form && form.submitted))); } } ErrorStateMatcher.decorators = [ { type: Injectable }, ]; /** @nocollapse */ ErrorStateMatcher.ctorParameters = () => []; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Injection token that can be used to provide options to the Hammerjs instance. * More info at http://hammerjs.github.io/api/. */ const MAT_HAMMER_OPTIONS = new InjectionToken('MAT_HAMMER_OPTIONS'); /** * Adjusts configuration of our gesture library, Hammer. */ class GestureConfig extends HammerGestureConfig { /** * @param {?=} _hammerOptions * @param {?=} commonModule */ constructor(_hammerOptions, commonModule) { super(); this._hammerOptions = _hammerOptions; this._hammer = typeof window !== 'undefined' ? (/** @type {?} */ (window)).Hammer : null; /** * List of new event names to add to the gesture support list */ this.events = this._hammer ? [ 'longpress', 'slide', 'slidestart', 'slideend', 'slideright', 'slideleft' ] : []; if (commonModule) { commonModule._checkHammerIsAvailable(); } } /** * Builds Hammer instance manually to add custom recognizers that match the Material Design spec. * * Our gesture names come from the Material Design gestures spec: * https://www.google.com/design/spec/patterns/gestures.html#gestures-touch-mechanics * * More information on default recognizers can be found in Hammer docs: * http://hammerjs.github.io/recognizer-pan/ * http://hammerjs.github.io/recognizer-press/ * * @param {?} element Element to which to assign the new HammerJS gestures. * @return {?} Newly-created HammerJS instance. */ buildHammer(element) { const /** @type {?} */ mc = new this._hammer(element, this._hammerOptions || undefined); // Default Hammer Recognizers. const /** @type {?} */ pan = new this._hammer.Pan(); const /** @type {?} */ swipe = new this._hammer.Swipe(); const /** @type {?} */ press = new this._hammer.Press(); // Notice that a HammerJS recognizer can only depend on one other recognizer once. // Otherwise the previous `recognizeWith` will be dropped. // TODO: Confirm threshold numbers with Material Design UX Team const /** @type {?} */ slide = this._createRecognizer(pan, { event: 'slide', threshold: 0 }, swipe); const /** @type {?} */ longpress = this._createRecognizer(press, { event: 'longpress', time: 500 }); // Overwrite the default `pan` event to use the swipe event. pan.recognizeWith(swipe); // Add customized gestures to Hammer manager mc.add([swipe, press, pan, slide, longpress]); return /** @type {?} */ (mc); } /** * Creates a new recognizer, without affecting the default recognizers of HammerJS * @param {?} base * @param {?} options * @param {...?} inheritances * @return {?} */ _createRecognizer(base, options, ...inheritances) { let /** @type {?} */ recognizer = new (/** @type {?} */ (base.constructor))(options); inheritances.push(base); inheritances.forEach(item => recognizer.recognizeWith(item)); return recognizer; } } GestureConfig.decorators = [ { type: Injectable }, ]; /** @nocollapse */ GestureConfig.ctorParameters = () => [ { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_HAMMER_OPTIONS,] },] }, { type: MatCommonModule, decorators: [{ type: Optional },] }, ]; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Shared directive to count lines inside a text area, such as a list item. * Line elements can be extracted with a \@ContentChildren(MatLine) query, then * counted by checking the query list's length. */ class MatLine { } MatLine.decorators = [ { type: Directive, args: [{ selector: '[mat-line], [matLine]', host: { 'class': 'mat-line' } },] }, ]; /** @nocollapse */ MatLine.ctorParameters = () => []; /** * Helper that takes a query list of lines and sets the correct class on the host. * \@docs-private */ class MatLineSetter { /** * @param {?} _lines * @param {?} _element */ constructor(_lines, _element) { this._lines = _lines; this._element = _element; this._setLineClass(this._lines.length); this._lines.changes.subscribe(() => { this._setLineClass(this._lines.length); }); } /** * @param {?} count * @return {?} */ _setLineClass(count) { this._resetClasses(); if (count === 2 || count === 3) { this._setClass(`mat-${count}-line`, true); } else if (count > 3) { this._setClass(`mat-multi-line`, true); } } /** * @return {?} */ _resetClasses() { this._setClass('mat-2-line', false); this._setClass('mat-3-line', false); this._setClass('mat-multi-line', false); } /** * @param {?} className * @param {?} isAdd * @return {?} */ _setClass(className, isAdd) { if (isAdd) { this._element.nativeElement.classList.add(className); } else { this._element.nativeElement.classList.remove(className); } } } class MatLineModule { } MatLineModule.decorators = [ { type: NgModule, args: [{ imports: [MatCommonModule], exports: [MatLine, MatCommonModule], declarations: [MatLine], },] }, ]; /** @nocollapse */ MatLineModule.ctorParameters = () => []; /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** @enum {number} */ const RippleState = { FADING_IN: 0, VISIBLE: 1, FADING_OUT: 2, HIDDEN: 3, }; RippleState[RippleState.FADING_IN] = "FADING_IN"; RippleState[RippleState.VISIBLE] = "VISIBLE"; RippleState[RippleState.FADING_OUT] = "FADING_OUT"; RippleState[RippleState.HIDDEN] = "HIDDEN"; /** * Reference to a previously launched ripple element. */ class RippleRef { /** * @param {?} _renderer * @param {?} element * @param {?} config */ constructor(_renderer, element, config) { this._renderer = _renderer; this.element = element; this.config = config; /** * Current state of the ripple reference. */ this.state = RippleState.HIDDEN; } /** * Fades out the ripple element. * @return {?} */ fadeOut() { this._renderer.fadeOutRipple(this); } } /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Interface that describes the configuration for the animation of a ripple. * There are two animation phases with different durations for the ripples. * @record */ /** * Interface that describes the target for launching ripples. * It defines the ripple configuration and disabled state for interaction ripples. * \@docs-private * @record */ /** * Default ripple animation configuration for ripples without an explicit * animation config specified. */ const defaultRippleAnimationConfig = { enterDuration: 450, exitDuration: 400 }; /** * Timeout for ignoring mouse events. Mouse events will be temporary ignored after touch * events to avoid synthetic mouse events. */ const ignoreMouseEventsTimeout = 800; /** * Helper service that performs DOM manipulations. Not intended to be used outside this module. * The constructor takes a reference to the ripple directive's host element and a map of DOM * event handlers to be installed on the element that triggers ripple animations. * This will eventually become a custom renderer once Angular support exists. * \@docs-private */ class RippleRenderer { /** * @param {?} _target * @param {?} _ngZone * @param {?} elementRef * @param {?} platform */ constructor(_target, _ngZone, elementRef, platform) { this._target = _target; this._ngZone = _ngZone; /** * Whether the pointer is currently down or not. */ this._isPointerDown = false; /** * Events to be registered on the trigger element. */ this._triggerEvents = new Map(); /** * Set of currently active ripple references. */ this._activeRipples = new Set(); /** * Options that apply to all the event listeners that are bound by the renderer. */ this._eventOptions = supportsPassiveEventListeners() ? (/** @type {?} */ ({ passive: true })) : false; /** * Function being called whenever the trigger is being pressed using mouse. */ this.onMousedown = (event) => { const /** @type {?} */ isSyntheticEvent = this._lastTouchStartEvent && Date.now() < this._lastTouchStartEvent + ignoreMouseEventsTimeout; if (!this._target.rippleDisabled && !isSyntheticEvent) { this._isPointerDown = true; this.fadeInRipple(event.clientX, event.clientY, this._target.rippleConfig); } }; /** * Function being called whenever the trigger is being pressed using touch. */ this.onTouchStart = (event) => { if (!this._target.rippleDisabled) { // Some browsers fire mouse events after a `touchstart` event. Those synthetic mouse // events will launch a second ripple if we don't ignore mouse events for a specific // time after a touchstart event. this._lastTouchStartEvent = Date.now(); this._isPointerDown = true; this.fadeInRipple(event.touches[0].clientX, event.touches[0].clientY, this._target.rippleConfig); } }; /** * Function being called whenever the trigger is being released. */ this.onPointerUp = () => { if (!this._isPointerDown) { return; } this._isPointerDown = false; // Fade-out all ripples that are visible and not persistent. this._activeRipples.forEach(ripple => { // By default, only ripples that are completely visible will fade out on pointer release. // If the `terminateOnPointerUp` option is set, ripples that still fade in will also fade out. const /** @type {?} */ isVisible = ripple.state === RippleState.VISIBLE || ripple.config.terminateOnPointerUp && ripple.state === RippleState.FADING_IN; if (!ripple.config.persistent && isVisible) { ripple.fadeOut(); } }); }; // Only do anything if we're on the browser. if (platform.isBrowser) { this._containerElement = elementRef.nativeElement; // Specify events which need to be registered on the trigger. this._triggerEvents.set('mousedown', this.onMousedown); this._triggerEvents.set('mouseup', this.onPointerUp); this._triggerEvents.set('mouseleave', this.onPointerUp); this._triggerEvents.set('touchstart', this.onTouchStart); this._triggerEvents.set('touchend', this.onPointerUp); } } /** * Fades in a ripple at the given coordinates. * @param {?} x Coordinate within the element, along the X axis at which to start the ripple. * @param {?} y Coordinate within the element, along the Y axis at which to start the ripple. * @param {?=} config Extra ripple options. * @return {?} */ fadeInRipple(x, y, config = {}) { const /** @type {?} */ containerRect = this._containerElement.getBoundingClientRect(); const /** @type {?} */ animationConfig = Object.assign({}, defaultRippleAnimationConfig, config.animation); if (config.centered) { x = containerRect.left + containerRect.width / 2; y = containerRect.top + containerRect.height / 2; } const /** @type {?} */ radius = config.radius || distanceToFurthestCorner(x, y, containerRect); const /** @type {?} */ offsetX = x - containerRect.left; const /** @type {?} */ offsetY = y - containerRect.top; const /** @type {?} */ duration = animationConfig.enterDuration / (config.speedFactor || 1); const /** @type {?} */ ripple = document.createElement('div'); ripple.classList.add('mat-ripple-element'); ripple.style.left = `${offsetX - radius}px`; ripple.style.top = `${offsetY - radius}px`; ripple.style.height = `${radius * 2}px`; ripple.style.width = `${radius * 2}px`; // If the color is not set, the default CSS color will be used. ripple.style.backgroundColor = config.color || null; ripple.style.transitionDuration = `${duration}ms`; this._containerElement.appendChild(ripple); // By default the browser does not recalculate the styles of dynamically created // ripple elements. This is critical because then the `scale` would not animate properly. enforceStyleRecalculation(ripple); ripple.style.transform = 'scale(1)'; // Exposed reference to the ripple that will be returned. const /** @type {?} */ rippleRef = new RippleRef(this, ripple, config); rippleRef.state = RippleState.FADING_IN; // Add the ripple reference to the list of all active ripples. this._activeRipples.add(rippleRef); // Wait for the ripple element to be completely faded in. // Once it's faded in, the ripple can be hidden immediately if the mouse is released. this.runTimeoutOutsideZone(() => { rippleRef.state = RippleState.VISIBLE; if (!config.persistent && !this._isPointerDown) { rippleRef.fadeOut(); } }, duration); return rippleRef; } /** * Fades out a ripple reference. * @param {?} rippleRef * @return {?} */ fadeOutRipple(rippleRef) { // For ripples that are not active anymore, don't re-un the fade-out animation. if (!this._activeRipples.delete(rippleRef)) { return; } const /** @type {?} */ rippleEl = rippleRef.element; const /** @type {?} */ animationConfig = Object.assign({}, defaultRippleAnimationConfig, rippleRef.config.animation); rippleEl.style.transitionDuration = `${animationConfig.exitDuration}ms`; rippleEl.style.opacity = '0'; rippleRef.state = RippleState.FADING_OUT; // Once the ripple faded out, the ripple can be safely removed from the DOM. this.runTimeoutOutsideZone(() => { rippleRef.state = RippleState.HIDDEN; /** @type {?} */ ((rippleEl.parentNode)).removeChild(rippleEl); }, animationConfig.exitDuration); } /** * Fades out all currently active ripples. * @return {?} */ fadeOutAll() { this._activeRipples.forEach(ripple => ripple.fadeOut()); } /** * Sets up the trigger event listeners * @param {?} element * @return {?} */ setupTriggerEvents(element) { if (!element || element === this._triggerElement) { return; } // Remove all previously registered event listeners from the trigger element. this._removeTriggerEvents(); this._ngZone.runOutsideAngular(() => { this._triggerEvents.forEach((fn, type) => element.addEventListener(type, fn, this._eventOptions)); }); this._triggerElement = element; } /** * Runs a timeout outside of the Angular zone to avoid triggering the change detection. * @param {?} fn * @param {?=} delay * @return {?} */ runTimeoutOutsideZone(fn, delay = 0) { this._ngZone.runOutsideAngular(() => setTimeout(fn, delay)); } /** * Removes previously registered event listeners from the trigger element. * @return {?} */ _removeTriggerEvents() { if (this._triggerElement) { this._triggerEvents.forEach((fn, type) => { /** @type {?} */ ((this._triggerElement)).removeEventListener(type, fn, this._eventOptions); }); } } } /** * Enforces a style recalculation of a DOM element by computing its styles. * @param {?} element * @return {?} */ function enforceStyleRecalculation(element) { // Enforce a style recalculation by calling `getComputedStyle` and accessing any property. // Calling `getPropertyValue` is important to let optimizers know that this is not a noop. // See: https://gist.github.com/paulirish/5d52fb081b3570c81e3a window.getComputedStyle(element).getPropertyValue('opacity'); } /** * Returns the distance from the point (x, y) to the furthest corner of a rectangle. * @param {?} x * @param {?} y * @param {?} rect * @return {?} */ function distanceToFurthestCorner(x, y, rect) { const /** @type {?} */ distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right)); const /** @type {?} */ distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom)); return Math.sqrt(distX * distX + distY * distY); } /** * @fileoverview added by tsickle * @suppress {checkTypes} checked by tsc */ /** * Configurable options for `matRipple`. * @record */ /** * Injection token that can be used to specify the global ripple options. */ const MAT_RIPPLE_GLOBAL_OPTIONS = new InjectionToken('mat-ripple-global-options'); class MatRipple { /** * @param {?} _elementRef * @param {?} ngZone * @param {?} platf