UNPKG

@angular/material

Version:
1,034 lines (1,019 loc) 119 kB
import * as i0 from '@angular/core'; import { Version, InjectionToken, inject, NgModule, LOCALE_ID, Injectable, Component, ViewEncapsulation, ChangeDetectionStrategy, Directive, ElementRef, ANIMATION_MODULE_TYPE, NgZone, Injector, Input, booleanAttribute, ChangeDetectorRef, EventEmitter, isSignal, Output, ViewChild } from '@angular/core'; import { HighContrastModeDetector, isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader, _IdGenerator } from '@angular/cdk/a11y'; import { BidiModule } from '@angular/cdk/bidi'; import { Subject } from 'rxjs'; import { startWith } from 'rxjs/operators'; import { normalizePassiveListenerOptions, _getEventTarget, Platform } from '@angular/cdk/platform'; import { coerceElement } from '@angular/cdk/coercion'; import { _CdkPrivateStyleLoader, _VisuallyHiddenLoader } from '@angular/cdk/private'; import { ENTER, SPACE, hasModifierKey } from '@angular/cdk/keycodes'; import { DOCUMENT } from '@angular/common'; /** Current version of Angular Material. */ const VERSION = new Version('19.1.4'); /** @docs-private */ class AnimationCurves { static STANDARD_CURVE = 'cubic-bezier(0.4,0.0,0.2,1)'; static DECELERATION_CURVE = 'cubic-bezier(0.0,0.0,0.2,1)'; static ACCELERATION_CURVE = 'cubic-bezier(0.4,0.0,1,1)'; static SHARP_CURVE = 'cubic-bezier(0.4,0.0,0.6,1)'; } /** @docs-private */ class AnimationDurations { static COMPLEX = '375ms'; static ENTERING = '225ms'; static EXITING = '195ms'; } /** * Injection token that configures whether the Material sanity checks are enabled. * @deprecated No longer used and will be removed. * @breaking-change 21.0.0 */ const MATERIAL_SANITY_CHECKS = new InjectionToken('mat-sanity-checks', { providedIn: 'root', factory: () => true, }); /** * 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). * @deprecated No longer used and will be removed. * @breaking-change 21.0.0 */ class MatCommonModule { constructor() { // While A11yModule also does this, we repeat it here to avoid importing A11yModule // in MatCommonModule. inject(HighContrastModeDetector)._applyBodyHighContrastModeCssClasses(); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatCommonModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.1.3", ngImport: i0, type: MatCommonModule, imports: [BidiModule], exports: [BidiModule] }); static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatCommonModule, imports: [BidiModule, BidiModule] }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatCommonModule, decorators: [{ type: NgModule, args: [{ imports: [BidiModule], exports: [BidiModule], }] }], ctorParameters: () => [] }); /** * Class that tracks the error state of a component. * @docs-private */ class _ErrorStateTracker { _defaultMatcher; ngControl; _parentFormGroup; _parentForm; _stateChanges; /** Whether the tracker is currently in an error state. */ errorState = false; /** User-defined matcher for the error state. */ matcher; constructor(_defaultMatcher, ngControl, _parentFormGroup, _parentForm, _stateChanges) { this._defaultMatcher = _defaultMatcher; this.ngControl = ngControl; this._parentFormGroup = _parentFormGroup; this._parentForm = _parentForm; this._stateChanges = _stateChanges; } /** Updates the error state based on the provided error state matcher. */ updateErrorState() { const oldState = this.errorState; const parent = this._parentFormGroup || this._parentForm; const matcher = this.matcher || this._defaultMatcher; const control = this.ngControl ? this.ngControl.control : null; const newState = matcher?.isErrorState(control, parent) ?? false; if (newState !== oldState) { this.errorState = newState; this._stateChanges.next(); } } } /** InjectionToken for datepicker that can be used to override default locale code. */ const MAT_DATE_LOCALE = new InjectionToken('MAT_DATE_LOCALE', { providedIn: 'root', factory: MAT_DATE_LOCALE_FACTORY, }); /** @docs-private */ function MAT_DATE_LOCALE_FACTORY() { return inject(LOCALE_ID); } const NOT_IMPLEMENTED = 'Method not implemented'; /** Adapts type `D` to be usable as a date by cdk-based components that work with dates. */ class DateAdapter { /** The locale to use for all dates. */ locale; _localeChanges = new Subject(); /** A stream that emits when the locale changes. */ localeChanges = this._localeChanges; /** * Sets the time of one date to the time of another. * @param target Date whose time will be set. * @param hours New hours to set on the date object. * @param minutes New minutes to set on the date object. * @param seconds New seconds to set on the date object. */ setTime(target, hours, minutes, seconds) { throw new Error(NOT_IMPLEMENTED); } /** * Gets the hours component of the given date. * @param date The date to extract the hours from. */ getHours(date) { throw new Error(NOT_IMPLEMENTED); } /** * Gets the minutes component of the given date. * @param date The date to extract the minutes from. */ getMinutes(date) { throw new Error(NOT_IMPLEMENTED); } /** * Gets the seconds component of the given date. * @param date The date to extract the seconds from. */ getSeconds(date) { throw new Error(NOT_IMPLEMENTED); } /** * Parses a date with a specific time from a user-provided value. * @param value The value to parse. * @param parseFormat The expected format of the value being parsed * (type is implementation-dependent). */ parseTime(value, parseFormat) { throw new Error(NOT_IMPLEMENTED); } /** * Adds an amount of seconds to the specified date. * @param date Date to which to add the seconds. * @param amount Amount of seconds to add to the date. */ addSeconds(date, amount) { throw new Error(NOT_IMPLEMENTED); } /** * Given a potential date object, returns that same date object if it is * a valid date, or `null` if it's not a valid date. * @param obj The object to check. * @returns A date or `null`. */ getValidDateOrNull(obj) { return this.isDateInstance(obj) && this.isValid(obj) ? obj : null; } /** * 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. * @returns 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. */ 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. * @returns 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)); } /** * Compares the time values of two dates. * @param first First date to compare. * @param second Second date to compare. * @returns 0 if the times are equal, a number less than 0 if the first time is earlier, * a number greater than 0 if the first time is later. */ compareTime(first, second) { return (this.getHours(first) - this.getHours(second) || this.getMinutes(first) - this.getMinutes(second) || this.getSeconds(first) - this.getSeconds(second)); } /** * Checks if two dates are equal. * @param first The first date to check. * @param second The second date to check. * @returns Whether the two dates are equal. * Null dates are considered equal to other null dates. */ sameDate(first, second) { if (first && second) { let firstValid = this.isValid(first); let secondValid = this.isValid(second); if (firstValid && secondValid) { return !this.compareDate(first, second); } return firstValid == secondValid; } return first == second; } /** * Checks if the times of two dates are equal. * @param first The first date to check. * @param second The second date to check. * @returns Whether the times of the two dates are equal. * Null dates are considered equal to other null dates. */ sameTime(first, second) { if (first && second) { const firstValid = this.isValid(first); const secondValid = this.isValid(second); if (firstValid && secondValid) { return !this.compareTime(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. * @returns `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; } } const MAT_DATE_FORMATS = new InjectionToken('mat-date-formats'); /** * 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 with an 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}))?)?$/; /** * Matches a time string. Supported formats: * - {{hours}}:{{minutes}} * - {{hours}}:{{minutes}}:{{seconds}} * - {{hours}}:{{minutes}} AM/PM * - {{hours}}:{{minutes}}:{{seconds}} AM/PM * - {{hours}}.{{minutes}} * - {{hours}}.{{minutes}}.{{seconds}} * - {{hours}}.{{minutes}} AM/PM * - {{hours}}.{{minutes}}.{{seconds}} AM/PM */ const TIME_REGEX = /^(\d?\d)[:.](\d?\d)(?:[:.](\d?\d))?\s*(AM|PM)?$/i; /** Creates an array and fills it with values. */ function range(length, valueFunction) { 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 { /** * @deprecated No longer being used. To be removed. * @breaking-change 14.0.0 */ useUtcForDisplay = false; /** The injected locale. */ _matDateLocale = inject(MAT_DATE_LOCALE, { optional: true }); constructor() { super(); const matDateLocale = inject(MAT_DATE_LOCALE, { optional: true }); if (matDateLocale !== undefined) { this._matDateLocale = matDateLocale; } super.setLocale(this._matDateLocale); } getYear(date) { return date.getFullYear(); } getMonth(date) { return date.getMonth(); } getDate(date) { return date.getDate(); } getDayOfWeek(date) { return date.getDay(); } getMonthNames(style) { const dtf = new Intl.DateTimeFormat(this.locale, { month: style, timeZone: 'utc' }); return range(12, i => this._format(dtf, new Date(2017, i, 1))); } getDateNames() { const dtf = new Intl.DateTimeFormat(this.locale, { day: 'numeric', timeZone: 'utc' }); return range(31, i => this._format(dtf, new Date(2017, 0, i + 1))); } getDayOfWeekNames(style) { const dtf = new Intl.DateTimeFormat(this.locale, { weekday: style, timeZone: 'utc' }); return range(7, i => this._format(dtf, new Date(2017, 0, i + 1))); } getYearName(date) { const dtf = new Intl.DateTimeFormat(this.locale, { year: 'numeric', timeZone: 'utc' }); return this._format(dtf, date); } getFirstDayOfWeek() { // At the time of writing `Intl.Locale` isn't available // in the internal types so we need to cast to `any`. if (typeof Intl !== 'undefined' && Intl.Locale) { const locale = new Intl.Locale(this.locale); // Some browsers implement a `getWeekInfo` method while others have a `weekInfo` getter. // Note that this isn't supported in all browsers so we need to null check it. const firstDay = (locale.getWeekInfo?.() || locale.weekInfo)?.firstDay ?? 0; // `weekInfo.firstDay` is a number between 1 and 7 where, starting from Monday, // whereas our representation is 0 to 6 where 0 is Sunday so we need to normalize it. return firstDay === 7 ? 0 : firstDay; } // Default to Sunday if the browser doesn't provide the week information. return 0; } getNumDaysInMonth(date) { return this.getDate(this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0)); } clone(date) { return new Date(date.getTime()); } createDate(year, month, date) { if (typeof ngDevMode === 'undefined' || ngDevMode) { // 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 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 && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw Error(`Invalid date "${date}" for month with index "${month}".`); } return result; } today() { return new Date(); } parse(value, parseFormat) { // 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; } format(date, displayFormat) { if (!this.isValid(date)) { throw Error('NativeDateAdapter: Cannot format invalid date.'); } const dtf = new Intl.DateTimeFormat(this.locale, { ...displayFormat, timeZone: 'utc' }); return this._format(dtf, date); } addCalendarYears(date, years) { return this.addCalendarMonths(date, years * 12); } addCalendarMonths(date, months) { 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; } addCalendarDays(date, days) { return this._createDateWithOverflow(this.getYear(date), this.getMonth(date), this.getDate(date) + days); } 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. */ 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 date = new Date(value); if (this.isValid(date)) { return date; } } } return super.deserialize(value); } isDateInstance(obj) { return obj instanceof Date; } isValid(date) { return !isNaN(date.getTime()); } invalid() { return new Date(NaN); } setTime(target, hours, minutes, seconds) { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!inRange(hours, 0, 23)) { throw Error(`Invalid hours "${hours}". Hours value must be between 0 and 23.`); } if (!inRange(minutes, 0, 59)) { throw Error(`Invalid minutes "${minutes}". Minutes value must be between 0 and 59.`); } if (!inRange(seconds, 0, 59)) { throw Error(`Invalid seconds "${seconds}". Seconds value must be between 0 and 59.`); } } const clone = this.clone(target); clone.setHours(hours, minutes, seconds, 0); return clone; } getHours(date) { return date.getHours(); } getMinutes(date) { return date.getMinutes(); } getSeconds(date) { return date.getSeconds(); } parseTime(userValue, parseFormat) { if (typeof userValue !== 'string') { return userValue instanceof Date ? new Date(userValue.getTime()) : null; } const value = userValue.trim(); if (value.length === 0) { return null; } // Attempt to parse the value directly. let result = this._parseTimeString(value); // Some locales add extra characters around the time, but are otherwise parseable // (e.g. `00:05 ч.` in bg-BG). Try replacing all non-number and non-colon characters. if (result === null) { const withoutExtras = value.replace(/[^0-9:(AM|PM)]/gi, '').trim(); if (withoutExtras.length > 0) { result = this._parseTimeString(withoutExtras); } } return result || this.invalid(); } addSeconds(date, amount) { return new Date(date.getTime() + amount * 1000); } /** Creates a date but allows the month and date to overflow. */ _createDateWithOverflow(year, month, date) { // Passing the year to the constructor causes year numbers <100 to be converted to 19xx. // To work around this we use `setFullYear` and `setHours` instead. const d = new Date(); d.setFullYear(year, month, date); d.setHours(0, 0, 0, 0); return d; } /** * Pads a number to make it two digits. * @param n The number to pad. * @returns The padded number. */ _2digit(n) { return ('00' + n).slice(-2); } /** * 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. * @param dtf Intl.DateTimeFormat object, containing 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 * @returns A Date object with its UTC representation based on the passed in date info */ _format(dtf, date) { // Passing the year to the constructor causes year numbers <100 to be converted to 19xx. // To work around this we use `setUTCFullYear` and `setUTCHours` instead. const d = new Date(); d.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate()); d.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); return dtf.format(d); } /** * Attempts to parse a time string into a date object. Returns null if it cannot be parsed. * @param value Time string to parse. */ _parseTimeString(value) { // Note: we can technically rely on the browser for the time parsing by generating // an ISO string and appending the string to the end of it. We don't do it, because // browsers aren't consistent in what they support. Some examples: // - Safari doesn't support AM/PM. // - Firefox produces a valid date object if the time string has overflows (e.g. 12:75) while // other browsers produce an invalid date. // - Safari doesn't allow padded numbers. const parsed = value.toUpperCase().match(TIME_REGEX); if (parsed) { let hours = parseInt(parsed[1]); const minutes = parseInt(parsed[2]); let seconds = parsed[3] == null ? undefined : parseInt(parsed[3]); const amPm = parsed[4]; if (hours === 12) { hours = amPm === 'AM' ? 0 : hours; } else if (amPm === 'PM') { hours += 12; } if (inRange(hours, 0, 23) && inRange(minutes, 0, 59) && (seconds == null || inRange(seconds, 0, 59))) { return this.setTime(this.today(), hours, minutes, seconds || 0); } } return null; } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateAdapter, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateAdapter }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateAdapter, decorators: [{ type: Injectable }], ctorParameters: () => [] }); /** Checks whether a number is within a certain range. */ function inRange(value, min, max) { return !isNaN(value) && value >= min && value <= max; } const MAT_NATIVE_DATE_FORMATS = { parse: { dateInput: null, timeInput: null, }, display: { dateInput: { year: 'numeric', month: 'numeric', day: 'numeric' }, timeInput: { hour: 'numeric', minute: 'numeric' }, monthYearLabel: { year: 'numeric', month: 'short' }, dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' }, monthYearA11yLabel: { year: 'numeric', month: 'long' }, timeOptionLabel: { hour: 'numeric', minute: 'numeric' }, }, }; class NativeDateModule { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.1.3", ngImport: i0, type: NativeDateModule }); static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateModule, providers: [{ provide: DateAdapter, useClass: NativeDateAdapter }] }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: NativeDateModule, decorators: [{ type: NgModule, args: [{ providers: [{ provide: DateAdapter, useClass: NativeDateAdapter }], }] }] }); class MatNativeDateModule { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatNativeDateModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.1.3", ngImport: i0, type: MatNativeDateModule }); static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatNativeDateModule, providers: [provideNativeDateAdapter()] }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatNativeDateModule, decorators: [{ type: NgModule, args: [{ providers: [provideNativeDateAdapter()], }] }] }); function provideNativeDateAdapter(formats = MAT_NATIVE_DATE_FORMATS) { return [ { provide: DateAdapter, useClass: NativeDateAdapter }, { provide: MAT_DATE_FORMATS, useValue: formats }, ]; } /** Error state matcher that matches when a control is invalid and dirty. */ class ShowOnDirtyErrorStateMatcher { isErrorState(control, form) { return !!(control && control.invalid && (control.dirty || (form && form.submitted))); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ShowOnDirtyErrorStateMatcher, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ShowOnDirtyErrorStateMatcher }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ShowOnDirtyErrorStateMatcher, decorators: [{ type: Injectable }] }); /** Provider that defines how form controls behave with regards to displaying error messages. */ class ErrorStateMatcher { isErrorState(control, form) { return !!(control && control.invalid && (control.touched || (form && form.submitted))); } static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ErrorStateMatcher, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ErrorStateMatcher, providedIn: 'root' }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: ErrorStateMatcher, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }] }); /** * Component used to load structural styles for focus indicators. * @docs-private */ class _StructuralStylesLoader { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: _StructuralStylesLoader, deps: [], target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.3", type: _StructuralStylesLoader, isStandalone: true, selector: "structural-styles", ngImport: i0, template: '', isInline: true, styles: [".mat-focus-indicator{position:relative}.mat-focus-indicator::before{top:0;left:0;right:0;bottom:0;position:absolute;box-sizing:border-box;pointer-events:none;display:var(--mat-focus-indicator-display, none);border-width:var(--mat-focus-indicator-border-width, 3px);border-style:var(--mat-focus-indicator-border-style, solid);border-color:var(--mat-focus-indicator-border-color, transparent);border-radius:var(--mat-focus-indicator-border-radius, 4px)}.mat-focus-indicator:focus::before{content:\"\"}@media(forced-colors: active){html{--mat-focus-indicator-display: block}}"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: _StructuralStylesLoader, decorators: [{ type: Component, args: [{ selector: 'structural-styles', encapsulation: ViewEncapsulation.None, template: '', changeDetection: ChangeDetectionStrategy.OnPush, styles: [".mat-focus-indicator{position:relative}.mat-focus-indicator::before{top:0;left:0;right:0;bottom:0;position:absolute;box-sizing:border-box;pointer-events:none;display:var(--mat-focus-indicator-display, none);border-width:var(--mat-focus-indicator-border-width, 3px);border-style:var(--mat-focus-indicator-border-style, solid);border-color:var(--mat-focus-indicator-border-color, transparent);border-radius:var(--mat-focus-indicator-border-radius, 4px)}.mat-focus-indicator:focus::before{content:\"\"}@media(forced-colors: active){html{--mat-focus-indicator-display: block}}"] }] }] }); /** * 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 { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatLine, deps: [], target: i0.ɵɵFactoryTarget.Directive }); static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.1.3", type: MatLine, isStandalone: true, selector: "[mat-line], [matLine]", host: { classAttribute: "mat-line" }, ngImport: i0 }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatLine, decorators: [{ type: Directive, args: [{ selector: '[mat-line], [matLine]', host: { 'class': 'mat-line' }, }] }] }); /** * Helper that takes a query list of lines and sets the correct class on the host. * @docs-private */ function setLines(lines, element, prefix = 'mat') { // Note: doesn't need to unsubscribe, because `changes` // gets completed by Angular when the view is destroyed. lines.changes.pipe(startWith(lines)).subscribe(({ length }) => { setClass(element, `${prefix}-2-line`, false); setClass(element, `${prefix}-3-line`, false); setClass(element, `${prefix}-multi-line`, false); if (length === 2 || length === 3) { setClass(element, `${prefix}-${length}-line`, true); } else if (length > 3) { setClass(element, `${prefix}-multi-line`, true); } }); } /** Adds or removes a class from an element. */ function setClass(element, className, isAdd) { element.nativeElement.classList.toggle(className, isAdd); } class MatLineModule { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatLineModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.1.3", ngImport: i0, type: MatLineModule, imports: [MatCommonModule, MatLine], exports: [MatLine, MatCommonModule] }); static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatLineModule, imports: [MatCommonModule, MatCommonModule] }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: MatLineModule, decorators: [{ type: NgModule, args: [{ imports: [MatCommonModule, MatLine], exports: [MatLine, MatCommonModule], }] }] }); /** Possible states for a ripple element. */ var RippleState; (function (RippleState) { RippleState[RippleState["FADING_IN"] = 0] = "FADING_IN"; RippleState[RippleState["VISIBLE"] = 1] = "VISIBLE"; RippleState[RippleState["FADING_OUT"] = 2] = "FADING_OUT"; RippleState[RippleState["HIDDEN"] = 3] = "HIDDEN"; })(RippleState || (RippleState = {})); /** * Reference to a previously launched ripple element. */ class RippleRef { _renderer; element; config; _animationForciblyDisabledThroughCss; /** Current state of the ripple. */ state = RippleState.HIDDEN; constructor(_renderer, /** Reference to the ripple HTML element. */ element, /** Ripple configuration used for the ripple. */ config, /* Whether animations are forcibly disabled for ripples through CSS. */ _animationForciblyDisabledThroughCss = false) { this._renderer = _renderer; this.element = element; this.config = config; this._animationForciblyDisabledThroughCss = _animationForciblyDisabledThroughCss; } /** Fades out the ripple element. */ fadeOut() { this._renderer.fadeOutRipple(this); } } /** Options used to bind a passive capturing event. */ const passiveCapturingEventOptions$1 = normalizePassiveListenerOptions({ passive: true, capture: true, }); /** Manages events through delegation so that as few event handlers as possible are bound. */ class RippleEventManager { _events = new Map(); /** Adds an event handler. */ addHandler(ngZone, name, element, handler) { const handlersForEvent = this._events.get(name); if (handlersForEvent) { const handlersForElement = handlersForEvent.get(element); if (handlersForElement) { handlersForElement.add(handler); } else { handlersForEvent.set(element, new Set([handler])); } } else { this._events.set(name, new Map([[element, new Set([handler])]])); ngZone.runOutsideAngular(() => { document.addEventListener(name, this._delegateEventHandler, passiveCapturingEventOptions$1); }); } } /** Removes an event handler. */ removeHandler(name, element, handler) { const handlersForEvent = this._events.get(name); if (!handlersForEvent) { return; } const handlersForElement = handlersForEvent.get(element); if (!handlersForElement) { return; } handlersForElement.delete(handler); if (handlersForElement.size === 0) { handlersForEvent.delete(element); } if (handlersForEvent.size === 0) { this._events.delete(name); document.removeEventListener(name, this._delegateEventHandler, passiveCapturingEventOptions$1); } } /** Event handler that is bound and which dispatches the events to the different targets. */ _delegateEventHandler = (event) => { const target = _getEventTarget(event); if (target) { this._events.get(event.type)?.forEach((handlers, element) => { if (element === target || element.contains(target)) { handlers.forEach(handler => handler.handleEvent(event)); } }); } }; } /** * Default ripple animation configuration for ripples without an explicit * animation config specified. */ const defaultRippleAnimationConfig = { enterDuration: 225, exitDuration: 150, }; /** * Timeout for ignoring mouse events. Mouse events will be temporary ignored after touch * events to avoid synthetic mouse events. */ const ignoreMouseEventsTimeout = 800; /** Options used to bind a passive capturing event. */ const passiveCapturingEventOptions = normalizePassiveListenerOptions({ passive: true, capture: true, }); /** Events that signal that the pointer is down. */ const pointerDownEvents = ['mousedown', 'touchstart']; /** Events that signal that the pointer is up. */ const pointerUpEvents = ['mouseup', 'mouseleave', 'touchend', 'touchcancel']; class _MatRippleStylesLoader { static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: _MatRippleStylesLoader, deps: [], target: i0.ɵɵFactoryTarget.Component }); static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.1.3", type: _MatRippleStylesLoader, isStandalone: true, selector: "ng-component", host: { attributes: { "mat-ripple-style-loader": "" } }, ngImport: i0, template: '', isInline: true, styles: [".mat-ripple{overflow:hidden;position:relative}.mat-ripple:not(:empty){transform:translateZ(0)}.mat-ripple.mat-ripple-unbounded{overflow:visible}.mat-ripple-element{position:absolute;border-radius:50%;pointer-events:none;transition:opacity,transform 0ms cubic-bezier(0, 0, 0.2, 1);transform:scale3d(0, 0, 0);background-color:var(--mat-ripple-color, color-mix(in srgb, var(--mat-sys-on-surface) 10%, transparent))}@media(forced-colors: active){.mat-ripple-element{display:none}}.cdk-drag-preview .mat-ripple-element,.cdk-drag-placeholder .mat-ripple-element{display:none}"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.3", ngImport: i0, type: _MatRippleStylesLoader, decorators: [{ type: Component, args: [{ template: '', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: { 'mat-ripple-style-loader': '' }, styles: [".mat-ripple{overflow:hidden;position:relative}.mat-ripple:not(:empty){transform:translateZ(0)}.mat-ripple.mat-ripple-unbounded{overflow:visible}.mat-ripple-element{position:absolute;border-radius:50%;pointer-events:none;transition:opacity,transform 0ms cubic-bezier(0, 0, 0.2, 1);transform:scale3d(0, 0, 0);background-color:var(--mat-ripple-color, color-mix(in srgb, var(--mat-sys-on-surface) 10%, transparent))}@media(forced-colors: active){.mat-ripple-element{display:none}}.cdk-drag-preview .mat-ripple-element,.cdk-drag-placeholder .mat-ripple-element{display:none}"] }] }] }); /** * 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 { _target; _ngZone; _platform; /** Element where the ripples are being added to. */ _containerElement; /** Element which triggers the ripple elements on mouse events. */ _triggerElement; /** Whether the pointer is currently down or not. */ _isPointerDown = false; /** * Map of currently active ripple references. * The ripple reference is mapped to its element event listeners. * The reason why `| null` is used is that event listeners are added only * when the condition is truthy (see the `_startFadeOutTransition` method). */ _activeRipples = new Map(); /** Latest non-persistent ripple that was triggered. */ _mostRecentTransientRipple; /** Time in milliseconds when the last touchstart event happened. */ _lastTouchStartEvent; /** Whether pointer-up event listeners have been registered. */ _pointerUpEventsRegistered = false; /** * Cached dimensions of the ripple container. Set when the first * ripple is shown and cleared once no more ripples are visible. */ _containerRect; static _eventManager = new RippleEventManager(); constructor(_target, _ngZone, elementOrElementRef, _platform, injector) { this._target = _target; this._ngZone = _ngZone; this._platform = _platform; // Only do anything if we're on the browser. if (_platform.isBrowser) { this._containerElement = coerceElement(elementOrElementRef); } if (injector) { injector.get(_CdkPrivateStyleLoader).load(_MatRippleStylesLoader); } } /** * 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. */ fadeInRipple(x, y, config = {}) { const containerRect = (this._containerRect = this._containerRect || this._containerElement.getBoundingClientRect()); const animationConfig = { ...defaultRippleAnimationConfig, ...config.animation }; if (config.centered) { x = containerRect.left + containerRect.width / 2; y = containerRect.top + containerRect.height / 2; } const radius = config.radius || distanceToFurthestCorner(x, y, containerRect); const offsetX = x - containerRect.left; const offsetY = y - containerRect.top; const enterDuration = animationConfig.enterDuration; const 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 a custom color has been specified, set it as inline style. If no color is // set, the default color will be applied through the ripple theme styles. if (config.color != null) { ripple.style.backgroundColor = config.color; } ripple.style.transitionDuration = `${enterDuration}ms`; this._containerElement.appendChild(ripple); // By default the browser does not recalculate the styles of dynamically created // ripple elements. This is critical to ensure that the `scale` animates properly. // We enforce a style recalculation by calling `getComputedStyle` and *accessing* a property. // See: https://gist.github.com/paulirish/5d52fb081b3570c81e3a const computedStyles = window.getComputedStyle(ripple); const userTransitionProperty = computedStyles.transitionProperty; const userTransitionDuration = computedStyles.transitionDuration; // Note: We detect whether animation is forcibly disabled through CSS (e.g. through // `transition: none` or `display: none`). This is technically unexpected since animations are // controlled through the animation config, but this exists for backwards compatibility. This // logic does not need to be super accurate since it covers some edge cases which can be easily // avoided by users. const animationForciblyDisabledThroughCss = userTransitionProperty === 'none' || // Note: The canonical unit for serialized CSS `<time>` properties is seconds. Additionally // some browsers expand the duration for every property (in our case `opacity` and `transform`). userTransitionDuration === '0s' || userTransitionDuration === '0s, 0s' || // If the container is 0x0, it's likely `display: none`. (containerRect.width === 0 && containerRect.height === 0); // Exposed reference to the ripple that will be returned. const rippleRef = new RippleRef(this, ripple, config, animationForciblyDisabledThroughCss); // Start the enter animation by setting the transform/scale to 100%. The animation will // execute as part of this statement because we forced a style recalculation before. // Note: We use a 3d transform here in order to avoid an issue in Safari where // the ripples aren't clipped when inside the shadow DOM (see #24028). ripple.style.transform = 'scale3d(1, 1, 1)'; rippleRef.state = RippleState.FADING_IN; if (!config.persistent) { this._mostRecentTransientRipple = rippleRef; } let eventListeners = null; // Do not register the `transition` event listener if fade-in and fade-out duration // are set to zero. The events won't fire anyway and we can save resources here. if (!animationForciblyDisabledThroughCss && (enterDuration || animationConfig.exitDuration)) { this._ngZone.runOutsideAngular(() => { const onTransitionEnd = () => { // Clear the fallback timer since the transition fired correctly. if (eventListeners) { eventListeners.fallbackTimer = null; } clearTimeout(fallbackTimer); this._finishRippleTransition(rippleRef); }; const onTransitionCancel = () => this._destroyRipple(rippleRef); // In some cases where there's a higher load on the browser, it can choose not to dispatch // neither `transitionend` nor `transitioncancel` (see b/227356674). This timer serves as a // fallback for such cases so that the ripple doesn't become stuck. We add a 100ms buffer // because timers aren't precise. Note that another approach can be to transition the ripple // to the `VISIBLE` state immediately above and to `FADING_IN` afterwards inside // `transitionstart`. We go with the timer because it's one less event listener and // it's less likely to break existing tests. const fallbackTimer = setTimeout(onTransitionCancel, enterDuration + 100); ripple.addEventListener('transitionend', onTransitionEnd); // If the transition is cancelled (e.g. due to DOM removal), we destroy the ripple // directly as otherwise we would keep it part of the ripple container forever. // https://www.w3.org/TR/css-transitions-1/#:~:text=no%20longer%20in%20the%20document. ripple.addEventListener('transitioncancel', onTransitionCancel); eventListeners = { onTransitionEnd, onTransitionCancel, fallbackTimer }; }); } // Add the ripple reference to the list of all active ripples. this._activeRipples.set(rippleRef, eventListeners); // In case there is no fade-in transition duration, we need to manually call the transition // end listener because `transitionend` doesn't fire if there is no transition. if (animationForciblyDisabledThroughCss || !enterDuration) { this._finishRippleTransition(rippleRef); } return rippleRef; } /** Fades out a ripple reference. */ fadeOutRipple(rippleRef) { // For ripples already fading out or hidden, this should be a noop. if (rippleRef.state === RippleState.FADING_OUT || rippleRef.state === RippleState.HIDDEN) { return; } const rippleEl = rippleRef.element; const animationConfig = { ...defaultRippleAnimationConfig, ...rippleRef.config.animation }; // This starts the fade-out transition and will fire the transition end listener that // removes the ripple element from the DOM. rippleEl.style.transitionDuration = `${animationConfig.exitDuration}ms`; rippleEl.style.opacity = '0'; rippleRef.state = RippleState.FADING_OUT; // In case there is no fade-out transition duration, we need to manually call the // transition end listener because `transitionend` doesn't fire if there is no transition. if (rippleRef._animationForciblyDisabledThroughCss || !animationConfig.exitDuration) { this._finishRippleTransition(rippleRef); } } /** Fades out all currently active ripples. */ fadeOutAll() { this._getActiveRipples().forEach(ripple => ripple.fadeOut()); } /** Fades out all currently active non-persistent ripples. */ fadeOutAllNonPersistent() { this._getActiveRipples().forEach(ripple => { if (!ripple.config.persistent) { ripple.fadeOut(); } }); } /** Sets up the trigger event listeners */ setupTriggerEvents(elementOrElementRef) { const element = coerceElement(elementOrElementRef); if (!this._platform.isBrowser || !element || element === this._triggerElement) { return; } // Remove all previously registered event listeners from the trigger element. this._removeTriggerEvents(