_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/core/_core-theme.scss_0_6151 | @use './theming/theming';
@use './theming/inspection';
@use './theming/validation';
@use './ripple/ripple-theme';
@use './option/option-theme';
@use './option/optgroup-theme';
@use './selection/pseudo-checkbox/pseudo-checkbox-theme';
@use './style/sass-utils';
@use './typography/typography';
@use './tokens/token-utils';
@use './tokens/m2/mat/app' as tokens-mat-app;
@use './tokens/m2/mat/ripple' as tokens-mat-ripple;
@use './tokens/m2/mat/option' as tokens-mat-option;
@use './tokens/m2/mat/optgroup' as tokens-mat-optgroup;
@use './tokens/m2/mat/full-pseudo-checkbox' as tokens-mat-full-pseudo-checkbox;
@use './tokens/m2/mat/minimal-pseudo-checkbox' as tokens-mat-minimal-pseudo-checkbox;
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include ripple-theme.base($theme);
@include option-theme.base($theme);
@include optgroup-theme.base($theme);
@include pseudo-checkbox-theme.base($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-app.$prefix,
tokens-mat-app.get-unthemable-tokens()
);
}
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include ripple-theme.color($theme);
@include option-theme.color($theme);
@include optgroup-theme.color($theme);
@include pseudo-checkbox-theme.color($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-app.$prefix,
tokens-mat-app.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include option-theme.typography($theme);
@include optgroup-theme.typography($theme);
@include pseudo-checkbox-theme.typography($theme);
@include ripple-theme.typography($theme);
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include option-theme.density($theme);
@include optgroup-theme.density($theme);
@include pseudo-checkbox-theme.density($theme);
@include ripple-theme.density($theme);
}
}
@function _define-overrides() {
$app-tokens: tokens-mat-app.get-token-slots();
$ripple-tokens: tokens-mat-ripple.get-token-slots();
$option-tokens: tokens-mat-option.get-token-slots();
$optgroup-tokens: tokens-mat-optgroup.get-token-slots();
$full-pseudo-checkbox-tokens: tokens-mat-full-pseudo-checkbox.get-token-slots();
$minimal-pseudo-checkbox-tokens: tokens-mat-minimal-pseudo-checkbox.get-token-slots();
@return (
(namespace: tokens-mat-app.$prefix, tokens: $app-tokens, prefix: 'app-'),
(namespace: tokens-mat-ripple.$prefix, tokens: $ripple-tokens, prefix: 'ripple-'),
(namespace: tokens-mat-option.$prefix, tokens: $option-tokens, prefix: 'option-'),
(namespace: tokens-mat-optgroup.$prefix, tokens: $optgroup-tokens, prefix: 'optgroup-'),
(
namespace: tokens-mat-full-pseudo-checkbox.$prefix,
tokens: $full-pseudo-checkbox-tokens,
prefix: 'pseudo-checkbox-full-'
),
(
namespace: tokens-mat-minimal-pseudo-checkbox.$prefix,
tokens: $minimal-pseudo-checkbox-tokens,
prefix: 'pseudo-checkbox-minimal-'
)
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
// Mixin that renders all of the core styles that depend on the theme.
@mixin theme($theme, $options...) {
// Wrap the sub-theme includes in the duplicate theme styles mixin. This ensures that
// there won't be multiple warnings. e.g. if `mat-core-theme` reports a warning, then
// the imported themes (such as `mat-ripple-theme`) should not report again.
@include theming.private-check-duplicate-theme-styles($theme, 'mat-core') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mat-app-tokens: token-utils.get-tokens-for($tokens, tokens-mat-app.$prefix, $options...);
$mat-ripple-tokens: token-utils.get-tokens-for($tokens, tokens-mat-ripple.$prefix, $options...);
$mat-option-tokens: token-utils.get-tokens-for($tokens, tokens-mat-option.$prefix, $options...);
$mat-optgroup-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-optgroup.$prefix,
$options...
);
$mat-full-pseudo-checkbox-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-full-pseudo-checkbox.$prefix,
$options...
);
$mat-minimal-pseudo-checkbox-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-minimal-pseudo-checkbox.$prefix,
$options...
);
@include token-utils.create-token-values(tokens-mat-app.$prefix, $mat-app-tokens);
@include token-utils.create-token-values(tokens-mat-ripple.$prefix, $mat-ripple-tokens);
@include token-utils.create-token-values(tokens-mat-option.$prefix, $mat-option-tokens);
@include token-utils.create-token-values(tokens-mat-optgroup.$prefix, $mat-optgroup-tokens);
@include token-utils.create-token-values(
tokens-mat-full-pseudo-checkbox.$prefix,
$mat-full-pseudo-checkbox-tokens
);
@include token-utils.create-token-values(
tokens-mat-minimal-pseudo-checkbox.$prefix,
$mat-minimal-pseudo-checkbox-tokens
);
}
| {
"end_byte": 6151,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/_core-theme.scss"
} |
components/src/material/core/public-api.ts_0_681 | /**
* @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.dev/license
*/
export * from './version';
export * from './animation/animation';
export * from './common-behaviors/index';
export * from './datetime/index';
export * from './error/error-options';
export * from './focus-indicators/structural-styles';
export * from './line/line';
export * from './option/index';
export * from './private/index';
export * from './ripple/index';
export * from './selection/index';
export {_MatInternalFormField} from './internal-form-field/internal-form-field';
| {
"end_byte": 681,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/public-api.ts"
} |
components/src/material/core/README.md_0_60 | Core library code for other `@angular/material` components.
| {
"end_byte": 60,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/README.md"
} |
components/src/material/core/_core.scss_0_2271 | @use './tokens/m2/mat/app' as tokens-mat-app;
@use './tokens/token-utils';
@use './style/elevation';
/// @deprecated This mixin is a no-op and is going to be removed in v21.
@mixin core() {}
// Emits the mat-app-background CSS class. This predefined class sets the
// background color and text color of an element.
@mixin app-background() {
// TODO: Move ripple styles to be dynamically loaded instead of in core.
// This variable is used as a fallback for the ripple element's
// background color. However, if it isn't defined anywhere, then MSS
// complains in its verification stage.
html {
--mat-sys-on-surface: initial;
}
// Wrapper element that provides the theme background when the
// user's content isn't inside of a `mat-sidenav-container`.
@at-root {
// Note: we need to emit fallback values here to avoid errors in internal builds.
@include token-utils.use-tokens(tokens-mat-app.$prefix, tokens-mat-app.get-token-slots()) {
.mat-app-background {
@include token-utils.create-token-slot(background-color, background-color, transparent);
@include token-utils.create-token-slot(color, text-color, inherit);
}
}
}
}
// Emits CSS classes for applying elevation. These classes follow the pattern
// mat-elevation-z#, where # is the elevation number you want, from 0 to 24.
// These predefined classes use the CSS box-shadow settings defined by the
// Material Design specification.
@mixin elevation-classes() {
@at-root {
@include token-utils.use-tokens(tokens-mat-app.$prefix, tokens-mat-app.get-token-slots()) {
// Provides external CSS classes for each elevation value. Each CSS class is formatted as
// `mat-elevation-z$z-value` where `$z-value` corresponds to the z-space to which the element
// is elevated.
@for $z-value from 0 through 24 {
$selector: elevation.$prefix + $z-value;
// We need the `mat-mdc-elevation-specific`, because some MDC mixins
// come with elevation baked in and we don't have a way of removing it.
.#{$selector}, .mat-mdc-elevation-specific.#{$selector} {
@include token-utils.create-token-slot(box-shadow, 'elevation-shadow-level-#{$z-value}',
none);
}
}
}
}
}
| {
"end_byte": 2271,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/_core.scss"
} |
components/src/material/core/BUILD.bazel_0_4700 | load("//src/material:config.bzl", "MATERIAL_SCSS_LIBS")
load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
exports_files(["theming/_theming.scss"])
ng_module(
name = "core",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":selection/pseudo-checkbox/pseudo-checkbox.css",
":option/option.css",
":option/optgroup.css",
":internal-form-field/internal-form-field.css",
":ripple/ripple-structure.css",
":focus-indicators/structural-styles.css",
] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/coercion",
"//src/cdk/keycodes",
"//src/cdk/platform",
"//src/cdk/private",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ALL_THEMING_FILES = [
# The `_core.scss` file needs to be added here too because it depends
# on the `_all-typography` file.
"_core.scss",
"color/_all-color.scss",
"density/private/_all-density.scss",
"theming/_all-theme.scss",
"typography/_all-typography.scss",
]
sass_library(
name = "core_scss_lib",
srcs = glob(
["**/_*.scss"],
exclude = ALL_THEMING_FILES + ["./tokens/m3/definitions/unused/**/*_.scss"],
),
deps = [
"//src/cdk:sass_lib",
],
)
sass_library(
name = "theming_scss_lib",
srcs = ALL_THEMING_FILES,
deps = MATERIAL_SCSS_LIBS + [
"//src/cdk:sass_lib",
],
)
sass_binary(
name = "structural_styles_scss",
src = "focus-indicators/structural-styles.scss",
deps = [":core_scss_lib"],
)
sass_binary(
name = "pseudo_checkbox_scss",
src = "selection/pseudo-checkbox/pseudo-checkbox.scss",
deps = [":core_scss_lib"],
)
sass_binary(
name = "option_scss",
src = "option/option.scss",
deps = [":core_scss_lib"],
)
sass_binary(
name = "optgroup_scss",
src = "option/optgroup.scss",
deps = [":core_scss_lib"],
)
sass_binary(
name = "internal_form_field_scss",
src = "internal-form-field/internal-form-field.scss",
deps = [":core_scss_lib"],
)
sass_binary(
name = "ripple_structure_scss",
src = "ripple/ripple-structure.scss",
deps = [":core_scss_lib"],
)
# M3 themes
sass_binary(
name = "azure_blue_prebuilt",
src = "theming/prebuilt/azure-blue.scss",
deps = [
":theming_scss_lib",
"//src/material-experimental:sass_lib",
],
)
sass_binary(
name = "rose_red_prebuilt",
src = "theming/prebuilt/rose-red.scss",
deps = [
":theming_scss_lib",
"//src/material-experimental:sass_lib",
],
)
sass_binary(
name = "cyan_orange_prebuilt",
src = "theming/prebuilt/cyan-orange.scss",
deps = [
":theming_scss_lib",
"//src/material-experimental:sass_lib",
],
)
sass_binary(
name = "magenta_violet_prebuilt",
src = "theming/prebuilt/magenta-violet.scss",
deps = [
":theming_scss_lib",
"//src/material-experimental:sass_lib",
],
)
# Legacy M2 themes
sass_binary(
name = "indigo_pink_prebuilt",
src = "theming/prebuilt/indigo-pink.scss",
deps = [":theming_scss_lib"],
)
sass_binary(
name = "deeppurple-amber_prebuilt",
src = "theming/prebuilt/deeppurple-amber.scss",
deps = [":theming_scss_lib"],
)
sass_binary(
name = "pink-bluegrey_prebuilt",
src = "theming/prebuilt/pink-bluegrey.scss",
deps = [":theming_scss_lib"],
)
sass_binary(
name = "purple-green_prebuilt",
src = "theming/prebuilt/purple-green.scss",
deps = [":theming_scss_lib"],
)
#################
# Test targets
#################
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":core",
"//src/cdk/keycodes",
"//src/cdk/platform",
"//src/cdk/testing/private",
"//src/material/testing",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [
"core.md",
"ripple/ripple.md",
],
)
extract_tokens(
name = "tokens",
srcs = [":core_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 4700,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/BUILD.bazel"
} |
components/src/material/core/core.md_0_194 | The `@angular/material/core` package contains common components and services used by multiple other
components in the library. See the API tab for a listing of components and classes available.
| {
"end_byte": 194,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/core.md"
} |
components/src/material/core/index.ts_0_234 | /**
* @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.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/index.ts"
} |
components/src/material/core/version.ts_0_345 | /**
* @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.dev/license
*/
import {Version} from '@angular/core';
/** Current version of Angular Material. */
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 345,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/version.ts"
} |
components/src/material/core/datetime/date-adapter.ts_0_779 | /**
* @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.dev/license
*/
import {inject, InjectionToken, LOCALE_ID} from '@angular/core';
import {Observable, Subject} from 'rxjs';
/** InjectionToken for datepicker that can be used to override default locale code. */
export const MAT_DATE_LOCALE = new InjectionToken<{}>('MAT_DATE_LOCALE', {
providedIn: 'root',
factory: MAT_DATE_LOCALE_FACTORY,
});
/** @docs-private */
export 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. */ | {
"end_byte": 779,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/date-adapter.ts"
} |
components/src/material/core/datetime/date-adapter.ts_780_8409 | export abstract class DateAdapter<D, L = any> {
/** The locale to use for all dates. */
protected locale: L;
protected readonly _localeChanges = new Subject<void>();
/** A stream that emits when the locale changes. */
readonly localeChanges: Observable<void> = this._localeChanges;
/**
* Gets the year component of the given date.
* @param date The date to extract the year from.
* @returns The year component.
*/
abstract getYear(date: D): number;
/**
* Gets the month component of the given date.
* @param date The date to extract the month from.
* @returns The month component (0-indexed, 0 = January).
*/
abstract getMonth(date: D): number;
/**
* Gets the date of the month component of the given date.
* @param date The date to extract the date of the month from.
* @returns The month component (1-indexed, 1 = first of month).
*/
abstract getDate(date: D): number;
/**
* Gets the day of the week component of the given date.
* @param date The date to extract the day of the week from.
* @returns The month component (0-indexed, 0 = Sunday).
*/
abstract getDayOfWeek(date: D): number;
/**
* Gets a list of names for the months.
* @param style The naming style (e.g. long = 'January', short = 'Jan', narrow = 'J').
* @returns An ordered list of all month names, starting with January.
*/
abstract getMonthNames(style: 'long' | 'short' | 'narrow'): string[];
/**
* Gets a list of names for the dates of the month.
* @returns An ordered list of all date of the month names, starting with '1'.
*/
abstract getDateNames(): string[];
/**
* Gets a list of names for the days of the week.
* @param style The naming style (e.g. long = 'Sunday', short = 'Sun', narrow = 'S').
* @returns An ordered list of all weekday names, starting with Sunday.
*/
abstract getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[];
/**
* Gets the name for the year of the given date.
* @param date The date to get the year name for.
* @returns The name of the given year (e.g. '2017').
*/
abstract getYearName(date: D): string;
/**
* Gets the first day of the week.
* @returns The first day of the week (0-indexed, 0 = Sunday).
*/
abstract getFirstDayOfWeek(): number;
/**
* Gets the number of days in the month of the given date.
* @param date The date whose month should be checked.
* @returns The number of days in the month of the given date.
*/
abstract getNumDaysInMonth(date: D): number;
/**
* Clones the given date.
* @param date The date to clone
* @returns A new date equal to the given date.
*/
abstract clone(date: D): D;
/**
* Creates a date with the given year, month, and date. Does not allow over/under-flow of the
* month and date.
* @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.
* @returns The new date, or null if invalid.
*/
abstract createDate(year: number, month: number, date: number): D;
/**
* Gets today's date.
* @returns Today's date.
*/
abstract today(): D;
/**
* Parses a date 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).
* @returns The parsed date.
*/
abstract parse(value: any, parseFormat: any): D | null;
/**
* Formats a date as a string according to the given format.
* @param date The value to format.
* @param displayFormat The format to use to display the date as a string.
* @returns The formatted date string.
*/
abstract format(date: D, displayFormat: any): string;
/**
* 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.
* @param date The date to add years to.
* @param years The number of years to add (may be negative).
* @returns A new date equal to the given one with the specified number of years added.
*/
abstract addCalendarYears(date: D, years: number): D;
/**
* 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.
* @param date The date to add months to.
* @param months The number of months to add (may be negative).
* @returns A new date equal to the given one with the specified number of months added.
*/
abstract addCalendarMonths(date: D, months: number): D;
/**
* Adds the given number of days to the date. Days are counted as if moving one cell on the
* calendar for each day.
* @param date The date to add days to.
* @param days The number of days to add (may be negative).
* @returns A new date equal to the given one with the specified number of days added.
*/
abstract addCalendarDays(date: D, days: number): D;
/**
* 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>`.
* @param date The date to get the ISO date string for.
* @returns The ISO date string date string.
*/
abstract toIso8601(date: D): string;
/**
* Checks whether the given object is considered a date instance by this DateAdapter.
* @param obj The object to check
* @returns Whether the object is a date instance.
*/
abstract isDateInstance(obj: any): boolean;
/**
* Checks whether the given date is valid.
* @param date The date to check.
* @returns Whether the date is valid.
*/
abstract isValid(date: D): boolean;
/**
* Gets date instance that is not valid.
* @returns An invalid date.
*/
abstract invalid(): D;
/**
* 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: D, hours: number, minutes: number, seconds: number): D {
throw new Error(NOT_IMPLEMENTED);
}
/**
* Gets the hours component of the given date.
* @param date The date to extract the hours from.
*/
getHours(date: D): number {
throw new Error(NOT_IMPLEMENTED);
}
/**
* Gets the minutes component of the given date.
* @param date The date to extract the minutes from.
*/
getMinutes(date: D): number {
throw new Error(NOT_IMPLEMENTED);
}
/**
* Gets the seconds component of the given date.
* @param date The date to extract the seconds from.
*/
getSeconds(date: D): number {
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: any, parseFormat: any): D | null {
throw new Error(NOT_IMPLEMENTED);
} | {
"end_byte": 8409,
"start_byte": 780,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/date-adapter.ts"
} |
components/src/material/core/datetime/date-adapter.ts_8413_13131 | /**
* 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: D, amount: number): D {
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: unknown): D | null {
return this.isDateInstance(obj) && this.isValid(obj as D) ? (obj as D) : 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: any): D | null {
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: L) {
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: D, second: D): number {
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: D, second: D): number {
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: D | null, second: D | null): boolean {
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: D | null, second: D | null): boolean {
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: D, min?: D | null, max?: D | null): D {
if (min && this.compareDate(date, min) < 0) {
return min;
}
if (max && this.compareDate(date, max) > 0) {
return max;
}
return date;
}
} | {
"end_byte": 13131,
"start_byte": 8413,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/date-adapter.ts"
} |
components/src/material/core/datetime/native-date-adapter.spec.ts_0_228 | import {LOCALE_ID} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {DEC, FEB, JAN, MAR} from '../../testing';
import {DateAdapter, MAT_DATE_LOCALE, NativeDateAdapter, NativeDateModule} from './index'; | {
"end_byte": 228,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.spec.ts"
} |
components/src/material/core/datetime/native-date-adapter.spec.ts_230_7056 | describe('NativeDateAdapter', () => {
let adapter: NativeDateAdapter;
let assertValidDate: (d: Date | null, valid: boolean) => void;
beforeEach(() => {
TestBed.configureTestingModule({imports: [NativeDateModule]});
adapter = TestBed.inject(DateAdapter) as NativeDateAdapter;
assertValidDate = (d: Date | null, valid: boolean) => {
expect(adapter.isDateInstance(d))
.not.withContext(`Expected ${d} to be a date instance`)
.toBeNull();
expect(adapter.isValid(d!))
.withContext(
`Expected ${d} to be ${valid ? 'valid' : 'invalid'}, but ` +
`was ${valid ? 'invalid' : 'valid'}`,
)
.toBe(valid);
};
});
it('should get year', () => {
expect(adapter.getYear(new Date(2017, JAN, 1))).toBe(2017);
});
it('should get month', () => {
expect(adapter.getMonth(new Date(2017, JAN, 1))).toBe(0);
});
it('should get date', () => {
expect(adapter.getDate(new Date(2017, JAN, 1))).toBe(1);
});
it('should get day of week', () => {
expect(adapter.getDayOfWeek(new Date(2017, JAN, 1))).toBe(0);
});
it('should get long month names', () => {
expect(adapter.getMonthNames('long')).toEqual([
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]);
});
it('should get short month names', () => {
expect(adapter.getMonthNames('short')).toEqual([
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]);
});
it('should get narrow month names', () => {
expect(adapter.getMonthNames('narrow')).toEqual([
'J',
'F',
'M',
'A',
'M',
'J',
'J',
'A',
'S',
'O',
'N',
'D',
]);
});
it('should get month names in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getMonthNames('long')).toEqual([
'1ζ',
'2ζ',
'3ζ',
'4ζ',
'5ζ',
'6ζ',
'7ζ',
'8ζ',
'9ζ',
'10ζ',
'11ζ',
'12ζ',
]);
});
it('should get date names', () => {
expect(adapter.getDateNames()).toEqual([
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',
]);
});
it('should get date names in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getDateNames()).toEqual([
'1ζ₯',
'2ζ₯',
'3ζ₯',
'4ζ₯',
'5ζ₯',
'6ζ₯',
'7ζ₯',
'8ζ₯',
'9ζ₯',
'10ζ₯',
'11ζ₯',
'12ζ₯',
'13ζ₯',
'14ζ₯',
'15ζ₯',
'16ζ₯',
'17ζ₯',
'18ζ₯',
'19ζ₯',
'20ζ₯',
'21ζ₯',
'22ζ₯',
'23ζ₯',
'24ζ₯',
'25ζ₯',
'26ζ₯',
'27ζ₯',
'28ζ₯',
'29ζ₯',
'30ζ₯',
'31ζ₯',
]);
});
it('should get long day of week names', () => {
expect(adapter.getDayOfWeekNames('long')).toEqual([
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
]);
});
it('should get short day of week names', () => {
expect(adapter.getDayOfWeekNames('short')).toEqual([
'Sun',
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
]);
});
it('should get narrow day of week names', () => {
expect(adapter.getDayOfWeekNames('narrow')).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']);
});
it('should get day of week names in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getDayOfWeekNames('long')).toEqual([
'ζ₯ζζ₯',
'ζζζ₯',
'η«ζζ₯',
'ζ°΄ζζ₯',
'ζ¨ζζ₯',
'ιζζ₯',
'εζζ₯',
]);
});
it('should get year name', () => {
expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017');
});
it('should get year name for low year numbers', () => {
const createAndFormat = (year: number) => {
return adapter.getYearName(adapter.createDate(year, JAN, 1));
};
expect(createAndFormat(50)).toBe('50');
expect(createAndFormat(99)).toBe('99');
expect(createAndFormat(100)).toBe('100');
});
it('should get year name in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017εΉ΄');
});
it('should get first day of week', () => {
expect(adapter.getFirstDayOfWeek()).toBe(0);
});
it('should create Date', () => {
expect(adapter.createDate(2017, JAN, 1)).toEqual(new Date(2017, JAN, 1));
});
it('should not create Date with month over/under-flow', () => {
expect(() => adapter.createDate(2017, DEC + 1, 1)).toThrow();
expect(() => adapter.createDate(2017, JAN - 1, 1)).toThrow();
});
it('should not create Date with date over/under-flow', () => {
expect(() => adapter.createDate(2017, JAN, 32)).toThrow();
expect(() => adapter.createDate(2017, JAN, 0)).toThrow();
});
it('should create Date with low year number', () => {
expect(adapter.createDate(-1, JAN, 1).getFullYear()).toBe(-1);
expect(adapter.createDate(0, JAN, 1).getFullYear()).toBe(0);
expect(adapter.createDate(50, JAN, 1).getFullYear()).toBe(50);
expect(adapter.createDate(99, JAN, 1).getFullYear()).toBe(99);
expect(adapter.createDate(100, JAN, 1).getFullYear()).toBe(100);
});
it('should format Date with low year number', () => {
const createAndFormat = (year: number) => {
return adapter.format(adapter.createDate(year, JAN, 1), {});
};
expect(createAndFormat(50)).toBe('1/1/50');
expect(createAndFormat(99)).toBe('1/1/99');
expect(createAndFormat(100)).toBe('1/1/100');
});
it("should get today's date", () => {
expect(adapter.sameDate(adapter.today(), new Date()))
.withContext("should be equal to today's date")
.toBe(true);
});
it('should parse string', () => {
expect(adapter.parse('1/1/2017')).toEqual(new Date(2017, JAN, 1));
});
it('should parse number', () => {
let timestamp = new Date().getTime();
expect(adapter.parse(timestamp)).toEqual(new Date(timestamp));
});
it('should parse Date', () => {
let date = new Date(2017, JAN, 1);
expect(adapter.parse(date)).toEqual(date);
expect(adapter.parse(date)).not.toBe(date);
});
it('should parse invalid value as invalid', () => {
let d = adapter.parse('hello');
expect(d).not.toBeNull();
expe | {
"end_byte": 7056,
"start_byte": 230,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.spec.ts"
} |
components/src/material/core/datetime/native-date-adapter.spec.ts_7060_13786 | dapter.isDateInstance(d))
.withContext('Expected string to have been fed through Date.parse')
.toBe(true);
expect(adapter.isValid(d as Date))
.withContext('Expected to parse as "invalid date" object')
.toBe(false);
});
it('should format', () => {
expect(adapter.format(new Date(2017, JAN, 1), {})).toEqual('1/1/2017');
});
it('should format with custom format', () => {
expect(
adapter.format(new Date(2017, JAN, 1), {
year: 'numeric',
month: 'long',
day: 'numeric',
}),
).toEqual('January 1, 2017');
});
it('should format with a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.format(new Date(2017, JAN, 1), {})).toEqual('2017/1/1');
});
it('should throw when attempting to format invalid date', () => {
expect(() => adapter.format(new Date(NaN), {})).toThrowError(
/NativeDateAdapter: Cannot format invalid date\./,
);
});
it('should add years', () => {
expect(adapter.addCalendarYears(new Date(2017, JAN, 1), 1)).toEqual(new Date(2018, JAN, 1));
expect(adapter.addCalendarYears(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, JAN, 1));
});
it('should respect leap years when adding years', () => {
expect(adapter.addCalendarYears(new Date(2016, FEB, 29), 1)).toEqual(new Date(2017, FEB, 28));
expect(adapter.addCalendarYears(new Date(2016, FEB, 29), -1)).toEqual(new Date(2015, FEB, 28));
});
it('should add months', () => {
expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, FEB, 1));
expect(adapter.addCalendarMonths(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 1));
});
it('should respect month length differences when adding months', () => {
expect(adapter.addCalendarMonths(new Date(2017, JAN, 31), 1)).toEqual(new Date(2017, FEB, 28));
expect(adapter.addCalendarMonths(new Date(2017, MAR, 31), -1)).toEqual(new Date(2017, FEB, 28));
});
it('should add days', () => {
expect(adapter.addCalendarDays(new Date(2017, JAN, 1), 1)).toEqual(new Date(2017, JAN, 2));
expect(adapter.addCalendarDays(new Date(2017, JAN, 1), -1)).toEqual(new Date(2016, DEC, 31));
});
it('should clone', () => {
let date = new Date(2017, JAN, 1);
expect(adapter.clone(date)).toEqual(date);
expect(adapter.clone(date)).not.toBe(date);
});
it('should preserve time when cloning', () => {
let date = new Date(2017, JAN, 1, 4, 5, 6);
expect(adapter.clone(date)).toEqual(date);
expect(adapter.clone(date)).not.toBe(date);
});
it('should compare dates', () => {
expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 2))).toBeLessThan(0);
expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, FEB, 1))).toBeLessThan(0);
expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1))).toBeLessThan(0);
expect(adapter.compareDate(new Date(2017, JAN, 1), new Date(2017, JAN, 1))).toBe(0);
expect(adapter.compareDate(new Date(2018, JAN, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0);
expect(adapter.compareDate(new Date(2017, FEB, 1), new Date(2017, JAN, 1))).toBeGreaterThan(0);
expect(adapter.compareDate(new Date(2017, JAN, 2), new Date(2017, JAN, 1))).toBeGreaterThan(0);
});
it('should clamp date at lower bound', () => {
expect(
adapter.clampDate(new Date(2017, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)),
).toEqual(new Date(2018, JAN, 1));
});
it('should clamp date at upper bound', () => {
expect(
adapter.clampDate(new Date(2020, JAN, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)),
).toEqual(new Date(2019, JAN, 1));
});
it('should clamp date already within bounds', () => {
expect(
adapter.clampDate(new Date(2018, FEB, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)),
).toEqual(new Date(2018, FEB, 1));
});
it('should use UTC for formatting by default', () => {
expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('14');
});
it('should count today as a valid date instance', () => {
let d = new Date();
expect(adapter.isValid(d)).toBe(true);
expect(adapter.isDateInstance(d)).toBe(true);
});
it('should count an invalid date as an invalid date instance', () => {
let d = new Date(NaN);
expect(adapter.isValid(d)).toBe(false);
expect(adapter.isDateInstance(d)).toBe(true);
});
it('should count a string as not a date instance', () => {
let d = '1/1/2017';
expect(adapter.isDateInstance(d)).toBe(false);
});
it('should provide a method to return a valid date or null', () => {
let d = new Date();
expect(adapter.getValidDateOrNull(d)).toBe(d);
expect(adapter.getValidDateOrNull(new Date(NaN))).toBeNull();
expect(adapter.getValidDateOrNull(null)).toBeNull();
expect(adapter.getValidDateOrNull(undefined)).toBeNull();
expect(adapter.getValidDateOrNull('')).toBeNull();
expect(adapter.getValidDateOrNull(0)).toBeNull();
expect(adapter.getValidDateOrNull('Wed Jul 28 1993')).toBeNull();
expect(adapter.getValidDateOrNull('1595204418000')).toBeNull();
});
it('should create dates from valid ISO strings', () => {
assertValidDate(adapter.deserialize('1985-04-12T23:20:50.52Z'), true);
assertValidDate(adapter.deserialize('1996-12-19T16:39:57-08:00'), true);
assertValidDate(adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true);
assertValidDate(adapter.deserialize('2017-01-01'), true);
assertValidDate(adapter.deserialize('2017-01-01T00:00:00'), true);
assertValidDate(adapter.deserialize('1990-13-31T23:59:00Z'), false);
assertValidDate(adapter.deserialize('1/1/2017'), false);
assertValidDate(adapter.deserialize('2017-01-01T'), false);
expect(adapter.deserialize('')).toBeNull();
expect(adapter.deserialize(null)).toBeNull();
assertValidDate(adapter.deserialize(new Date()), true);
assertValidDate(adapter.deserialize(new Date(NaN)), false);
});
it('should create an invalid date', () => {
assertValidDate(adapter.invalid(), false);
});
it('should not throw when attempting to format a date with a year less than 1', () => {
expect(() => adapter.format(new Date(-1, 1, 1), {})).not.toThrow();
});
it('should not throw when attempting to format a date with a year greater than 9999', () => {
expect(() => adapter.format(new Date(10000, 1, 1), {})).not.toThrow();
});
it('should get hours', () => {
expect(adapter.getHours(new Date(2024, JAN, 1, 14))).toBe(14);
});
it('should get minutes', () => {
expect(adapter.getMinutes(new Date(2024, JAN, 1, 14, 53))).toBe(53);
});
it('should | {
"end_byte": 13786,
"start_byte": 7060,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.spec.ts"
} |
components/src/material/core/datetime/native-date-adapter.spec.ts_13790_21594 | seconds', () => {
expect(adapter.getSeconds(new Date(2024, JAN, 1, 14, 53, 42))).toBe(42);
});
it('should set the time of a date', () => {
const target = new Date(2024, JAN, 1, 0, 0, 0);
const result = adapter.setTime(target, 14, 53, 42);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(53);
expect(adapter.getSeconds(result)).toBe(42);
});
it('should throw when passing in invalid hours to setTime', () => {
expect(() => adapter.setTime(adapter.today(), -1, 0, 0)).toThrowError(
'Invalid hours "-1". Hours value must be between 0 and 23.',
);
expect(() => adapter.setTime(adapter.today(), 51, 0, 0)).toThrowError(
'Invalid hours "51". Hours value must be between 0 and 23.',
);
});
it('should throw when passing in invalid minutes to setTime', () => {
expect(() => adapter.setTime(adapter.today(), 0, -1, 0)).toThrowError(
'Invalid minutes "-1". Minutes value must be between 0 and 59.',
);
expect(() => adapter.setTime(adapter.today(), 0, 65, 0)).toThrowError(
'Invalid minutes "65". Minutes value must be between 0 and 59.',
);
});
it('should throw when passing in invalid seconds to setTime', () => {
expect(() => adapter.setTime(adapter.today(), 0, 0, -1)).toThrowError(
'Invalid seconds "-1". Seconds value must be between 0 and 59.',
);
expect(() => adapter.setTime(adapter.today(), 0, 0, 65)).toThrowError(
'Invalid seconds "65". Seconds value must be between 0 and 59.',
);
});
it('should parse a 24-hour time string', () => {
const result = adapter.parseTime('14:52')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a 12-hour time string', () => {
const result = adapter.parseTime('2:52 PM')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a 12-hour time string with seconds', () => {
const result = adapter.parseTime('2:52:46 PM')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(46);
});
it('should parse a padded 12-hour time string', () => {
const result = adapter.parseTime('02:52 PM')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a padded time string', () => {
const result = adapter.parseTime('03:04:05')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(3);
expect(adapter.getMinutes(result)).toBe(4);
expect(adapter.getSeconds(result)).toBe(5);
});
it('should parse a time string that uses dot as a separator', () => {
const result = adapter.parseTime('14.52')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a time string with characters around the time', () => {
const result = adapter.parseTime('14:52 Ρ.')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a 12-hour time string using a dot separator', () => {
const result = adapter.parseTime('2.52.46 PM')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(46);
});
it('should return an invalid date when parsing invalid time string', () => {
expect(adapter.isValid(adapter.parseTime('abc')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('123')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('14:52 PM')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('24:05')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('00:61:05')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('14:52:78')!)).toBe(false);
expect(adapter.isValid(adapter.parseTime('12:10 PM11:10 PM')!)).toBe(false);
});
it('should return null when parsing unsupported time values', () => {
expect(adapter.parseTime(321)).toBeNull();
expect(adapter.parseTime('')).toBeNull();
expect(adapter.parseTime(' ')).toBeNull();
expect(adapter.parseTime(true)).toBeNull();
expect(adapter.parseTime(undefined)).toBeNull();
});
it('should compare times', () => {
// Use different dates to guarantee that we only compare the times.
const aDate = [2024, JAN, 1] as const;
const bDate = [2024, FEB, 7] as const;
expect(
adapter.compareTime(new Date(...aDate, 12, 0, 0), new Date(...bDate, 13, 0, 0)),
).toBeLessThan(0);
expect(
adapter.compareTime(new Date(...aDate, 12, 50, 0), new Date(...bDate, 12, 51, 0)),
).toBeLessThan(0);
expect(adapter.compareTime(new Date(...aDate, 1, 2, 3), new Date(...bDate, 1, 2, 3))).toBe(0);
expect(
adapter.compareTime(new Date(...aDate, 13, 0, 0), new Date(...bDate, 12, 0, 0)),
).toBeGreaterThan(0);
expect(
adapter.compareTime(new Date(...aDate, 12, 50, 11), new Date(...bDate, 12, 50, 10)),
).toBeGreaterThan(0);
expect(
adapter.compareTime(new Date(...aDate, 13, 0, 0), new Date(...bDate, 10, 59, 59)),
).toBeGreaterThan(0);
});
it('should add seconds to a date', () => {
const amount = 20;
const initial = new Date(2024, JAN, 1, 12, 34, 56);
const result = adapter.addSeconds(initial, amount);
expect(result).not.toBe(initial);
expect(result.getTime() - initial.getTime()).toBe(amount * 1000);
});
});
describe('NativeDateAdapter with MAT_DATE_LOCALE override', () => {
let adapter: NativeDateAdapter;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NativeDateModule],
providers: [{provide: MAT_DATE_LOCALE, useValue: 'da-DK'}],
});
adapter = TestBed.inject(DateAdapter) as NativeDateAdapter;
});
it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => {
const expectedValue = ['sΓΈndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lΓΈrdag'];
expect(adapter.getDayOfWeekNames('long')).toEqual(expectedValue);
});
});
describe('NativeDateAdapter with LOCALE_ID override', () => {
let adapter: NativeDateAdapter;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NativeDateModule],
providers: [{provide: LOCALE_ID, useValue: 'da-DK'}],
});
adapter = TestBed.inject(DateAdapter) as NativeDateAdapter;
});
it('should cascade locale id from the LOCALE_ID injection token to MAT_DATE_LOCALE', () => {
const expectedValue = ['sΓΈndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lΓΈrdag'];
expect(adapter.getDayOfWeekNames('long')).toEqual(expectedValue);
});
});
| {
"end_byte": 21594,
"start_byte": 13790,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.spec.ts"
} |
components/src/material/core/datetime/native-date-formats.ts_0_750 | /**
* @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.dev/license
*/
import {MatDateFormats} from './date-formats';
export const MAT_NATIVE_DATE_FORMATS: MatDateFormats = {
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'},
},
};
| {
"end_byte": 750,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-formats.ts"
} |
components/src/material/core/datetime/native-date-adapter.ts_0_1448 | /**
* @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.dev/license
*/
import {inject, Injectable} from '@angular/core';
import {DateAdapter, MAT_DATE_LOCALE} from './date-adapter';
/**
* 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<T>(length: number, valueFunction: (index: number) => T): T[] {
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. */ | {
"end_byte": 1448,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.ts"
} |
components/src/material/core/datetime/native-date-adapter.ts_1449_8850 | @Injectable()
export class NativeDateAdapter extends DateAdapter<Date> {
/**
* @deprecated No longer being used. To be removed.
* @breaking-change 14.0.0
*/
useUtcForDisplay: boolean = false;
/** The injected locale. */
private readonly _matDateLocale = inject(MAT_DATE_LOCALE, {optional: true});
constructor(...args: unknown[]);
constructor() {
super();
const matDateLocale = inject(MAT_DATE_LOCALE, {optional: true});
if (matDateLocale !== undefined) {
this._matDateLocale = matDateLocale;
}
super.setLocale(this._matDateLocale);
}
getYear(date: Date): number {
return date.getFullYear();
}
getMonth(date: Date): number {
return date.getMonth();
}
getDate(date: Date): number {
return date.getDate();
}
getDayOfWeek(date: Date): number {
return date.getDay();
}
getMonthNames(style: 'long' | 'short' | 'narrow'): string[] {
const dtf = new Intl.DateTimeFormat(this.locale, {month: style, timeZone: 'utc'});
return range(12, i => this._format(dtf, new Date(2017, i, 1)));
}
getDateNames(): string[] {
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: 'long' | 'short' | 'narrow'): string[] {
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: Date): string {
const dtf = new Intl.DateTimeFormat(this.locale, {year: 'numeric', timeZone: 'utc'});
return this._format(dtf, date);
}
getFirstDayOfWeek(): number {
// 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 as any).Locale) {
const locale = new (Intl as any).Locale(this.locale) as {
getWeekInfo?: () => {firstDay: number};
weekInfo?: {firstDay: number};
};
// 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: Date): number {
return this.getDate(
this._createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0),
);
}
clone(date: Date): Date {
return new Date(date.getTime());
}
createDate(year: number, month: number, date: number): 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(): Date {
return new Date();
}
parse(value: any, parseFormat?: any): Date | null {
// 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: Date, displayFormat: Object): string {
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: Date, years: number): Date {
return this.addCalendarMonths(date, years * 12);
}
addCalendarMonths(date: Date, months: number): Date {
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: Date, days: number): Date {
return this._createDateWithOverflow(
this.getYear(date),
this.getMonth(date),
this.getDate(date) + days,
);
}
toIso8601(date: Date): string {
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.
*/
override deserialize(value: any): Date | null {
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: any) {
return obj instanceof Date;
}
isValid(date: Date) {
return !isNaN(date.getTime());
}
invalid(): Date {
return new Date(NaN);
}
override setTime(target: Date, hours: number, minutes: number, seconds: number): Date {
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;
}
override getHours(date: Date): number {
return date.getHours();
}
override getMinutes(date: Date): number {
return date.getMinutes();
}
override getSeconds(date: Date): number {
return date.getSeconds();
} | {
"end_byte": 8850,
"start_byte": 1449,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.ts"
} |
components/src/material/core/datetime/native-date-adapter.ts_8854_13160 | override parseTime(userValue: any, parseFormat?: any): Date | null {
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();
}
override addSeconds(date: Date, amount: number): Date {
return new Date(date.getTime() + amount * 1000);
}
/** Creates a date but allows the month and date to overflow. */
private _createDateWithOverflow(year: number, month: number, date: number) {
// 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.
*/
private _2digit(n: number) {
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
*/
private _format(dtf: Intl.DateTimeFormat, date: 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.
*/
private _parseTimeString(value: string): Date | null {
// 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: number | undefined = parsed[3] == null ? undefined : parseInt(parsed[3]);
const amPm = parsed[4] as 'AM' | 'PM' | undefined;
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;
}
}
/** Checks whether a number is within a certain range. */
function inRange(value: number, min: number, max: number): boolean {
return !isNaN(value) && value >= min && value <= max;
}
| {
"end_byte": 13160,
"start_byte": 8854,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/native-date-adapter.ts"
} |
components/src/material/core/datetime/index.ts_0_1077 | /**
* @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.dev/license
*/
import {NgModule, Provider} from '@angular/core';
import {DateAdapter} from './date-adapter';
import {MAT_DATE_FORMATS, MatDateFormats} from './date-formats';
import {NativeDateAdapter} from './native-date-adapter';
import {MAT_NATIVE_DATE_FORMATS} from './native-date-formats';
export * from './date-adapter';
export * from './date-formats';
export * from './native-date-adapter';
export * from './native-date-formats';
@NgModule({
providers: [{provide: DateAdapter, useClass: NativeDateAdapter}],
})
export class NativeDateModule {}
@NgModule({
providers: [provideNativeDateAdapter()],
})
export class MatNativeDateModule {}
export function provideNativeDateAdapter(
formats: MatDateFormats = MAT_NATIVE_DATE_FORMATS,
): Provider[] {
return [
{provide: DateAdapter, useClass: NativeDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: formats},
];
}
| {
"end_byte": 1077,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/index.ts"
} |
components/src/material/core/datetime/date-formats.ts_0_617 | /**
* @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.dev/license
*/
import {InjectionToken} from '@angular/core';
export type MatDateFormats = {
parse: {
dateInput: any;
timeInput?: any;
};
display: {
dateInput: any;
monthLabel?: any;
monthYearLabel: any;
dateA11yLabel: any;
monthYearA11yLabel: any;
timeInput?: any;
timeOptionLabel?: any;
};
};
export const MAT_DATE_FORMATS = new InjectionToken<MatDateFormats>('mat-date-formats');
| {
"end_byte": 617,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/datetime/date-formats.ts"
} |
components/src/material/core/common-behaviors/error-state.ts_0_1615 | /**
* @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.dev/license
*/
import {AbstractControl, FormGroupDirective, NgControl, NgForm} from '@angular/forms';
import {Subject} from 'rxjs';
import {ErrorStateMatcher as _ErrorStateMatcher} from '../error/error-options';
// Declare ErrorStateMatcher as an interface to have compatibility with Closure Compiler.
interface ErrorStateMatcher extends _ErrorStateMatcher {}
/**
* Class that tracks the error state of a component.
* @docs-private
*/
export class _ErrorStateTracker {
/** Whether the tracker is currently in an error state. */
errorState = false;
/** User-defined matcher for the error state. */
matcher: ErrorStateMatcher;
constructor(
private _defaultMatcher: ErrorStateMatcher | null,
public ngControl: NgControl | null,
private _parentFormGroup: FormGroupDirective | null,
private _parentForm: NgForm | null,
private _stateChanges: Subject<void>,
) {}
/** 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 as AbstractControl) : null;
const newState = matcher?.isErrorState(control, parent) ?? false;
if (newState !== oldState) {
this.errorState = newState;
this._stateChanges.next();
}
}
}
| {
"end_byte": 1615,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/common-behaviors/error-state.ts"
} |
components/src/material/core/common-behaviors/palette.ts_0_312 | /**
* @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.dev/license
*/
/** Possible color palette values. */
export type ThemePalette = 'primary' | 'accent' | 'warn' | undefined;
| {
"end_byte": 312,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/common-behaviors/palette.ts"
} |
components/src/material/core/common-behaviors/index.ts_0_415 | /**
* @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.dev/license
*/
export {
MatCommonModule,
MATERIAL_SANITY_CHECKS,
SanityChecks,
GranularSanityChecks,
} from './common-module';
export {ThemePalette} from './palette';
export {_ErrorStateTracker} from './error-state';
| {
"end_byte": 415,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/common-behaviors/index.ts"
} |
components/src/material/core/common-behaviors/common-module.ts_0_1916 | /**
* @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.dev/license
*/
import {HighContrastModeDetector} from '@angular/cdk/a11y';
import {BidiModule} from '@angular/cdk/bidi';
import {inject, InjectionToken, NgModule} from '@angular/core';
import {_isTestEnvironment} from '@angular/cdk/platform';
/**
* Injection token that configures whether the Material sanity checks are enabled.
* @deprecated No longer used and will be removed.
* @breaking-change 21.0.0
*/
export const MATERIAL_SANITY_CHECKS = new InjectionToken<SanityChecks>('mat-sanity-checks', {
providedIn: 'root',
factory: () => true,
});
/**
* Possible sanity checks that can be enabled. If set to
* true/false, all checks will be enabled/disabled.
* @deprecated No longer used and will be removed.
* @breaking-change 21.0.0
*/
export type SanityChecks = boolean | GranularSanityChecks;
/**
* Object that can be used to configure the sanity checks granularly.
* @deprecated No longer used and will be removed.
* @breaking-change 21.0.0
*/
export interface GranularSanityChecks {
doctype: boolean;
theme: boolean;
version: boolean;
}
/**
* 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
*/
@NgModule({
imports: [BidiModule],
exports: [BidiModule],
})
export class MatCommonModule {
constructor(...args: any[]);
constructor() {
// While A11yModule also does this, we repeat it here to avoid importing A11yModule
// in MatCommonModule.
inject(HighContrastModeDetector)._applyBodyHighContrastModeCssClasses();
}
}
| {
"end_byte": 1916,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/common-behaviors/common-module.ts"
} |
components/src/material/core/color/_all-color.scss_0_475 | @use '../theming/all-theme';
@use '../theming/inspection';
// Includes all of the color styles.
@mixin all-component-colors($theme) {
@if not inspection.theme-has($theme, color) {
@error 'No color configuration specified.';
}
@include all-theme.all-component-themes(
inspection.theme-remove($theme, base, typography, density));
}
// @deprecated Use `all-component-colors`.
@mixin angular-material-color($theme) {
@include all-component-colors($theme);
}
| {
"end_byte": 475,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/color/_all-color.scss"
} |
components/src/material/core/density/private/_all-density.scss_0_3203 | @use '../../theming/inspection';
@use '../../../button/button-theme';
@use '../../../button/icon-button-theme';
@use '../../../button/fab-theme';
@use '../../../expansion/expansion-theme';
@use '../../../stepper/stepper-theme';
@use '../../../toolbar/toolbar-theme';
@use '../../../tree/tree-theme';
@use '../../../paginator/paginator-theme';
@use '../../../form-field/form-field-theme';
@use '../../../button-toggle/button-toggle-theme';
@use '../../../card/card-theme';
@use '../../../progress-bar/progress-bar-theme';
@use '../../../progress-spinner/progress-spinner-theme';
@use '../../../tooltip/tooltip-theme';
@use '../../../input/input-theme';
@use '../../../autocomplete/autocomplete-theme';
@use '../../../checkbox/checkbox-theme';
@use '../../../core/core-theme';
@use '../../../select/select-theme';
@use '../../../dialog/dialog-theme';
@use '../../../chips/chips-theme';
@use '../../../slide-toggle/slide-toggle-theme';
@use '../../../radio/radio-theme';
@use '../../../slider/slider-theme';
@use '../../../menu/menu-theme';
@use '../../../list/list-theme';
@use '../../../tabs/tabs-theme';
@use '../../../snack-bar/snack-bar-theme';
@use '../../../table/table-theme';
// Includes all of the density styles.
@mixin all-component-densities($theme) {
@if not inspection.theme-has($theme, density) {
@error 'No density configuration specified.';
}
// TODO: COMP-309: Do not use individual mixins. Instead, use the all-theme mixin and only
// specify a `density` config while setting `color` and `typography` to `null`. This is currently
// not possible as it would introduce a circular dependency for density because the `mat-core`
// mixin that is transitively loaded by the `all-theme` file, imports `all-density` which
// would then load `all-theme` again. This ultimately results a circular dependency.
@include form-field-theme.density($theme);
@include card-theme.density($theme);
@include progress-bar-theme.density($theme);
@include progress-spinner-theme.density($theme);
@include tooltip-theme.density($theme);
@include input-theme.density($theme);
@include core-theme.density($theme);
@include select-theme.density($theme);
@include checkbox-theme.density($theme);
@include autocomplete-theme.density($theme);
@include dialog-theme.density($theme);
@include chips-theme.density($theme);
@include slide-toggle-theme.density($theme);
@include radio-theme.density($theme);
@include slider-theme.density($theme);
@include menu-theme.density($theme);
@include list-theme.density($theme);
@include paginator-theme.density($theme);
@include tabs-theme.density($theme);
@include snack-bar-theme.density($theme);
@include button-theme.density($theme);
@include icon-button-theme.density($theme);
@include fab-theme.density($theme);
@include table-theme.density($theme);
@include expansion-theme.density($theme);
@include stepper-theme.density($theme);
@include toolbar-theme.density($theme);
@include tree-theme.density($theme);
@include button-toggle-theme.density($theme);
}
// @deprecated Use `all-component-densities`.
@mixin angular-material-density($theme) {
@include all-component-densities($theme);
}
| {
"end_byte": 3203,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/density/private/_all-density.scss"
} |
components/src/material/core/focus-indicators/structural-styles.scss_0_58 | @use './private';
@include private.structural-styling();
| {
"end_byte": 58,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/focus-indicators/structural-styles.scss"
} |
components/src/material/core/focus-indicators/_private.scss_0_3566 | @use 'sass:map';
@use 'sass:meta';
@use '@angular/cdk';
@use '../style/layout-common';
@use '../theming/theming';
@use '../theming/inspection';
// Private sass variables that will be used as reference throughout component stylesheets.
$default-border-width: 3px;
$default-border-style: solid;
$default-border-color: transparent;
$default-border-radius: 4px;
// Mixin that renders the focus indicator structural styles.
@mixin structural-styling() {
.mat-focus-indicator {
position: relative;
&::before {
@include layout-common.fill();
box-sizing: border-box;
pointer-events: none;
display: var(--mat-focus-indicator-display, none); // Hide the indicator by default.
border-width: var(--mat-focus-indicator-border-width, #{$default-border-width});
border-style: var(--mat-focus-indicator-border-style, #{$default-border-style});
border-color: var(--mat-focus-indicator-border-color, #{$default-border-color});
border-radius: var(--mat-focus-indicator-border-radius, #{$default-border-radius});
}
// By default, render the focus indicator when the focus indicator host element takes focus.
// Defining a pseudo element's content will cause it to render.
&:focus::before {
content: '';
}
}
// Enable the indicator in high contrast mode.
@include cdk.high-contrast {
@include _customize-focus-indicators((display: block));
}
}
// Generates CSS variable declarations from a map.
@mixin _output-variables($map) {
@each $key, $value in $map {
@if ($value) {
--#{$key}: #{$value};
}
}
}
// Mixin that dedups CSS variables for the strong-focus-indicators mixin.
@mixin _customize-focus-indicators($config) {
$border-style: map.get($config, border-style);
$border-width: map.get($config, border-width);
$border-radius: map.get($config, border-radius);
$border-color: map.get($config, border-color);
$display: map.get($config, display);
$map: (
'mat-focus-indicator-border-style': $border-style,
'mat-focus-indicator-border-width': $border-width,
'mat-focus-indicator-border-radius': $border-radius,
'mat-focus-indicator-border-color': $border-color,
'mat-focus-indicator-display': $display,
);
@if (&) {
@include _output-variables($map);
}
@else {
// We use `html` here instead of `:root`, because the
// latter causes some issues with internal tooling.
html {
@include _output-variables($map);
}
}
}
@mixin strong-focus-indicators($config: ()) {
// Default focus indicator config.
$default-config: (
border-color: black,
display: block,
);
// Merge default config with user config.
$config: map.merge($default-config, $config);
@include _customize-focus-indicators($config);
}
@mixin strong-focus-indicators-color($theme-or-color) {
@if meta.type-of($theme-or-color) == 'color' {
@include _customize-focus-indicators((border-color: $theme-or-color));
}
@else {
$border-color: inspection.get-theme-color($theme-or-color, primary);
@include _customize-focus-indicators((border-color: $border-color));
}
}
@mixin strong-focus-indicators-theme($theme-or-color) {
@if meta.type-of($theme-or-color) == 'color' {
@include _customize-focus-indicators((border-color: $theme-or-color));
}
@else {
@include theming.private-check-duplicate-theme-styles($theme-or-color, 'mat-focus-indicators') {
@if inspection.theme-has($theme-or-color, color) {
@include strong-focus-indicators-color($theme-or-color);
}
}
}
}
| {
"end_byte": 3566,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/focus-indicators/_private.scss"
} |
components/src/material/core/focus-indicators/structural-styles.ts_0_615 | /**
* @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.dev/license
*/
import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core';
/**
* Component used to load structural styles for focus indicators.
* @docs-private
*/
@Component({
selector: 'structural-styles',
styleUrl: 'structural-styles.css',
encapsulation: ViewEncapsulation.None,
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class _StructuralStylesLoader {}
| {
"end_byte": 615,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/focus-indicators/structural-styles.ts"
} |
components/src/material/core/animation/animation.ts_0_632 | /**
* @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.dev/license
*/
/** @docs-private */
export 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 */
export class AnimationDurations {
static COMPLEX = '375ms';
static ENTERING = '225ms';
static EXITING = '195ms';
}
| {
"end_byte": 632,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/animation/animation.ts"
} |
components/src/material/core/ripple/ripple.ts_0_7447 | /**
* @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.dev/license
*/
import {Platform} from '@angular/cdk/platform';
import {
Directive,
ElementRef,
InjectionToken,
Input,
NgZone,
OnDestroy,
OnInit,
ANIMATION_MODULE_TYPE,
Injector,
inject,
} from '@angular/core';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {RippleAnimationConfig, RippleConfig, RippleRef} from './ripple-ref';
import {RippleRenderer, RippleTarget} from './ripple-renderer';
/** Configurable options for `matRipple`. */
export interface RippleGlobalOptions {
/**
* Whether ripples should be disabled. Ripples can be still launched manually by using
* the `launch()` method. Therefore focus indicators will still show up.
*/
disabled?: boolean;
/**
* Default configuration for the animation duration of the ripples. There are two phases with
* different durations for the ripples: `enter` and `leave`. The durations will be overwritten
* by the value of `matRippleAnimation` or if the `NoopAnimationsModule` is included.
*/
animation?: RippleAnimationConfig;
/**
* Whether ripples should start fading out immediately after the mouse or touch is released. By
* default, ripples will wait for the enter animation to complete and for mouse or touch release.
*/
terminateOnPointerUp?: boolean;
/**
* A namespace to use for ripple loader to allow multiple instances to exist on the same page.
*/
namespace?: string;
}
/** Injection token that can be used to specify the global ripple options. */
export const MAT_RIPPLE_GLOBAL_OPTIONS = new InjectionToken<RippleGlobalOptions>(
'mat-ripple-global-options',
);
@Directive({
selector: '[mat-ripple], [matRipple]',
exportAs: 'matRipple',
host: {
'class': 'mat-ripple',
'[class.mat-ripple-unbounded]': 'unbounded',
},
})
export class MatRipple implements OnInit, OnDestroy, RippleTarget {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
/** Custom color for all ripples. */
@Input('matRippleColor') color: string;
/** Whether the ripples should be visible outside the component's bounds. */
@Input('matRippleUnbounded') unbounded: boolean;
/**
* Whether the ripple always originates from the center of the host element's bounds, rather
* than originating from the location of the click event.
*/
@Input('matRippleCentered') centered: boolean;
/**
* If set, the radius in pixels of foreground ripples when fully expanded. If unset, the radius
* will be the distance from the center of the ripple to the furthest corner of the host element's
* bounding rectangle.
*/
@Input('matRippleRadius') radius: number = 0;
/**
* Configuration for the ripple animation. Allows modifying the enter and exit animation
* duration of the ripples. The animation durations will be overwritten if the
* `NoopAnimationsModule` is being used.
*/
@Input('matRippleAnimation') animation: RippleAnimationConfig;
/**
* Whether click events will not trigger the ripple. Ripples can be still launched manually
* by using the `launch()` method.
*/
@Input('matRippleDisabled')
get disabled() {
return this._disabled;
}
set disabled(value: boolean) {
if (value) {
this.fadeOutAllNonPersistent();
}
this._disabled = value;
this._setupTriggerEventsIfEnabled();
}
private _disabled: boolean = false;
/**
* The element that triggers the ripple when click events are received.
* Defaults to the directive's host element.
*/
@Input('matRippleTrigger')
get trigger() {
return this._trigger || this._elementRef.nativeElement;
}
set trigger(trigger: HTMLElement) {
this._trigger = trigger;
this._setupTriggerEventsIfEnabled();
}
private _trigger: HTMLElement;
/** Renderer for the ripple DOM manipulations. */
private _rippleRenderer: RippleRenderer;
/** Options that are set globally for all ripples. */
private _globalOptions: RippleGlobalOptions;
/** @docs-private Whether ripple directive is initialized and the input bindings are set. */
_isInitialized: boolean = false;
constructor(...args: unknown[]);
constructor() {
const ngZone = inject(NgZone);
const platform = inject(Platform);
const globalOptions = inject<RippleGlobalOptions>(MAT_RIPPLE_GLOBAL_OPTIONS, {optional: true});
const injector = inject(Injector);
// Note: cannot use `inject()` here, because this class
// gets instantiated manually in the ripple loader.
this._globalOptions = globalOptions || {};
this._rippleRenderer = new RippleRenderer(this, ngZone, this._elementRef, platform, injector);
}
ngOnInit() {
this._isInitialized = true;
this._setupTriggerEventsIfEnabled();
}
ngOnDestroy() {
this._rippleRenderer._removeTriggerEvents();
}
/** Fades out all currently showing ripple elements. */
fadeOutAll() {
this._rippleRenderer.fadeOutAll();
}
/** Fades out all currently showing non-persistent ripple elements. */
fadeOutAllNonPersistent() {
this._rippleRenderer.fadeOutAllNonPersistent();
}
/**
* Ripple configuration from the directive's input values.
* @docs-private Implemented as part of RippleTarget
*/
get rippleConfig(): RippleConfig {
return {
centered: this.centered,
radius: this.radius,
color: this.color,
animation: {
...this._globalOptions.animation,
...(this._animationMode === 'NoopAnimations' ? {enterDuration: 0, exitDuration: 0} : {}),
...this.animation,
},
terminateOnPointerUp: this._globalOptions.terminateOnPointerUp,
};
}
/**
* Whether ripples on pointer-down are disabled or not.
* @docs-private Implemented as part of RippleTarget
*/
get rippleDisabled(): boolean {
return this.disabled || !!this._globalOptions.disabled;
}
/** Sets up the trigger event listeners if ripples are enabled. */
private _setupTriggerEventsIfEnabled() {
if (!this.disabled && this._isInitialized) {
this._rippleRenderer.setupTriggerEvents(this.trigger);
}
}
/**
* Launches a manual ripple using the specified ripple configuration.
* @param config Configuration for the manual ripple.
*/
launch(config: RippleConfig): RippleRef;
/**
* Launches a manual ripple at the specified coordinates relative to the viewport.
* @param x Coordinate along the X axis at which to fade-in the ripple. Coordinate
* should be relative to the viewport.
* @param y Coordinate along the Y axis at which to fade-in the ripple. Coordinate
* should be relative to the viewport.
* @param config Optional ripple configuration for the manual ripple.
*/
launch(x: number, y: number, config?: RippleConfig): RippleRef;
/** Launches a manual ripple at the specified coordinated or just by the ripple config. */
launch(configOrX: number | RippleConfig, y: number = 0, config?: RippleConfig): RippleRef {
if (typeof configOrX === 'number') {
return this._rippleRenderer.fadeInRipple(configOrX, y, {...this.rippleConfig, ...config});
} else {
return this._rippleRenderer.fadeInRipple(0, 0, {...this.rippleConfig, ...configOrX});
}
}
}
| {
"end_byte": 7447,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_0_1930 | import {Platform} from '@angular/cdk/platform';
import {
createMouseEvent,
createTouchEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchMouseEvent,
dispatchTouchEvent,
} from '@angular/cdk/testing/private';
import {Component, ViewChild, ViewEncapsulation} from '@angular/core';
import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {
MAT_RIPPLE_GLOBAL_OPTIONS,
MatRipple,
MatRippleModule,
RippleAnimationConfig,
RippleGlobalOptions,
RippleState,
} from './index';
describe('MatRipple', () => {
let fixture: ComponentFixture<any>;
let rippleTarget: HTMLElement;
let originalBodyMargin: string | null;
let platform: Platform;
/** Extracts the numeric value of a pixel size string like '123px'. */
const pxStringToFloat = (s: string | null) => (s ? parseFloat(s) : 0);
const startingWindowWidth = window.innerWidth;
const startingWindowHeight = window.innerHeight;
/** Flushes the transition of the ripple element inside of the ripple target. */
function flushTransition() {
dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend');
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MatRippleModule,
BasicRippleContainer,
RippleContainerWithInputBindings,
RippleContainerWithoutBindings,
RippleContainerWithNgIf,
RippleCssTransitionNone,
RippleCssTransitionDurationZero,
RippleWithDomRemovalOnClick,
],
});
});
beforeEach(inject([Platform], (p: Platform) => {
platform = p;
// Set body margin to 0 during tests so it doesn't mess up position calculations.
originalBodyMargin = document.body.style.margin;
document.body.style.margin = '0';
}));
afterEach(() => {
document.body.style.margin = originalBodyMargin!;
}); | {
"end_byte": 1930,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_1934_10921 | describe('basic ripple', () => {
let rippleDirective: MatRipple;
const TARGET_HEIGHT = 200;
const TARGET_WIDTH = 300;
beforeEach(() => {
fixture = TestBed.createComponent(BasicRippleContainer);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
rippleDirective = fixture.componentInstance.ripple;
});
it('sizes ripple to cover element', () => {
// This test is consistently flaky on iOS (vs. Safari on desktop and all other browsers).
// Temporarily skip this test on iOS until we can determine the source of the flakiness.
// TODO(jelbourn): determine the source of flakiness here
if (platform.IOS) {
return;
}
let elementRect = rippleTarget.getBoundingClientRect();
// Dispatch a ripple at the following relative coordinates (X: 50| Y: 75)
dispatchMouseEvent(rippleTarget, 'mousedown', 50, 75);
dispatchMouseEvent(rippleTarget, 'mouseup');
// Calculate distance from the click to farthest edge of the ripple target.
let maxDistanceX = TARGET_WIDTH - 50;
let maxDistanceY = TARGET_HEIGHT - 75;
// At this point the foreground ripple should be created with a div centered at the click
// location, and large enough to reach the furthest corner, which is 250px to the right
// and 125px down relative to the click position.
let expectedRadius = Math.sqrt(maxDistanceX * maxDistanceX + maxDistanceY * maxDistanceY);
let expectedLeft = elementRect.left + 50 - expectedRadius;
let expectedTop = elementRect.top + 75 - expectedRadius;
let ripple = rippleTarget.querySelector('.mat-ripple-element') as HTMLElement;
// Note: getBoundingClientRect won't work because there's a transform applied to make the
// ripple start out tiny.
expect(pxStringToFloat(ripple.style.left)).toBeCloseTo(expectedLeft, 1);
expect(pxStringToFloat(ripple.style.top)).toBeCloseTo(expectedTop, 1);
expect(pxStringToFloat(ripple.style.width)).toBeCloseTo(2 * expectedRadius, 1);
expect(pxStringToFloat(ripple.style.height)).toBeCloseTo(2 * expectedRadius, 1);
});
it('creates ripple on mousedown', () => {
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(2);
});
it('should launch ripples on touchstart', () => {
dispatchTouchEvent(rippleTarget, 'touchstart');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchTouchEvent(rippleTarget, 'touchend');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should clear ripples if the touch sequence is cancelled', () => {
dispatchTouchEvent(rippleTarget, 'touchstart');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchTouchEvent(rippleTarget, 'touchcancel');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should launch multiple ripples for multi-touch', () => {
const touchEvent = createTouchEvent('touchstart');
Object.defineProperties(touchEvent, {
changedTouches: {
value: [
{pageX: 0, pageY: 0},
{pageX: 10, pageY: 10},
{pageX: 20, pageY: 20},
],
},
});
dispatchEvent(rippleTarget, touchEvent);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(3);
const rippleElements = rippleTarget.querySelectorAll('.mat-ripple-element');
// Flush the fade-in transition of all three ripples.
dispatchFakeEvent(rippleElements[0], 'transitionend');
dispatchFakeEvent(rippleElements[1], 'transitionend');
dispatchFakeEvent(rippleElements[2], 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(3);
dispatchTouchEvent(rippleTarget, 'touchend');
// Flush the fade-out transition of all three ripples.
dispatchFakeEvent(rippleElements[0], 'transitionend');
dispatchFakeEvent(rippleElements[1], 'transitionend');
dispatchFakeEvent(rippleElements[2], 'transitionend');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should ignore synthetic mouse events after touchstart', () => {
dispatchTouchEvent(rippleTarget, 'touchstart');
dispatchTouchEvent(rippleTarget, 'mousedown');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchTouchEvent(rippleTarget, 'touchend');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should ignore fake mouse events from screen readers', () => {
const event = createMouseEvent('mousedown');
Object.defineProperties(event, {buttons: {get: () => 0}, detail: {get: () => 0}});
dispatchEvent(rippleTarget, event);
expect(rippleTarget.querySelector('.mat-ripple-element')).toBeFalsy();
});
it('removes ripple after timeout', () => {
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Flush fade-in and fade-out transition.
flushTransition();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should remove ripples after mouseup', () => {
dispatchMouseEvent(rippleTarget, 'mousedown');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Flush the transition of fading in. Also flush the potential fading-out transition in
// order to make sure that the ripples didn't fade-out before mouseup.
flushTransition();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchMouseEvent(rippleTarget, 'mouseup');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('creates ripples when manually triggered', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
rippleDirective.launch(0, 0);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('creates manual ripples with the default ripple config', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
// Calculate the diagonal distance and divide it by two for the center radius.
let radius = Math.sqrt(TARGET_HEIGHT * TARGET_HEIGHT + TARGET_WIDTH * TARGET_WIDTH) / 2;
rippleDirective.centered = true;
fixture.changeDetectorRef.markForCheck();
rippleDirective.launch(0, 0);
let rippleElement = rippleTarget.querySelector('.mat-ripple-element') as HTMLElement;
expect(rippleElement).toBeTruthy();
expect(parseFloat(rippleElement.style.left as string)).toBeCloseTo(
TARGET_WIDTH / 2 - radius,
1,
);
expect(parseFloat(rippleElement.style.top as string)).toBeCloseTo(
TARGET_HEIGHT / 2 - radius,
1,
);
});
it('cleans up the event handlers when the container gets destroyed', () => {
fixture = TestBed.createComponent(RippleContainerWithNgIf);
fixture.detectChanges();
rippleTarget = fixture.debugElement.nativeElement.querySelector('.mat-ripple');
fixture.componentInstance.isDestroyed = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should only persist the latest ripple on pointer down', () => {
dispatchMouseEvent(rippleTarget, 'mousedown');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchMouseEvent(rippleTarget, 'mousedown');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(2);
// Flush the fade-in transition.
flushTransition();
// Flush the fade-out transition.
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
}); | {
"end_byte": 10921,
"start_byte": 1934,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_10927_18011 | describe('when page is scrolled', () => {
let veryLargeElement: HTMLDivElement = document.createElement('div');
let pageScrollTop = 500;
let pageScrollLeft = 500;
beforeEach(() => {
// Add a very large element to make the page scroll
veryLargeElement.style.width = '4000px';
veryLargeElement.style.height = '4000px';
document.body.appendChild(veryLargeElement);
document.body.scrollTop = pageScrollTop;
document.body.scrollLeft = pageScrollLeft;
// Firefox
document.documentElement!.scrollLeft = pageScrollLeft;
document.documentElement!.scrollTop = pageScrollTop;
// Mobile safari
window.scrollTo(pageScrollLeft, pageScrollTop);
});
afterEach(() => {
veryLargeElement.remove();
document.body.scrollTop = 0;
document.body.scrollLeft = 0;
// Firefox
document.documentElement!.scrollLeft = 0;
document.documentElement!.scrollTop = 0;
// Mobile safari
window.scrollTo(0, 0);
});
it('create ripple with correct position', () => {
let elementTop = 600;
let elementLeft = 750;
let left = 50;
let top = 75;
rippleTarget.style.left = `${elementLeft}px`;
rippleTarget.style.top = `${elementTop}px`;
// Simulate a keyboard-triggered click by setting event coordinates to 0.
dispatchMouseEvent(
rippleTarget,
'mousedown',
left + elementLeft - pageScrollLeft,
top + elementTop - pageScrollTop,
);
let expectedRadius = Math.sqrt(250 * 250 + 125 * 125);
let expectedLeft = left - expectedRadius;
let expectedTop = top - expectedRadius;
let ripple = rippleTarget.querySelector('.mat-ripple-element') as HTMLElement;
// In the iOS simulator (BrowserStack & SauceLabs), adding the content to the
// body causes karma's iframe for the test to stretch to fit that content once we attempt to
// scroll the page. Setting width / height / maxWidth / maxHeight on the iframe does not
// successfully constrain its size. As such, skip assertions in environments where the
// window size has changed since the start of the test.
if (window.innerWidth > startingWindowWidth || window.innerHeight > startingWindowHeight) {
return;
}
expect(pxStringToFloat(ripple.style.left)).toBeCloseTo(expectedLeft, 1);
expect(pxStringToFloat(ripple.style.top)).toBeCloseTo(expectedTop, 1);
expect(pxStringToFloat(ripple.style.width)).toBeCloseTo(2 * expectedRadius, 1);
expect(pxStringToFloat(ripple.style.height)).toBeCloseTo(2 * expectedRadius, 1);
});
});
});
describe('manual ripples', () => {
let rippleDirective: MatRipple;
beforeEach(() => {
fixture = TestBed.createComponent(BasicRippleContainer);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
rippleDirective = fixture.componentInstance.ripple;
});
it('should allow persistent ripple elements', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
let rippleRef = rippleDirective.launch(0, 0, {persistent: true});
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Flush the fade-in transition. Additionally flush the potential fade-out transition
// in order to make sure that the ripple is persistent and won't fade-out.
flushTransition();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
rippleRef.fadeOut();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should remove ripples that are not done fading in', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
rippleDirective.launch(0, 0);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// The ripple should still fade in right now. Now by calling `fadeOutAll` the ripple should
// immediately start fading out. We can verify this by just flushing the current transition
// and verifying if the ripple has been removed from the DOM.
rippleDirective.fadeOutAll();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to be active after calling fadeOutAll.')
.toBe(0);
});
it('should properly set ripple states', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
let rippleRef = rippleDirective.launch(0, 0, {persistent: true});
expect(rippleRef.state).toBe(RippleState.FADING_IN);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
flushTransition();
expect(rippleRef.state).toBe(RippleState.VISIBLE);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
rippleRef.fadeOut();
expect(rippleRef.state).toBe(RippleState.FADING_OUT);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
flushTransition();
expect(rippleRef.state).toBe(RippleState.HIDDEN);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should allow setting a specific animation config for a ripple', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
const rippleRef = rippleDirective.launch(0, 0, {
animation: {enterDuration: 120, exitDuration: 0},
});
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Since we cannot use `fakeAsync`, we manually verify that the element has
// the specified transition duration.
expect(rippleRef.element.style.transitionDuration).toBe('120ms');
// We still flush the 120ms transition and should check if the 0ms exit transition happened
// properly.
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should allow passing only a configuration', () => {
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
const rippleRef = rippleDirective.launch({persistent: true});
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Flush the fade-in transition. Additionally flush the potential fade-out transition
// in order to make sure that the ripple is persistent and won't fade-out.
flushTransition();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
rippleRef.fadeOut();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
}); | {
"end_byte": 18011,
"start_byte": 10927,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_18015_22547 | describe('global ripple options', () => {
let rippleDirective: MatRipple;
function createTestComponent(
rippleConfig: RippleGlobalOptions,
testComponent: any = BasicRippleContainer,
extraImports: any[] = [],
) {
// Reset the previously configured testing module to be able set new providers.
// The testing module has been initialized in the root describe group for the ripples.
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [MatRippleModule, ...extraImports, testComponent],
providers: [{provide: MAT_RIPPLE_GLOBAL_OPTIONS, useValue: rippleConfig}],
});
fixture = TestBed.createComponent(testComponent);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
rippleDirective = fixture.componentInstance.ripple;
}
it('should work without having any binding set', () => {
createTestComponent({disabled: true}, RippleContainerWithoutBindings);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('when disabled should not show any ripples on mousedown', () => {
createTestComponent({disabled: true});
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('when disabled should still allow manual ripples', () => {
createTestComponent({disabled: true});
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
rippleDirective.launch(0, 0);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('should support changing the animation duration', () => {
createTestComponent({
animation: {enterDuration: 100, exitDuration: 150},
});
const rippleRef = rippleDirective.launch(0, 0);
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
expect(rippleRef.element.style.transitionDuration).toBe('100ms');
flushTransition();
expect(rippleRef.element.style.transitionDuration).toBe('150ms');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should allow ripples to fade out immediately on pointer up', () => {
createTestComponent({
terminateOnPointerUp: true,
});
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
// Just flush the fade-out duration because we immediately fired the mouseup after the
// mousedown. This means that the ripple should just fade out, and there shouldn't be an
// enter animation.
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should not mutate the global options when NoopAnimationsModule is present', () => {
const options: RippleGlobalOptions = {};
createTestComponent(options, RippleContainerWithoutBindings, [NoopAnimationsModule]);
expect(options.animation).toBeFalsy();
});
});
describe('with disabled animations', () => {
let rippleDirective: MatRipple;
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [NoopAnimationsModule, MatRippleModule, BasicRippleContainer],
});
fixture = TestBed.createComponent(BasicRippleContainer);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
rippleDirective = fixture.componentInstance.ripple;
});
it('should set the animation durations to zero', () => {
expect(rippleDirective.rippleConfig.animation!.enterDuration).toBe(0);
expect(rippleDirective.rippleConfig.animation!.exitDuration).toBe(0);
});
}); | {
"end_byte": 22547,
"start_byte": 18015,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_22551_31494 | describe('configuring behavior', () => {
let controller: RippleContainerWithInputBindings;
beforeEach(() => {
fixture = TestBed.createComponent(RippleContainerWithInputBindings);
fixture.detectChanges();
controller = fixture.debugElement.componentInstance;
rippleTarget = fixture.debugElement.nativeElement.querySelector('.mat-ripple');
});
it('sets ripple color', () => {
const backgroundColor = 'rgba(12, 34, 56, 0.8)';
controller.color = backgroundColor;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
let ripple = rippleTarget.querySelector('.mat-ripple-element')!;
expect(window.getComputedStyle(ripple).backgroundColor).toBe(backgroundColor);
});
it('does not respond to events when disabled input is set', () => {
controller.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
controller.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('fades out non-persistent ripples when disabled input is set', () => {
dispatchMouseEvent(rippleTarget, 'mousedown');
controller.ripple.launch(0, 0, {persistent: true});
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(2);
spyOn(controller.ripple, 'fadeOutAllNonPersistent').and.callThrough();
controller.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(controller.ripple.fadeOutAllNonPersistent).toHaveBeenCalled();
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('allows specifying custom trigger element', () => {
let alternateTrigger = fixture.debugElement.nativeElement.querySelector(
'.alternateTrigger',
) as HTMLElement;
dispatchMouseEvent(alternateTrigger, 'mousedown');
dispatchMouseEvent(alternateTrigger, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
// Set the trigger element, and now events should create ripples.
controller.trigger = alternateTrigger;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(alternateTrigger, 'mousedown');
dispatchMouseEvent(alternateTrigger, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('expands ripple from center if centered input is set', () => {
controller.centered = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let elementRect = rippleTarget.getBoundingClientRect();
// Click the ripple element 50 px to the right and 75px down from its upper left.
dispatchMouseEvent(rippleTarget, 'mousedown', 50, 75);
dispatchMouseEvent(rippleTarget, 'mouseup');
// Because the centered input is true, the center of the ripple should be the midpoint of the
// bounding rect. The ripple should expand to cover the rect corners, which are 150px
// horizontally and 100px vertically from the midpoint.
let expectedRadius = Math.sqrt(150 * 150 + 100 * 100);
let expectedLeft = elementRect.left + elementRect.width / 2 - expectedRadius;
let expectedTop = elementRect.top + elementRect.height / 2 - expectedRadius;
let ripple = rippleTarget.querySelector('.mat-ripple-element') as HTMLElement;
expect(pxStringToFloat(ripple.style.left)).toBeCloseTo(expectedLeft, 1);
expect(pxStringToFloat(ripple.style.top)).toBeCloseTo(expectedTop, 1);
expect(pxStringToFloat(ripple.style.width)).toBeCloseTo(2 * expectedRadius, 1);
expect(pxStringToFloat(ripple.style.height)).toBeCloseTo(2 * expectedRadius, 1);
});
it('uses custom radius if set', () => {
let customRadius = 42;
controller.radius = customRadius;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let elementRect = rippleTarget.getBoundingClientRect();
// Click the ripple element 50 px to the right and 75px down from its upper left.
dispatchMouseEvent(rippleTarget, 'mousedown', 50, 75);
dispatchMouseEvent(rippleTarget, 'mouseup');
let expectedLeft = elementRect.left + 50 - customRadius;
let expectedTop = elementRect.top + 75 - customRadius;
let ripple = rippleTarget.querySelector('.mat-ripple-element') as HTMLElement;
expect(pxStringToFloat(ripple.style.left)).toBeCloseTo(expectedLeft, 1);
expect(pxStringToFloat(ripple.style.top)).toBeCloseTo(expectedTop, 1);
expect(pxStringToFloat(ripple.style.width)).toBeCloseTo(2 * customRadius, 1);
expect(pxStringToFloat(ripple.style.height)).toBeCloseTo(2 * customRadius, 1);
});
it('should be able to specify animation config through binding', () => {
controller.animationConfig = {enterDuration: 120, exitDuration: 150};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
const rippleElement = rippleTarget.querySelector('.mat-ripple-element')! as HTMLElement;
expect(rippleElement.style.transitionDuration).toBe('120ms');
flushTransition();
expect(rippleElement.style.transitionDuration).toBe('150ms');
flushTransition();
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
});
describe('edge cases', () => {
it('should handle forcibly disabled animations through CSS `transition: none`', async () => {
fixture = TestBed.createComponent(RippleCssTransitionNone);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
dispatchMouseEvent(rippleTarget, 'mousedown');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should handle forcibly disabled animations through CSS `transition-duration: 0ms`', async () => {
fixture = TestBed.createComponent(RippleCssTransitionDurationZero);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
dispatchMouseEvent(rippleTarget, 'mousedown');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(1);
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(rippleTarget.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it('should destroy the ripple if the transition is being canceled due to DOM removal', async () => {
fixture = TestBed.createComponent(RippleWithDomRemovalOnClick);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
dispatchMouseEvent(rippleTarget, 'click');
const fadingRipple = rippleTarget.querySelector('.mat-ripple-element');
expect(fadingRipple).not.toBe(null);
// The ripple animation is still on-going but the element is now removed from DOM as
// part of the change detecton (given `show` being set to `false` on click)
fixture.detectChanges();
// The `transitioncancel` event is emitted when a CSS transition is canceled due
// to e.g. DOM removal. More details in the CSS transitions spec:
// https://www.w3.org/TR/css-transitions-1/#:~:text=no%20longer%20in%20the%20document.
dispatchFakeEvent(fadingRipple!, 'transitioncancel');
// There should be no ripple element anymore because the fading-in ripple from
// before had its animation canceled due the DOM removal.
expect(rippleTarget.querySelector('.mat-ripple-element')).toBeNull();
});
});
});
@Component({
template: `
<div id="container" #ripple="matRipple" matRipple
style="position: relative; width:300px; height:200px;">
</div>
`,
standalone: true,
imports: [MatRippleModule],
})
class BasicRippleContainer {
@ViewChild('ripple') ripple: MatRipple;
} | {
"end_byte": 31494,
"start_byte": 22551,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple.spec.ts_31496_33325 | @Component({
template: `
<div id="container" style="position: relative; width:300px; height:200px;"
matRipple
[matRippleTrigger]="trigger"
[matRippleCentered]="centered"
[matRippleRadius]="radius"
[matRippleDisabled]="disabled"
[matRippleAnimation]="animationConfig"
[matRippleColor]="color">
</div>
<div class="alternateTrigger"></div>
`,
standalone: true,
imports: [MatRippleModule],
})
class RippleContainerWithInputBindings {
animationConfig: RippleAnimationConfig;
trigger: HTMLElement;
centered = false;
disabled = false;
radius = 0;
color = '';
@ViewChild(MatRipple) ripple: MatRipple;
}
@Component({
template: `<div id="container" #ripple="matRipple" matRipple></div>`,
standalone: true,
imports: [MatRippleModule],
})
class RippleContainerWithoutBindings {}
@Component({
template: `@if (!isDestroyed) {<div id="container" matRipple></div>}`,
standalone: true,
imports: [MatRippleModule],
})
class RippleContainerWithNgIf {
@ViewChild(MatRipple) ripple: MatRipple;
isDestroyed = false;
}
@Component({
styles: `* { transition: none !important; }`,
template: `<div id="container" matRipple></div>`,
encapsulation: ViewEncapsulation.None,
standalone: true,
imports: [MatRippleModule],
})
class RippleCssTransitionNone {}
@Component({
styles: `* { transition-duration: 0ms !important; }`,
template: `<div id="container" matRipple></div>`,
encapsulation: ViewEncapsulation.None,
standalone: true,
imports: [MatRippleModule],
})
class RippleCssTransitionDurationZero {}
@Component({
template: `
@if (show) {
<div (click)="show = false" matRipple>Click to remove this element.</div>
}
`,
standalone: true,
imports: [MatRippleModule],
})
class RippleWithDomRemovalOnClick {
show = true;
} | {
"end_byte": 33325,
"start_byte": 31496,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.spec.ts"
} |
components/src/material/core/ripple/ripple-structure.scss_0_42 | @use './ripple';
@include ripple.ripple;
| {
"end_byte": 42,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-structure.scss"
} |
components/src/material/core/ripple/ripple.md_0_5842 | Connect user input to screen reactions by using ripples to both indicate the point of touch, and to
confirm that touch input was received. For touch or mouse, this occurs at the point of contact.
The `matRipple` attribute directive defines an area in which a ripple animates on user interaction.
```html
<div matRipple [matRippleColor]="myColor">
<ng-content></ng-content>
</div>
```
By default, a ripple is activated when the host element of the `matRipple` directive receives
mouse or touch events. Upon being pressed, a ripple will begin fading in from the point of contact,
radiating to cover the host element. Each ripple will fade out only upon release of the mouse or touch.
Ripples can also be triggered programmatically by getting a reference to the MatRipple directive
and calling its `launch` method.
### Ripple trigger
By default ripples will fade in on interaction with the directive's host element.
In some situations, developers may want to show ripples on interaction with *some other* element,
but still want to have the ripples placed in another location. This can be done by specifying
the `matRippleTrigger` option that expects a reference to an `HTMLElement`.
```html
<div>
<div matRipple [matRippleTrigger]="trigger" class="my-ripple-container">
<!-- This is the ripple container, but not the trigger element for ripples. -->
</div>
<div #trigger></div>
</div>
```
### Manual ripples
Ripples can be shown programmatically by getting a reference to the `MatRipple` directive.
```ts
class MyComponent {
/** Reference to the directive instance of the ripple. */
@ViewChild(MatRipple) ripple: MatRipple;
/** Shows a centered and persistent ripple. */
launchRipple() {
const rippleRef = this.ripple.launch({
persistent: true,
centered: true
});
// Fade out the ripple later.
rippleRef.fadeOut();
}
}
```
In the example above, no specific coordinates have been passed, because the `centered`
ripple option has been set to `true` and the coordinates would not matter.
Ripples that are being dispatched programmatically can be launched with the `persistent` option.
This means that the ripples will not fade out automatically, and need to be faded out using
the `RippleRef` (*useful for focus indicators*).
In case, developers want to launch ripples at specific coordinates within the element, the
`launch()` method also accepts `x` and `y` coordinates as parameters. Those coordinates
are relative to the ripple container element.
```ts
const rippleRef = this.ripple.launch(10, 10, {persistent: true});
```
### Global options
Developers are able to specify options for all ripples inside of their application.
The speed of the ripples can be adjusted and the ripples can be disabled globally as well.
Global ripple options can be specified by setting the `MAT_RIPPLE_GLOBAL_OPTIONS` provider.
```ts
const globalRippleConfig: RippleGlobalOptions = {
disabled: true,
animation: {
enterDuration: 300,
exitDuration: 0
}
};
@NgModule({
providers: [
{provide: MAT_RIPPLE_GLOBAL_OPTIONS, useValue: globalRippleConfig}
]
})
```
All available global options can be seen in the `RippleGlobalOptions` interface.
### Disabling animation
The animation of ripples can be disabled by using the `animation` global option. If the
`enterDuration` and `exitDuration` is being set to `0`, ripples will just appear without any
animation.
This is specifically useful in combination with the `disabled` global option, because globally
disabling ripples won't affect the focus indicator ripples. If someone still wants to disable
those ripples for performance reasons, the duration can be set to `0`, to remove the ripple feel.
```ts
const globalRippleConfig: RippleGlobalOptions = {
disabled: true,
animation: {
enterDuration: 0,
exitDuration: 0
}
};
```
**Note**: Ripples will also have no animation if the `NoopAnimationsModule` is being used. This
also means that the durations in the `animation` configuration won't be taken into account.
### Animation behavior
There are two different animation behaviors for the fade-out of ripples shown in the Material
Design specifications.
By default, all ripples will start fading out if the mouse or touch is released and the enter
animation completed. The second possible behavior, which is also shown in the specifications, is
that ripples start to fade out immediately on mouse or touch release.
In some scenarios, developers might prefer that behavior over the default and would like to have
the same for Angular Material. This behavior can be activated by specifying the
`terminateOnPointerUp` global ripple option.
```ts
const globalRippleConfig: RippleGlobalOptions = {
terminateOnPointerUp: true
};
```
### Updating global options at runtime
To change global ripple options at runtime, just inject the `MAT_RIPPLE_GLOBAL_OPTIONS`
provider and update the desired options.
There are various ways of injecting the global options. In order to make it easier to
inject and update options at runtime, it's recommended to create a service that implements
the `RippleGlobalOptions` interface.
```ts
@Injectable({providedIn: 'root'})
export class AppGlobalRippleOptions implements RippleGlobalOptions {
/** Whether ripples should be disabled globally. */
disabled: boolean = false;
}
```
```ts
@NgModule({
providers: [
{provide: MAT_RIPPLE_GLOBAL_OPTIONS, useExisting: AppGlobalRippleOptions},
]
})
export class MyModule {...}
```
Now that the global ripple options are set to a service we can inject, the service can be
used update any global ripple option at runtime.
```ts
@Component(...)
export class MyComponent {
constructor(private _appRippleOptions: AppGlobalRippleOptions) {}
disableRipples() {
this._appRippleOptions.disabled = true;
}
}
```
| {
"end_byte": 5842,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.md"
} |
components/src/material/core/ripple/ripple.zone.spec.ts_0_1753 | import {dispatchMouseEvent} from '@angular/cdk/testing/private';
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatRippleModule} from '.';
import {MatRipple} from './ripple';
describe('MatRipple Zone.js integration', () => {
let fixture: ComponentFixture<any>;
let rippleTarget: HTMLElement;
let originalBodyMargin: string | null;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatRippleModule, BasicRippleContainer],
});
});
beforeEach(() => {
// Set body margin to 0 during tests so it doesn't mess up position calculations.
originalBodyMargin = document.body.style.margin;
document.body.style.margin = '0';
});
afterEach(() => {
document.body.style.margin = originalBodyMargin!;
});
describe('basic ripple', () => {
beforeEach(() => {
fixture = TestBed.createComponent(BasicRippleContainer);
fixture.detectChanges();
rippleTarget = fixture.nativeElement.querySelector('.mat-ripple');
});
it('does not run events inside the NgZone', () => {
const spy = jasmine.createSpy('zone unstable callback');
const subscription = fixture.ngZone!.onUnstable.subscribe(spy);
dispatchMouseEvent(rippleTarget, 'mousedown');
dispatchMouseEvent(rippleTarget, 'mouseup');
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
});
});
@Component({
template: `
<div id="container" #ripple="matRipple" matRipple
style="position: relative; width:300px; height:200px;">
</div>
`,
standalone: true,
imports: [MatRippleModule],
})
class BasicRippleContainer {
@ViewChild('ripple') ripple: MatRipple;
}
| {
"end_byte": 1753,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple.zone.spec.ts"
} |
components/src/material/core/ripple/_ripple.scss_0_2088 | @use '@angular/cdk';
@use '../tokens/m2/mat/ripple' as tokens-mat-ripple;
@use '../tokens/token-utils';
@mixin ripple() {
// The host element of an mat-ripple directive should always have a position of "absolute" or
// "relative" so that the ripples inside are correctly positioned relatively to the container.
.mat-ripple {
overflow: hidden;
// By default, every ripple container should have position: relative in favor of creating an
// easy API for developers using the MatRipple directive.
position: relative;
// Promote containers that have ripples to a new layer. We want to target `:not(:empty)`,
// because we don't want all ripple containers to have their own layer since they're used in a
// lot of places and the layer is only relevant while animating. Note that ideally we'd use
// the `contain` property here (see #13175), because `:empty` can be broken by having extra
// text inside the element, but it isn't very well supported yet.
&: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);
// 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).
transform: scale3d(0, 0, 0);
@include token-utils.use-tokens(
tokens-mat-ripple.$prefix, tokens-mat-ripple.get-token-slots()) {
// We have to emit a fallback value here, because some internal builds depend on it.
background-color: token-utils.get-token-variable(color, $fallback: rgba(#000, 0.1));
}
// In high contrast mode the ripple is opaque, causing it to obstruct the content.
@include cdk.high-contrast {
display: none;
}
// Hide ripples inside cloned drag&drop elements since they won't go away.
.cdk-drag-preview &,
.cdk-drag-placeholder & {
display: none;
}
}
}
| {
"end_byte": 2088,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/_ripple.scss"
} |
components/src/material/core/ripple/ripple-event-manager.ts_0_2484 | /**
* @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.dev/license
*/
import {normalizePassiveListenerOptions, _getEventTarget} from '@angular/cdk/platform';
import {NgZone} from '@angular/core';
/** Options used to bind a passive capturing event. */
const passiveCapturingEventOptions = normalizePassiveListenerOptions({
passive: true,
capture: true,
});
/** Manages events through delegation so that as few event handlers as possible are bound. */
export class RippleEventManager {
private _events = new Map<string, Map<HTMLElement, Set<EventListenerObject>>>();
/** Adds an event handler. */
addHandler(ngZone: NgZone, name: string, element: HTMLElement, handler: EventListenerObject) {
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);
});
}
}
/** Removes an event handler. */
removeHandler(name: string, element: HTMLElement, handler: EventListenerObject) {
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);
}
}
/** Event handler that is bound and which dispatches the events to the different targets. */
private _delegateEventHandler = (event: Event) => {
const target = _getEventTarget(event);
if (target) {
this._events.get(event.type)?.forEach((handlers, element) => {
if (element === target || element.contains(target as Node)) {
handlers.forEach(handler => handler.handleEvent(event));
}
});
}
};
}
| {
"end_byte": 2484,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-event-manager.ts"
} |
components/src/material/core/ripple/ripple-ref.ts_0_1585 | /**
* @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.dev/license
*/
/** Possible states for a ripple element. */
export enum RippleState {
FADING_IN,
VISIBLE,
FADING_OUT,
HIDDEN,
}
export type RippleConfig = {
color?: string;
centered?: boolean;
radius?: number;
persistent?: boolean;
animation?: RippleAnimationConfig;
terminateOnPointerUp?: boolean;
};
/**
* Interface that describes the configuration for the animation of a ripple.
* There are two animation phases with different durations for the ripples.
*/
export interface RippleAnimationConfig {
/** Duration in milliseconds for the enter animation (expansion from point of contact). */
enterDuration?: number;
/** Duration in milliseconds for the exit animation (fade-out). */
exitDuration?: number;
}
/**
* Reference to a previously launched ripple element.
*/
export class RippleRef {
/** Current state of the ripple. */
state: RippleState = RippleState.HIDDEN;
constructor(
private _renderer: {fadeOutRipple(ref: RippleRef): void},
/** Reference to the ripple HTML element. */
public element: HTMLElement,
/** Ripple configuration used for the ripple. */
public config: RippleConfig,
/* Whether animations are forcibly disabled for ripples through CSS. */
public _animationForciblyDisabledThroughCss = false,
) {}
/** Fades out the ripple element. */
fadeOut() {
this._renderer.fadeOutRipple(this);
}
}
| {
"end_byte": 1585,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-ref.ts"
} |
components/src/material/core/ripple/index.ts_0_628 | /**
* @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.dev/license
*/
import {NgModule} from '@angular/core';
import {MatCommonModule} from '../common-behaviors/common-module';
import {MatRipple} from './ripple';
export * from './ripple';
export * from './ripple-ref';
export {RippleRenderer, RippleTarget, defaultRippleAnimationConfig} from './ripple-renderer';
@NgModule({
imports: [MatCommonModule, MatRipple],
exports: [MatRipple, MatCommonModule],
})
export class MatRippleModule {}
| {
"end_byte": 628,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/index.ts"
} |
components/src/material/core/ripple/ripple-renderer.ts_0_2802 | /**
* @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.dev/license
*/
import {
ElementRef,
NgZone,
Component,
ChangeDetectionStrategy,
ViewEncapsulation,
Injector,
} from '@angular/core';
import {Platform, normalizePassiveListenerOptions, _getEventTarget} from '@angular/cdk/platform';
import {isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader} from '@angular/cdk/a11y';
import {coerceElement} from '@angular/cdk/coercion';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {RippleRef, RippleState, RippleConfig} from './ripple-ref';
import {RippleEventManager} from './ripple-event-manager';
/**
* Interface that describes the target for launching ripples.
* It defines the ripple configuration and disabled state for interaction ripples.
* @docs-private
*/
export interface RippleTarget {
/** Configuration for ripples that are launched on pointer down. */
rippleConfig: RippleConfig;
/** Whether ripples on pointer down should be disabled. */
rippleDisabled: boolean;
}
/** Interfaces the defines ripple element transition event listeners. */
interface RippleEventListeners {
onTransitionEnd: EventListener;
onTransitionCancel: EventListener;
fallbackTimer: ReturnType<typeof setTimeout> | null;
}
/**
* Default ripple animation configuration for ripples without an explicit
* animation config specified.
*/
export 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'];
@Component({
template: '',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
styleUrl: 'ripple-structure.css',
host: {'mat-ripple-style-loader': ''},
})
export class _MatRippleStylesLoader {}
/**
* 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
*/ | {
"end_byte": 2802,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-renderer.ts"
} |
components/src/material/core/ripple/ripple-renderer.ts_2803_10795 | export class RippleRenderer implements EventListenerObject {
/** Element where the ripples are being added to. */
private _containerElement: HTMLElement;
/** Element which triggers the ripple elements on mouse events. */
private _triggerElement: HTMLElement | null;
/** Whether the pointer is currently down or not. */
private _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).
*/
private _activeRipples = new Map<RippleRef, RippleEventListeners | null>();
/** Latest non-persistent ripple that was triggered. */
private _mostRecentTransientRipple: RippleRef | null;
/** Time in milliseconds when the last touchstart event happened. */
private _lastTouchStartEvent: number;
/** Whether pointer-up event listeners have been registered. */
private _pointerUpEventsRegistered = false;
/**
* Cached dimensions of the ripple container. Set when the first
* ripple is shown and cleared once no more ripples are visible.
*/
private _containerRect: DOMRect | null;
private static _eventManager = new RippleEventManager();
constructor(
private _target: RippleTarget,
private _ngZone: NgZone,
elementOrElementRef: HTMLElement | ElementRef<HTMLElement>,
private _platform: Platform,
injector?: Injector,
) {
// 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: number, y: number, config: RippleConfig = {}): RippleRef {
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: RippleEventListeners | null = 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. */ | {
"end_byte": 10795,
"start_byte": 2803,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-renderer.ts"
} |
components/src/material/core/ripple/ripple-renderer.ts_10798_19485 | fadeOutRipple(rippleRef: 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: HTMLElement | ElementRef<HTMLElement>) {
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();
this._triggerElement = element;
// Use event delegation for the trigger events since they're
// set up during creation and are performance-sensitive.
pointerDownEvents.forEach(type => {
RippleRenderer._eventManager.addHandler(this._ngZone, type, element, this);
});
}
/**
* Handles all registered events.
* @docs-private
*/
handleEvent(event: Event) {
if (event.type === 'mousedown') {
this._onMousedown(event as MouseEvent);
} else if (event.type === 'touchstart') {
this._onTouchStart(event as TouchEvent);
} else {
this._onPointerUp();
}
// If pointer-up events haven't been registered yet, do so now.
// We do this on-demand in order to reduce the total number of event listeners
// registered by the ripples, which speeds up the rendering time for large UIs.
if (!this._pointerUpEventsRegistered) {
// The events for hiding the ripple are bound directly on the trigger, because:
// 1. Some of them occur frequently (e.g. `mouseleave`) and any advantage we get from
// delegation will be diminished by having to look through all the data structures often.
// 2. They aren't as performance-sensitive, because they're bound only after the user
// has interacted with an element.
this._ngZone.runOutsideAngular(() => {
pointerUpEvents.forEach(type => {
this._triggerElement!.addEventListener(type, this, passiveCapturingEventOptions);
});
});
this._pointerUpEventsRegistered = true;
}
}
/** Method that will be called if the fade-in or fade-in transition completed. */
private _finishRippleTransition(rippleRef: RippleRef) {
if (rippleRef.state === RippleState.FADING_IN) {
this._startFadeOutTransition(rippleRef);
} else if (rippleRef.state === RippleState.FADING_OUT) {
this._destroyRipple(rippleRef);
}
}
/**
* Starts the fade-out transition of the given ripple if it's not persistent and the pointer
* is not held down anymore.
*/
private _startFadeOutTransition(rippleRef: RippleRef) {
const isMostRecentTransientRipple = rippleRef === this._mostRecentTransientRipple;
const {persistent} = rippleRef.config;
rippleRef.state = RippleState.VISIBLE;
// When the timer runs out while the user has kept their pointer down, we want to
// keep only the persistent ripples and the latest transient ripple. We do this,
// because we don't want stacked transient ripples to appear after their enter
// animation has finished.
if (!persistent && (!isMostRecentTransientRipple || !this._isPointerDown)) {
rippleRef.fadeOut();
}
}
/** Destroys the given ripple by removing it from the DOM and updating its state. */
private _destroyRipple(rippleRef: RippleRef) {
const eventListeners = this._activeRipples.get(rippleRef) ?? null;
this._activeRipples.delete(rippleRef);
// Clear out the cached bounding rect if we have no more ripples.
if (!this._activeRipples.size) {
this._containerRect = null;
}
// If the current ref is the most recent transient ripple, unset it
// avoid memory leaks.
if (rippleRef === this._mostRecentTransientRipple) {
this._mostRecentTransientRipple = null;
}
rippleRef.state = RippleState.HIDDEN;
if (eventListeners !== null) {
rippleRef.element.removeEventListener('transitionend', eventListeners.onTransitionEnd);
rippleRef.element.removeEventListener('transitioncancel', eventListeners.onTransitionCancel);
if (eventListeners.fallbackTimer !== null) {
clearTimeout(eventListeners.fallbackTimer);
}
}
rippleRef.element.remove();
}
/** Function being called whenever the trigger is being pressed using mouse. */
private _onMousedown(event: MouseEvent) {
// Screen readers will fire fake mouse events for space/enter. Skip launching a
// ripple in this case for consistency with the non-screen-reader experience.
const isFakeMousedown = isFakeMousedownFromScreenReader(event);
const isSyntheticEvent =
this._lastTouchStartEvent &&
Date.now() < this._lastTouchStartEvent + ignoreMouseEventsTimeout;
if (!this._target.rippleDisabled && !isFakeMousedown && !isSyntheticEvent) {
this._isPointerDown = true;
this.fadeInRipple(event.clientX, event.clientY, this._target.rippleConfig);
}
}
/** Function being called whenever the trigger is being pressed using touch. */
private _onTouchStart(event: TouchEvent) {
if (!this._target.rippleDisabled && !isFakeTouchstartFromScreenReader(event)) {
// 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;
// Use `changedTouches` so we skip any touches where the user put
// their finger down, but used another finger to tap the element again.
const touches = event.changedTouches as TouchList | undefined;
// According to the typings the touches should always be defined, but in some cases
// the browser appears to not assign them in tests which leads to flakes.
if (touches) {
for (let i = 0; i < touches.length; i++) {
this.fadeInRipple(touches[i].clientX, touches[i].clientY, this._target.rippleConfig);
}
}
}
}
/** Function being called whenever the trigger is being released. */
private _onPointerUp() {
if (!this._isPointerDown) {
return;
}
this._isPointerDown = false;
// Fade-out all ripples that are visible and not persistent.
this._getActiveRipples().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 isVisible =
ripple.state === RippleState.VISIBLE ||
(ripple.config.terminateOnPointerUp && ripple.state === RippleState.FADING_IN);
if (!ripple.config.persistent && isVisible) {
ripple.fadeOut();
}
});
}
private _getActiveRipples(): RippleRef[] {
return Array.from(this._activeRipples.keys());
}
/** Removes previously registered event listeners from the trigger element. */
_removeTriggerEvents() {
const trigger = this._triggerElement;
if (trigger) {
pointerDownEvents.forEach(type =>
RippleRenderer._eventManager.removeHandler(type, trigger, this),
);
if (this._pointerUpEventsRegistered) {
pointerUpEvents.forEach(type =>
trigger.removeEventListener(type, this, passiveCapturingEventOptions),
);
this._pointerUpEventsRegistered = false;
}
}
}
} | {
"end_byte": 19485,
"start_byte": 10798,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-renderer.ts"
} |
components/src/material/core/ripple/ripple-renderer.ts_19487_19859 | /**
* Returns the distance from the point (x, y) to the furthest corner of a rectangle.
*/
function distanceToFurthestCorner(x: number, y: number, rect: DOMRect) {
const distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right));
const distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom));
return Math.sqrt(distX * distX + distY * distY);
} | {
"end_byte": 19859,
"start_byte": 19487,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/ripple-renderer.ts"
} |
components/src/material/core/ripple/_ripple-theme.scss_0_2792 | @use 'sass:map';
@use '../tokens/m2/mat/ripple' as tokens-mat-ripple;
@use '../tokens/token-utils';
@use '../style/sass-utils';
@use '../theming/theming';
@use '../theming/inspection';
@use '../theming/validation';
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-ripple.$prefix,
tokens-mat-ripple.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-ripple.$prefix,
tokens-mat-ripple.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-ripple.$prefix,
tokens-mat-ripple.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-ripple.$prefix,
tokens: tokens-mat-ripple.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-ripple') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-ripple.$prefix,
map.get($tokens, tokens-mat-ripple.$prefix)
);
}
}
| {
"end_byte": 2792,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/ripple/_ripple-theme.scss"
} |
components/src/material/core/style/_layout-common.scss_0_178 | // This mixin ensures an element spans to fill the nearest ancestor with defined positioning.
@mixin fill {
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
}
| {
"end_byte": 178,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_layout-common.scss"
} |
components/src/material/core/style/_variables.scss_0_1700 | // Media queries
// TODO(josephperrott): Change $mat-xsmall and $mat-small usages to rely on BreakpointObserver,
$xsmall: 'max-width: 599px';
$small: 'max-width: 959px';
// TODO: Revisit all z-indices before beta
// z-index main list
$z-index-fab: 20 !default;
$z-index-drawer: 100 !default;
// Global constants
$pi: 3.14159265;
// Padding between input toggles and their labels
$toggle-padding: 8px !default;
// Width and height of input toggles
$toggle-size: 20px !default;
// Easing Curves
// TODO(jelbourn): all of these need to be revisited
// The default animation curves used by material design.
$linear-out-slow-in-timing-function: cubic-bezier(0, 0, 0.2, 0.1) !default;
$fast-out-slow-in-timing-function: cubic-bezier(0.4, 0, 0.2, 1) !default;
$fast-out-linear-in-timing-function: cubic-bezier(0.4, 0, 1, 1) !default;
$ease-in-out-curve-function: cubic-bezier(0.35, 0, 0.25, 1) !default;
$swift-ease-out-duration: 400ms !default;
$swift-ease-out-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1) !default;
$swift-ease-out: all $swift-ease-out-duration $swift-ease-out-timing-function !default;
$swift-ease-in-duration: 300ms !default;
$swift-ease-in-timing-function: cubic-bezier(0.55, 0, 0.55, 0.2) !default;
$swift-ease-in: all $swift-ease-in-duration $swift-ease-in-timing-function !default;
$swift-ease-in-out-duration: 500ms !default;
$swift-ease-in-out-timing-function: $ease-in-out-curve-function !default;
$swift-ease-in-out: all $swift-ease-in-out-duration $swift-ease-in-out-timing-function !default;
$swift-linear-duration: 80ms !default;
$swift-linear-timing-function: linear !default;
$swift-linear: all $swift-linear-duration $swift-linear-timing-function !default;
| {
"end_byte": 1700,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_variables.scss"
} |
components/src/material/core/style/_form-common.scss_0_918 | @use '../theming/inspection';
@use './sass-utils';
// Renders a gradient for showing the dashed line when the input is disabled.
// Unlike using a border, a gradient allows us to adjust the spacing of the dotted line
// to match the Material Design spec.
@mixin private-control-disabled-underline($color) {
background-image: linear-gradient(to right, $color 0%, $color 33%, transparent 0%);
background-size: 4px 100%;
background-repeat: repeat-x;
}
// Figures out the color of the placeholder for a form control.
// Used primarily to prevent the various form controls from
// becoming out of sync since these colors aren't in a palette.
@function private-control-placeholder-color($theme) {
$is-dark-theme: inspection.get-theme-type($theme) == dark;
@return sass-utils.safe-color-change(
inspection.get-theme-color($theme, foreground, secondary-text),
$alpha: if($is-dark-theme, 0.5, 0.42));
}
| {
"end_byte": 918,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_form-common.scss"
} |
components/src/material/core/style/_menu-common.scss_0_2216 | @use '@angular/cdk';
@use './list-common';
@use './layout-common';
// The mixins below are shared between mat-menu and mat-select
// menu width must be a multiple of 56px
$overlay-min-width: 112px !default; // 56 * 2
$overlay-max-width: 280px !default; // 56 * 5
$item-height: 48px !default;
$side-padding: 16px !default;
$icon-margin: 16px !default;
@mixin base() {
min-width: $overlay-min-width;
max-width: $overlay-max-width;
overflow: auto;
-webkit-overflow-scrolling: touch; // for momentum scroll on mobile
}
@mixin item-base() {
@include list-common.truncate-line();
// Needs to be a block for the ellipsis to work.
display: block;
line-height: $item-height;
height: $item-height;
padding: 0 $side-padding;
text-align: left;
text-decoration: none; // necessary to reset anchor tags
// Required for Edge not to show scrollbars when setting the width manually. See #12112.
max-width: 100%;
&[disabled] {
cursor: default;
}
[dir='rtl'] & {
text-align: right;
}
.mat-icon {
margin-right: $icon-margin;
vertical-align: middle;
svg {
vertical-align: top;
}
[dir='rtl'] & {
margin-left: $icon-margin;
margin-right: 0;
}
}
}
@mixin item-submenu-icon($item-spacing, $icon-size) {
width: $icon-size;
height: 10px;
fill: currentColor;
// We use `padding` here, because the margin can collapse depending on the other content.
padding-left: $item-spacing;
[dir='rtl'] & {
padding-right: $item-spacing;
padding-left: 0;
// Invert the arrow direction.
polygon {
transform: scaleX(-1);
transform-origin: center;
}
}
// Fix for Chromium-based browsers blending in the `currentColor` with the background.
@include cdk.high-contrast {
fill: CanvasText;
}
}
@mixin item-ripple() {
@include layout-common.fill;
// Prevent any pointer events on the ripple container for a menu item. The ripple container is
// not the trigger element for the ripples and can be therefore disabled like that. Disabling
// the pointer events ensures that there is no `click` event that can bubble up and cause
// the menu panel to close.
pointer-events: none;
}
| {
"end_byte": 2216,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_menu-common.scss"
} |
components/src/material/core/style/_sass-utils.scss_0_4141 | @use 'sass:color';
@use 'sass:string';
@use 'sass:list';
@use 'sass:map';
@use 'sass:meta';
/// Whether our theming API is using --sys- variables for color tokens.
$use-system-color-variables: false;
/// Whether our theming API is using --sys- variables for typography tokens.
$use-system-typography-variables: false;
/// Include content under the current selector (&) or the document root if there is no current
/// selector.
/// @param {String} $root [html] The default root selector to use when there is no current selector.
/// @output The given content under the current selector, or root selector if there is no current
/// selector.
/// @content Content to output under the current selector, or root selector if there is no current
/// selector.
@mixin current-selector-or-root($root: html) {
@if & {
@content;
}
@else {
#{$root} {
@content;
}
}
}
/// A version of the standard `map.merge` function that takes a variable number of arguments.
/// Each argument is merged into the final result from left to right.
/// @param {List} $maps The maps to combine with map.merge
/// @return {Map} The combined result of successively calling map.merge with each parameter.
@function merge-all($maps...) {
$result: ();
@each $map in $maps {
$result: map.merge($result, $map);
}
@return $result;
}
/// A version of the standard `map.deep-merge` function that takes a variable number of arguments.
/// Each argument is deep-merged into the final result from left to right.
/// @param {List} $maps The maps to combine with map.deep-merge
/// @return {Map} The combined result of successively calling map.deep-merge with each parameter.
@function deep-merge-all($maps...) {
$result: ();
@each $map in $maps {
$result: map.deep-merge($result, $map);
}
@return $result;
}
/// Coerces the given value to a list, by converting any non-list value into a single-item list.
/// This should be used when dealing with user-passed lists of args to avoid confusing errors,
/// since Sass treats `($x)` as equivalent to `$x`.
/// @param {Any} $value The value to coerce to a list.
/// @return {List} The original $value if it was a list, otherwise a single-item list containing
/// $value.
@function coerce-to-list($value) {
@return if(meta.type-of($value) != 'list', ($value,), $value);
}
/// A version of the Sass `color.change` function that is safe ot use with CSS variables.
@function safe-color-change($color, $args...) {
$args: meta.keywords($args);
$use-color-mix: $use-system-color-variables or
(is-css-var-name($color) and string.index($color, '--mat') == 1);
@if (meta.type-of($color) == 'color') {
@return color.change($color, $args...);
}
@else if ($color != null and
map.get($args, alpha) != null and $use-color-mix) {
$opacity: map.get($args, alpha);
@if meta.type-of($opacity) == number {
$opacity: ($opacity * 100) + '%';
}
@if (is-css-var-name($opacity)) {
$opacity: calc(var($opacity) * 100%);
}
@if (is-css-var-name($color)) {
$color: var($color);
}
@return #{color-mix(in srgb, #{$color} #{$opacity}, transparent)};
}
@return $color;
}
/// Gets the given arguments as a map of keywords and validates that only supported arguments were
/// passed.
/// @param {ArgList} $args The arguments to convert to a keywords map.
/// @param {List} $supported-args The supported argument names.
/// @return {Map} The $args as a map of argument name to argument value.
@function validate-keyword-args($args, $supported-args) {
@if list.length($args) > 0 {
@error #{'Expected keyword args, but got positional args: '}#{$args};
}
$kwargs: meta.keywords($args);
@each $arg, $v in $kwargs {
@if list.index($supported-args, $arg) == null {
@error #{'Unsupported argument '}#{$arg}#{'. Valid arguments are: '}#{$supported-args};
}
}
@return $kwargs;
}
// Returns whether the $value is a CSS variable name based on whether it's a string prefixed
// by "--".
@function is-css-var-name($value) {
@return meta.type-of($value) == string and string.index($value, '--') == 1;
}
| {
"end_byte": 4141,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_sass-utils.scss"
} |
components/src/material/core/style/_checkbox-common.scss_0_349 | // The width/height of the checkbox element.
$size: 18px !default;
// The width/height of the legacy-checkbox element.
$legacy-size: 16px !default;
// The width of the checkbox border shown when the checkbox is unchecked.
$border-width: 2px;
// The base duration used for the majority of transitions for the checkbox.
$transition-duration: 90ms;
| {
"end_byte": 349,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_checkbox-common.scss"
} |
components/src/material/core/style/_vendor-prefixes.scss_0_1052 | // stylelint-disable material/no-prefixes
@mixin user-select($value) {
-webkit-user-select: $value;
user-select: $value;
}
@mixin input-placeholder {
&::placeholder {
@content;
}
&::-moz-placeholder {
@content;
}
&::-webkit-input-placeholder {
@content;
}
// Note: this isn't necessary anymore since we don't support
// IE, but it caused some presubmit failures in #23416.
&:-ms-input-placeholder {
@content;
}
}
@mixin backface-visibility($value) {
-webkit-backface-visibility: $value;
backface-visibility: $value;
}
@mixin color-adjust($value) {
-webkit-print-color-adjust: $value;
color-adjust: $value;
}
@mixin private-background-clip($value) {
-webkit-background-clip: $value;
background-clip: $value;
}
@mixin clip-path($value) {
-webkit-clip-path: $value;
clip-path: $value;
}
@mixin smooth-font {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
@mixin mask-image($value) {
-webkit-mask-image: $value;
mask-image: $value;
}
// stylelint-enable
| {
"end_byte": 1052,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_vendor-prefixes.scss"
} |
components/src/material/core/style/_elevation.scss_0_3721 | @use 'sass:map';
@use 'sass:math';
@use 'sass:meta';
@use 'sass:string';
@use './variables';
@use './sass-utils';
$_umbra-opacity: 0.2;
$_penumbra-opacity: 0.14;
$_ambient-opacity: 0.12;
$_umbra-map: (
0: '0px 0px 0px 0px',
1: '0px 2px 1px -1px',
2: '0px 3px 1px -2px',
3: '0px 3px 3px -2px',
4: '0px 2px 4px -1px',
5: '0px 3px 5px -1px',
6: '0px 3px 5px -1px',
7: '0px 4px 5px -2px',
8: '0px 5px 5px -3px',
9: '0px 5px 6px -3px',
10: '0px 6px 6px -3px',
11: '0px 6px 7px -4px',
12: '0px 7px 8px -4px',
13: '0px 7px 8px -4px',
14: '0px 7px 9px -4px',
15: '0px 8px 9px -5px',
16: '0px 8px 10px -5px',
17: '0px 8px 11px -5px',
18: '0px 9px 11px -5px',
19: '0px 9px 12px -6px',
20: '0px 10px 13px -6px',
21: '0px 10px 13px -6px',
22: '0px 10px 14px -6px',
23: '0px 11px 14px -7px',
24: '0px 11px 15px -7px',
);
$_penumbra-map: (
0: '0px 0px 0px 0px',
1: '0px 1px 1px 0px',
2: '0px 2px 2px 0px',
3: '0px 3px 4px 0px',
4: '0px 4px 5px 0px',
5: '0px 5px 8px 0px',
6: '0px 6px 10px 0px',
7: '0px 7px 10px 1px',
8: '0px 8px 10px 1px',
9: '0px 9px 12px 1px',
10: '0px 10px 14px 1px',
11: '0px 11px 15px 1px',
12: '0px 12px 17px 2px',
13: '0px 13px 19px 2px',
14: '0px 14px 21px 2px',
15: '0px 15px 22px 2px',
16: '0px 16px 24px 2px',
17: '0px 17px 26px 2px',
18: '0px 18px 28px 2px',
19: '0px 19px 29px 2px',
20: '0px 20px 31px 3px',
21: '0px 21px 33px 3px',
22: '0px 22px 35px 3px',
23: '0px 23px 36px 3px',
24: '0px 24px 38px 3px',
);
$_ambient-map: (
0: '0px 0px 0px 0px',
1: '0px 1px 3px 0px',
2: '0px 1px 5px 0px',
3: '0px 1px 8px 0px',
4: '0px 1px 10px 0px',
5: '0px 1px 14px 0px',
6: '0px 1px 18px 0px',
7: '0px 2px 16px 1px',
8: '0px 3px 14px 2px',
9: '0px 3px 16px 2px',
10: '0px 4px 18px 3px',
11: '0px 4px 20px 3px',
12: '0px 5px 22px 4px',
13: '0px 5px 24px 4px',
14: '0px 5px 26px 4px',
15: '0px 6px 28px 5px',
16: '0px 6px 30px 5px',
17: '0px 6px 32px 5px',
18: '0px 7px 34px 6px',
19: '0px 7px 36px 6px',
20: '0px 8px 38px 7px',
21: '0px 8px 40px 7px',
22: '0px 8px 42px 7px',
23: '0px 9px 44px 8px',
24: '0px 9px 46px 8px',
);
// A collection of mixins and CSS classes that can be used to apply elevation to a material
// element.
// See: https://material.io/design/environment/elevation.html
// Examples:
//
//
// .mat-foo {
// @include $mat-elevation(2);
//
// &:active {
// @include $mat-elevation(8);
// }
// }
//
// <div id="external-card" class="mat-elevation-z2"><p>Some content</p></div>
//
// For an explanation of the design behind how elevation is implemented, see the design doc at
// https://docs.google.com/document/d/1W3NGSLqDZzjbBBLW2C6y_6NUxtvdZAVaJvg58LY3Q0E/edit
// The default duration value for elevation transitions.
$transition-duration: 280ms !default;
// The default easing value for elevation transitions.
$transition-timing-function: variables.$fast-out-slow-in-timing-function;
// The default color for elevation shadows.
$color: black !default;
// Prefix for elevation-related selectors.
$prefix: 'mat-elevation-z';
// Applies the correct css rules to an element to give it the elevation specified by $zValue.
// The $zValue must be between 0 and 24.
@mixin elevation($zValue, $color: $color, $opacity: null) {
box-shadow: get-box-shadow($zValue, $color, $opacity);
}
// Applies the elevation to an element in a manner that allows
// consumers to override it via the Material elevation classes.
@mixin overridable-elevation($zValue, $color: $color, $opacity: null) {
&:not([class*='#{$prefix}']) {
@include elevation($zValue, $color, $opacity);
}
}
// Gets the box shadow value for a specific elevation. | {
"end_byte": 3721,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_elevation.scss"
} |
components/src/material/core/style/_elevation.scss_3722_6060 | @function get-box-shadow($zValue, $shadow-color: black, $opacity: null) {
@if $zValue == null {
@return null;
}
@if (sass-utils.is-css-var-name($zValue)) {
@return $zValue;
}
@if meta.type-of($zValue) != number or not math.is-unitless($zValue) {
@error '$zValue must be a unitless number, but received `#{$zValue}`';
}
@if $zValue < 0 or $zValue > 24 {
@error '$zValue must be between 0 and 24, but received `#{$zValue}`';
}
$umbra-z-value: map.get($_umbra-map, $zValue);
$penumbra-z-value: map.get($_penumbra-map, $zValue);
$ambient-z-value: map.get($_ambient-map, $zValue);
$color-opacity: if($opacity != null, $opacity, 1);
$umbra-color: _compute-color-opacity($shadow-color, $_umbra-opacity * $color-opacity);
$penumbra-color: _compute-color-opacity($shadow-color, $_penumbra-opacity * $color-opacity);
$ambient-color: _compute-color-opacity($shadow-color, $_ambient-opacity * $color-opacity);
@return string.unquote('#{$umbra-z-value} #{$umbra-color}, #{$penumbra-z-value} ' +
'#{$penumbra-color}, #{$ambient-z-value} #{$ambient-color}');
}
// Returns a string that can be used as the value for a transition property for elevation.
// Calling this function directly is useful in situations where a component needs to transition
// more than one property.
//
// .foo {
// transition: mat-elevation-transition-property-value(), opacity 100ms ease;
// }
@function private-transition-property-value(
$duration: $transition-duration,
$easing: $transition-timing-function) {
@return box-shadow #{$duration} #{$easing};
}
// Applies the correct css rules needed to have an element transition between elevations.
// This mixin should be applied to elements whose elevation values will change depending on their
// context (e.g. when active or disabled).
//
// NOTE(traviskaufman): Both this mixin and the above function use default parameters so they can
// be used in the same way by clients.
@mixin elevation-transition(
$duration: $transition-duration,
$easing: $transition-timing-function) {
transition: private-transition-property-value($duration, $easing);
}
@function _compute-color-opacity($color, $opacity) {
@if meta.type-of($color) == color and $opacity != null {
@return rgba($color, $opacity);
}
@else {
@return $color;
}
} | {
"end_byte": 6060,
"start_byte": 3722,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_elevation.scss"
} |
components/src/material/core/style/_button-common.scss_0_561 | @use './vendor-prefixes';
// Mixin overriding default button styles like the gray background, the border, and the outline.
@mixin reset {
@include vendor-prefixes.user-select(none);
cursor: pointer;
outline: none;
border: none;
-webkit-tap-highlight-color: transparent;
// The `outline: none` from above works on all browsers, however Firefox also
// adds a special `focus-inner` which we have to disable explicitly. See:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Firefox
&::-moz-focus-inner {
border: 0;
}
}
| {
"end_byte": 561,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_button-common.scss"
} |
components/src/material/core/style/_private.scss_0_1202 | @use './elevation';
@use '../theming/inspection';
@mixin private-theme-elevation($zValue, $theme) {
$elevation-color: inspection.get-theme-color($theme, foreground, elevation);
$elevation-color-or-default: if($elevation-color == null, elevation.$color, $elevation-color);
@include elevation.elevation($zValue, $elevation-color-or-default);
}
@mixin private-theme-overridable-elevation($zValue, $theme) {
$elevation-color: inspection.get-theme-color($theme, foreground, elevation);
$elevation-color-or-default: if($elevation-color == null, elevation.$color, $elevation-color);
@include elevation.overridable-elevation($zValue, $elevation-color-or-default);
}
// If the mat-animation-noop class is present on the components root element,
// prevent non css animations from running.
// NOTE: Currently this mixin should only be used with components that do not
// have any projected content.
@mixin private-animation-noop() {
&._mat-animation-noopable {
// Use !important here since we don't know what context this mixin will
// be included in and MDC can have some really specific selectors.
transition: none !important;
animation: none !important;
@content;
}
}
| {
"end_byte": 1202,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_private.scss"
} |
components/src/material/core/style/_validation.scss_0_1565 | @use 'sass:list';
@use 'sass:meta';
/// Validates that the object's type matches any of the expected types.
/// @param {any} $obj The object to test
/// @param {List} $types The expected types
/// @return {String} null if no error, else the unexpected type.
@function validate-type($obj, $types...) {
$result: meta.type-of($obj);
// A zero-length list is the same as a zero-length map.
@if ($result == list and list.index($types, map) and list.length($obj) == 0) {
@return null;
}
@return if(list.index($types, $result), null, $result);
}
/// Validates that a list contains only values from the allowed list of values.
/// @param {List} $list The list to test
/// @param {List} $allowed The allowed values
/// @return {List} null if no error, else the list of non-allowed values.
@function validate-allowed-values($list, $allowed...) {
$invalid: ();
@each $element in $list {
@if not list.index($allowed, $element) {
$invalid: list.append($invalid, $element);
}
}
@return if(list.length($invalid) > 0, $invalid, null);
}
/// Validates that a list contains all values from the required list of values.
/// @param {List} $list The list to test
/// @param {List} $required The required values
/// @return {List} null if no error, else the list of missing values.
@function validate-required-values($list, $required...) {
$invalid: ();
@each $element in $required {
@if not list.index($list, $element) {
$invalid: list.append($invalid, $element);
}
}
@return if(list.length($invalid) > 0, $invalid, null);
}
| {
"end_byte": 1565,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_validation.scss"
} |
components/src/material/core/style/_list-common.scss_0_1219 | // This mixin will ensure that lines that overflow the container will hide the overflow and
// truncate neatly with an ellipsis.
@mixin truncate-line() {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// Mixin to provide all mat-line styles, changing secondary font size based on whether the list
// is in dense mode.
@mixin base($secondary-font-size) {
.mat-line {
@include truncate-line();
display: block;
box-sizing: border-box;
// all lines but the top line should have smaller text
&:nth-child(n+2) {
font-size: $secondary-font-size;
}
}
}
// This mixin normalizes default element styles, e.g. font weight for heading text.
@mixin normalize-text() {
& > * {
margin: 0;
padding: 0;
font-weight: normal;
font-size: inherit;
}
}
// This mixin provides base styles for the wrapper around mat-line elements in a list.
@mixin wrapper-base() {
display: flex;
flex-direction: column;
flex: auto;
box-sizing: border-box;
overflow: hidden;
@include normalize-text();
// Must remove wrapper when lines are empty or it takes up horizontal
// space and pushes other elements to the right.
&:empty {
display: none;
}
}
| {
"end_byte": 1219,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/style/_list-common.scss"
} |
components/src/material/core/option/_optgroup-theme.scss_0_2643 | @use 'sass:map';
@use '../tokens/m2/mat/optgroup' as tokens-mat-optgroup;
@use '../tokens/token-utils';
@use '../style/sass-utils';
@use '../theming/theming';
@use '../theming/validation';
@use '../theming/inspection';
@use '../typography/typography';
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-optgroup.$prefix,
tokens-mat-optgroup.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-optgroup.$prefix,
tokens-mat-optgroup.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-optgroup.$prefix,
tokens: tokens-mat-optgroup.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-optgroup') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-optgroup.$prefix,
map.get($tokens, tokens-mat-optgroup.$prefix)
);
}
}
| {
"end_byte": 2643,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/_optgroup-theme.scss"
} |
components/src/material/core/option/optgroup.html_0_283 | <span
class="mat-mdc-optgroup-label"
role="presentation"
[class.mdc-list-item--disabled]="disabled"
[id]="_labelId">
<span class="mdc-list-item__primary-text">{{ label }} <ng-content></ng-content></span>
</span>
<ng-content select="mat-option, ng-container"></ng-content>
| {
"end_byte": 283,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/optgroup.html"
} |
components/src/material/core/option/option.html_0_1426 | <!-- Set aria-hidden="true" to this DOM node and other decorative nodes in this file. This might
be contributing to issue where sometimes VoiceOver focuses on a TextNode in the a11y tree instead
of the Option node (#23202). Most assistive technology will generally ignore non-role,
non-text-content elements. Adding aria-hidden seems to make VoiceOver behave more consistently. -->
@if (multiple) {
<mat-pseudo-checkbox
class="mat-mdc-option-pseudo-checkbox"
[disabled]="disabled"
[state]="selected ? 'checked' : 'unchecked'"
aria-hidden="true"></mat-pseudo-checkbox>
}
<ng-content select="mat-icon"></ng-content>
<span class="mdc-list-item__primary-text" #text><ng-content></ng-content></span>
<!-- Render checkmark at the end for single-selection. -->
@if (!multiple && selected && !hideSingleSelectionIndicator) {
<mat-pseudo-checkbox
class="mat-mdc-option-pseudo-checkbox"
[disabled]="disabled"
state="checked"
aria-hidden="true"
appearance="minimal"></mat-pseudo-checkbox>
}
<!-- See a11y notes inside optgroup.ts for context behind this element. -->
@if (group && group._inert) {
<span class="cdk-visually-hidden">({{ group.label }})</span>
}
<div class="mat-mdc-option-ripple mat-focus-indicator" aria-hidden="true" mat-ripple
[matRippleTrigger]="_getHostElement()" [matRippleDisabled]="disabled || disableRipple">
</div>
| {
"end_byte": 1426,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.html"
} |
components/src/material/core/option/option.scss_0_7268 | @use '@angular/cdk';
@use '../tokens/m2/mat/option' as tokens-mat-option;
@use '../tokens/m2/mdc/list' as tokens-mdc-list;
@use '../tokens/token-utils';
@use '../style/vendor-prefixes';
@use '../style/layout-common';
$_side-padding: 16px;
.mat-mdc-option {
@include vendor-prefixes.user-select(none);
@include vendor-prefixes.smooth-font();
display: flex;
position: relative;
align-items: center;
justify-content: flex-start;
overflow: hidden;
min-height: 48px;
padding: 0 16px;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
@include token-utils.use-tokens(
tokens-mat-option.$prefix, tokens-mat-option.get-token-slots()) {
@include token-utils.create-token-slot(color, label-text-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
@include token-utils.create-token-slot(font-weight, label-text-weight);
// Increase specificity to override styles from list theme.
&:hover:not(.mdc-list-item--disabled) {
@include token-utils.create-token-slot(background-color, hover-state-layer-color);
}
&:focus.mdc-list-item,
&.mat-mdc-option-active.mdc-list-item {
@include token-utils.create-token-slot(background-color, focus-state-layer-color);
outline: 0;
}
&.mdc-list-item--selected:not(.mdc-list-item--disabled) {
.mdc-list-item__primary-text {
@include token-utils.create-token-slot(color, selected-state-label-text-color);
}
// We don't change the background in multiple mode since
// it has the checkbox to show the selected state.
&:not(.mat-mdc-option-multiple) {
@include token-utils.create-token-slot(background-color, selected-state-layer-color);
}
}
.mat-pseudo-checkbox {
--mat-minimal-pseudo-checkbox-selected-checkmark-color: #{
token-utils.get-token-variable(selected-state-label-text-color)};
}
}
&.mdc-list-item {
// If the MDC list is loaded after the option, this gets overwritten which breaks the text
// alignment. Ideally we'd wrap all the MDC mixins above with this selector, but the increased
// specificity breaks some internal overrides.
align-items: center;
// List items in MDC have a default background color which can be different from the container
// in which the option is projected. Set the base background to transparent since options
// should always have the same color as their container.
background: transparent;
}
&.mdc-list-item--disabled {
// This is the same as `mdc-list-mixins.list-disabled-opacity` which
// we can't use directly, because it comes with some selectors.
cursor: default;
// Prevent clicking on disabled options with mouse. Support focusing on disabled option using
// keyboard, but not with mouse.
pointer-events: none;
// Give the visual content of this list item a lower opacity. This creates the "gray" appearance
// for disabled state. Set the opacity on the pseudo checkbox and projected content. Set
// opacity only on the visual content rather than the entire list-item so we don't affect the
// focus ring from `.mat-focus-indicator`.
//
// MatOption uses a child `<div>` element for its focus state to align with how ListItem does
// its focus state.
.mat-mdc-option-pseudo-checkbox, .mdc-list-item__primary-text, > mat-icon {
opacity: 0.38;
}
}
// Note that we bump the padding here, rather than padding inside the
// group so that ripples still reach to the edges of the panel.
.mat-mdc-optgroup &:not(.mat-mdc-option-multiple) {
padding-left: $_side-padding * 2;
[dir='rtl'] & {
padding-left: $_side-padding;
padding-right: $_side-padding * 2;
}
}
.mat-icon,
.mat-pseudo-checkbox-full {
margin-right: $_side-padding;
flex-shrink: 0;
[dir='rtl'] & {
margin-right: 0;
margin-left: $_side-padding;
}
}
.mat-pseudo-checkbox-minimal {
margin-left: $_side-padding;
flex-shrink: 0;
[dir='rtl'] & {
margin-right: $_side-padding;
margin-left: 0;
}
}
// Increase specificity because ripple styles are part of the `mat-core` mixin and can
// potentially overwrite the absolute position of the container.
.mat-mdc-option-ripple {
@include layout-common.fill;
// Disable pointer events for the ripple container because the container will overlay the
// user content and we don't want to disable mouse events on the user content.
// Pointer events can be safely disabled because the ripple trigger element is the host element.
pointer-events: none;
}
// Needs to be overwritten explicitly, because the style can
// leak in from the list and cause the text to truncate.
.mdc-list-item__primary-text {
white-space: normal;
// MDC assigns the typography to this element, rather than the option itself, which will break
// existing overrides. Set all of the typography-related properties to `inherit` so that any
// styles set on the host can propagate down.
font-size: inherit;
font-weight: inherit;
letter-spacing: inherit;
line-height: inherit;
font-family: inherit;
text-decoration: inherit;
text-transform: inherit;
margin-right: auto;
[dir='rtl'] & {
margin-right: 0;
margin-left: auto;
}
}
@include cdk.high-contrast {
// In single selection mode, the selected option is indicated by changing its
// background color, but that doesn't work in high contrast mode. We add an
// alternate indication by rendering out a circle.
&.mdc-list-item--selected:not(:has(.mat-mdc-option-pseudo-checkbox))::after {
$size: 10px;
content: '';
position: absolute;
top: 50%;
right: $_side-padding;
transform: translateY(-50%);
width: $size;
height: 0;
border-bottom: solid $size;
border-radius: $size;
}
[dir='rtl'] &.mdc-list-item--selected:not(:has(.mat-mdc-option-pseudo-checkbox))::after {
right: auto;
left: $_side-padding;
}
}
}
.mat-mdc-option-multiple {
// Multi-select options in the selected state aren't supposed to change their background color,
// because the checkbox already indicates that they're selected. This happened to work in M2,
// due to `list-item-selected-container-color` being the same as `list-item-container-color`,
// but that's no longer the case in M3. This overrides ensures that the appearance is consistent.
@include token-utils.use-tokens(tokens-mdc-list.$prefix, tokens-mdc-list.get-token-slots()) {
$selected-token: token-utils.get-token-variable-name(list-item-selected-container-color);
$base-token: token-utils.get-token-variable(list-item-container-color, $fallback: transparent);
#{$selected-token}: $base-token;
}
}
// For options, render the focus indicator when the class .mat-mdc-option-active is present.
.mat-mdc-option-active .mat-focus-indicator::before {
content: '';
}
| {
"end_byte": 7268,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.scss"
} |
components/src/material/core/option/optgroup.scss_0_1634 | @use '../tokens/m2/mat/optgroup' as tokens-mat-optgroup;
@use '../tokens/token-utils';
.mat-mdc-optgroup {
// These tokens are set on the root option group to make them easier to override.
@include token-utils.use-tokens(
tokens-mat-optgroup.$prefix, tokens-mat-optgroup.get-token-slots()) {
@include token-utils.create-token-slot(color, label-text-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
@include token-utils.create-token-slot(font-weight, label-text-weight);
}
}
.mat-mdc-optgroup-label {
display: flex;
position: relative;
align-items: center;
justify-content: flex-start;
overflow: hidden;
min-height: 48px;
padding: 0 16px;
outline: none;
&.mdc-list-item--disabled {
opacity: 0.38;
}
// Needs to be overwritten explicitly, because the style can
// leak in from the list and cause the text to truncate.
.mdc-list-item__primary-text {
// MDC assigns the typography to this element, rather than the element itself, which will break
// existing overrides. Set all of the typography-related properties to `inherit` so that any
// styles set on the host can propagate down.
font-size: inherit;
font-weight: inherit;
letter-spacing: inherit;
line-height: inherit;
font-family: inherit;
text-decoration: inherit;
text-transform: inherit;
white-space: normal;
}
}
| {
"end_byte": 1634,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/optgroup.scss"
} |
components/src/material/core/option/option.ts_0_1630 | /**
* @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.dev/license
*/
import {FocusableOption, FocusOrigin} from '@angular/cdk/a11y';
import {ENTER, hasModifierKey, SPACE} from '@angular/cdk/keycodes';
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
ElementRef,
ChangeDetectorRef,
AfterViewChecked,
OnDestroy,
Input,
Output,
EventEmitter,
QueryList,
ViewChild,
booleanAttribute,
inject,
isSignal,
Signal,
} from '@angular/core';
import {Subject} from 'rxjs';
import {MAT_OPTGROUP, MatOptgroup} from './optgroup';
import {MatOptionParentComponent, MAT_OPTION_PARENT_COMPONENT} from './option-parent';
import {MatRipple} from '../ripple/ripple';
import {MatPseudoCheckbox} from '../selection/pseudo-checkbox/pseudo-checkbox';
import {_StructuralStylesLoader} from '../focus-indicators/structural-styles';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
/**
* Option IDs need to be unique across components, so this counter exists outside of
* the component definition.
*/
let _uniqueIdCounter = 0;
/** Event object emitted by MatOption when selected or deselected. */
export class MatOptionSelectionChange<T = any> {
constructor(
/** Reference to the option that emitted the event. */
public source: MatOption<T>,
/** Whether the change in the option's value was a result of a user action. */
public isUserInput = false,
) {}
}
/**
* Single option inside of a `<mat-select>` element.
*/ | {
"end_byte": 1630,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.ts"
} |
components/src/material/core/option/option.ts_1631_10097 | @Component({
selector: 'mat-option',
exportAs: 'matOption',
host: {
'role': 'option',
'[class.mdc-list-item--selected]': 'selected',
'[class.mat-mdc-option-multiple]': 'multiple',
'[class.mat-mdc-option-active]': 'active',
'[class.mdc-list-item--disabled]': 'disabled',
'[id]': 'id',
// Set aria-selected to false for non-selected items and true for selected items. Conform to
// [WAI ARIA Listbox authoring practices guide](
// https://www.w3.org/WAI/ARIA/apg/patterns/listbox/), "If any options are selected, each
// selected option has either aria-selected or aria-checked set to true. All options that are
// selectable but not selected have either aria-selected or aria-checked set to false." Align
// aria-selected implementation of Chips and List components.
//
// Set `aria-selected="false"` on not-selected listbox options to fix VoiceOver announcing
// every option as "selected" (#21491).
'[attr.aria-selected]': 'selected',
'[attr.aria-disabled]': 'disabled.toString()',
'(click)': '_selectViaInteraction()',
'(keydown)': '_handleKeydown($event)',
'class': 'mat-mdc-option mdc-list-item',
},
styleUrl: 'option.css',
templateUrl: 'option.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatPseudoCheckbox, MatRipple],
})
export class MatOption<T = any> implements FocusableOption, AfterViewChecked, OnDestroy {
private _element = inject<ElementRef<HTMLElement>>(ElementRef);
_changeDetectorRef = inject(ChangeDetectorRef);
private _parent = inject<MatOptionParentComponent>(MAT_OPTION_PARENT_COMPONENT, {optional: true});
group = inject<MatOptgroup>(MAT_OPTGROUP, {optional: true});
private _signalDisableRipple = false;
private _selected = false;
private _active = false;
private _disabled = false;
private _mostRecentViewValue = '';
/** Whether the wrapping component is in multiple selection mode. */
get multiple() {
return this._parent && this._parent.multiple;
}
/** Whether or not the option is currently selected. */
get selected(): boolean {
return this._selected;
}
/** The form value of the option. */
@Input() value: T;
/** The unique ID of the option. */
@Input() id: string = `mat-option-${_uniqueIdCounter++}`;
/** Whether the option is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return (this.group && this.group.disabled) || this._disabled;
}
set disabled(value: boolean) {
this._disabled = value;
}
/** Whether ripples for the option are disabled. */
get disableRipple(): boolean {
return this._signalDisableRipple
? (this._parent!.disableRipple as Signal<boolean>)()
: !!this._parent?.disableRipple;
}
/** Whether to display checkmark for single-selection. */
get hideSingleSelectionIndicator(): boolean {
return !!(this._parent && this._parent.hideSingleSelectionIndicator);
}
/** Event emitted when the option is selected or deselected. */
// tslint:disable-next-line:no-output-on-prefix
@Output() readonly onSelectionChange = new EventEmitter<MatOptionSelectionChange<T>>();
/** Element containing the option's text. */
@ViewChild('text', {static: true}) _text: ElementRef<HTMLElement> | undefined;
/** Emits when the state of the option changes and any parents have to be notified. */
readonly _stateChanges = new Subject<void>();
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
this._signalDisableRipple = !!this._parent && isSignal(this._parent.disableRipple);
}
/**
* Whether or not the option is currently active and ready to be selected.
* An active option displays styles as if it is focused, but the
* focus is actually retained somewhere else. This comes in handy
* for components like autocomplete where focus must remain on the input.
*/
get active(): boolean {
return this._active;
}
/**
* The displayed value of the option. It is necessary to show the selected option in the
* select's trigger.
*/
get viewValue(): string {
// TODO(kara): Add input property alternative for node envs.
return (this._text?.nativeElement.textContent || '').trim();
}
/** Selects the option. */
select(emitEvent = true): void {
if (!this._selected) {
this._selected = true;
this._changeDetectorRef.markForCheck();
if (emitEvent) {
this._emitSelectionChangeEvent();
}
}
}
/** Deselects the option. */
deselect(emitEvent = true): void {
if (this._selected) {
this._selected = false;
this._changeDetectorRef.markForCheck();
if (emitEvent) {
this._emitSelectionChangeEvent();
}
}
}
/** Sets focus onto this option. */
focus(_origin?: FocusOrigin, options?: FocusOptions): void {
// Note that we aren't using `_origin`, but we need to keep it because some internal consumers
// use `MatOption` in a `FocusKeyManager` and we need it to match `FocusableOption`.
const element = this._getHostElement();
if (typeof element.focus === 'function') {
element.focus(options);
}
}
/**
* This method sets display styles on the option to make it appear
* active. This is used by the ActiveDescendantKeyManager so key
* events will display the proper options as active on arrow key events.
*/
setActiveStyles(): void {
if (!this._active) {
this._active = true;
this._changeDetectorRef.markForCheck();
}
}
/**
* This method removes display styles on the option that made it appear
* active. This is used by the ActiveDescendantKeyManager so key
* events will display the proper options as active on arrow key events.
*/
setInactiveStyles(): void {
if (this._active) {
this._active = false;
this._changeDetectorRef.markForCheck();
}
}
/** Gets the label to be used when determining whether the option should be focused. */
getLabel(): string {
return this.viewValue;
}
/** Ensures the option is selected when activated from the keyboard. */
_handleKeydown(event: KeyboardEvent): void {
if ((event.keyCode === ENTER || event.keyCode === SPACE) && !hasModifierKey(event)) {
this._selectViaInteraction();
// Prevent the page from scrolling down and form submits.
event.preventDefault();
}
}
/**
* `Selects the option while indicating the selection came from the user. Used to
* determine if the select's view -> model callback should be invoked.`
*/
_selectViaInteraction(): void {
if (!this.disabled) {
this._selected = this.multiple ? !this._selected : true;
this._changeDetectorRef.markForCheck();
this._emitSelectionChangeEvent(true);
}
}
/** Returns the correct tabindex for the option depending on disabled state. */
// This method is only used by `MatLegacyOption`. Keeping it here to avoid breaking the types.
// That's because `MatLegacyOption` use `MatOption` type in a few places such as
// `MatOptionSelectionChange`. It is safe to delete this when `MatLegacyOption` is deleted.
_getTabIndex(): string {
return this.disabled ? '-1' : '0';
}
/** Gets the host DOM element. */
_getHostElement(): HTMLElement {
return this._element.nativeElement;
}
ngAfterViewChecked() {
// Since parent components could be using the option's label to display the selected values
// (e.g. `mat-select`) and they don't have a way of knowing if the option's label has changed
// we have to check for changes in the DOM ourselves and dispatch an event. These checks are
// relatively cheap, however we still limit them only to selected options in order to avoid
// hitting the DOM too often.
if (this._selected) {
const viewValue = this.viewValue;
if (viewValue !== this._mostRecentViewValue) {
if (this._mostRecentViewValue) {
this._stateChanges.next();
}
this._mostRecentViewValue = viewValue;
}
}
}
ngOnDestroy() {
this._stateChanges.complete();
}
/** Emits the selection change event. */
private _emitSelectionChangeEvent(isUserInput = false): void {
this.onSelectionChange.emit(new MatOptionSelectionChange<T>(this, isUserInput));
}
} | {
"end_byte": 10097,
"start_byte": 1631,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.ts"
} |
components/src/material/core/option/option.ts_10099_11660 | /**
* Counts the amount of option group labels that precede the specified option.
* @param optionIndex Index of the option at which to start counting.
* @param options Flat list of all of the options.
* @param optionGroups Flat list of all of the option groups.
* @docs-private
*/
export function _countGroupLabelsBeforeOption(
optionIndex: number,
options: QueryList<MatOption>,
optionGroups: QueryList<MatOptgroup>,
): number {
if (optionGroups.length) {
let optionsArray = options.toArray();
let groups = optionGroups.toArray();
let groupCounter = 0;
for (let i = 0; i < optionIndex + 1; i++) {
if (optionsArray[i].group && optionsArray[i].group === groups[groupCounter]) {
groupCounter++;
}
}
return groupCounter;
}
return 0;
}
/**
* Determines the position to which to scroll a panel in order for an option to be into view.
* @param optionOffset Offset of the option from the top of the panel.
* @param optionHeight Height of the options.
* @param currentScrollPosition Current scroll position of the panel.
* @param panelHeight Height of the panel.
* @docs-private
*/
export function _getOptionScrollPosition(
optionOffset: number,
optionHeight: number,
currentScrollPosition: number,
panelHeight: number,
): number {
if (optionOffset < currentScrollPosition) {
return optionOffset;
}
if (optionOffset + optionHeight > currentScrollPosition + panelHeight) {
return Math.max(0, optionOffset - panelHeight + optionHeight);
}
return currentScrollPosition;
} | {
"end_byte": 11660,
"start_byte": 10099,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.ts"
} |
components/src/material/core/option/_option-theme.scss_0_4365 | @use '../tokens/m2/mat/option' as tokens-mat-option;
@use '../tokens/token-utils';
@use '../style/sass-utils';
@use '../theming/theming';
@use '../theming/inspection';
@use '../theming/validation';
@use '../typography/typography';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-option.
/// @param {Map} $theme The theme to generate base styles for.
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
/// Outputs color theme styles for the mat-option.
/// @param {Map} $theme The theme to generate color styles for.
/// @param {ArgList} Additional optional arguments (only supported for M3 themes):
/// $color-variant: The color variant to use for the selected option: primary, secondary,
/// tertiary, or error (If not specified, default secondary color will be used).
@mixin color($theme, $options...) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...);
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-option.$prefix,
tokens-mat-option.get-color-tokens($theme)
);
}
.mat-accent {
@include token-utils.create-token-values(
tokens-mat-option.$prefix,
tokens-mat-option.get-color-tokens($theme, accent)
);
}
.mat-warn {
@include token-utils.create-token-values(
tokens-mat-option.$prefix,
tokens-mat-option.get-color-tokens($theme, warn)
);
}
}
}
/// Outputs typography theme styles for the mat-option.
/// @param {Map} $theme The theme to generate typography styles for.
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-option.$prefix,
tokens-mat-option.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-option.
/// @param {Map} $theme The theme to generate density styles for.
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-option.$prefix,
tokens: tokens-mat-option.get-token-slots(),
),
);
}
/// Outputs the CSS variable values for the given tokens.
/// @param {Map} $tokens The token values to emit.
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
/// Outputs all (base, color, typography, and density) theme styles for the mat-option.
/// @param {Map} $theme The theme to generate styles for.
/// @param {ArgList} Additional optional arguments (only supported for M3 themes):
/// $color-variant: The color variant to use for the selected option: primary, secondary,
/// tertiary, or error (If not specified, default secondary color will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-option') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mat-option-tokens: token-utils.get-tokens-for($tokens, tokens-mat-option.$prefix, $options...);
@include token-utils.create-token-values(tokens-mat-option.$prefix, $mat-option-tokens);
}
| {
"end_byte": 4365,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/_option-theme.scss"
} |
components/src/material/core/option/index.ts_0_765 | /**
* @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.dev/license
*/
import {NgModule} from '@angular/core';
import {MatRippleModule} from '../ripple/index';
import {MatPseudoCheckboxModule} from '../selection/index';
import {MatCommonModule} from '../common-behaviors/common-module';
import {MatOption} from './option';
import {MatOptgroup} from './optgroup';
@NgModule({
imports: [MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, MatOption, MatOptgroup],
exports: [MatOption, MatOptgroup],
})
export class MatOptionModule {}
export * from './option';
export * from './optgroup';
export * from './option-parent';
| {
"end_byte": 765,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/index.ts"
} |
components/src/material/core/option/option.spec.ts_0_9151 | import {waitForAsync, ComponentFixture, TestBed} from '@angular/core/testing';
import {Component, DebugElement, signal} from '@angular/core';
import {By} from '@angular/platform-browser';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
createKeyboardEvent,
dispatchEvent,
} from '@angular/cdk/testing/private';
import {SPACE, ENTER} from '@angular/cdk/keycodes';
import {MatOption, MatOptionModule, MAT_OPTION_PARENT_COMPONENT} from './index';
describe('MatOption component', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatOptionModule, BasicOption],
});
}));
it('should complete the `stateChanges` stream on destroy', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionInstance: MatOption = fixture.debugElement.query(
By.directive(MatOption),
)!.componentInstance;
const completeSpy = jasmine.createSpy('complete spy');
const subscription = optionInstance._stateChanges.subscribe({complete: completeSpy});
fixture.destroy();
expect(completeSpy).toHaveBeenCalled();
subscription.unsubscribe();
});
it('should not emit to `onSelectionChange` if selecting an already-selected option', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionInstance: MatOption = fixture.debugElement.query(
By.directive(MatOption),
)!.componentInstance;
optionInstance.select();
expect(optionInstance.selected).toBe(true);
const spy = jasmine.createSpy('selection change spy');
const subscription = optionInstance.onSelectionChange.subscribe(spy);
optionInstance.select();
fixture.detectChanges();
expect(optionInstance.selected).toBe(true);
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it('should not emit to `onSelectionChange` if deselecting an unselected option', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionInstance: MatOption = fixture.debugElement.query(
By.directive(MatOption),
)!.componentInstance;
optionInstance.deselect();
expect(optionInstance.selected).toBe(false);
const spy = jasmine.createSpy('selection change spy');
const subscription = optionInstance.onSelectionChange.subscribe(spy);
optionInstance.deselect();
fixture.detectChanges();
expect(optionInstance.selected).toBe(false);
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it('should be able to set a custom id', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.componentInstance.id.set('custom-option');
fixture.detectChanges();
const optionInstance = fixture.debugElement.query(By.directive(MatOption))!.componentInstance;
expect(optionInstance.id).toBe('custom-option');
});
it('should select the option when pressing space', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionDebugElement = fixture.debugElement.query(By.directive(MatOption))!;
const optionNativeElement: HTMLElement = optionDebugElement.nativeElement;
const optionInstance: MatOption = optionDebugElement.componentInstance;
const spy = jasmine.createSpy('selection change spy');
const subscription = optionInstance.onSelectionChange.subscribe(spy);
const event = dispatchKeyboardEvent(optionNativeElement, 'keydown', SPACE);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
subscription.unsubscribe();
});
it('should select the option when pressing enter', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionDebugElement = fixture.debugElement.query(By.directive(MatOption))!;
const optionNativeElement: HTMLElement = optionDebugElement.nativeElement;
const optionInstance: MatOption = optionDebugElement.componentInstance;
const spy = jasmine.createSpy('selection change spy');
const subscription = optionInstance.onSelectionChange.subscribe(spy);
const event = dispatchKeyboardEvent(optionNativeElement, 'keydown', ENTER);
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
subscription.unsubscribe();
});
it('should not do anything when pressing the selection keys with a modifier', () => {
const fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
const optionDebugElement = fixture.debugElement.query(By.directive(MatOption))!;
const optionNativeElement: HTMLElement = optionDebugElement.nativeElement;
const optionInstance: MatOption = optionDebugElement.componentInstance;
const spy = jasmine.createSpy('selection change spy');
const subscription = optionInstance.onSelectionChange.subscribe(spy);
[ENTER, SPACE].forEach(key => {
const event = createKeyboardEvent('keydown', key);
Object.defineProperty(event, 'shiftKey', {get: () => true});
dispatchEvent(optionNativeElement, event);
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
});
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
describe('ripples', () => {
let fixture: ComponentFixture<BasicOption>;
let optionDebugElement: DebugElement;
let optionNativeElement: HTMLElement;
let optionInstance: MatOption;
beforeEach(() => {
fixture = TestBed.createComponent(BasicOption);
fixture.detectChanges();
optionDebugElement = fixture.debugElement.query(By.directive(MatOption))!;
optionNativeElement = optionDebugElement.nativeElement;
optionInstance = optionDebugElement.componentInstance;
});
it('should show ripples by default', () => {
expect(optionInstance.disableRipple)
.withContext('Expected ripples to be enabled by default')
.toBeFalsy();
expect(optionNativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to show up initially')
.toBe(0);
dispatchFakeEvent(optionNativeElement, 'mousedown');
dispatchFakeEvent(optionNativeElement, 'mouseup');
expect(optionNativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected one ripple to show up after a fake click.')
.toBe(1);
});
it('should not show ripples if the option is disabled', () => {
expect(optionNativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to show up initially')
.toBe(0);
fixture.componentInstance.disabled.set(true);
fixture.detectChanges();
dispatchFakeEvent(optionNativeElement, 'mousedown');
dispatchFakeEvent(optionNativeElement, 'mouseup');
expect(optionNativeElement.querySelectorAll('.mat-ripple-element').length)
.withContext('Expected no ripples to show up after click on a disabled option.')
.toBe(0);
});
});
it('should have a focus indicator', () => {
const fixture = TestBed.createComponent(BasicOption);
const optionNativeElement = fixture.debugElement.query(By.directive(MatOption))!.nativeElement;
expect(optionNativeElement.parentElement.querySelector('.mat-focus-indicator'))
.withContext(
'expected to find a focus indicator on ' +
"either the mat-option element or one of it's children",
)
.not.toBeNull();
});
describe('inside inert group', () => {
let fixture: ComponentFixture<InsideGroup>;
beforeEach(waitForAsync(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [MatOptionModule, InsideGroup],
providers: [
{
provide: MAT_OPTION_PARENT_COMPONENT,
useValue: {inertGroups: true},
},
],
});
fixture = TestBed.createComponent(InsideGroup);
fixture.detectChanges();
}));
it('should remove all accessibility-related attributes from the group', () => {
const group: HTMLElement = fixture.nativeElement.querySelector('mat-optgroup');
expect(group.hasAttribute('role')).toBe(false);
expect(group.hasAttribute('aria-disabled')).toBe(false);
expect(group.hasAttribute('aria-labelledby')).toBe(false);
});
it('should mirror the group label inside the option', () => {
const option: HTMLElement = fixture.nativeElement.querySelector('mat-option');
expect(option.textContent?.trim()).toBe('Option(Group)');
});
});
});
@Component({
template: `<mat-option [id]="id()" [disabled]="disabled()"></mat-option>`,
standalone: true,
imports: [MatOptionModule],
})
class BasicOption {
disabled = signal(false);
id = signal('');
}
@Component({
template: `
<mat-optgroup label="Group">
<mat-option>Option</mat-option>
</mat-optgroup>
`,
standalone: true,
imports: [MatOptionModule],
})
class InsideGroup {}
| {
"end_byte": 9151,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option.spec.ts"
} |
components/src/material/core/option/option-parent.ts_0_783 | /**
* @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.dev/license
*/
import {InjectionToken, Signal} from '@angular/core';
/**
* Describes a parent component that manages a list of options.
* Contains properties that the options can inherit.
* @docs-private
*/
export interface MatOptionParentComponent {
disableRipple?: boolean | Signal<boolean>;
multiple?: boolean;
inertGroups?: boolean;
hideSingleSelectionIndicator?: boolean;
}
/**
* Injection token used to provide the parent component to options.
*/
export const MAT_OPTION_PARENT_COMPONENT = new InjectionToken<MatOptionParentComponent>(
'MAT_OPTION_PARENT_COMPONENT',
);
| {
"end_byte": 783,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/option-parent.ts"
} |
components/src/material/core/option/optgroup.ts_0_3575 | /**
* @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.dev/license
*/
import {
Component,
ViewEncapsulation,
ChangeDetectionStrategy,
Input,
InjectionToken,
booleanAttribute,
inject,
} from '@angular/core';
import {MatOptionParentComponent, MAT_OPTION_PARENT_COMPONENT} from './option-parent';
// Notes on the accessibility pattern used for `mat-optgroup`.
// The option group has two different "modes": regular and inert. The regular mode uses the
// recommended a11y pattern which has `role="group"` on the group element with `aria-labelledby`
// pointing to the label. This works for `mat-select`, but it seems to hit a bug for autocomplete
// under VoiceOver where the group doesn't get read out at all. The bug appears to be that if
// there's __any__ a11y-related attribute on the group (e.g. `role` or `aria-labelledby`),
// VoiceOver on Safari won't read it out.
// We've introduced the `inert` mode as a workaround. Under this mode, all a11y attributes are
// removed from the group, and we get the screen reader to read out the group label by mirroring it
// inside an invisible element in the option. This is sub-optimal, because the screen reader will
// repeat the group label on each navigation, whereas the default pattern only reads the group when
// the user enters a new group. The following alternate approaches were considered:
// 1. Reading out the group label using the `LiveAnnouncer` solves the problem, but we can't control
// when the text will be read out so sometimes it comes in too late or never if the user
// navigates quickly.
// 2. `<mat-option aria-describedby="groupLabel"` - This works on Safari, but VoiceOver in Chrome
// won't read out the description at all.
// 3. `<mat-option aria-labelledby="optionLabel groupLabel"` - This works on Chrome, but Safari
// doesn't read out the text at all. Furthermore, on
// Counter for unique group ids.
let _uniqueOptgroupIdCounter = 0;
/**
* Injection token that can be used to reference instances of `MatOptgroup`. It serves as
* alternative token to the actual `MatOptgroup` class which could cause unnecessary
* retention of the class and its component metadata.
*/
export const MAT_OPTGROUP = new InjectionToken<MatOptgroup>('MatOptgroup');
/**
* Component that is used to group instances of `mat-option`.
*/
@Component({
selector: 'mat-optgroup',
exportAs: 'matOptgroup',
templateUrl: 'optgroup.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrl: 'optgroup.css',
host: {
'class': 'mat-mdc-optgroup',
'[attr.role]': '_inert ? null : "group"',
'[attr.aria-disabled]': '_inert ? null : disabled.toString()',
'[attr.aria-labelledby]': '_inert ? null : _labelId',
},
providers: [{provide: MAT_OPTGROUP, useExisting: MatOptgroup}],
})
export class MatOptgroup {
/** Label for the option group. */
@Input() label: string;
/** whether the option group is disabled. */
@Input({transform: booleanAttribute}) disabled: boolean = false;
/** Unique id for the underlying label. */
_labelId: string = `mat-optgroup-label-${_uniqueOptgroupIdCounter++}`;
/** Whether the group is in inert a11y mode. */
_inert: boolean;
constructor(...args: unknown[]);
constructor() {
const parent = inject<MatOptionParentComponent>(MAT_OPTION_PARENT_COMPONENT, {optional: true});
this._inert = parent?.inertGroups ?? false;
}
}
| {
"end_byte": 3575,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/option/optgroup.ts"
} |
components/src/material/core/testing/option-harness.spec.ts_0_4144 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component, QueryList, ViewChildren, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {
MAT_OPTION_PARENT_COMPONENT,
MatOption,
MatOptionModule,
MatOptionParentComponent,
} from '@angular/material/core';
import {MatOptionHarness} from './option-harness';
describe('MatOptionHarness', () => {
let fixture: ComponentFixture<OptionHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatOptionModule, OptionHarnessTest],
});
fixture = TestBed.createComponent(OptionHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all option harnesses', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness);
expect(options.length).toBe(2);
});
it('should filter options by text', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness.with({text: 'Disabled option'}));
expect(options.length).toBe(1);
});
it('should filter options text by a pattern', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness.with({text: /option/}));
expect(options.length).toBe(2);
});
it('should filter options text by its selected state', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness);
let selectedOptions = await loader.getAllHarnesses(MatOptionHarness.with({isSelected: true}));
expect(options.length).toBe(2);
expect(selectedOptions.length).toBe(0);
await options[0].click();
selectedOptions = await loader.getAllHarnesses(MatOptionHarness.with({isSelected: true}));
expect(selectedOptions.length).toBe(1);
});
it('should get the text of options', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness);
const texts = await parallel(() => options.map(option => option.getText()));
expect(texts).toEqual(['Plain option', 'Disabled option']);
});
it('should get whether an option is disabled', async () => {
const options = await loader.getAllHarnesses(MatOptionHarness);
const disabledStates = await parallel(() => options.map(option => option.isDisabled()));
expect(disabledStates).toEqual([false, true]);
});
it('should get whether an option is selected', async () => {
const option = await loader.getHarness(MatOptionHarness);
expect(await option.isSelected()).toBe(false);
await option.click();
expect(await option.isSelected()).toBe(true);
});
it('should get whether an option is active', async () => {
const option = await loader.getHarness(MatOptionHarness);
expect(await option.isActive()).toBe(false);
// Set the option as active programmatically since
// it's usually the parent component that does it.
fixture.componentInstance.options.first.setActiveStyles();
fixture.detectChanges();
expect(await option.isActive()).toBe(true);
});
it('should get whether an option is in multi-selection mode', async () => {
const option = await loader.getHarness(MatOptionHarness);
expect(await option.isMultiple()).toBe(false);
// Options take their `multiple` state from the parent component.
fixture.componentInstance.multiple = true;
fixture.detectChanges();
expect(await option.isMultiple()).toBe(true);
});
});
@Component({
providers: [
{
provide: MAT_OPTION_PARENT_COMPONENT,
useExisting: OptionHarnessTest,
},
],
template: `
<mat-option>Plain option</mat-option>
<mat-option disabled>Disabled option</mat-option>
`,
standalone: true,
imports: [MatOptionModule],
})
class OptionHarnessTest implements MatOptionParentComponent {
@ViewChildren(MatOption) options: QueryList<{setActiveStyles(): void}>;
private readonly _multiple = signal(false);
get multiple() {
return this._multiple();
}
set multiple(v: boolean) {
this._multiple.set(v);
}
}
| {
"end_byte": 4144,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/option-harness.spec.ts"
} |
components/src/material/core/testing/public-api.ts_0_360 | /**
* @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.dev/license
*/
export * from './option-harness';
export * from './option-harness-filters';
export * from './optgroup-harness';
export * from './optgroup-harness-filters';
| {
"end_byte": 360,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/public-api.ts"
} |
components/src/material/core/testing/optgroup-harness.ts_0_2028 | /**
* @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.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {OptgroupHarnessFilters} from './optgroup-harness-filters';
import {MatOptionHarness} from './option-harness';
import {OptionHarnessFilters} from './option-harness-filters';
/** Harness for interacting with a `mat-optgroup` in tests. */
export class MatOptgroupHarness extends ComponentHarness {
/** Selector used to locate option group instances. */
static hostSelector = '.mat-mdc-optgroup';
private _label = this.locatorFor('.mat-mdc-optgroup-label');
/**
* Gets a `HarnessPredicate` that can be used to search for a option group with specific
* attributes.
* @param options Options for filtering which option instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatOptgroupHarness>(
this: ComponentHarnessConstructor<T>,
options: OptgroupHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'labelText',
options.labelText,
async (harness, title) => HarnessPredicate.stringMatches(await harness.getLabelText(), title),
);
}
/** Gets the option group's label text. */
async getLabelText(): Promise<string> {
return (await this._label()).text();
}
/** Gets whether the option group is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-disabled')) === 'true';
}
/**
* Gets the options that are inside the group.
* @param filter Optionally filters which options are included.
*/
async getOptions(filter: OptionHarnessFilters = {}): Promise<MatOptionHarness[]> {
return this.locatorForAll(MatOptionHarness.with(filter))();
}
}
| {
"end_byte": 2028,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/optgroup-harness.ts"
} |
components/src/material/core/testing/optgroup-harness-filters.ts_0_364 | /**
* @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.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
export interface OptgroupHarnessFilters extends BaseHarnessFilters {
labelText?: string | RegExp;
}
| {
"end_byte": 364,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/optgroup-harness-filters.ts"
} |
components/src/material/core/testing/BUILD.bazel_0_676 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/testing",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/core",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 676,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/BUILD.bazel"
} |
components/src/material/core/testing/index.ts_0_234 | /**
* @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.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/index.ts"
} |
components/src/material/core/testing/optgroup-harness.spec.ts_0_2644 | import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatOptionModule} from '@angular/material/core';
import {MatOptgroupHarness} from './optgroup-harness';
describe('MatOptgroupHarness', () => {
let fixture: ComponentFixture<OptgroupHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatOptionModule, OptgroupHarnessTest],
});
fixture = TestBed.createComponent(OptgroupHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all option group harnesses', async () => {
const groups = await loader.getAllHarnesses(MatOptgroupHarness);
expect(groups.length).toBe(2);
});
it('should filter groups based on their text', async () => {
const groups = await loader.getAllHarnesses(
MatOptgroupHarness.with({
labelText: 'Disabled group',
}),
);
expect(groups.length).toBe(1);
});
it('should filter group label text by a pattern', async () => {
const groups = await loader.getAllHarnesses(MatOptgroupHarness.with({labelText: /group/}));
expect(groups.length).toBe(2);
});
it('should get the group label text', async () => {
const groups = await loader.getAllHarnesses(MatOptgroupHarness);
const texts = await parallel(() => groups.map(group => group.getLabelText()));
expect(texts).toEqual(['Plain group', 'Disabled group']);
});
it('should get the group disabled state', async () => {
const groups = await loader.getAllHarnesses(MatOptgroupHarness);
const disabledStates = await parallel(() => groups.map(group => group.isDisabled()));
expect(disabledStates).toEqual([false, true]);
});
it('should get the options inside the groups', async () => {
const group = await loader.getHarness(MatOptgroupHarness);
const optionTexts = await group.getOptions().then(async options => {
return await parallel(() => options.map(option => option.getText()));
});
expect(optionTexts).toEqual(['Option 1', 'Option 2']);
});
});
@Component({
template: `
<mat-optgroup label="Plain group">
<mat-option>Option 1</mat-option>
<mat-option>Option 2</mat-option>
</mat-optgroup>
<mat-optgroup label="Disabled group" disabled>
<mat-option>Disabled option 1</mat-option>
</mat-optgroup>
`,
standalone: true,
imports: [MatOptionModule],
})
class OptgroupHarnessTest {}
| {
"end_byte": 2644,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/optgroup-harness.spec.ts"
} |
components/src/material/core/testing/option-harness-filters.ts_0_381 | /**
* @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.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
export interface OptionHarnessFilters extends BaseHarnessFilters {
text?: string | RegExp;
isSelected?: boolean;
}
| {
"end_byte": 381,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/option-harness-filters.ts"
} |
components/src/material/core/testing/option-harness.ts_0_2397 | /**
* @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.dev/license
*/
import {
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessPredicate,
} from '@angular/cdk/testing';
import {OptionHarnessFilters} from './option-harness-filters';
/** Harness for interacting with a `mat-option` in tests. */
export class MatOptionHarness extends ContentContainerComponentHarness {
/** Selector used to locate option instances. */
static hostSelector = '.mat-mdc-option';
/** Element containing the option's text. */
private _text = this.locatorFor('.mdc-list-item__primary-text');
/**
* Gets a `HarnessPredicate` that can be used to search for an option with specific attributes.
* @param options Options for filtering which option instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatOptionHarness>(
this: ComponentHarnessConstructor<T>,
options: OptionHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('text', options.text, async (harness, title) =>
HarnessPredicate.stringMatches(await harness.getText(), title),
)
.addOption(
'isSelected',
options.isSelected,
async (harness, isSelected) => (await harness.isSelected()) === isSelected,
);
}
/** Clicks the option. */
async click(): Promise<void> {
return (await this.host()).click();
}
/** Gets the option's label text. */
async getText(): Promise<string> {
return (await this._text()).text();
}
/** Gets whether the option is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mdc-list-item--disabled');
}
/** Gets whether the option is selected. */
async isSelected(): Promise<boolean> {
return (await this.host()).hasClass('mdc-list-item--selected');
}
/** Gets whether the option is active. */
async isActive(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-option-active');
}
/** Gets whether the option is in multiple selection mode. */
async isMultiple(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-option-multiple');
}
}
| {
"end_byte": 2397,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/testing/option-harness.ts"
} |
components/src/material/core/theming/_m2-inspection.scss_0_7006 | @use 'sass:list';
@use 'sass:map';
@use 'sass:meta';
@use './theming';
@use '../m2/theming' as m2-theming;
@use '../m2/typography-utils' as m2-typography-utils;
@use '../typography/versioning' as typography-versioning;
/// Key used to access the Angular Material theme internals.
$_internals: _mat-theming-internals-do-not-access;
/// Keys that indicate a config object is a color config.
$_color-keys: (
primary,
accent,
warn,
foreground,
background,
is-dark,
color, /* included for themes that incorrectly nest the color config: (color: (color: (....))) */
);
/// Keys that indicate a config object is a typography config.
$_typography-keys: (
headline-1,
headline-2,
headline-3,
headline-4,
headline-5,
headline-6,
subtitle-1,
font-family,
subtitle-2,
body-1,
body-2,
button,
caption,
overline,
);
/// The CSS typography properties supported by the inspection API.
$_typography-properties: (font, font-family, line-height, font-size, letter-spacing, font-weight);
/// Gets the m2-config from the theme.
@function _get-m2-config($theme) {
// It is possible for a user to pass a "density theme" that is just a number.
@if meta.type-of($theme) != 'map' {
@return $theme;
}
$internal: map.get($theme, $_internals, m2-config);
$theme: map.remove($theme, $_internals);
@return if(_is-error-theme($theme), $internal, $theme);
}
/// Checks whether the given theme contains error values.
/// @param {*} $theme The theme to check.
/// @return {Boolean} true if the theme contains error values, else false.
@function _is-error-theme($theme) {
@if meta.type-of($theme) != 'map' {
@return false;
}
@if map.get($theme, ERROR) {
@return true;
}
@return _is-error-theme(list.nth(map.values($theme), 1));
}
/// Checks whether the given theme object has any of the given keys.
/// @param {Map} $theme The theme to check
/// @param {List} $keys The keys to check for
/// @return {Boolean} Whether the theme has any of the given keys.
@function _has-any-key($theme, $keys) {
@each $key in $keys {
@if map.has-key($theme, $key) {
@return true;
}
}
@return false;
}
/// Checks whether the given theme is a density scale value.
/// @param {*} $theme The theme to check.
/// @return {Boolean} true if the theme is a density scale value, else false.
@function _is-density-value($theme) {
@return $theme == minimum or $theme == maximum or meta.type-of($theme) == 'number';
}
/// Gets the type of theme represented by a theme object (light or dark).
/// @param {Map} $theme The theme
/// @return {String} The type of theme (either `light` or `dark`).
@function get-theme-type($theme) {
$theme: _get-m2-config($theme);
@if not theme-has($theme, color) {
@error 'Color information is not available on this theme.';
}
$colors: m2-theming.get-color-config($theme);
// Some apps seem to have mistakenly created nested color themes that somehow work with our old
// theme normalization logic. This check allows those apps to keep working.
@if theme-has($colors, color) {
$colors: m2-theming.get-color-config($colors);
}
@return if(map.get($colors, is-dark), dark, light);
}
/// Gets a color from a theme object. This function can take 2 or 3 arguments. If 2 arguments are
/// passed, the second argument is treated as the name of a color role. If 3 arguments are passed,
/// the second argument is treated as the name of a color palette (primary, secondary, etc.) and the
/// third is treated as the palette hue (10, 50, etc.)
/// @param {Map} $theme The theme
/// @param {String} $palette-name The name of a color palette.
/// @param {Number} $hue The palette hue to get (passing this argument means the second argument is
/// interpreted as a palette name).
/// @return {Color} The requested theme color.
@function get-theme-color($theme, $palette-name, $args...) {
$theme: _get-m2-config($theme);
@if not theme-has($theme, color) {
@error 'Color information is not available on this theme.';
}
$colors: m2-theming.get-color-config($theme);
// Some apps seem to have mistakenly created nested color themes that somehow work with our old
// theme normalization logic. This check allows those apps to keep working.
@if theme-has($colors, color) {
$colors: m2-theming.get-color-config($colors);
}
$palette: map.get($colors, $palette-name);
@if not $palette {
@error $palette-name $args $theme;
@error #{'Unrecognized palette name:'} $palette-name;
}
@return m2-theming.get-color-from-palette($palette, $args...);
}
/// Gets a typography value from a theme object.
/// @param {Map} $theme The theme
/// @param {String} $typescale The typescale name.
/// @param {String} $property The CSS font property to get
/// (font, font-family, font-size, font-weight, line-height, or letter-spacing).
/// @return {*} The value of the requested font property.
@function get-theme-typography($theme, $typescale, $property) {
$theme: _get-m2-config($theme);
@if not theme-has($theme, typography) {
@error 'Typography information is not available on this theme.';
}
$typography: typography-versioning.private-typography-to-2018-config(
m2-theming.get-typography-config($theme));
@if $property == font {
$font-weight: m2-typography-utils.font-weight($typography, $typescale);
$font-size: m2-typography-utils.font-size($typography, $typescale);
$line-height: m2-typography-utils.line-height($typography, $typescale);
$font-family: m2-typography-utils.font-family($typography, $typescale);
@return ($font-weight list.slash($font-size, $line-height) $font-family);
}
@else if $property == font-family {
$result: m2-typography-utils.font-family($typography, $typescale);
@return $result or m2-typography-utils.font-family($typography);
}
@else if $property == font-size {
@return m2-typography-utils.font-size($typography, $typescale);
}
@else if $property == font-weight {
@return m2-typography-utils.font-weight($typography, $typescale);
}
@else if $property == line-height {
@return m2-typography-utils.line-height($typography, $typescale);
}
@else if $property == letter-spacing {
@return m2-typography-utils.letter-spacing($typography, $typescale);
}
@else {
@error #{'Valid typography properties are: #{$_typography-properties}. Got:'} $property;
}
}
/// Gets the density scale from a theme object.
/// @param {Map} $theme The theme
/// @return {Number} The density scale.
@function get-theme-density($theme) {
$theme: _get-m2-config($theme);
@if not theme-has($theme, density) {
@error 'Density information is not available on this theme.';
}
$scale: m2-theming.get-density-config($theme);
@return theming.clamp-density($scale, -5);
}
/// Checks whether the theme has information about given theming system.
/// @param {Map} $theme The theme
/// @param {String} $system The system to check
/// @param {Boolean} Whether the theme has information about the system. | {
"end_byte": 7006,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_m2-inspection.scss"
} |
components/src/material/core/theming/_m2-inspection.scss_7007_10302 | @function theme-has($theme, $system) {
$theme: _get-m2-config($theme);
@if $system == base {
@return true;
}
@if $system == color {
$color: m2-theming.get-color-config($theme);
@return $color != null and _has-any-key($color, $_color-keys);
}
@if $system == typography {
$typography: m2-theming.get-typography-config($theme);
@return $typography != null and _has-any-key($typography, $_typography-keys);
}
@if $system == density {
// Backwards compatibility for the case where an explicit, but invalid density is given
// (this was previously treated as density 0).
@if meta.type-of($theme) == 'map' and map.get($theme, density) {
@return true;
}
$density: m2-theming.get-density-config($theme);
@return $density != null and _is-density-value($density);
}
@error 'Valid systems are: base, color, typography, density. Got:' $system;
}
/// Removes the information about the given theming system(s) from the given theme.
/// @param {Map} $theme The theme to remove information from
/// @param {String...} $systems The systems to remove
/// @return {Map} A version of the theme without the removed theming systems.
@function theme-remove($theme, $systems...) {
$internal: map.get($theme, $_internals, m2-config);
@each $system in $systems {
@if $system == color {
$theme: map.set($theme, color, null);
}
@else if $system == typography {
$theme: map.set($theme, typography, null);
}
@else if $system == density {
$theme: map.set($theme, density, null);
}
}
@if $internal {
$internal: theme-remove($internal, $systems...);
$theme: map.set($theme, $_internals, m2-config, $internal);
}
@return $theme;
}
/// Gets a version of the theme with a modified typography config that preserves old behavior in
/// some components that previously used `private-typography-to-2014-config`.
/// Do not introduce new usages of this, it should be cleaned up and removed.
/// @deprecated
@function private-get-typography-back-compat-theme($theme) {
// It is possible for a user to pass a "density theme" that is just a number.
@if meta.type-of($theme) != 'map' {
@return $theme;
}
$internal: map.get($theme, $_internals, m2-config);
$theme: map.remove($theme, $_internals);
@if theme-has($theme, typography) {
$typography-config: m2-theming.get-typography-config($theme);
// gmat configs have both 2018 and 2014 keys.
@if (not typography-versioning.private-typography-is-2014-config($typography-config)) or
(not typography-versioning.private-typography-is-2018-config($typography-config)) {
@return $theme;
}
$new-typography-config: typography-versioning.private-typography-to-2018-config(
$typography-config, true);
// subtitle-2 is mapped differently by `private-typography-to-2014-config`.
$new-typography-config: map.set(
$new-typography-config, subtitle-2, map.get($new-typography-config, body-1));
$theme: if($theme == $typography-config, $new-typography-config,
map.set($theme, typography, $new-typography-config));
}
@if $internal {
$internal: private-get-typography-back-compat-theme($internal);
$theme: map.set($theme, $_internals, m2-config, $internal);
}
@return $theme;
} | {
"end_byte": 10302,
"start_byte": 7007,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_m2-inspection.scss"
} |
components/src/material/core/theming/_color-api-backwards-compatibility.scss_0_3935 | @use '../../badge/badge-theme';
@use '../../button/button-theme';
@use '../../button/fab-theme';
@use '../../button/icon-button-theme';
@use '../../checkbox/checkbox-theme';
@use '../../chips/chips-theme';
@use '../../datepicker/datepicker-theme';
@use '../../icon/icon-theme';
@use '../../progress-bar/progress-bar-theme';
@use '../../progress-spinner/progress-spinner-theme';
@use '../../radio/radio-theme';
@use '../../select/select-theme';
@use '../../slide-toggle/slide-toggle-theme';
@use '../../slider/slider-theme';
@use '../../stepper/stepper-theme';
@use '../../tabs/tabs-theme';
@use '../../form-field/form-field-theme';
@use '../option/option-theme';
@use '../selection/pseudo-checkbox/pseudo-checkbox-theme';
// We want to emit only the overrides, because the backwards compatibility styles are usually
// emitted after all the tokens have been included once already. This allows us to save ~50kb
// from the bundle.
$_overrides-only: true;
@mixin color-variant-styles($theme, $color-variant) {
$primary-options: (color-variant: $color-variant, emit-overrides-only: $_overrides-only);
// Some components use the secondary color rather than primary color for `.mat-primary`.
// Those components should use the $secondary-color-variant.
$secondary-options: (
color-variant: if($color-variant == primary, secondary, $color-variant),
emit-overrides-only: $_overrides-only
);
@include option-theme.color($theme, $secondary-options...);
@include progress-spinner-theme.color($theme, $primary-options...);
@include pseudo-checkbox-theme.color($theme, $primary-options...);
@include stepper-theme.color($theme, $primary-options...);
&.mat-icon {
@include icon-theme.color($theme, $primary-options...);
}
&.mat-mdc-checkbox {
@include checkbox-theme.color($theme, $primary-options...);
}
&.mat-mdc-slider {
@include slider-theme.color($theme, $primary-options...);
}
&.mat-mdc-tab-group,
&.mat-mdc-tab-nav-bar {
@include tabs-theme.color($theme, $primary-options...);
}
&.mat-mdc-slide-toggle {
@include slide-toggle-theme.color($theme, $primary-options...);
}
&.mat-mdc-form-field {
@include select-theme.color($theme, $primary-options...);
}
&.mat-mdc-radio-button {
@include radio-theme.color($theme, $primary-options...);
}
&.mat-mdc-progress-bar {
@include progress-bar-theme.color($theme, $primary-options...);
}
&.mat-mdc-form-field {
@include form-field-theme.color($theme, $primary-options...);
}
&.mat-datepicker-content {
@include datepicker-theme.color($theme, $primary-options...);
}
&.mat-mdc-button-base {
@include button-theme.color($theme, $primary-options...);
@include icon-button-theme.color($theme, $primary-options...);
}
&.mat-mdc-standard-chip {
@include chips-theme.color($theme, $secondary-options...);
}
.mdc-list-item__start,
.mdc-list-item__end {
@include checkbox-theme.color($theme, $primary-options...);
@include radio-theme.color($theme, $primary-options...);
}
// M3 dropped support for warn/error color FABs.
@if $color-variant != error {
&.mat-mdc-fab,
&.mat-mdc-mini-fab {
@include fab-theme.color($theme, $primary-options...);
}
}
}
@mixin color-variants-backwards-compatibility($theme) {
.mat-primary {
@include color-variant-styles($theme, primary);
}
.mat-badge {
@include badge-theme.color($theme, $color-variant: primary,
$emit-overrides-only: $_overrides-only);
}
.mat-accent {
@include color-variant-styles($theme, tertiary);
}
.mat-badge-accent {
@include badge-theme.color($theme, $color-variant: tertiary,
$emit-overrides-only: $_overrides-only);
}
.mat-warn {
@include color-variant-styles($theme, error);
}
.mat-badge-warn {
@include badge-theme.color($theme, $color-variant: error,
$emit-overrides-only: $_overrides-only);
}
}
| {
"end_byte": 3935,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_color-api-backwards-compatibility.scss"
} |
components/src/material/core/theming/_config-validation.scss_0_5732 | @use 'sass:list';
@use 'sass:map';
@use 'sass:meta';
@use 'sass:string';
@use '../style/validation';
@use './palettes';
/// Creates an error message by finding `$config` in the existing message and appending a suffix to
/// it.
/// @param {List|String} $err The error message.
/// @param {String} $suffix The suffix to add.
/// @return {List|String} The updated error message.
@function _create-dollar-config-error-message($err, $suffix) {
@if meta.type-of($err) == 'list' {
@for $i from 1 through list.length($err) {
$err: list.set-nth($err, $i,
_create-dollar-config-error-message(list.nth($err, $i), $suffix));
}
}
@else if meta.type-of($err) == 'string' {
$start: string.index($err, '$config');
@if $start {
$err: string.insert($err, $suffix, $start + 7);
}
}
@return $err;
}
/// Validates that the given object is an M3 palette.
/// @param {*} $palette The object to test
/// @return {Boolean|null} null if it is a valid M3 palette, else true.
@function validate-palette($palette) {
@if not meta.type-of($palette) == 'map' {
@return true;
}
$keys: map.keys($palette);
$expected-keys: map.keys(palettes.$red-palette);
@if validation.validate-allowed-values($keys, $expected-keys...) or
validation.validate-required-values($keys, $expected-keys...) {
@return true;
}
$nv-keys: map.keys(map.get($palette, neutral-variant));
$expected-nv-keys: map.keys(map.get(palettes.$red-palette, neutral-variant));
@if validation.validate-allowed-values($nv-keys, $expected-nv-keys...) or
validation.validate-required-values($nv-keys, $expected-nv-keys...) {
@return true;
}
@return null;
}
/// Validates a theme config.
/// @param {Map} $config The config to test.
/// @return {List} null if no error, else the error message
@function validate-theme-config($config) {
$err: validation.validate-type($config, 'map', 'null');
@if $err {
@return (#{'$config should be a configuration object. Got:'} $config);
}
$allowed: (color, typography, density);
$err: validation.validate-allowed-values(map.keys($config or ()), $allowed...);
@if $err {
@return (
#{'$config has unexpected properties. Valid properties are'}
#{'#{$allowed}.'}
#{'Found:'}
$err
);
}
$err: validate-color-config(map.get($config, color));
@if $err {
@return _create-dollar-config-error-message($err, '.color');
}
$err: validate-typography-config(map.get($config, typography));
@if $err {
@return _create-dollar-config-error-message($err, '.typography');
}
$err: validate-density-config(map.get($config, density));
@if $err {
@return _create-dollar-config-error-message($err, '.density');
}
@return null;
}
/// Validates a theme color config.
/// @param {Map} $config The config to test.
/// @return {List} null if no error, else the error message
@function validate-color-config($config) {
$err: validation.validate-type($config, 'map', 'null');
@if $err {
@return (#{'$config should be a color configuration object. Got:'} $config);
}
$allowed: (theme-type, primary, tertiary, use-system-variables, system-variables-prefix);
$err: validation.validate-allowed-values(map.keys($config or ()), $allowed...);
@if $err {
@return (
#{'$config has unexpected properties. Valid properties are'}
#{'#{$allowed}.'}
#{'Found:'}
$err
);
}
@if $config and map.has-key($config, theme-type) and
not list.index((light, dark, color-scheme), map.get($config, theme-type)) {
@return (
#{'Expected $config.theme-type to be one of: light, dark, color-scheme. Got:'}
map.get($config, theme-type)
);
}
@each $palette in (primary, secondary, tertiary) {
@if $config and map.has-key($config, $palette) {
$err: validate-palette(map.get($config, $palette));
@if $err {
@return (
#{'Expected $config.#{$palette} to be a valid M3 palette. Got:'}
map.get($config, $palette)
);
}
}
}
@return null;
}
/// Validates a theme typography config.
/// @param {Map} $config The config to test.
/// @return {List} null if no error, else the error message
@function validate-typography-config($config) {
$err: validation.validate-type($config, 'map', 'null');
@if $err {
@return (#{'$config should be a typography configuration object. Got:'} $config);
}
$allowed: (
brand-family,
plain-family,
bold-weight,
medium-weight,
regular-weight,
use-system-variables,
system-variables-prefix
);
$err: validation.validate-allowed-values(map.keys($config or ()), $allowed...);
@if $err {
@return (
#{'$config has unexpected properties. Valid properties are'}
#{'#{$allowed}.'}
#{'Found:'}
$err
);
}
@return null;
}
/// Validates a theme density config.
/// @param {Map} $config The config to test.
/// @return {List} null if no error, else the error message
@function validate-density-config($config) {
$err: validation.validate-type($config, 'map', 'null');
@if $err {
@return (#{'$config should be a density configuration object. Got:'} $config);
}
$err: validation.validate-allowed-values(map.keys($config or ()), scale);
@if $err {
@return (#{'$config has unexpected properties. Valid properties are: scale. Found:'} $err);
}
@if $config and map.has-key($config, scale) {
$allowed-scales: (0, -1, -2, -3, -4, -5, minimum, maximum);
@if validation.validate-allowed-values(map.get($config, scale), $allowed-scales...) {
@return (
#{'Expected $config.scale to be one of: #{$allowed-scales}. Got:'}
map.get($config, scale)
);
}
}
@return null;
}
| {
"end_byte": 5732,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_config-validation.scss"
} |
components/src/material/core/theming/_palettes.scss_0_588 | @use 'sass:map';
/// Adds the error colors to the given palette.
@function _patch-error-palette($palette) {
@return map.merge(
$palette,
(
error: (
0: #000000,
10: #410002,
20: #690005,
25: #7e0007,
30: #93000a,
35: #a80710,
40: #ba1a1a,
50: #de3730,
60: #ff5449,
70: #ff897d,
80: #ffb4ab,
90: #ffdad6,
95: #ffedea,
98: #fff8f7,
99: #fffbff,
100: #ffffff,
),
)
);
}
/// Red color palette to be used as primary or tertiary palette. | {
"end_byte": 588,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_palettes.scss_589_3964 | $red-palette: _patch-error-palette((
0: #000000,
10: #410000,
20: #690100,
25: #7e0100,
30: #930100,
35: #a90100,
40: #c00100,
50: #ef0000,
60: #ff5540,
70: #ff8a78,
80: #ffb4a8,
90: #ffdad4,
95: #ffedea,
98: #fff8f6,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #2c1512,
20: #442925,
25: #513430,
30: #5d3f3b,
35: #6a4b46,
40: #775651,
50: #926f69,
60: #ae8882,
70: #caa29c,
80: #e7bdb6,
90: #ffdad4,
95: #ffedea,
98: #fff8f6,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #201a19,
20: #362f2e,
25: #413a38,
30: #4d4544,
35: #59504f,
40: #655c5b,
50: #7f7573,
60: #998e8d,
70: #b4a9a7,
80: #d0c4c2,
90: #ede0dd,
95: #fbeeec,
98: #fff8f6,
99: #fffbff,
100: #ffffff,
4: #130d0c,
6: #181211,
12: #251e1d,
17: #302828,
22: #3b3332,
24: #3f3737,
87: #e4d7d6,
92: #f3e5e4,
94: #f9ebe9,
96: #fef1ef,
),
neutral-variant: (
0: #000000,
10: #251917,
20: #3b2d2b,
25: #473836,
30: #534341,
35: #5f4f4c,
40: #6c5a58,
50: #857370,
60: #a08c89,
70: #bca7a3,
80: #d8c2be,
90: #f5ddda,
95: #ffedea,
98: #fff8f6,
99: #fffbff,
100: #ffffff,
),
));
/// Green color palette to be used as primary or tertiary palette.
$green-palette: _patch-error-palette((
0: #000000,
10: #002200,
20: #013a00,
25: #014600,
30: #015300,
35: #026100,
40: #026e00,
50: #038b00,
60: #03a800,
70: #03c700,
80: #02e600,
90: #77ff61,
95: #cbffb8,
98: #edffe1,
99: #f7ffee,
100: #ffffff,
secondary: (
0: #000000,
10: #121f0e,
20: #263422,
25: #313f2c,
30: #3c4b37,
35: #485642,
40: #54634d,
50: #6c7b65,
60: #86957e,
70: #a0b097,
80: #bbcbb2,
90: #d7e8cd,
95: #e5f6da,
98: #eeffe3,
99: #f7ffee,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1a1c18,
20: #2f312d,
25: #3a3c38,
30: #454743,
35: #51534e,
40: #5d5f5a,
50: #767872,
60: #90918c,
70: #abaca6,
80: #c6c7c1,
90: #e2e3dc,
95: #f1f1eb,
98: #f9faf3,
99: #fcfdf6,
100: #ffffff,
4: #0c0f0b,
6: #121410,
12: #1e201c,
17: #282b26,
22: #333531,
24: #383a35,
87: #dadbd3,
92: #e8e9e1,
94: #eeeee7,
96: #f3f4ed,
),
neutral-variant: (
0: #000000,
10: #181d15,
20: #2c3229,
25: #373d34,
30: #43483f,
35: #4e544a,
40: #5a6056,
50: #73796e,
60: #8d9387,
70: #a7ada1,
80: #c3c8bc,
90: #dfe4d7,
95: #edf3e5,
98: #f6fbee,
99: #f9fef1,
100: #ffffff,
),
));
/// Blue color palette to be used as primary or tertiary palette.
$blue-palette: _patch-error-palette((
0: #000000,
10: #00006e,
20: #0001ac,
25: #0001cd,
30: #0000ef,
35: #1a21ff,
40: #343dff,
50: #5a64ff,
60: #7c84ff,
70: #9da3ff,
80: #bec2ff,
90: #e0e0ff,
95: #f1efff,
98: #fbf8ff,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #191a2c,
20: #2e2f42,
25: #393a4d,
30: #444559,
35: #505165,
40: #5c5d72,
50: #75758b,
60: #8f8fa6,
70: #a9a9c1,
80: #c5c4dd,
90: #e1e0f9,
95: #f1efff,
98: #fbf8ff,
99: #fffbff,
100: #ffffff,
),
neutral: | {
"end_byte": 3964,
"start_byte": 589,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_palettes.scss_3965_7701 | (
0: #000000,
10: #1b1b1f,
20: #303034,
25: #3c3b3f,
30: #47464a,
35: #535256,
40: #5f5e62,
50: #78767a,
60: #929094,
70: #adaaaf,
80: #c8c5ca,
90: #e5e1e6,
95: #f3eff4,
98: #fcf8fd,
99: #fffbff,
100: #ffffff,
4: #0e0e11,
6: #131316,
12: #201f22,
17: #2a292d,
22: #353438,
24: #3a393c,
87: #dcd9dd,
92: #ebe7eb,
94: #f0edf1,
96: #f6f2f7,
),
neutral-variant: (
0: #000000,
10: #1b1b23,
20: #303038,
25: #3b3b43,
30: #46464f,
35: #52515b,
40: #5e5d67,
50: #777680,
60: #91909a,
70: #acaab4,
80: #c7c5d0,
90: #e4e1ec,
95: #f2effa,
98: #fbf8ff,
99: #fffbff,
100: #ffffff,
),
));
/// Yellow color palette to be used as primary or tertiary palette.
$yellow-palette: _patch-error-palette((
0: #000000,
10: #1d1d00,
20: #323200,
25: #3e3e00,
30: #494900,
35: #555500,
40: #626200,
50: #7b7b00,
60: #969600,
70: #b1b100,
80: #cdcd00,
90: #eaea00,
95: #f9f900,
98: #fffeac,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #1d1d06,
20: #323218,
25: #3d3d22,
30: #49482d,
35: #545438,
40: #606043,
50: #7a795a,
60: #949272,
70: #aead8b,
80: #cac8a5,
90: #e7e4bf,
95: #f5f3cd,
98: #fefbd5,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1c1c17,
20: #31312b,
25: #3c3c35,
30: #484741,
35: #54524c,
40: #605e58,
50: #797770,
60: #939189,
70: #aeaba3,
80: #c9c6be,
90: #e6e2d9,
95: #f4f0e8,
98: #fdf9f0,
99: #fffbff,
100: #ffffff,
4: #0f0e0a,
6: #14140f,
12: #20201b,
17: #2b2a25,
22: #36352f,
24: #3a3933,
87: #dddad1,
92: #ece8df,
94: #f1ede5,
96: #f7f3ea,
),
neutral-variant: (
0: #000000,
10: #1c1c11,
20: #313125,
25: #3d3c2f,
30: #48473a,
35: #545345,
40: #605f51,
50: #797869,
60: #939182,
70: #aeac9b,
80: #cac7b6,
90: #e6e3d1,
95: #f4f1df,
98: #fdfae7,
99: #fffbff,
100: #ffffff,
),
));
/// Cyan color palette to be used as primary or tertiary palette.
$cyan-palette: _patch-error-palette((
0: #000000,
10: #002020,
20: #003737,
25: #004343,
30: #004f4f,
35: #005c5c,
40: #006a6a,
50: #008585,
60: #00a1a1,
70: #00bebe,
80: #00dddd,
90: #00fbfb,
95: #adfffe,
98: #e2fffe,
99: #f1fffe,
100: #ffffff,
secondary: (
0: #000000,
10: #051f1f,
20: #1b3534,
25: #27403f,
30: #324b4b,
35: #3e5757,
40: #4a6363,
50: #627c7b,
60: #7b9695,
70: #95b0b0,
80: #b0cccb,
90: #cce8e7,
95: #daf6f5,
98: #e3fffe,
99: #f1fffe,
100: #ffffff,
),
neutral: (
0: #000000,
10: #191c1c,
20: #2d3131,
25: #383c3c,
30: #444747,
35: #4f5353,
40: #5b5f5f,
50: #747877,
60: #8e9191,
70: #a9acab,
80: #c4c7c6,
90: #e0e3e2,
95: #eff1f0,
98: #f7faf9,
99: #fafdfc,
100: #ffffff,
4: #0b0f0e,
6: #101414,
12: #1c2020,
17: #272b2a,
22: #313635,
24: #363a39,
87: #d7dbd9,
92: #e6e9e7,
94: #ebefed,
96: #f1f4f3,
),
neutral-variant: (
0: #000000,
10: #141d1d,
20: #293232,
25: #343d3d,
30: #3f4948,
35: #4a5454,
40: #566060,
50: #6f7979,
60: #889392,
70: #a3adad,
80: #bec9c8,
90: #dae5e4,
95: #e9f3f2,
98: #f1fbfa,
99: #f4fefd,
100: #ffffff,
),
));
/// Magenta color palette to be used as primary or tertiary palette.
$magenta-palette: _patch-error-palette((
0: #000000,
10: #380038,
20: #5b005b,
25: #6e006e,
30: #810081,
35 | {
"end_byte": 7701,
"start_byte": 3965,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_palettes.scss_7701_10975 | : #950094,
40: #a900a9,
50: #d200d2,
60: #fe00fe,
70: #ff76f6,
80: #ffabf3,
90: #ffd7f5,
95: #ffebf8,
98: #fff7f9,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #271624,
20: #3d2b3a,
25: #493545,
30: #554151,
35: #614c5d,
40: #6e5869,
50: #877082,
60: #a2899c,
70: #bea4b7,
80: #dabfd2,
90: #f7daef,
95: #ffebf8,
98: #fff7f9,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1e1a1d,
20: #342f32,
25: #3f3a3d,
30: #4b4548,
35: #575154,
40: #635d60,
50: #7c7579,
60: #968f92,
70: #b1a9ad,
80: #cdc4c8,
90: #e9e0e4,
95: #f8eef2,
98: #fff7f9,
99: #fffbff,
100: #ffffff,
4: #110d10,
6: #161215,
12: #231e22,
17: #2d292c,
22: #383337,
24: #3d383b,
87: #e1d7dc,
92: #efe6ea,
94: #f5ebf0,
96: #fbf1f5,
),
neutral-variant: (
0: #000000,
10: #21191f,
20: #372e34,
25: #423940,
30: #4e444b,
35: #5a4f57,
40: #665b63,
50: #80747c,
60: #9a8d95,
70: #b5a7b0,
80: #d1c2cb,
90: #eedee7,
95: #fcecf5,
98: #fff7f9,
99: #fffbff,
100: #ffffff,
),
));
/// Orange color palette to be used as primary or tertiary palette.
$orange-palette: _patch-error-palette((
0: #000000,
10: #311300,
20: #502400,
25: #612d00,
30: #723600,
35: #843f00,
40: #964900,
50: #bc5d00,
60: #e37100,
70: #ff8e36,
80: #ffb787,
90: #ffdcc7,
95: #ffede4,
98: #fff8f5,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #2b1708,
20: #422b1b,
25: #4f3625,
30: #5b4130,
35: #684c3b,
40: #755846,
50: #90715d,
60: #ab8a75,
70: #c8a48e,
80: #e5bfa8,
90: #ffdcc7,
95: #ffede4,
98: #fff8f5,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #201a17,
20: #362f2b,
25: #413a36,
30: #4d4541,
35: #59514d,
40: #655d58,
50: #7e7571,
60: #998f8a,
70: #b4a9a4,
80: #d0c4bf,
90: #ece0da,
95: #fbeee8,
98: #fff8f5,
99: #fffbff,
100: #ffffff,
4: #120d0b,
6: #181210,
12: #241e1b,
17: #2f2926,
22: #3a3330,
24: #3f3834,
87: #e3d8d3,
92: #f2e6e1,
94: #f8ebe6,
96: #fef1ec,
),
neutral-variant: (
0: #000000,
10: #241912,
20: #3a2e26,
25: #463931,
30: #52443c,
35: #5e4f47,
40: #6b5b52,
50: #84746a,
60: #9f8d83,
70: #baa79d,
80: #d7c3b8,
90: #f4ded3,
95: #ffede4,
98: #fff8f5,
99: #fffbff,
100: #ffffff,
),
));
/// Chartreuse color palette to be used as primary or tertiary palette.
$chartreuse-palette: _patch-error-palette((
0: #000000,
10: #0b2000,
20: #173800,
25: #1e4400,
30: #245100,
35: #2b5e00,
40: #326b00,
50: #418700,
60: #50a400,
70: #60c100,
80: #70e000,
90: #82ff10,
95: #cfffa9,
98: #eeffdc,
99: #f8ffeb,
100: #ffffff,
secondary: (
0: #000000,
10: #141e0c,
20: #293420,
25: #333f2a,
30: #3f4a35,
35: #4a5640,
40: #56624b,
50: #6f7b62,
60: #88957b,
70: #a2b094,
80: #becbaf,
90: #dae7ca,
95: #e8f5d7,
98: #f0fee0,
99: #f8ffeb,
100: #ffffff,
),
neutral: | {
"end_byte": 10975,
"start_byte": 7701,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_palettes.scss_10976_14710 | (
0: #000000,
10: #1a1c18,
20: #2f312c,
25: #3a3c37,
30: #464742,
35: #52534e,
40: #5e5f5a,
50: #767872,
60: #90918b,
70: #abaca5,
80: #c7c7c0,
90: #e3e3dc,
95: #f1f1ea,
98: #fafaf2,
99: #fdfdf5,
100: #ffffff,
4: #0c0f0b,
6: #121410,
12: #1e201c,
17: #282b26,
22: #333531,
24: #383a35,
87: #dadbd3,
92: #e8e9e1,
94: #eeeee7,
96: #f3f4ed,
),
neutral-variant: (
0: #000000,
10: #181d14,
20: #2d3228,
25: #383d33,
30: #44483e,
35: #4f5449,
40: #5b6055,
50: #74796d,
60: #8e9286,
70: #a8ada0,
80: #c4c8bb,
90: #e0e4d6,
95: #eef2e4,
98: #f7fbec,
99: #fafeef,
100: #ffffff,
),
));
/// Spring Green color palette to be used as primary or tertiary palette.
$spring-green-palette: _patch-error-palette((
0: #000000,
10: #00210b,
20: #003917,
25: #00461e,
30: #005225,
35: #00602c,
40: #006d33,
50: #008942,
60: #00a751,
70: #00c561,
80: #00e472,
90: #63ff94,
95: #c4ffcb,
98: #eaffe9,
99: #f5fff2,
100: #ffffff,
secondary: (
0: #000000,
10: #0e1f12,
20: #233425,
25: #2e4030,
30: #394b3b,
35: #445746,
40: #506352,
50: #697c6a,
60: #829682,
70: #9cb19c,
80: #b7ccb7,
90: #d3e8d2,
95: #e1f6e0,
98: #eaffe9,
99: #f5fff2,
100: #ffffff,
),
neutral: (
0: #000000,
10: #191c19,
20: #2e312e,
25: #393c39,
30: #454744,
35: #51534f,
40: #5d5f5b,
50: #757873,
60: #8f918d,
70: #aaaca7,
80: #c5c7c2,
90: #e2e3de,
95: #f0f1ec,
98: #f9faf4,
99: #fcfdf7,
100: #ffffff,
4: #0c0f0c,
6: #111411,
12: #1d201d,
17: #282b27,
22: #323632,
24: #373a36,
87: #d9dbd5,
92: #e7e9e3,
94: #edefe8,
96: #f2f4ee,
),
neutral-variant: (
0: #000000,
10: #161d17,
20: #2b322b,
25: #363d36,
30: #414941,
35: #4d544c,
40: #596058,
50: #717970,
60: #8b9389,
70: #a6ada4,
80: #c1c9be,
90: #dde5da,
95: #ebf3e8,
98: #f4fcf0,
99: #f7fef3,
100: #ffffff,
),
));
/// Azure color palette to be used as primary or tertiary palette.
$azure-palette: _patch-error-palette((
0: #000000,
10: #001b3f,
20: #002f65,
25: #003a7a,
30: #00458f,
35: #0050a5,
40: #005cbb,
50: #0074e9,
60: #438fff,
70: #7cabff,
80: #abc7ff,
90: #d7e3ff,
95: #ecf0ff,
98: #f9f9ff,
99: #fdfbff,
100: #ffffff,
secondary: (
0: #000000,
10: #131c2b,
20: #283041,
25: #333c4d,
30: #3e4759,
35: #4a5365,
40: #565e71,
50: #6f778b,
60: #8891a5,
70: #a3abc0,
80: #bec6dc,
90: #dae2f9,
95: #ecf0ff,
98: #f9f9ff,
99: #fdfbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1a1b1f,
20: #2f3033,
25: #3b3b3f,
30: #46464a,
35: #525256,
40: #5e5e62,
50: #77777a,
60: #919094,
70: #ababaf,
80: #c7c6ca,
90: #e3e2e6,
95: #f2f0f4,
98: #faf9fd,
99: #fdfbff,
100: #ffffff,
4: #0d0e11,
6: #121316,
12: #1f2022,
17: #292a2c,
22: #343537,
24: #38393c,
87: #dbd9dd,
92: #e9e7eb,
94: #efedf0,
96: #f4f3f6,
),
neutral-variant: (
0: #000000,
10: #181c22,
20: #2d3038,
25: #383b43,
30: #44474e,
35: #4f525a,
40: #5b5e66,
50: #74777f,
60: #8e9099,
70: #a9abb4,
80: #c4c6d0,
90: #e0e2ec,
95: #eff0fa,
98: #f9f9ff,
99: #fdfbff,
100: #ffffff,
),
));
/// Violet color palette to be used as primary or tertiary palette.
$violet-palette: _patch-error-palette((
0: #000000,
10: #270057,
20: #42008a,
25: #5000a4,
30: | {
"end_byte": 14710,
"start_byte": 10976,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_palettes.scss_14711_17334 | #5f00c0,
35: #6e00dc,
40: #7d00fa,
50: #944aff,
60: #a974ff,
70: #bf98ff,
80: #d5baff,
90: #ecdcff,
95: #f7edff,
98: #fef7ff,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #1f182a,
20: #352d40,
25: #40384c,
30: #4b4357,
35: #574f63,
40: #645b70,
50: #7d7389,
60: #978ca4,
70: #b2a7bf,
80: #cec2db,
90: #eadef7,
95: #f7edff,
98: #fef7ff,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #1d1b1e,
20: #323033,
25: #3d3a3e,
30: #49464a,
35: #545155,
40: #605d61,
50: #7a767a,
60: #948f94,
70: #aeaaae,
80: #cac5ca,
90: #e6e1e6,
95: #f5eff4,
98: #fef8fc,
99: #fffbff,
100: #ffffff,
4: #0f0d11,
6: #151316,
12: #211f22,
17: #2b292d,
22: #363437,
24: #3b383c,
87: #ded8dd,
92: #ede6eb,
94: #f2ecf1,
96: #f8f2f6,
),
neutral-variant: (
0: #000000,
10: #1d1a22,
20: #332f37,
25: #3e3a42,
30: #49454e,
35: #55515a,
40: #615c66,
50: #7b757f,
60: #958e99,
70: #b0a9b3,
80: #cbc4cf,
90: #e8e0eb,
95: #f6eef9,
98: #fef7ff,
99: #fffbff,
100: #ffffff,
),
));
/// Rose color palette to be used as primary or tertiary palette.
$rose-palette: _patch-error-palette((
0: #000000,
10: #3f001b,
20: #65002f,
25: #7a003a,
30: #8f0045,
35: #a40050,
40: #ba005c,
50: #e80074,
60: #ff4a8e,
70: #ff84a9,
80: #ffb1c5,
90: #ffd9e1,
95: #ffecef,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
secondary: (
0: #000000,
10: #2b151b,
20: #422930,
25: #4f343b,
30: #5b3f46,
35: #684b52,
40: #74565d,
50: #8f6f76,
60: #aa888f,
70: #c6a2aa,
80: #e3bdc5,
90: #ffd9e1,
95: #ffecef,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
),
neutral: (
0: #000000,
10: #201a1b,
20: #352f30,
25: #413a3b,
30: #4c4546,
35: #585052,
40: #655c5e,
50: #7e7576,
60: #988e90,
70: #b3a9aa,
80: #cfc4c5,
90: #ece0e1,
95: #faeeef,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
4: #120d0e,
6: #171213,
12: #241e1f,
17: #2f2829,
22: #3a3334,
24: #3e3738,
87: #e3d7d8,
92: #f1e5e6,
94: #f7ebec,
96: #fdf1f2,
),
neutral-variant: (
0: #000000,
10: #24191b,
20: #3a2d30,
25: #45383b,
30: #514346,
35: #5d4f52,
40: #6a5a5e,
50: #847376,
60: #9e8c90,
70: #baa7aa,
80: #d6c2c5,
90: #f3dde1,
95: #ffecef,
98: #fff8f8,
99: #fffbff,
100: #ffffff,
),
)); | {
"end_byte": 17334,
"start_byte": 14711,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palettes.scss"
} |
components/src/material/core/theming/_definition.scss_0_4512 | // This file contains functions used to define Angular Material theme objects.
@use 'sass:map';
@use '../style/sass-utils';
@use './palettes';
@use '../tokens/m3-tokens';
@use './config-validation';
// Prefix used for component token fallback variables, e.g.
// `color: var(--mdc-text-button-label-text-color, var(--mat-sys-primary));`
$system-fallback-prefix: mat-sys;
// Default system level prefix to use when directly calling the `system-level-*` mixins.
// Prefix used for component token fallback variables, e.g.
// `color: var(--mdc-text-button-label-text-color, var(--mat-sys-primary));`
// TODO: Remove this variable after internal clients are migrated from "sys"
$system-level-prefix: mat-sys;
/// Map key used to store internals of theme config.
$internals: _mat-theming-internals-do-not-access;
/// The theme version of generated themes.
$theme-version: 1;
/// Defines an Angular Material theme object with color, typography, and density settings.
/// @param {Map} $config The theme configuration
/// @return {Map} A theme object
@function define-theme($config: ()) {
$err: config-validation.validate-theme-config($config);
@if $err {
@error $err;
}
@return sass-utils.deep-merge-all(
define-colors(map.get($config, color) or ()),
define-typography(map.get($config, typography) or ()),
define-density(map.get($config, density) or ()),
($internals: (base-tokens: m3-tokens.generate-base-tokens())),
);
}
/// Defines an Angular Material theme object with color settings.
/// @param {Map} $config The color configuration
/// @return {Map} A theme object
@function define-colors($config: ()) {
$err: config-validation.validate-color-config($config);
@if $err {
@error $err;
}
$type: map.get($config, theme-type) or light;
$primary: map.get($config, primary) or palettes.$violet-palette;
$tertiary: map.get($config, tertiary) or $primary;
$system-variables-prefix: map.get($config, system-variables-prefix) or $system-level-prefix;
sass-utils.$use-system-color-variables: map.get($config, use-system-variables) or false;
@return (
$internals: (
theme-version: $theme-version,
theme-type: $type,
palettes: (
primary: map.remove($primary, neutral, neutral-variant, secondary),
secondary: map.get($primary, secondary),
tertiary: map.remove($tertiary, neutral, neutral-variant, secondary),
neutral: map.get($primary, neutral),
neutral-variant: map.get($primary, neutral-variant),
error: map.get($primary, error),
),
color-system-variables-prefix: $system-variables-prefix,
color-tokens: m3-tokens.generate-color-tokens(
$type, $primary, $tertiary, map.get($primary, error), $system-variables-prefix)
)
);
}
/// Defines an Angular Material theme object with typography settings.
/// @param {Map} $config The typography configuration
/// @return {Map} A theme object
@function define-typography($config: ()) {
$err: config-validation.validate-typography-config($config);
@if $err {
@error $err;
}
$plain: map.get($config, plain-family) or (Roboto, sans-serif);
$brand: map.get($config, brand-family) or $plain;
$bold: map.get($config, bold-weight) or 700;
$medium: map.get($config, medium-weight) or 500;
$regular: map.get($config, regular-weight) or 400;
$system-variables-prefix: map.get($config, system-variables-prefix) or $system-level-prefix;
sass-utils.$use-system-typography-variables: map.get($config, use-system-variables) or false;
@return (
$internals: (
theme-version: $theme-version,
font-definition: (
plain: $plain,
brand: $brand,
bold: $bold,
medium: $medium,
regular: $regular,
),
typography-system-variables-prefix: $system-variables-prefix,
typography-tokens: m3-tokens.generate-typography-tokens(
$brand, $plain, $bold, $medium, $regular, $system-variables-prefix)
)
);
}
/// Defines an Angular Material theme object with density settings.
/// @param {Map} $config The density configuration
/// @return {Map} A theme object
@function define-density($config: ()) {
$err: config-validation.validate-density-config($config);
@if $err {
@error $err;
}
$density-scale: map.get($config, scale) or 0;
@return (
$internals: (
theme-version: $theme-version,
density-scale: $density-scale,
density-tokens: m3-tokens.generate-density-tokens($density-scale)
)
);
}
| {
"end_byte": 4512,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_definition.scss"
} |
components/src/material/core/theming/_palette-deprecated.scss_0_2241 | @use './palette';
// @deprecated Use `$red-palette` instead
$red: palette.$red-palette;
// @deprecated Use `$pink-palette` instead
$pink: palette.$pink-palette;
// @deprecated Use `$indigo-palette` instead
$indigo: palette.$indigo-palette;
// @deprecated Use `$purple-palette` instead.
$purple: palette.$purple-palette;
// @deprecated Use `$deep-purple-palette` instead.
$deep-purple: palette.$deep-purple-palette;
// @deprecated Use `$blue-palette` instead.
$blue: palette.$blue-palette;
// @deprecated Use `$light-blue-palette` instead.
$light-blue: palette.$light-blue-palette;
// @deprecated Use `$cyan-palette` instead.
$cyan: palette.$cyan-palette;
// @deprecated Use `$teal-palette` instead.
$teal: palette.$teal-palette;
// @deprecated Use `$green-palette` instead.
$green: palette.$green-palette;
// @deprecated Use `$light-green-palette` instead.
$light-green: palette.$light-green-palette;
// @deprecated Use `$lime-palette` instead.
$lime: palette.$lime-palette;
// @deprecated Use `$yellow-palette` instead.
$yellow: palette.$yellow-palette;
// @deprecated Use `$amber-palette` instead.
$amber: palette.$amber-palette;
// @deprecated Use `$orange-palette` instead.
$orange: palette.$orange-palette;
// @deprecated Use `$deep-orange-palette` instead.
$deep-orange: palette.$deep-orange-palette;
// @deprecated Use `$brown-palette` instead.
$brown: palette.$brown-palette;
// @deprecated Use `$grey-palette` instead.
$grey: palette.$grey-palette;
// @deprecated Use `$gray-palette` instead.
$gray: palette.$gray-palette;
// @deprecated Use `$blue-grey-palette` instead.
$blue-grey: palette.$blue-grey-palette;
// @deprecated Use `$blue-gray-palette` instead.
$blue-gray: palette.$blue-gray-palette;
// @deprecated Use `$light-theme-background-palette` instead.
$light-theme-background: palette.$light-theme-background-palette;
// @deprecated Use `$dark-theme-background-palette` instead.
$dark-theme-background: palette.$dark-theme-background-palette;
// @deprecated Use `$light-theme-foreground-palette` instead.
$light-theme-foreground: palette.$light-theme-foreground-palette;
// @deprecated Use `$dark-theme-foreground-palette` instead.
$dark-theme-foreground: palette.$dark-theme-foreground-palette;
| {
"end_byte": 2241,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_palette-deprecated.scss"
} |
components/src/material/core/theming/_inspection.scss_0_2853 | @use 'sass:list';
@use 'sass:map';
@use '../style/validation';
@use './m2-inspection';
$_internals: _mat-theming-internals-do-not-access;
$_m3-typescales: (
display-large,
display-medium,
display-small,
headline-large,
headline-medium,
headline-small,
title-large,
title-medium,
title-small,
label-large,
label-medium,
label-small,
body-large,
body-medium,
body-small,
);
$_typography-properties: (font, font-family, line-height, font-size, letter-spacing, font-weight);
/// Validates that the given value is a versioned theme object.
/// @param {Any} $theme The theme object to validate.
/// @return {Boolean|Null} true if the theme has errors, else null.
@function _validate-theme-object($theme) {
$err: validation.validate-type($theme, 'map') or
map.get($theme, $_internals, theme-version) == null;
@return if($err, true, null);
}
/// Gets the version number of a theme object. A theme that is not a valid versioned theme object is
/// considered to be version 0.
/// @param {Map} $theme The theme to check the version of
/// @return {Number} The version number of the theme (0 if unknown).
@function get-theme-version($theme) {
$err: _validate-theme-object($theme);
@return if($err, 0, map.get($theme, $_internals, theme-version) or 0);
}
/// Gets the type of theme represented by a theme object (light or dark).
/// @param {Map} $theme The theme
/// @return {String} The type of theme (either `light` or `dark`).
@function get-theme-type($theme) {
$version: get-theme-version($theme);
@if $version == 0 {
@return m2-inspection.get-theme-type($theme);
}
@else if $version == 1 {
@if not theme-has($theme, color) {
@error 'Color information is not available on this theme.';
}
@return map.get($theme, $_internals, theme-type) or light;
}
@else {
@error #{'Unrecognized theme version:'} $version;
}
}
/// Gets a color from a theme object. This function can take 2 or 3 arguments. If 2 arguments are
/// passed, the second argument is treated as the name of a color role. If 3 arguments are passed,
/// the second argument is treated as the name of a color palette (primary, secondary, etc.) and the
/// third is treated as the palette hue (10, 50, etc.)
/// @param {Map} $theme The theme
/// @param {String} $color-role-or-palette-name The name of the color role to get, or the name of a
/// color palette.
/// @param {Number} $hue The palette hue to get (passing this argument means the second argument is
/// interpreted as a palette name).
/// @return {Color} The requested theme color.
@function get-theme-color($theme, $args...) {
$version: get-theme-version($theme);
$args-count: list.length($args);
@if $args-count != 1 and $args-count != 2 and $args-count != 3 {
@error #{'Expected between 2 and 4 arguments. Got:'} $args-count + 1;
} | {
"end_byte": 2853,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_inspection.scss"
} |
components/src/material/core/theming/_inspection.scss_2857_10048 | @if $version == 0 {
@return m2-inspection.get-theme-color($theme, $args...);
}
@else if $version == 1 {
@if $args-count == 1 {
@return _get-theme-role-color($theme, $args...);
}
@else if $args-count == 2 {
@return _get-theme-palette-color($theme, $args...);
}
}
@else {
@error #{'Unrecognized theme version:'} $version;
}
}
/// Gets a role color from a theme object.
/// @param {Map} $theme The theme
/// @param {String} $color-role-name The name of the color role to get.
/// @return {Color} The requested role color.
@function _get-theme-role-color($theme, $color-role-name) {
$err: _validate-theme-object($theme);
@if $err {
// TODO(mmalerba): implement for old style theme objects.
@error #{'get-theme-color does not support legacy theme objects.'};
}
@if not theme-has($theme, color) {
@error 'Color information is not available on this theme.';
}
$color-roles: map.get($theme, $_internals, color-tokens, (mdc, theme));
$result: map.get($color-roles, $color-role-name);
@if not $result {
@error #{'Valid color roles are: #{map.keys($color-roles)}. Got:'} $color-role-name;
}
@return $result;
}
/// Gets a palette color from a theme object.
/// @param {Map} $theme The theme
/// @param {String} $palette-name The name of the palette to get the color from.
/// @param {Number} $hue The hue to read from the palette.
/// @return {Color} The requested palette color.
@function _get-theme-palette-color($theme, $palette-name, $hue) {
$err: _validate-theme-object($theme);
@if $err {
// TODO(mmalerba): implement for old style theme objects.
@error #{'get-theme-color does not support legacy theme objects.'};
}
@if not theme-has($theme, color) {
@error 'Color information is not available on this theme.';
}
$palettes: map.get($theme, $_internals, palettes);
$palette: map.get($palettes, $palette-name);
@if not $palette {
$supported-palettes: map.keys($palettes);
@error #{'Valid palettes are: #{$supported-palettes}. Got:'} $palette-name;
}
$result: map.get($palette, $hue);
@if not $result {
$supported-hues: map.keys($palette);
@error #{'Valid hues for'} $palette-name #{'are: #{$supported-hues}. Got:'} $hue;
}
@return $result;
}
/// Gets a typography value from a theme object.
/// @param {Map} $theme The theme
/// @param {String} $typescale The typescale name.
/// @param {String} $property The CSS font property to get
/// (font, font-family, font-size, font-weight, line-height, or letter-spacing).
/// @return {*} The value of the requested font property.
@function get-theme-typography($theme, $typescale, $property: font) {
$version: get-theme-version($theme);
@if $version == 0 {
@return m2-inspection.get-theme-typography($theme, $typescale, $property);
}
@else if $version == 1 {
@if not theme-has($theme, typography) {
@error 'Typography information is not available on this theme.';
}
@if not list.index($_m3-typescales, $typescale) {
@error #{'Valid typescales are: #{$_m3-typescales}. Got:'} $typescale;
}
@if not list.index($_typography-properties, $property) {
@error #{'Valid typography properties are: #{$_typography-properties}. Got:'} $property;
}
$property-key: map.get((
font: '',
font-family: '-font',
line-height: '-line-height',
font-size: '-size',
letter-spacing: '-tracking',
font-weight: '-weight'
), $property);
$token-name: '#{$typescale}#{$property-key}';
@return map.get($theme, $_internals, typography-tokens, (mdc, typography), $token-name);
}
@else {
@error #{'Unrecognized theme version:'} $version;
}
}
/// Gets the density scale from a theme object.
/// @param {Map} $theme The theme
/// @return {Number} The density scale.
@function get-theme-density($theme) {
$version: get-theme-version($theme);
@if $version == 0 {
@return m2-inspection.get-theme-density($theme);
}
@else if $version == 1 {
@if not theme-has($theme, density) {
@error 'Density information is not available on this theme.';
}
@return map.get($theme, $_internals, density-scale);
}
@else {
@error #{'Unrecognized theme version:'} $version;
}
}
/// Checks whether the theme has information about given theming system.
/// @param {Map} $theme The theme
/// @param {String} $system The system to check
/// @param {Boolean} Whether the theme has information about the system.
@function theme-has($theme, $system) {
$version: get-theme-version($theme);
@if $version == 0 {
@return m2-inspection.theme-has($theme, $system);
}
@else if $version == 1 {
@if $system == base {
@return map.get($theme, $_internals, base-tokens) != null;
}
@if $system == color {
@return map.get($theme, $_internals, color-tokens) != null and
map.get($theme, $_internals, theme-type) != null and
map.get($theme, $_internals, palettes) != null;
}
@if $system == typography {
@return map.get($theme, $_internals, typography-tokens) != null;
}
@if $system == density {
@return map.get($theme, $_internals, density-scale) != null;
}
@error 'Valid systems are: base, color, typography, density. Got:' $system;
}
@else {
@error #{'Unrecognized theme version:'} $version;
}
}
/// Removes the information about the given theming system(s) from the given theme.
/// @param {Map} $theme The theme to remove information from
/// @param {String...} $systems The systems to remove
/// @return {Map} A version of the theme without the removed theming systems.
@function theme-remove($theme, $systems...) {
$err: validation.validate-allowed-values($systems, color, typography, density, base);
@if $err {
@error #{'Expected $systems to contain valid system names (color, typography, density, or'}
#{'base). Got invalid system names:'} $err;
}
$version: get-theme-version($theme);
@if $version == 0 {
@return m2-inspection.theme-remove($theme, $systems...);
}
@else if $version == 1 {
@each $system in $systems {
@if $system == base {
$theme: map.deep-remove($theme, $_internals, base-tokens);
}
@else if $system == color {
$theme: map.deep-remove($theme, $_internals, color-tokens);
$theme: map.deep-remove($theme, $_internals, theme-type);
$theme: map.deep-remove($theme, $_internals, palettes);
}
@else if $system == typography {
$theme: map.deep-remove($theme, $_internals, typography-tokens);
}
@else if $system == density {
$theme: map.deep-remove($theme, $_internals, density-scale);
$theme: map.deep-remove($theme, $_internals, density-tokens);
}
}
@return $theme;
}
}
/// Gets the set of tokens from the given theme, limited to those affected by the requested theming
/// systems.
/// @param {Map} $theme The theme to get tokens from.
/// @param {String...} $systems The theming systems to get tokens for. Valid values are: color,
/// typography, density, base. If no systems are passed, all tokens will be returned.
/// @return {Map} The requested tokens for the theme. | {
"end_byte": 10048,
"start_byte": 2857,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_inspection.scss"
} |
components/src/material/core/theming/_inspection.scss_10049_11217 | @function get-theme-tokens($theme, $systems...) {
$systems: if(list.length($systems) == 0, (color, typography, density, base), $systems);
$err: _validate-theme-object($theme);
@if $err {
@error #{'Expected $theme to be an Angular Material theme object. Got:'} $theme;
}
$err: validation.validate-allowed-values($systems, color, typography, density, base);
@if $err {
@error #{'Expected $systems to contain valid system names (color, typography, density, or'}
#{'base). Got invalid system names:'} $err;
}
$result: ();
@each $system in $systems {
$result: map.deep-merge($result, map.get($theme, $_internals, '#{$system}-tokens') or ());
}
@return $result;
}
/// Gets a version of the theme with a modified typography config that preserves old behavior in
/// some components that previously used `private-typography-to-2014-config`.
/// Do not introduce new usages of this, it should be cleaned up and removed.
/// @deprecated
@function private-get-typography-back-compat-theme($theme) {
@return if(
get-theme-version($theme) == 0,
m2-inspection.private-get-typography-back-compat-theme($theme),
$theme
);
} | {
"end_byte": 11217,
"start_byte": 10049,
"url": "https://github.com/angular/components/blob/main/src/material/core/theming/_inspection.scss"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.