_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/stepper/stepper.md_0_8435
Angular Material's stepper provides a wizard-like workflow by dividing content into logical steps. Material stepper builds on the foundation of the CDK stepper that is responsible for the logic that drives a stepped workflow. Material stepper extends the CDK stepper and has Material Design styling. ### Stepper variants There are two stepper variants: `horizontal` and `vertical`. You can switch between the two using the `orientation` attribute. <!-- example(stepper-overview) --> <!-- example(stepper-vertical) --> ### Labels If a step's label is only text, then the `label` attribute can be used. <!-- example({"example": "stepper-overview", "file": "stepper-overview-example.html", "region": "label"}) --> For more complex labels, add a template with the `matStepLabel` directive inside the `mat-step`. <!-- example({"example": "stepper-editable", "file": "stepper-editable-example.html", "region": "step-label"}) --> #### Label position For a horizontal `mat-stepper` it's possible to define the position of the label. `end` is the default value, while `bottom` will place it under the step icon instead of at its side. This behaviour is controlled by `labelPosition` property. <!-- example({"example": "stepper-label-position-bottom", "file": "stepper-label-position-bottom-example.html", "region": "label-position"}) --> #### Header position If you're using a horizontal stepper, you can control where the stepper's content is positioned using the `headerPosition` input. By default it's on top of the content, but it can also be placed under it. <!-- example(stepper-header-position) --> ### Stepper buttons There are two button directives to support navigation between different steps: `matStepperPrevious` and `matStepperNext`. <!-- example({"example": "stepper-label-position-bottom", "file": "stepper-label-position-bottom-example.html", "region": "buttons"}) --> ### Linear stepper The `linear` attribute can be set on `mat-stepper` to create a linear stepper that requires the user to complete previous steps before proceeding to following steps. For each `mat-step`, the `stepControl` attribute can be set to the top level `AbstractControl` that is used to check the validity of the step. There are two possible approaches. One is using a single form for stepper, and the other is using a different form for each step. Alternatively, if you don't want to use the Angular forms, you can pass in the `completed` property to each of the steps which won't allow the user to continue until it becomes `true`. Note that if both `completed` and `stepControl` are set, the `stepControl` will take precedence. #### Using a single form When using a single form for the stepper, `matStepperPrevious` and `matStepperNext` have to be set to `type="button"` in order to prevent submission of the form before all steps are completed. ```html <form [formGroup]="formGroup"> <mat-stepper formArrayName="formArray" linear> <mat-step formGroupName="0" [stepControl]="formArray.get([0])"> ... <div> <button mat-button matStepperNext type="button">Next</button> </div> </mat-step> <mat-step formGroupName="1" [stepControl]="formArray.get([1])"> ... <div> <button mat-button matStepperPrevious type="button">Back</button> <button mat-button matStepperNext type="button">Next</button> </div> </mat-step> ... </mat-stepper> </form> ``` #### Using a different form for each step ```html <mat-stepper orientation="vertical" linear> <mat-step [stepControl]="formGroup1"> <form [formGroup]="formGroup1"> ... </form> </mat-step> <mat-step [stepControl]="formGroup2"> <form [formGroup]="formGroup2"> ... </form> </mat-step> </mat-stepper> ``` ### Types of steps #### Optional step If completion of a step in linear stepper is not required, then the `optional` attribute can be set on `mat-step`. <!-- example({"example": "stepper-optional", "file": "stepper-optional-example.html", "region": "optional"}) --> #### Editable step By default, steps are editable, which means users can return to previously completed steps and edit their responses. `editable="false"` can be set on `mat-step` to change the default. <!-- example({"example": "stepper-editable", "file": "stepper-editable-example.html", "region": "editable"}) --> #### Completed step By default, the `completed` attribute of a step returns `true` if the step is valid (in case of linear stepper) and the user has interacted with the step. The user, however, can also override this default `completed` behavior by setting the `completed` attribute as needed. #### Overriding icons By default, the step headers will use the `create` and `done` icons from the Material design icon set via `<mat-icon>` elements. If you want to provide a different set of icons, you can do so by placing a `matStepperIcon` for each of the icons that you want to override. The `index`, `active`, and `optional` values of the individual steps are available through template variables: <!-- example({"example": "stepper-states", "file": "stepper-states-example.html", "region": "override-icons"}) --> Note that you aren't limited to using the `mat-icon` component when providing custom icons. ### Controlling the stepper animation You can control the duration of the stepper's animation using the `animationDuration` input. If you want to disable the animation completely, you can do so by setting the properties to `0ms`. <!-- example(stepper-animations) --> #### Step States You can set the state of a step to whatever you want. The given state by default maps to an icon. However, it can be overridden the same way as mentioned above. <!-- example({"example": "stepper-states", "file": "stepper-states-example.html", "region": "states"}) --> In order to use the custom step states, you must add the `displayDefaultIndicatorType` option to the global default stepper options which can be specified by providing a value for `STEPPER_GLOBAL_OPTIONS` in your application's root module. ```ts @NgModule({ providers: [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: { displayDefaultIndicatorType: false } } ] }) ``` <!-- example(stepper-states) --> ### Error State If you want to show an error when the user moved past a step that hasn't been filled out correctly, you can set the error message through the `errorMessage` input and configure the stepper to show errors via the `showError` option in the `STEPPER_GLOBAL_OPTIONS` injection token. Note that since `linear` steppers prevent a user from advancing past an invalid step to begin with, this setting will not affect steppers marked as `linear`. ```ts @NgModule({ providers: [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: { showError: true } } ] }) ``` <!-- example(stepper-errors) --> ### Lazy rendering By default, the stepper will render all of it's content when it's initialized. If you have some content that you want to defer until the particular step is opened, you can put it inside an `ng-template` with the `matStepContent` attribute. <!-- example(stepper-lazy-content) --> ### Responsive stepper If your app supports a wide variety of screens and a stepper's layout doesn't fit a particular screen size, you can control its `orientation` dynamically to change the layout based on the viewport. <!-- example(stepper-responsive) --> ### Keyboard interaction | Keyboard shortcut | Action | |------------------------|---------------------------------| | <kbd>Left Arrow</kbd> | Focus the previous step header. | | <kbd>Right Arrow</kbd> | Focus the next step header. | | <kbd>Enter</kbd> | Select the focused step. | | <kbd>Space</kbd> | Select the focused step. | ### Localizing labels Labels used by the stepper are provided through `MatStepperIntl`. Localization of these messages can be done by providing a subclass with translated values in your application root module. ```ts @NgModule({ imports: [MatStepperModule], providers: [ {provide: MatStepperIntl, useClass: MyIntl}, ], }) export class MyApp {} ``` <!-- example(stepper-intl) -->
{ "commit_id": "ea0d1ba7b", "end_byte": 8435, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.md" }
components/src/material/stepper/stepper.md_8435_10101
### Accessibility The stepper is treated as a tabbed view for accessibility purposes, so it is given `role="tablist"` by default. The header of step that can be clicked to select the step is given `role="tab"`, and the content that can be expanded upon selection is given `role="tabpanel"`. `aria-selected` attribute of step header is automatically set based on step selection change. The stepper and each step should be given a meaningful label via `aria-label` or `aria-labelledby`. Prefer vertical steppers when building for small screen sizes, as horizontal steppers typically take up significantly more horizontal space thus introduce horizontal scrolling. Applications with multiple scrolling dimensions make content harder to consume for some users. See the [Responsive Stepper section](#responsive-stepper) above for an example on building a stepper that adjusts its layout based on viewport size. #### Forms Steppers often contain forms and form controls. If validation errors inside of a stepper's form prevents moving to another step, make sure that your form controls communicate error messages to assistive technology. This helps the user know why they can't advance to another step. You can accomplish this by using `<mat-error>` with `<mat-form-field>`, or by using an ARIA live region. When a step contains a forms validation error, `MatStepper` will display the error in the step's header if specified. See the [Error State section](#error-state) for an example of a stepper with an error message. For non-linear steppers, you should use an ARIA live region to announce error messages when users navigate away from a step with an error message.
{ "commit_id": "ea0d1ba7b", "end_byte": 10101, "start_byte": 8435, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.md" }
components/src/material/stepper/BUILD.bazel_0_2162
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"]) ng_module( name = "stepper", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [ ":stepper.css", ":step-header.css", ] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/portal", "//src/cdk/stepper", "//src/material/core", "//src/material/icon", "@npm//@angular/animations", "@npm//@angular/common", "@npm//@angular/core", "@npm//@angular/forms", "@npm//rxjs", ], ) sass_library( name = "stepper_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "stepper_scss", src = "stepper.scss", deps = [ ":stepper_scss_lib", "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) sass_binary( name = "step_header_scss", src = "step-header.scss", deps = [ ":stepper_scss_lib", "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":stepper", "//src/cdk/bidi", "//src/cdk/keycodes", "//src/cdk/platform", "//src/cdk/stepper", "//src/cdk/testing/private", "//src/material/core", "//src/material/form-field", "//src/material/input", "@npm//@angular/forms", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":stepper.md"], ) extract_tokens( name = "tokens", srcs = [":stepper_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 2162, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/BUILD.bazel" }
components/src/material/stepper/stepper-module.ts_0_1419
/** * @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 {PortalModule} from '@angular/cdk/portal'; import {CdkStepperModule} from '@angular/cdk/stepper'; import {NgModule} from '@angular/core'; import {ErrorStateMatcher, MatCommonModule, MatRippleModule} from '@angular/material/core'; import {MatIconModule} from '@angular/material/icon'; import {MatStepHeader} from './step-header'; import {MatStepLabel} from './step-label'; import {MatStep, MatStepper} from './stepper'; import {MatStepperNext, MatStepperPrevious} from './stepper-button'; import {MatStepperIcon} from './stepper-icon'; import {MAT_STEPPER_INTL_PROVIDER} from './stepper-intl'; import {MatStepContent} from './step-content'; @NgModule({ imports: [ MatCommonModule, PortalModule, CdkStepperModule, MatIconModule, MatRippleModule, MatStep, MatStepLabel, MatStepper, MatStepperNext, MatStepperPrevious, MatStepHeader, MatStepperIcon, MatStepContent, ], exports: [ MatCommonModule, MatStep, MatStepLabel, MatStepper, MatStepperNext, MatStepperPrevious, MatStepHeader, MatStepperIcon, MatStepContent, ], providers: [MAT_STEPPER_INTL_PROVIDER, ErrorStateMatcher], }) export class MatStepperModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 1419, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper-module.ts" }
components/src/material/stepper/step.html_0_115
<ng-template> <ng-content></ng-content> <ng-template [cdkPortalOutlet]="_portal"></ng-template> </ng-template>
{ "commit_id": "ea0d1ba7b", "end_byte": 115, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/step.html" }
components/src/material/stepper/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';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/index.ts" }
components/src/material/stepper/_stepper-variables.scss_0_959
$header-height: 72px !default; // Minimum height for highest density stepper's is determined based on how much // stepper headers can shrink until the step icon or step label exceed. We can't use // a value below `42px` because the optional label for steps would otherwise exceed. $header-minimum-height: 42px !default; $header-maximum-height: $header-height !default; $density-config: ( height: ( default: $header-height, maximum: $header-maximum-height, minimum: $header-minimum-height, ) ) !default; // Note: These variables are not denoted with `!default` because they are used in the non-theme // component styles. Modifying these variables does not have the desired effect for consumers. $label-header-height: 24px; $label-position-bottom-top-gap: 16px; $label-min-width: 50px; $vertical-stepper-content-margin: 36px; $side-gap: 24px; $line-width: 1px; $line-gap: 8px; $step-sub-label-font-size: 12px; $step-header-icon-size: 16px;
{ "commit_id": "ea0d1ba7b", "end_byte": 959, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/_stepper-variables.scss" }
components/src/material/stepper/stepper.spec.ts_0_1628
import {Direction, Directionality} from '@angular/cdk/bidi'; import { DOWN_ARROW, END, ENTER, HOME, LEFT_ARROW, RIGHT_ARROW, SPACE, UP_ARROW, } from '@angular/cdk/keycodes'; import {_supportsShadowDom} from '@angular/cdk/platform'; import { CdkStep, STEPPER_GLOBAL_OPTIONS, STEP_STATE, StepperOrientation, } from '@angular/cdk/stepper'; import { createKeyboardEvent, dispatchEvent, dispatchKeyboardEvent, } from '@angular/cdk/testing/private'; import { Component, DebugElement, EventEmitter, Provider, QueryList, Type, ViewChild, ViewChildren, ViewEncapsulation, inject, signal, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush} from '@angular/core/testing'; import { AbstractControl, AsyncValidatorFn, FormBuilder, FormControl, FormGroup, ReactiveFormsModule, ValidationErrors, Validators, } from '@angular/forms'; import {MatRipple, ThemePalette} from '@angular/material/core'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Observable, Subject, merge} from 'rxjs'; import {map, take} from 'rxjs/operators'; import {MatStepHeader, MatStepperModule} from './index'; import {MatStep, MatStepper} from './stepper'; import {MatStepperNext, MatStepperPrevious} from './stepper-button'; import {MatStepperIntl} from './stepper-intl'; const VALID_REGEX = /valid/; let dir: {value: Direction; readonly change: EventEmitter<Direction>};
{ "commit_id": "ea0d1ba7b", "end_byte": 1628, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_1630_10903
describe('MatStepper', () => { beforeEach(() => { dir = { value: 'ltr', change: new EventEmitter(), }; }); describe('basic stepper', () => { let fixture: ComponentFixture<SimpleMatVerticalStepperApp>; beforeEach(() => { fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); }); it('should default to the first step', () => { const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); }); it('should throw when a negative `selectedIndex` is assigned', () => { const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; expect(() => { stepperComponent.selectedIndex = -10; fixture.detectChanges(); }).toThrowError(/Cannot assign out-of-bounds/); }); it('should throw when an out-of-bounds `selectedIndex` is assigned', () => { const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; expect(() => { stepperComponent.selectedIndex = 1337; fixture.detectChanges(); }).toThrowError(/Cannot assign out-of-bounds/); }); it('should change selected index on header click', () => { const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); expect(stepperComponent.selected instanceof MatStep).toBe(true); // select the second step let stepHeaderEl = stepHeaders[1].nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(stepperComponent.selected instanceof MatStep).toBe(true); // select the third step stepHeaderEl = stepHeaders[2].nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); expect(stepperComponent.selected instanceof MatStep).toBe(true); }); it('should set the "tablist" role on stepper', () => { const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('role')).toBe('tablist'); }); it('should display the correct label', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; let selectedLabel = fixture.nativeElement.querySelector('[aria-selected="true"]'); expect(selectedLabel.textContent).toMatch('Step 1'); stepperComponent.selectedIndex = 2; fixture.detectChanges(); selectedLabel = fixture.nativeElement.querySelector('[aria-selected="true"]'); expect(selectedLabel.textContent).toMatch('Step 3'); fixture.componentInstance.inputLabel.set('New Label'); fixture.detectChanges(); selectedLabel = fixture.nativeElement.querySelector('[aria-selected="true"]'); expect(selectedLabel.textContent).toMatch('New Label'); }); it('should go to next available step when the next button is clicked', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); let nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[1] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[2] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); }); it('should set the next stepper button type to "submit"', () => { const button = fixture.debugElement.query(By.directive(MatStepperNext))!.nativeElement; expect(button.type) .withContext(`Expected the button to have "submit" set as type.`) .toBe('submit'); }); it('should go to previous available step when the previous button is clicked', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); stepperComponent.selectedIndex = 2; let previousButtonNativeEl = fixture.debugElement.queryAll( By.directive(MatStepperPrevious), )[2].nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); previousButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperPrevious))[1] .nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); previousButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperPrevious))[0] .nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); }); it('should set the previous stepper button type to "button"', () => { const button = fixture.debugElement.query(By.directive(MatStepperPrevious))!.nativeElement; expect(button.type) .withContext(`Expected the button to have "button" set as type.`) .toBe('button'); }); it('should set the correct step position for animation', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent._getAnimationDirection(0)).toBe('current'); expect(stepperComponent._getAnimationDirection(1)).toBe('next'); expect(stepperComponent._getAnimationDirection(2)).toBe('next'); stepperComponent.selectedIndex = 1; fixture.detectChanges(); expect(stepperComponent._getAnimationDirection(0)).toBe('previous'); expect(stepperComponent._getAnimationDirection(2)).toBe('next'); expect(stepperComponent._getAnimationDirection(1)).toBe('current'); stepperComponent.selectedIndex = 2; fixture.detectChanges(); expect(stepperComponent._getAnimationDirection(0)).toBe('previous'); expect(stepperComponent._getAnimationDirection(1)).toBe('previous'); expect(stepperComponent._getAnimationDirection(2)).toBe('current'); }); it('should not set focus on header of selected step if header is not clicked', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] .nativeElement; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; spyOn(stepHeaderEl, 'focus'); nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(stepHeaderEl.focus).not.toHaveBeenCalled(); }); it('should focus next step header if focus is inside the stepper', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] .nativeElement; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; spyOn(stepHeaderEl, 'focus'); nextButtonNativeEl.focus(); nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(stepHeaderEl.focus).toHaveBeenCalled(); }); it('should focus next step header if focus is inside the stepper with shadow DOM', () => { if (!_supportsShadowDom()) { return; } fixture.destroy(); TestBed.resetTestingModule(); fixture = createComponent(SimpleMatVerticalStepperApp, [], [], ViewEncapsulation.ShadowDom); fixture.detectChanges(); const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] .nativeElement; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; spyOn(stepHeaderEl, 'focus'); nextButtonNativeEl.focus(); nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(stepHeaderEl.focus).toHaveBeenCalled(); });
{ "commit_id": "ea0d1ba7b", "end_byte": 10903, "start_byte": 1630, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_10909_20156
it('should only be able to return to a previous step if it is editable', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; stepperComponent.selectedIndex = 1; stepperComponent.steps.toArray()[0].editable = false; const previousButtonNativeEl = fixture.debugElement.queryAll( By.directive(MatStepperPrevious), )[1].nativeElement; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); stepperComponent.steps.toArray()[0].editable = true; previousButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); }); it('should set create icon if step is editable and completed', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; expect(stepperComponent._getIndicatorType(0)).toBe('number'); stepperComponent.steps.toArray()[0].editable = true; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent._getIndicatorType(0)).toBe('edit'); }); it('should set done icon if step is not editable and is completed', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; expect(stepperComponent._getIndicatorType(0)).toBe('number'); stepperComponent.steps.toArray()[0].editable = false; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent._getIndicatorType(0)).toBe('done'); }); it('should emit an event when the enter animation is done', fakeAsync(() => { const stepper = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; const selectionChangeSpy = jasmine.createSpy('selectionChange spy'); const animationDoneSpy = jasmine.createSpy('animationDone spy'); const selectionChangeSubscription = stepper.selectionChange.subscribe(selectionChangeSpy); const animationDoneSubscription = stepper.animationDone.subscribe(animationDoneSpy); stepper.selectedIndex = 1; fixture.detectChanges(); expect(selectionChangeSpy).toHaveBeenCalledTimes(1); expect(animationDoneSpy).not.toHaveBeenCalled(); flush(); expect(selectionChangeSpy).toHaveBeenCalledTimes(1); expect(animationDoneSpy).toHaveBeenCalledTimes(1); selectionChangeSubscription.unsubscribe(); animationDoneSubscription.unsubscribe(); })); it('should set the correct aria-posinset and aria-setsize', () => { const headers = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-step-header'), ); expect(headers.map(header => header.getAttribute('aria-posinset'))).toEqual(['1', '2', '3']); expect(headers.every(header => header.getAttribute('aria-setsize') === '3')).toBe(true); }); it('should adjust the index when removing a step before the current one', () => { const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; stepperComponent.selectedIndex = 2; fixture.detectChanges(); // Re-assert since the setter has some extra logic. expect(stepperComponent.selectedIndex).toBe(2); expect(() => { fixture.componentInstance.showStepTwo.set(false); fixture.detectChanges(); }).not.toThrow(); expect(stepperComponent.selectedIndex).toBe(1); }); it('should not do anything when pressing the ENTER key with a modifier', () => { const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertSelectKeyWithModifierInteraction(fixture, stepHeaders, 'vertical', ENTER); }); it('should not do anything when pressing the SPACE key with a modifier', () => { const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertSelectKeyWithModifierInteraction(fixture, stepHeaders, 'vertical', SPACE); }); it('should have a focus indicator', () => { const stepHeaderNativeElements = [ ...fixture.debugElement.nativeElement.querySelectorAll('.mat-vertical-stepper-header'), ]; expect( stepHeaderNativeElements.every(element => element.querySelector('.mat-focus-indicator')), ).toBe(true); }); it('should hide the header icons from assistive technology', () => { const icon = fixture.nativeElement.querySelector('.mat-step-icon span'); expect(icon.getAttribute('aria-hidden')).toBe('true'); }); it('should add units to unit-less values passed in to animationDuration', () => { const stepperComponent: MatStepper = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; stepperComponent.animationDuration = '1337'; expect(stepperComponent.animationDuration).toBe('1337ms'); }); }); describe('basic stepper when attempting to set the selected step too early', () => { it('should not throw', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; expect(() => stepperComponent.selected).not.toThrow(); }); }); describe('basic stepper when attempting to set the selected step too early', () => { it('should not throw', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); const stepperComponent: MatStepper = fixture.debugElement.query( By.css('mat-stepper'), )!.componentInstance; expect(() => (stepperComponent.selected = null!)).not.toThrow(); expect(stepperComponent.selectedIndex).toBe(-1); }); }); describe('basic stepper with i18n label change', () => { let i18nFixture: ComponentFixture<SimpleMatHorizontalStepperApp>; beforeEach(() => { i18nFixture = createComponent(SimpleMatHorizontalStepperApp); i18nFixture.detectChanges(); }); it('should re-render when the i18n labels change', () => { const intl = TestBed.inject(MatStepperIntl); const header = i18nFixture.debugElement.queryAll(By.css('mat-step-header'))[2].nativeElement; const optionalLabel = header.querySelector('.mat-step-optional'); expect(optionalLabel).toBeTruthy(); expect(optionalLabel.textContent).toBe('Optional'); intl.optionalLabel = 'Valgfri'; intl.changes.next(); i18nFixture.detectChanges(); expect(optionalLabel.textContent).toBe('Valgfri'); }); }); describe('basic stepper with completed label change', () => { let fixture: ComponentFixture<SimpleMatHorizontalStepperApp>; beforeEach(() => { fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); }); it('should re-render when the completed labels change', () => { const intl = TestBed.inject(MatStepperIntl); const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = false; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); const completedLabel = header.querySelector('.cdk-visually-hidden'); expect(completedLabel).toBeTruthy(); expect(completedLabel.textContent).toBe('Completed'); intl.completedLabel = 'Completada'; intl.changes.next(); fixture.detectChanges(); expect(completedLabel.textContent).toBe('Completada'); }); }); describe('basic stepper with editable label change', () => { let fixture: ComponentFixture<SimpleMatHorizontalStepperApp>; beforeEach(() => { fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); }); it('should re-render when the editable label changes', () => { const intl = TestBed.inject(MatStepperIntl); const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = true; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); const editableLabel = header.querySelector('.cdk-visually-hidden'); expect(editableLabel).toBeTruthy(); expect(editableLabel.textContent).toBe('Editable'); intl.editableLabel = 'Modificabile'; intl.changes.next(); fixture.detectChanges(); expect(editableLabel.textContent).toBe('Modificabile'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 20156, "start_byte": 10909, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_20160_22989
describe('icon overrides', () => { let fixture: ComponentFixture<IconOverridesStepper>; beforeEach(() => { fixture = createComponent(IconOverridesStepper); fixture.detectChanges(); }); it('should allow for the `edit` icon to be overridden', () => { const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = true; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); expect(header.textContent).toContain('Custom edit'); }); it('should allow for the `done` icon to be overridden', () => { const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = false; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); expect(header.textContent).toContain('Custom done'); }); it('should allow for the `number` icon to be overridden with context', () => { const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const headers = stepperDebugElement.nativeElement.querySelectorAll('mat-step-header'); expect(headers[2].textContent).toContain('III'); }); }); describe('RTL', () => { let fixture: ComponentFixture<SimpleMatVerticalStepperApp>; beforeEach(() => { dir.value = 'rtl'; fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); }); it('should reverse animation in RTL mode', () => { const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent._getAnimationDirection(0)).toBe('current'); expect(stepperComponent._getAnimationDirection(1)).toBe('previous'); expect(stepperComponent._getAnimationDirection(2)).toBe('previous'); stepperComponent.selectedIndex = 1; fixture.detectChanges(); expect(stepperComponent._getAnimationDirection(0)).toBe('next'); expect(stepperComponent._getAnimationDirection(2)).toBe('previous'); expect(stepperComponent._getAnimationDirection(1)).toBe('current'); stepperComponent.selectedIndex = 2; fixture.detectChanges(); expect(stepperComponent._getAnimationDirection(0)).toBe('next'); expect(stepperComponent._getAnimationDirection(1)).toBe('next'); expect(stepperComponent._getAnimationDirection(2)).toBe('current'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 22989, "start_byte": 20160, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_22993_32227
describe('linear stepper', () => { let fixture: ComponentFixture<LinearMatVerticalStepperApp>; let testComponent: LinearMatVerticalStepperApp; let stepperComponent: MatStepper; beforeEach(() => { fixture = createComponent(LinearMatVerticalStepperApp, [], [], undefined, []); fixture.detectChanges(); testComponent = fixture.componentInstance; stepperComponent = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('should have true linear attribute', () => { expect(stepperComponent.linear).toBe(true); }); it('should not move to next step if current step is invalid', () => { expect(testComponent.oneGroup.get('oneCtrl')!.value).toBe(''); expect(testComponent.oneGroup.get('oneCtrl')!.valid).toBe(false); expect(testComponent.oneGroup.valid).toBe(false); expect(testComponent.oneGroup.invalid).toBe(true); expect(stepperComponent.selectedIndex).toBe(0); const stepHeaderEl = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header'))[1] .nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); testComponent.oneGroup.get('oneCtrl')!.setValue('answer'); stepHeaderEl.click(); fixture.detectChanges(); expect(testComponent.oneGroup.valid).toBe(true); expect(stepperComponent.selectedIndex).toBe(1); }); it('should not move to next step if current step is pending', () => { const stepHeaderEl = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header'))[2] .nativeElement; const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[1] .nativeElement; testComponent.oneGroup.get('oneCtrl')!.setValue('input'); testComponent.twoGroup.get('twoCtrl')!.setValue('input'); stepperComponent.selectedIndex = 1; fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); // Step status = PENDING // Assert that linear stepper does not allow step selection change expect(testComponent.twoGroup.pending).toBe(true); stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); // Trigger asynchronous validation testComponent.validationTrigger.next(); // Asynchronous validation completed: // Step status = VALID expect(testComponent.twoGroup.pending).toBe(false); expect(testComponent.twoGroup.valid).toBe(true); stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); stepperComponent.selectedIndex = 1; fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); }); it('should be able to focus step header upon click if it is unable to be selected', () => { const stepHeaderEl = fixture.debugElement.queryAll(By.css('mat-step-header'))[1] .nativeElement; fixture.detectChanges(); expect(stepHeaderEl.getAttribute('tabindex')).toBe('-1'); }); it('should be able to move to next step even when invalid if current step is optional', () => { testComponent.oneGroup.get('oneCtrl')!.setValue('input'); testComponent.twoGroup.get('twoCtrl')!.setValue('input'); testComponent.validationTrigger.next(); stepperComponent.selectedIndex = 1; fixture.detectChanges(); stepperComponent.selectedIndex = 2; fixture.detectChanges(); expect(stepperComponent.steps.toArray()[2].optional).toBe(true); expect(stepperComponent.selectedIndex).toBe(2); expect(testComponent.threeGroup.get('threeCtrl')!.valid).toBe(true); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[2] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex) .withContext('Expected selectedIndex to change when optional step input is empty.') .toBe(3); stepperComponent.selectedIndex = 2; testComponent.threeGroup.get('threeCtrl')!.setValue('input'); nextButtonNativeEl.click(); fixture.detectChanges(); expect(testComponent.threeGroup.get('threeCtrl')!.valid).toBe(false); expect(stepperComponent.selectedIndex) .withContext('Expected selectedIndex to change when optional step input is invalid.') .toBe(3); }); it('should be able to reset the stepper to its initial state', () => { const steps = stepperComponent.steps.toArray(); testComponent.oneGroup.get('oneCtrl')!.setValue('value'); fixture.detectChanges(); stepperComponent.next(); fixture.detectChanges(); stepperComponent.next(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(steps[0].interacted).toBe(true); expect(steps[0].completed).toBe(true); expect(testComponent.oneGroup.get('oneCtrl')!.valid).toBe(true); expect(testComponent.oneGroup.get('oneCtrl')!.value).toBe('value'); expect(steps[1].interacted).toBe(true); expect(steps[1].completed).toBe(false); expect(testComponent.twoGroup.get('twoCtrl')!.valid).toBe(false); stepperComponent.reset(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); expect(steps[0].interacted).toBe(false); expect(steps[0].completed).toBe(false); expect(testComponent.oneGroup.get('oneCtrl')!.valid).toBe(false); expect(testComponent.oneGroup.get('oneCtrl')!.value).toBeFalsy(); expect(steps[1].interacted).toBe(false); expect(steps[1].completed).toBe(false); expect(testComponent.twoGroup.get('twoCtrl')!.valid).toBe(false); }); it('should reset back to the first step when some of the steps are not editable', () => { const steps = stepperComponent.steps.toArray(); steps[0].editable = false; testComponent.oneGroup.get('oneCtrl')!.setValue('value'); fixture.detectChanges(); stepperComponent.next(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); stepperComponent.reset(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); }); it('should not clobber the `complete` binding when resetting', () => { const steps: CdkStep[] = stepperComponent.steps.toArray(); const fillOutStepper = () => { testComponent.oneGroup.get('oneCtrl')!.setValue('input'); testComponent.twoGroup.get('twoCtrl')!.setValue('input'); testComponent.threeGroup.get('threeCtrl')!.setValue('valid'); testComponent.validationTrigger.next(); stepperComponent.selectedIndex = 1; fixture.detectChanges(); stepperComponent.selectedIndex = 2; fixture.detectChanges(); stepperComponent.selectedIndex = 3; fixture.detectChanges(); }; fillOutStepper(); expect(steps[2].completed) .withContext('Expected third step to be considered complete after the first run through.') .toBe(true); stepperComponent.reset(); fixture.detectChanges(); fillOutStepper(); expect(steps[2].completed) .withContext( 'Expected third step to be considered complete when doing a run after ' + 'a reset.', ) .toBe(true); }); it('should be able to skip past the current step if a custom `completed` value is set', () => { expect(testComponent.oneGroup.get('oneCtrl')!.value).toBe(''); expect(testComponent.oneGroup.get('oneCtrl')!.valid).toBe(false); expect(testComponent.oneGroup.valid).toBe(false); expect(stepperComponent.selectedIndex).toBe(0); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(0); stepperComponent.steps.first.completed = true; nextButtonNativeEl.click(); fixture.detectChanges(); expect(testComponent.oneGroup.valid).toBe(false); expect(stepperComponent.selectedIndex).toBe(1); }); it('should set aria-disabled if the user is not able to navigate to a step', () => { const stepHeaders = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-vertical-stepper-header'), ); expect(stepHeaders.map(step => step.getAttribute('aria-disabled'))).toEqual([ null, 'true', 'true', 'true', ]); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 32227, "start_byte": 22993, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_32231_39274
describe('linear stepper with a pre-defined selectedIndex', () => { let preselectedFixture: ComponentFixture<SimplePreselectedMatHorizontalStepperApp>; let stepper: MatStepper; beforeEach(() => { preselectedFixture = createComponent(SimplePreselectedMatHorizontalStepperApp); preselectedFixture.detectChanges(); stepper = preselectedFixture.debugElement.query(By.directive(MatStepper))!.componentInstance; }); it('should not throw', () => { expect(() => preselectedFixture.detectChanges()).not.toThrow(); }); it('selectedIndex should be typeof number', () => { expect(typeof stepper.selectedIndex).toBe('number'); }); it('value of selectedIndex should be the pre-defined value', () => { expect(stepper.selectedIndex).toBe(0); }); }); describe('linear stepper with no `stepControl`', () => { let noStepControlFixture: ComponentFixture<SimpleStepperWithoutStepControl>; beforeEach(() => { noStepControlFixture = createComponent(SimpleStepperWithoutStepControl); noStepControlFixture.detectChanges(); }); it('should not move to the next step if the current one is not completed ', () => { const stepper: MatStepper = noStepControlFixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const headers = noStepControlFixture.debugElement.queryAll( By.css('.mat-horizontal-stepper-header'), ); expect(stepper.selectedIndex).toBe(0); headers[1].nativeElement.click(); noStepControlFixture.detectChanges(); expect(stepper.selectedIndex).toBe(0); }); }); describe('linear stepper with `stepControl`', () => { let controlAndBindingFixture: ComponentFixture<SimpleStepperWithStepControlAndCompletedBinding>; beforeEach(() => { controlAndBindingFixture = createComponent(SimpleStepperWithStepControlAndCompletedBinding); controlAndBindingFixture.detectChanges(); }); it('should have the `stepControl` take precedence when `completed` is set', () => { expect(controlAndBindingFixture.componentInstance.steps[0].control.valid).toBe(true); expect(controlAndBindingFixture.componentInstance.steps[0].completed).toBe(false); const stepper: MatStepper = controlAndBindingFixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; const headers = controlAndBindingFixture.debugElement.queryAll( By.css('.mat-horizontal-stepper-header'), ); expect(stepper.selectedIndex).toBe(0); headers[1].nativeElement.click(); controlAndBindingFixture.detectChanges(); expect(stepper.selectedIndex).toBe(1); }); }); describe('vertical stepper', () => { it('should set the aria-orientation to "vertical"', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('aria-orientation')).toBe('vertical'); }); it('should support using the left/right arrows to move focus', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); }); it('should support using the up/down arrows to move focus', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'vertical'); }); it('should reverse arrow key focus in RTL mode', () => { dir.value = 'rtl'; const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); assertArrowKeyInteractionInRtl(fixture, stepHeaders); }); it('should be able to disable ripples', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.directive(MatStepHeader)); const headerRipples = stepHeaders.map(headerDebugEl => headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple), ); expect(headerRipples.every(ripple => ripple.disabled)).toBe(false); fixture.componentInstance.disableRipple.set(true); fixture.detectChanges(); expect(headerRipples.every(ripple => ripple.disabled)).toBe(true); }); it('should be able to disable ripples', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.directive(MatStepHeader)); stepHeaders[0].componentInstance.focus('mouse'); stepHeaders[1].componentInstance.focus(); expect(stepHeaders[1].nativeElement.classList).toContain('cdk-focused'); expect(stepHeaders[1].nativeElement.classList).toContain('cdk-mouse-focused'); }); it('should be able to set the theme for all steps', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const headers = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-step-header'), ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(false); expect(headers.some(element => element.classList.contains('mat-warn'))).toBe(false); fixture.componentInstance.stepperTheme.set('accent'); fixture.detectChanges(); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-primary'))).toBe(false); expect(headers.some(element => element.classList.contains('mat-warn'))).toBe(false); }); it('should be able to set the theme for a specific step', () => { const fixture = createComponent(SimpleMatVerticalStepperApp); fixture.detectChanges(); const headers = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-step-header'), ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); fixture.componentInstance.secondStepTheme.set('accent'); fixture.detectChanges(); expect(headers[0].classList.contains('mat-primary')).toBe(true); expect(headers[1].classList.contains('mat-primary')).toBe(false); expect(headers[2].classList.contains('mat-primary')).toBe(true); expect(headers[1].classList.contains('mat-accent')).toBe(true); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 39274, "start_byte": 32231, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_39278_48625
describe('horizontal stepper', () => { it('should set the aria-orientation to "horizontal"', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepperEl = fixture.debugElement.query(By.css('mat-stepper'))!.nativeElement; expect(stepperEl.getAttribute('aria-orientation')).toBe('horizontal'); }); it('should support using the left/right arrows to move focus', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); }); it('should reverse arrow key focus in RTL mode', () => { dir.value = 'rtl'; const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertArrowKeyInteractionInRtl(fixture, stepHeaders); }); it('should maintain the correct navigation order when a step is added later on', () => { const fixture = createComponent(HorizontalStepperWithDelayedStep); fixture.detectChanges(); fixture.componentInstance.renderSecondStep.set(true); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); }); it('should reverse arrow key focus when switching into RTL after init', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); assertCorrectKeyboardInteraction(fixture, stepHeaders, 'horizontal'); dir.value = 'rtl'; dir.change.emit('rtl'); fixture.detectChanges(); assertArrowKeyInteractionInRtl(fixture, stepHeaders); }); it('should be able to disable ripples', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.directive(MatStepHeader)); const headerRipples = stepHeaders.map(headerDebugEl => headerDebugEl.query(By.directive(MatRipple))!.injector.get(MatRipple), ); expect(headerRipples.every(ripple => ripple.disabled)).toBe(false); fixture.componentInstance.disableRipple.set(true); fixture.detectChanges(); expect(headerRipples.every(ripple => ripple.disabled)).toBe(true); }); it('should be able to set the theme for all steps', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const headers = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-step-header'), ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(false); expect(headers.some(element => element.classList.contains('mat-warn'))).toBe(false); fixture.componentInstance.stepperTheme.set('accent'); fixture.detectChanges(); expect(headers.some(element => element.classList.contains('mat-accent'))).toBe(true); expect(headers.some(element => element.classList.contains('mat-primary'))).toBe(false); expect(headers.some(element => element.classList.contains('mat-warn'))).toBe(false); }); it('should be able to set the theme for a specific step', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const headers = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.mat-step-header'), ); expect(headers.every(element => element.classList.contains('mat-primary'))).toBe(true); fixture.componentInstance.secondStepTheme.set('accent'); fixture.detectChanges(); expect(headers[0].classList.contains('mat-primary')).toBe(true); expect(headers[1].classList.contains('mat-primary')).toBe(false); expect(headers[2].classList.contains('mat-primary')).toBe(true); expect(headers[1].classList.contains('mat-accent')).toBe(true); }); it('should be able to mark all steps as interacted', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepper: MatStepper = fixture.debugElement.query( By.directive(MatStepper), ).componentInstance; expect(stepper.steps.map(step => step.interacted)).toEqual([false, false, false]); stepper.next(); fixture.detectChanges(); expect(stepper.steps.map(step => step.interacted)).toEqual([true, false, false]); stepper.next(); fixture.detectChanges(); expect(stepper.steps.map(step => step.interacted)).toEqual([true, true, false]); stepper.next(); fixture.detectChanges(); expect(stepper.steps.map(step => step.interacted)).toEqual([true, true, true]); }); it('should emit when the user has interacted with a step', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepper: MatStepper = fixture.debugElement.query( By.directive(MatStepper), ).componentInstance; const interactedSteps: number[] = []; const subscription = merge(...stepper.steps.map(step => step.interactedStream)).subscribe( step => interactedSteps.push(stepper.steps.toArray().indexOf(step as MatStep)), ); expect(interactedSteps).toEqual([]); stepper.next(); fixture.detectChanges(); expect(interactedSteps).toEqual([0]); stepper.next(); fixture.detectChanges(); expect(interactedSteps).toEqual([0, 1]); stepper.next(); fixture.detectChanges(); expect(interactedSteps).toEqual([0, 1, 2]); subscription.unsubscribe(); }); it('should set a class on the host if the header is positioned at the bottom', () => { const fixture = createComponent(SimpleMatHorizontalStepperApp); fixture.detectChanges(); const stepperHost = fixture.nativeElement.querySelector('.mat-stepper-horizontal'); expect(stepperHost.classList).not.toContain('mat-stepper-header-position-bottom'); fixture.componentInstance.headerPosition.set('bottom'); fixture.detectChanges(); expect(stepperHost.classList).toContain('mat-stepper-header-position-bottom'); }); }); describe('linear stepper with valid step', () => { let fixture: ComponentFixture<LinearStepperWithValidOptionalStep>; let testComponent: LinearStepperWithValidOptionalStep; let stepper: MatStepper; beforeEach(() => { fixture = createComponent(LinearStepperWithValidOptionalStep); fixture.detectChanges(); testComponent = fixture.componentInstance; stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('must be visited if not optional', () => { stepper.selectedIndex = 1; fixture.componentRef.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(stepper.selectedIndex).toBe(1); stepper.selectedIndex = 2; fixture.componentRef.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(stepper.selectedIndex).toBe(2); }); it('can be skipped entirely if optional', () => { testComponent.step2Optional.set(true); fixture.detectChanges(); stepper.selectedIndex = 2; fixture.detectChanges(); expect(stepper.selectedIndex).toBe(2); }); }); describe('aria labelling', () => { let fixture: ComponentFixture<StepperWithAriaInputs>; let stepHeader: HTMLElement; beforeEach(() => { fixture = createComponent(StepperWithAriaInputs); fixture.detectChanges(); stepHeader = fixture.nativeElement.querySelector('.mat-step-header'); }); it('should not set aria-label or aria-labelledby attributes if they are not passed in', () => { expect(stepHeader.hasAttribute('aria-label')).toBe(false); expect(stepHeader.hasAttribute('aria-labelledby')).toBe(false); }); it('should set the aria-label attribute', () => { fixture.componentInstance.ariaLabel.set('First step'); fixture.detectChanges(); expect(stepHeader.getAttribute('aria-label')).toBe('First step'); }); it('should set the aria-labelledby attribute', () => { fixture.componentInstance.ariaLabelledby.set('first-step-label'); fixture.detectChanges(); expect(stepHeader.getAttribute('aria-labelledby')).toBe('first-step-label'); }); it('should not be able to set both an aria-label and aria-labelledby', () => { fixture.componentInstance.ariaLabel.set('First step'); fixture.componentInstance.ariaLabelledby.set('first-step-label'); fixture.detectChanges(); expect(stepHeader.getAttribute('aria-label')).toBe('First step'); expect(stepHeader.hasAttribute('aria-labelledby')).toBe(false); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 48625, "start_byte": 39278, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_48629_57644
describe('stepper with error state', () => { let fixture: ComponentFixture<MatHorizontalStepperWithErrorsApp>; let stepper: MatStepper; function createFixture(showErrorByDefault: boolean | undefined) { fixture = createComponent( MatHorizontalStepperWithErrorsApp, [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: {showError: showErrorByDefault}, }, ], [MatFormFieldModule, MatInputModule], ); fixture.detectChanges(); stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; } it('should show error state', () => { createFixture(true); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; stepper.selectedIndex = 1; stepper.steps.first.hasError = true; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepper._getIndicatorType(0)).toBe(STEP_STATE.ERROR); }); it('should respect a custom falsy hasError value', () => { createFixture(true); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; stepper.selectedIndex = 1; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepper._getIndicatorType(0)).toBe(STEP_STATE.ERROR); stepper.steps.first.hasError = false; fixture.detectChanges(); expect(stepper._getIndicatorType(0)).not.toBe(STEP_STATE.ERROR); }); it('should show error state if explicitly enabled, even when disabled globally', () => { createFixture(undefined); const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; stepper.selectedIndex = 1; stepper.steps.first.hasError = true; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepper._getIndicatorType(0)).toBe(STEP_STATE.ERROR); }); }); describe('stepper using Material UI Guideline logic', () => { let fixture: ComponentFixture<MatHorizontalStepperWithErrorsApp>; let stepper: MatStepper; beforeEach(() => { fixture = createComponent( MatHorizontalStepperWithErrorsApp, [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: {displayDefaultIndicatorType: false}, }, ], [MatFormFieldModule, MatInputModule], ); fixture.detectChanges(); stepper = fixture.debugElement.query(By.css('mat-stepper'))!.componentInstance; }); it('should show done state when step is completed and its not the current step', () => { const nextButtonNativeEl = fixture.debugElement.queryAll(By.directive(MatStepperNext))[0] .nativeElement; stepper.selectedIndex = 1; stepper.steps.first.completed = true; nextButtonNativeEl.click(); fixture.detectChanges(); expect(stepper._getIndicatorType(0)).toBe(STEP_STATE.DONE); }); it('should show edit state when step is editable and its the current step', () => { stepper.selectedIndex = 1; stepper.steps.toArray()[1].editable = true; fixture.detectChanges(); expect(stepper._getIndicatorType(1)).toBe(STEP_STATE.EDIT); }); }); describe('indirect descendants', () => { it('should be able to change steps when steps are indirect descendants', () => { const fixture = createComponent(StepperWithIndirectDescendantSteps); fixture.detectChanges(); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-vertical-stepper-header')); const stepperComponent = fixture.debugElement.query( By.directive(MatStepper), )!.componentInstance; expect(stepperComponent.selectedIndex).toBe(0); expect(stepperComponent.selected instanceof MatStep).toBe(true); // select the second step let stepHeaderEl = stepHeaders[1].nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(1); expect(stepperComponent.selected instanceof MatStep).toBe(true); // select the third step stepHeaderEl = stepHeaders[2].nativeElement; stepHeaderEl.click(); fixture.detectChanges(); expect(stepperComponent.selectedIndex).toBe(2); expect(stepperComponent.selected instanceof MatStep).toBe(true); }); it('should allow for the `edit` icon to be overridden', () => { const fixture = createComponent(IndirectDescendantIconOverridesStepper); fixture.detectChanges(); const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = true; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); expect(header.textContent).toContain('Custom edit'); }); it('should allow for the `done` icon to be overridden', () => { const fixture = createComponent(IndirectDescendantIconOverridesStepper); fixture.detectChanges(); const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const stepperComponent: MatStepper = stepperDebugElement.componentInstance; stepperComponent.steps.toArray()[0].editable = false; stepperComponent.next(); fixture.detectChanges(); const header = stepperDebugElement.nativeElement.querySelector('mat-step-header'); expect(header.textContent).toContain('Custom done'); }); it('should allow for the `number` icon to be overridden with context', () => { const fixture = createComponent(IndirectDescendantIconOverridesStepper); fixture.detectChanges(); const stepperDebugElement = fixture.debugElement.query(By.directive(MatStepper))!; const headers = stepperDebugElement.nativeElement.querySelectorAll('mat-step-header'); expect(headers[2].textContent).toContain('III'); }); }); it('should be able to toggle steps via ngIf', () => { const fixture = createComponent(StepperWithNgIf); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('.mat-step-header').length).toBe(1); fixture.componentInstance.showStep2.set(true); fixture.detectChanges(); expect(fixture.nativeElement.querySelectorAll('.mat-step-header').length).toBe(2); }); it('should not pick up the steps from descendant steppers', () => { const fixture = createComponent(NestedSteppers); fixture.detectChanges(); const steppers = fixture.componentInstance.steppers.toArray(); expect(steppers[0].steps.length).toBe(3); expect(steppers[1].steps.length).toBe(2); }); it('should not throw when trying to change steps after initializing to an out-of-bounds index', () => { const fixture = createComponent(StepperWithStaticOutOfBoundsIndex); fixture.detectChanges(); const stepper = fixture.componentInstance.stepper; expect(stepper.selectedIndex).toBe(0); expect(stepper.selected).toBeTruthy(); expect(() => { stepper.selectedIndex = 1; fixture.detectChanges(); }).not.toThrow(); expect(stepper.selectedIndex).toBe(1); expect(stepper.selected).toBeTruthy(); }); describe('stepper with lazy content', () => { it('should render the content of the selected step on init', () => { const fixture = createComponent(StepperWithLazyContent); const element = fixture.nativeElement; fixture.componentInstance.selectedIndex.set(1); fixture.detectChanges(); expect(element.textContent).not.toContain('Step 1 content'); expect(element.textContent).toContain('Step 2 content'); expect(element.textContent).not.toContain('Step 3 content'); }); it('should render the content of steps when the user navigates to them', () => { const fixture = createComponent(StepperWithLazyContent); const element = fixture.nativeElement; fixture.componentInstance.selectedIndex.set(0); fixture.detectChanges(); expect(element.textContent).toContain('Step 1 content'); expect(element.textContent).not.toContain('Step 2 content'); expect(element.textContent).not.toContain('Step 3 content'); fixture.componentInstance.selectedIndex.set(1); fixture.detectChanges(); expect(element.textContent).toContain('Step 1 content'); expect(element.textContent).toContain('Step 2 content'); expect(element.textContent).not.toContain('Step 3 content'); fixture.componentInstance.selectedIndex.set(2); fixture.detectChanges(); expect(element.textContent).toContain('Step 1 content'); expect(element.textContent).toContain('Step 2 content'); expect(element.textContent).toContain('Step 3 content'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 57644, "start_byte": 48629, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_57648_65624
describe('stepper with two-way binding on selectedIndex', () => { it('should update selectedIndex in component on navigation', () => { const fixture = createComponent(StepperWithTwoWayBindingOnSelectedIndex); fixture.detectChanges(); expect(fixture.componentInstance.index).toBe(0); const stepHeaders = fixture.debugElement.queryAll(By.css('.mat-horizontal-stepper-header')); let lastStepHeaderEl = stepHeaders[2].nativeElement; lastStepHeaderEl.click(); fixture.detectChanges(); expect(fixture.componentInstance.index).toBe(2); let middleStepHeaderEl = stepHeaders[1].nativeElement; middleStepHeaderEl.click(); fixture.detectChanges(); expect(fixture.componentInstance.index).toBe(1); let firstStepHeaderEl = stepHeaders[0].nativeElement; firstStepHeaderEl.click(); fixture.detectChanges(); expect(fixture.componentInstance.index).toBe(0); }); }); }); /** Asserts that keyboard interaction works correctly. */ function assertCorrectKeyboardInteraction( fixture: ComponentFixture<any>, stepHeaders: DebugElement[], orientation: StepperOrientation, ) { const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; const nextKey = orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW; const prevKey = orientation === 'vertical' ? UP_ARROW : LEFT_ARROW; expect(stepperComponent._getFocusIndex()).toBe(0); expect(stepperComponent.selectedIndex).toBe(0); let stepHeaderEl = stepHeaders[0].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', nextKey); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext('Expected index of focused step to increase by 1 after pressing the next key.') .toBe(1); expect(stepperComponent.selectedIndex) .withContext('Expected index of selected step to remain unchanged after pressing the next key.') .toBe(0); stepHeaderEl = stepHeaders[1].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', ENTER); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext('Expected index of focused step to remain unchanged after ENTER event.') .toBe(1); expect(stepperComponent.selectedIndex) .withContext( 'Expected index of selected step to change to index of focused step ' + 'after ENTER event.', ) .toBe(1); stepHeaderEl = stepHeaders[1].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', prevKey); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext( 'Expected index of focused step to decrease by 1 after pressing the ' + 'previous key.', ) .toBe(0); expect(stepperComponent.selectedIndex) .withContext( 'Expected index of selected step to remain unchanged after pressing the ' + 'previous key.', ) .toBe(1); // When the focus is on the last step and right arrow key is pressed, the focus should cycle // through to the first step. stepperComponent._keyManager.updateActiveItem(2); stepHeaderEl = stepHeaders[2].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', nextKey); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext( 'Expected index of focused step to cycle through to index 0 after pressing ' + 'the next key.', ) .toBe(0); expect(stepperComponent.selectedIndex) .withContext( 'Expected index of selected step to remain unchanged after pressing ' + 'the next key.', ) .toBe(1); stepHeaderEl = stepHeaders[0].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', SPACE); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext('Expected index of focused to remain unchanged after SPACE event.') .toBe(0); expect(stepperComponent.selectedIndex) .withContext( 'Expected index of selected step to change to index of focused step ' + 'after SPACE event.', ) .toBe(0); const endEvent = dispatchKeyboardEvent(stepHeaderEl, 'keydown', END); expect(stepperComponent._getFocusIndex()) .withContext('Expected last step to be focused when pressing END.') .toBe(stepHeaders.length - 1); expect(endEvent.defaultPrevented) .withContext('Expected default END action to be prevented.') .toBe(true); const homeEvent = dispatchKeyboardEvent(stepHeaderEl, 'keydown', HOME); expect(stepperComponent._getFocusIndex()) .withContext('Expected first step to be focused when pressing HOME.') .toBe(0); expect(homeEvent.defaultPrevented) .withContext('Expected default HOME action to be prevented.') .toBe(true); } /** Asserts that arrow key direction works correctly in RTL mode. */ function assertArrowKeyInteractionInRtl( fixture: ComponentFixture<any>, stepHeaders: DebugElement[], ) { const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; expect(stepperComponent._getFocusIndex()).toBe(0); let stepHeaderEl = stepHeaders[0].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', LEFT_ARROW); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()).toBe(1); stepHeaderEl = stepHeaders[1].nativeElement; dispatchKeyboardEvent(stepHeaderEl, 'keydown', RIGHT_ARROW); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()).toBe(0); } /** Asserts that keyboard interaction works correctly when the user is pressing a modifier key. */ function assertSelectKeyWithModifierInteraction( fixture: ComponentFixture<any>, stepHeaders: DebugElement[], orientation: StepperOrientation, selectionKey: number, ) { const stepperComponent = fixture.debugElement.query(By.directive(MatStepper))!.componentInstance; const modifiers = ['altKey', 'shiftKey', 'ctrlKey', 'metaKey']; expect(stepperComponent._getFocusIndex()).toBe(0); expect(stepperComponent.selectedIndex).toBe(0); dispatchKeyboardEvent( stepHeaders[0].nativeElement, 'keydown', orientation === 'vertical' ? DOWN_ARROW : RIGHT_ARROW, ); fixture.detectChanges(); expect(stepperComponent._getFocusIndex()) .withContext( 'Expected index of focused step to increase by 1 after pressing ' + 'the next key.', ) .toBe(1); expect(stepperComponent.selectedIndex) .withContext( 'Expected index of selected step to remain unchanged after pressing ' + 'the next key.', ) .toBe(0); modifiers.forEach(modifier => { const event = createKeyboardEvent('keydown', selectionKey); Object.defineProperty(event, modifier, {get: () => true}); dispatchEvent(stepHeaders[1].nativeElement, event); fixture.detectChanges(); expect(stepperComponent.selectedIndex) .withContext( `Expected selected index to remain unchanged ` + `when pressing the selection key with ${modifier} modifier.`, ) .toBe(0); expect(event.defaultPrevented).toBe(false); }); } function asyncValidator(minLength: number, validationTrigger: Subject<void>): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors | null> => { return validationTrigger.pipe( map(() => control.value && control.value.length >= minLength ? null : {asyncValidation: {}}, ), take(1), ); }; } function createComponent<T>( component: Type<T>, providers: Provider[] = [], imports: any[] = [], encapsulation?: ViewEncapsulation, declarations = [component], ): ComponentFixture<T> { TestBed.configureTestingModule({ imports: [MatStepperModule, NoopAnimationsModule, ReactiveFormsModule, ...imports], providers: [{provide: Directionality, useFactory: () => dir}, ...providers], declarations, }); if (encapsulation != null) { TestBed.overrideComponent(component, { set: {encapsulation}, }); } return TestBed.createComponent<T>(component); }
{ "commit_id": "ea0d1ba7b", "end_byte": 65624, "start_byte": 57648, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_65626_73021
@Component({ template: ` <form [formGroup]="formGroup"> <mat-stepper> <mat-step errorMessage="This field is required" [stepControl]="formGroup.get('firstNameCtrl')"> <ng-template matStepLabel>Step 1</ng-template> <mat-form-field> <mat-label>First name</mat-label> <input matInput formControlName="firstNameCtrl" required> <mat-error>This field is required</mat-error> </mat-form-field> <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> <mat-step> <ng-template matStepLabel>Step 2</ng-template> Content 2 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> </mat-stepper> </form> `, standalone: false, }) class MatHorizontalStepperWithErrorsApp { private readonly _formBuilder = inject(FormBuilder); formGroup = this._formBuilder.group({ firstNameCtrl: ['', Validators.required], lastNameCtrl: ['', Validators.required], }); } @Component({ template: ` <mat-stepper [disableRipple]="disableRipple()" [color]="stepperTheme()" [headerPosition]="headerPosition()"> <mat-step> <ng-template matStepLabel>Step 1</ng-template> Content 1 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> <mat-step [color]="secondStepTheme()"> <ng-template matStepLabel>Step 2</ng-template> Content 2 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> <mat-step [label]="inputLabel" optional> Content 3 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> </mat-stepper> `, standalone: false, }) class SimpleMatHorizontalStepperApp { inputLabel = 'Step 3'; disableRipple = signal(false); stepperTheme = signal<ThemePalette>(undefined); secondStepTheme = signal<ThemePalette>(undefined); headerPosition = signal(''); } @Component({ template: ` <mat-stepper orientation="vertical" [disableRipple]="disableRipple()" [color]="stepperTheme()"> <mat-step> <ng-template matStepLabel>Step 1</ng-template> Content 1 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> @if (showStepTwo()) { <mat-step [color]="secondStepTheme()"> <ng-template matStepLabel>Step 2</ng-template> Content 2 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> } <mat-step [label]="inputLabel()"> Content 3 <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext>Next</button> </div> </mat-step> </mat-stepper> `, standalone: false, }) class SimpleMatVerticalStepperApp { inputLabel = signal('Step 3'); showStepTwo = signal(true); disableRipple = signal(false); stepperTheme = signal<ThemePalette>(undefined); secondStepTheme = signal<ThemePalette>(undefined); } @Component({ standalone: true, template: ` <mat-stepper orientation="vertical" linear> <mat-step [stepControl]="oneGroup"> <form [formGroup]="oneGroup"> <ng-template matStepLabel>Step one</ng-template> <input formControlName="oneCtrl" required> <div> <button matStepperPrevious>Back</button> <button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step [stepControl]="twoGroup"> <form [formGroup]="twoGroup"> <ng-template matStepLabel>Step two</ng-template> <input formControlName="twoCtrl" required> <div> <button matStepperPrevious>Back</button> <button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step [stepControl]="threeGroup" optional> <form [formGroup]="threeGroup"> <ng-template matStepLabel>Step two</ng-template> <input formControlName="threeCtrl"> <div> <button matStepperPrevious>Back</button> <button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step> Done </mat-step> </mat-stepper> `, imports: [ReactiveFormsModule, MatStepperModule], }) class LinearMatVerticalStepperApp { validationTrigger = new Subject<void>(); oneGroup = new FormGroup({ oneCtrl: new FormControl('', Validators.required), }); twoGroup = new FormGroup({ twoCtrl: new FormControl('', Validators.required, asyncValidator(3, this.validationTrigger)), }); threeGroup = new FormGroup({ threeCtrl: new FormControl('', Validators.pattern(VALID_REGEX)), }); } @Component({ template: ` <mat-stepper [linear]="true" [selectedIndex]="index"> <mat-step label="One"></mat-step> <mat-step label="Two"></mat-step> <mat-step label="Three"></mat-step> </mat-stepper> `, standalone: false, }) class SimplePreselectedMatHorizontalStepperApp { index = 0; } @Component({ template: ` <mat-stepper linear> @for (step of steps; track step) { <mat-step [label]="step.label" [completed]="step.completed"></mat-step> } </mat-stepper> `, standalone: false, }) class SimpleStepperWithoutStepControl { steps = [ {label: 'One', completed: false}, {label: 'Two', completed: false}, {label: 'Three', completed: false}, ]; } @Component({ template: ` <mat-stepper linear> @for (step of steps; track step) { <mat-step [label]="step.label" [stepControl]="step.control" [completed]="step.completed"></mat-step> } </mat-stepper> `, standalone: false, }) class SimpleStepperWithStepControlAndCompletedBinding { steps = [ {label: 'One', completed: false, control: new FormControl('')}, {label: 'Two', completed: false, control: new FormControl('')}, {label: 'Three', completed: false, control: new FormControl('')}, ]; } @Component({ template: ` <mat-stepper> <ng-template matStepperIcon="edit">Custom edit</ng-template> <ng-template matStepperIcon="done">Custom done</ng-template> <ng-template matStepperIcon="number" let-index="index"> {{getRomanNumeral(index + 1)}} </ng-template> <mat-step>Content 1</mat-step> <mat-step>Content 2</mat-step> <mat-step>Content 3</mat-step> </mat-stepper> `, standalone: false, }) class IconOverridesStepper { getRomanNumeral(value: number) { const numberMap: {[key: number]: string} = { 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX', }; return numberMap[value]; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 73021, "start_byte": 65626, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.spec.ts_73023_77376
@Component({ template: ` <mat-stepper> @if (true) { <ng-template matStepperIcon="edit">Custom edit</ng-template> <ng-template matStepperIcon="done">Custom done</ng-template> <ng-template matStepperIcon="number" let-index="index"> {{getRomanNumeral(index + 1)}} </ng-template> } <mat-step>Content 1</mat-step> <mat-step>Content 2</mat-step> <mat-step>Content 3</mat-step> </mat-stepper> `, standalone: false, }) class IndirectDescendantIconOverridesStepper extends IconOverridesStepper {} @Component({ template: ` <mat-stepper linear> <mat-step label="Step 1" [stepControl]="controls[0]"></mat-step> <mat-step label="Step 2" [stepControl]="controls[1]" [optional]="step2Optional"></mat-step> <mat-step label="Step 3" [stepControl]="controls[2]"></mat-step> </mat-stepper> `, standalone: false, }) class LinearStepperWithValidOptionalStep { controls = [0, 0, 0].map(() => new FormControl('')); step2Optional = signal(false); } @Component({ template: ` <mat-stepper> <mat-step [aria-label]="ariaLabel()" [aria-labelledby]="ariaLabelledby()" label="One"></mat-step> </mat-stepper> `, standalone: false, }) class StepperWithAriaInputs { ariaLabel = signal(''); ariaLabelledby = signal(''); } @Component({ template: ` <mat-stepper orientation="vertical"> @if (true) { <mat-step label="Step 1">Content 1</mat-step> <mat-step label="Step 2">Content 2</mat-step> <mat-step label="Step 3">Content 3</mat-step> } </mat-stepper> `, standalone: false, }) class StepperWithIndirectDescendantSteps {} @Component({ template: ` <mat-stepper orientation="vertical"> <mat-step> <ng-template matStepLabel>Step 1</ng-template> </mat-step> @if (showStep2()) { <mat-step> <ng-template matStepLabel>Step 2</ng-template> </mat-step> } </mat-stepper> `, standalone: false, }) class StepperWithNgIf { showStep2 = signal(false); } @Component({ template: ` <mat-stepper orientation="vertical"> <mat-step label="Step 1">Content 1</mat-step> <mat-step label="Step 2">Content 2</mat-step> <mat-step label="Step 3"> <mat-stepper> <mat-step label="Sub-Step 1">Sub-Content 1</mat-step> <mat-step label="Sub-Step 2">Sub-Content 2</mat-step> </mat-stepper> </mat-step> </mat-stepper> `, standalone: false, }) class NestedSteppers { @ViewChildren(MatStepper) steppers: QueryList<MatStepper>; } @Component({ template: ` <mat-stepper orientation="vertical" selectedIndex="1337"> <mat-step label="Step 1">Content 1</mat-step> <mat-step label="Step 2">Content 2</mat-step> <mat-step label="Step 3">Content 3</mat-step> </mat-stepper> `, standalone: false, }) class StepperWithStaticOutOfBoundsIndex { @ViewChild(MatStepper) stepper: MatStepper; } @Component({ template: ` <mat-stepper orientation="vertical" [selectedIndex]="selectedIndex()"> <mat-step> <ng-template matStepLabel>Step 1</ng-template> <ng-template matStepContent>Step 1 content</ng-template> </mat-step> <mat-step> <ng-template matStepLabel>Step 2</ng-template> <ng-template matStepContent>Step 2 content</ng-template> </mat-step> <mat-step> <ng-template matStepLabel>Step 3</ng-template> <ng-template matStepContent>Step 3 content</ng-template> </mat-step> </mat-stepper> `, standalone: false, }) class StepperWithLazyContent { selectedIndex = signal(0); } @Component({ template: ` <mat-stepper> <mat-step label="Step 1">Content 1</mat-step> @if (renderSecondStep()) { <mat-step label="Step 2">Content 2</mat-step> } <mat-step label="Step 3">Content 3</mat-step> </mat-stepper> `, standalone: false, }) class HorizontalStepperWithDelayedStep { renderSecondStep = signal(false); } @Component({ template: ` <mat-stepper [(selectedIndex)]="index"> <mat-step label="One"></mat-step> <mat-step label="Two"></mat-step> <mat-step label="Three"></mat-step> </mat-stepper> `, standalone: false, }) class StepperWithTwoWayBindingOnSelectedIndex { index: number = 0; }
{ "commit_id": "ea0d1ba7b", "end_byte": 77376, "start_byte": 73023, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.spec.ts" }
components/src/material/stepper/stepper.ts_0_4057
/** * @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 {CdkStep, CdkStepper, StepContentPositionState} from '@angular/cdk/stepper'; import {AnimationEvent} from '@angular/animations'; import { AfterContentInit, ChangeDetectionStrategy, Component, ContentChild, ContentChildren, ElementRef, EventEmitter, inject, Input, OnDestroy, Output, QueryList, TemplateRef, ViewChildren, ViewContainerRef, ViewEncapsulation, } from '@angular/core'; import {AbstractControl, FormGroupDirective, NgForm} from '@angular/forms'; import {ErrorStateMatcher, ThemePalette} from '@angular/material/core'; import {CdkPortalOutlet, TemplatePortal} from '@angular/cdk/portal'; import {Subject, Subscription} from 'rxjs'; import {takeUntil, map, startWith, switchMap} from 'rxjs/operators'; import {MatStepHeader} from './step-header'; import {MatStepLabel} from './step-label'; import { DEFAULT_HORIZONTAL_ANIMATION_DURATION, DEFAULT_VERTICAL_ANIMATION_DURATION, matStepperAnimations, } from './stepper-animations'; import {MatStepperIcon, MatStepperIconContext} from './stepper-icon'; import {MatStepContent} from './step-content'; import {NgTemplateOutlet} from '@angular/common'; import {Platform} from '@angular/cdk/platform'; @Component({ selector: 'mat-step', templateUrl: 'step.html', providers: [ {provide: ErrorStateMatcher, useExisting: MatStep}, {provide: CdkStep, useExisting: MatStep}, ], encapsulation: ViewEncapsulation.None, exportAs: 'matStep', changeDetection: ChangeDetectionStrategy.OnPush, imports: [CdkPortalOutlet], host: { 'hidden': '', // Hide the steps so they don't affect the layout. }, }) export class MatStep extends CdkStep implements ErrorStateMatcher, AfterContentInit, OnDestroy { private _errorStateMatcher = inject(ErrorStateMatcher, {skipSelf: true}); private _viewContainerRef = inject(ViewContainerRef); private _isSelected = Subscription.EMPTY; /** Content for step label given by `<ng-template matStepLabel>`. */ // We need an initializer here to avoid a TS error. @ContentChild(MatStepLabel) override stepLabel: MatStepLabel = undefined!; /** * Theme color for the particular step. This API is supported in M2 themes * only, it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: ThemePalette; /** Content that will be rendered lazily. */ @ContentChild(MatStepContent, {static: false}) _lazyContent: MatStepContent; /** Currently-attached portal containing the lazy content. */ _portal: TemplatePortal; ngAfterContentInit() { this._isSelected = this._stepper.steps.changes .pipe( switchMap(() => { return this._stepper.selectionChange.pipe( map(event => event.selectedStep === this), startWith(this._stepper.selected === this), ); }), ) .subscribe(isSelected => { if (isSelected && this._lazyContent && !this._portal) { this._portal = new TemplatePortal(this._lazyContent._template, this._viewContainerRef!); } }); } ngOnDestroy() { this._isSelected.unsubscribe(); } /** Custom error state matcher that additionally checks for validity of interacted form. */ isErrorState(control: AbstractControl | null, form: FormGroupDirective | NgForm | null): boolean { const originalErrorState = this._errorStateMatcher.isErrorState(control, form); // Custom error state checks for the validity of form that is not submitted or touched // since user can trigger a form change by calling for another step without directly // interacting with the current form. const customErrorState = !!(control && control.invalid && this.interacted); return originalErrorState || customErrorState; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 4057, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.ts" }
components/src/material/stepper/stepper.ts_4059_8963
@Component({ selector: 'mat-stepper, mat-vertical-stepper, mat-horizontal-stepper, [matStepper]', exportAs: 'matStepper, matVerticalStepper, matHorizontalStepper', templateUrl: 'stepper.html', styleUrl: 'stepper.css', host: { '[class.mat-stepper-horizontal]': 'orientation === "horizontal"', '[class.mat-stepper-vertical]': 'orientation === "vertical"', '[class.mat-stepper-label-position-end]': 'orientation === "horizontal" && labelPosition == "end"', '[class.mat-stepper-label-position-bottom]': 'orientation === "horizontal" && labelPosition == "bottom"', '[class.mat-stepper-header-position-bottom]': 'headerPosition === "bottom"', '[attr.aria-orientation]': 'orientation', 'role': 'tablist', }, animations: [ matStepperAnimations.horizontalStepTransition, matStepperAnimations.verticalStepTransition, ], providers: [{provide: CdkStepper, useExisting: MatStepper}], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, imports: [NgTemplateOutlet, MatStepHeader], }) export class MatStepper extends CdkStepper implements AfterContentInit { /** The list of step headers of the steps in the stepper. */ // We need an initializer here to avoid a TS error. @ViewChildren(MatStepHeader) override _stepHeader: QueryList<MatStepHeader> = undefined as unknown as QueryList<MatStepHeader>; /** Full list of steps inside the stepper, including inside nested steppers. */ // We need an initializer here to avoid a TS error. @ContentChildren(MatStep, {descendants: true}) override _steps: QueryList<MatStep> = undefined as unknown as QueryList<MatStep>; /** Steps that belong to the current stepper, excluding ones from nested steppers. */ override readonly steps: QueryList<MatStep> = new QueryList<MatStep>(); /** Custom icon overrides passed in by the consumer. */ @ContentChildren(MatStepperIcon, {descendants: true}) _icons: QueryList<MatStepperIcon>; /** Event emitted when the current step is done transitioning in. */ @Output() readonly animationDone: EventEmitter<void> = new EventEmitter<void>(); /** Whether ripples should be disabled for the step headers. */ @Input() disableRipple: boolean; /** * Theme color for all of the steps in stepper. This API is supported in M2 * themes only, it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: ThemePalette; /** * Whether the label should display in bottom or end position. * Only applies in the `horizontal` orientation. */ @Input() labelPosition: 'bottom' | 'end' = 'end'; /** * Position of the stepper's header. * Only applies in the `horizontal` orientation. */ @Input() headerPosition: 'top' | 'bottom' = 'top'; /** Consumer-specified template-refs to be used to override the header icons. */ _iconOverrides: Record<string, TemplateRef<MatStepperIconContext>> = {}; /** Stream of animation `done` events when the body expands/collapses. */ readonly _animationDone = new Subject<AnimationEvent>(); /** Duration for the animation. Will be normalized to milliseconds if no units are set. */ @Input() get animationDuration(): string { return this._animationDuration; } set animationDuration(value: string) { this._animationDuration = /^\d+$/.test(value) ? value + 'ms' : value; } private _animationDuration = ''; /** Whether the stepper is rendering on the server. */ protected _isServer: boolean = !inject(Platform).isBrowser; constructor(...args: unknown[]); constructor() { super(); const elementRef = inject<ElementRef<HTMLElement>>(ElementRef); const nodeName = elementRef.nativeElement.nodeName.toLowerCase(); this.orientation = nodeName === 'mat-vertical-stepper' ? 'vertical' : 'horizontal'; } override ngAfterContentInit() { super.ngAfterContentInit(); this._icons.forEach(({name, templateRef}) => (this._iconOverrides[name] = templateRef)); // Mark the component for change detection whenever the content children query changes this.steps.changes.pipe(takeUntil(this._destroyed)).subscribe(() => { this._stateChanged(); }); this._animationDone.pipe(takeUntil(this._destroyed)).subscribe(event => { if ((event.toState as StepContentPositionState) === 'current') { this.animationDone.emit(); } }); } _stepIsNavigable(index: number, step: MatStep): boolean { return step.completed || this.selectedIndex === index || !this.linear; } _getAnimationDuration() { if (this.animationDuration) { return this.animationDuration; } return this.orientation === 'horizontal' ? DEFAULT_HORIZONTAL_ANIMATION_DURATION : DEFAULT_VERTICAL_ANIMATION_DURATION; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 8963, "start_byte": 4059, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper.ts" }
components/src/material/stepper/stepper-animations.ts_0_2451
/** * @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 { animate, state, style, transition, trigger, AnimationTriggerMetadata, group, query, animateChild, } from '@angular/animations'; export const DEFAULT_HORIZONTAL_ANIMATION_DURATION = '500ms'; export const DEFAULT_VERTICAL_ANIMATION_DURATION = '225ms'; /** * Animations used by the Material steppers. * @docs-private */ export const matStepperAnimations: { readonly horizontalStepTransition: AnimationTriggerMetadata; readonly verticalStepTransition: AnimationTriggerMetadata; } = { /** Animation that transitions the step along the X axis in a horizontal stepper. */ horizontalStepTransition: trigger('horizontalStepTransition', [ state('previous', style({transform: 'translate3d(-100%, 0, 0)', visibility: 'hidden'})), // Transition to `inherit`, rather than `visible`, // because visibility on a child element the one from the parent, // making this element focusable inside of a `hidden` element. state('current', style({transform: 'none', visibility: 'inherit'})), state('next', style({transform: 'translate3d(100%, 0, 0)', visibility: 'hidden'})), transition( '* => *', group([ animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)'), query('@*', animateChild(), {optional: true}), ]), { params: {'animationDuration': DEFAULT_HORIZONTAL_ANIMATION_DURATION}, }, ), ]), /** Animation that transitions the step along the Y axis in a vertical stepper. */ verticalStepTransition: trigger('verticalStepTransition', [ state('previous', style({height: '0px', visibility: 'hidden'})), state('next', style({height: '0px', visibility: 'hidden'})), // Transition to `inherit`, rather than `visible`, // because visibility on a child element the one from the parent, // making this element focusable inside of a `hidden` element. state('current', style({height: '*', visibility: 'inherit'})), transition( '* <=> current', group([ animate('{{animationDuration}} cubic-bezier(0.4, 0.0, 0.2, 1)'), query('@*', animateChild(), {optional: true}), ]), { params: {'animationDuration': DEFAULT_VERTICAL_ANIMATION_DURATION}, }, ), ]), };
{ "commit_id": "ea0d1ba7b", "end_byte": 2451, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/stepper-animations.ts" }
components/src/material/stepper/step-label.ts_0_393
/** * @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 {Directive} from '@angular/core'; import {CdkStepLabel} from '@angular/cdk/stepper'; @Directive({ selector: '[matStepLabel]', }) export class MatStepLabel extends CdkStepLabel {}
{ "commit_id": "ea0d1ba7b", "end_byte": 393, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/step-label.ts" }
components/src/material/stepper/testing/stepper-button-harnesses.ts_0_2436
/** * @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, HarnessPredicate} from '@angular/cdk/testing'; import {StepperButtonHarnessFilters} from './step-harness-filters'; /** Base class for stepper button harnesses. */ abstract class StepperButtonHarness extends ComponentHarness { /** Gets the text of the button. */ async getText(): Promise<string> { return (await this.host()).text(); } /** Clicks the button. */ async click(): Promise<void> { return (await this.host()).click(); } } /** Harness for interacting with a standard Angular Material stepper next button in tests. */ export class MatStepperNextHarness extends StepperButtonHarness { /** The selector for the host element of a `MatStep` instance. */ static hostSelector = '.mat-stepper-next'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatStepperNextHarness` that meets * certain criteria. * @param options Options for filtering which steps are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: StepperButtonHarnessFilters = {}): HarnessPredicate<MatStepperNextHarness> { return new HarnessPredicate(MatStepperNextHarness, options).addOption( 'text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ); } } /** Harness for interacting with a standard Angular Material stepper previous button in tests. */ export class MatStepperPreviousHarness extends StepperButtonHarness { /** The selector for the host element of a `MatStep` instance. */ static hostSelector = '.mat-stepper-previous'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatStepperPreviousHarness` * that meets certain criteria. * @param options Options for filtering which steps are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with( options: StepperButtonHarnessFilters = {}, ): HarnessPredicate<MatStepperPreviousHarness> { return new HarnessPredicate(MatStepperPreviousHarness, options).addOption( 'text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2436, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/stepper-button-harnesses.ts" }
components/src/material/stepper/testing/stepper-harness.ts_0_2299
/** * @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, HarnessPredicate} from '@angular/cdk/testing'; import {MatStepHarness} from './step-harness'; import { StepperHarnessFilters, StepHarnessFilters, StepperOrientation, } from './step-harness-filters'; /** Harness for interacting with a standard Material stepper in tests. */ export class MatStepperHarness extends ComponentHarness { /** The selector for the host element of a `MatStepper` instance. */ static hostSelector = '.mat-stepper-horizontal, .mat-stepper-vertical'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatStepperHarness` that meets * certain criteria. * @param options Options for filtering which stepper instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: StepperHarnessFilters = {}): HarnessPredicate<MatStepperHarness> { return new HarnessPredicate(MatStepperHarness, options).addOption( 'orientation', options.orientation, async (harness, orientation) => (await harness.getOrientation()) === orientation, ); } /** * Gets the list of steps in the stepper. * @param filter Optionally filters which steps are included. */ async getSteps(filter: StepHarnessFilters = {}): Promise<MatStepHarness[]> { return this.locatorForAll(MatStepHarness.with(filter))(); } /** Gets the orientation of the stepper. */ async getOrientation(): Promise<StepperOrientation> { const host = await this.host(); return (await host.hasClass('mat-stepper-horizontal')) ? StepperOrientation.HORIZONTAL : StepperOrientation.VERTICAL; } /** * Selects a step in this stepper. * @param filter An optional filter to apply to the child steps. The first step matching the * filter will be selected. */ async selectStep(filter: StepHarnessFilters = {}): Promise<void> { const steps = await this.getSteps(filter); if (!steps.length) { throw Error(`Cannot find mat-step matching filter ${JSON.stringify(filter)}`); } await steps[0].select(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2299, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/stepper-harness.ts" }
components/src/material/stepper/testing/public-api.ts_0_355
/** * @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 './stepper-harness'; export * from './step-harness'; export * from './step-harness-filters'; export * from './stepper-button-harnesses';
{ "commit_id": "ea0d1ba7b", "end_byte": 355, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/public-api.ts" }
components/src/material/stepper/testing/stepper-harness.spec.ts_0_728
import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ReactiveFormsModule, FormGroup, FormControl, Validators} from '@angular/forms'; import {HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatStepperModule} from '@angular/material/stepper'; import {STEPPER_GLOBAL_OPTIONS} from '@angular/cdk/stepper'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatStepperHarness} from './stepper-harness'; import {MatStepperNextHarness, MatStepperPreviousHarness} from './stepper-button-harnesses'; import {StepperOrientation} from './step-harness-filters';
{ "commit_id": "ea0d1ba7b", "end_byte": 728, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/stepper-harness.spec.ts" }
components/src/material/stepper/testing/stepper-harness.spec.ts_730_8969
describe('MatStepperHarness', () => { let fixture: ComponentFixture<StepperHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatStepperModule, NoopAnimationsModule, ReactiveFormsModule, StepperHarnessTest], providers: [ { provide: STEPPER_GLOBAL_OPTIONS, useValue: {showError: true}, // Required so the error state shows up in tests. }, ], }); fixture = TestBed.createComponent(StepperHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all stepper harnesses', async () => { const steppers = await loader.getAllHarnesses(MatStepperHarness); expect(steppers.length).toBe(3); }); it('should filter steppers by their orientation', async () => { const [verticalSteppers, horizontalSteppers] = await parallel(() => [ loader.getAllHarnesses(MatStepperHarness.with({orientation: StepperOrientation.VERTICAL})), loader.getAllHarnesses(MatStepperHarness.with({orientation: StepperOrientation.HORIZONTAL})), ]); expect(verticalSteppers.length).toBe(2); expect(horizontalSteppers.length).toBe(1); }); it('should get the orientation of a stepper', async () => { const steppers = await loader.getAllHarnesses(MatStepperHarness); expect(await parallel(() => steppers.map(stepper => stepper.getOrientation()))).toEqual([ StepperOrientation.VERTICAL, StepperOrientation.HORIZONTAL, StepperOrientation.VERTICAL, ]); }); it('should get the steps of a stepper', async () => { const steppers = await loader.getAllHarnesses(MatStepperHarness); const steps = await parallel(() => steppers.map(stepper => stepper.getSteps())); expect(steps.map(current => current.length)).toEqual([4, 3, 2]); }); it('should filter the steps of a stepper', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps({label: /Two|Four/}); expect(await parallel(() => steps.map(step => step.getLabel()))).toEqual(['Two', 'Four']); }); it('should be able to select a particular step that matches a filter', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ true, false, false, false, ]); await stepper.selectStep({label: 'Three'}); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ false, false, true, false, ]); }); it('should be able to get the text-based label of a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.getLabel()))).toEqual([ 'One', 'Two', 'Three', 'Four', ]); }); it('should be able to get the template-based label of a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#two-stepper'})); const steps = await stepper.getSteps(); expect( await parallel(() => { return steps.map(step => step.getLabel()); }), ).toEqual(['One', 'Two', 'Three']); }); it('should be able to get the aria-label of a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.getAriaLabel()))).toEqual([ null, null, null, 'Fourth step', ]); }); it('should be able to get the aria-labelledby of a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.getAriaLabelledby()))).toEqual([ null, null, 'some-label', null, ]); }); it('should get the selected state of a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ true, false, false, false, ]); }); it('should be able to select a step', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ true, false, false, false, ]); await steps[2].select(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ false, false, true, false, ]); }); it('should get whether a step is optional', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#two-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.isOptional()))).toEqual([false, true, true]); }); it('should be able to get harness loader for an element inside a tab', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const [step] = await stepper.getSteps({label: 'Two'}); const [nextButton, previousButton] = await parallel(() => [ step.getHarness(MatStepperNextHarness), step.getHarness(MatStepperPreviousHarness), ]); expect(await nextButton.getText()).toBe('Next'); expect(await previousButton.getText()).toBe('Previous'); }); it('should go forward when pressing the next button', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); const secondStep = steps[1]; const nextButton = await secondStep.getHarness(MatStepperNextHarness); await secondStep.select(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ false, true, false, false, ]); await nextButton.click(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ false, false, true, false, ]); }); it('should go backward when pressing the previous button', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#one-stepper'})); const steps = await stepper.getSteps(); const secondStep = steps[1]; const previousButton = await secondStep.getHarness(MatStepperPreviousHarness); await secondStep.select(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ false, true, false, false, ]); await previousButton.click(); expect(await parallel(() => steps.map(step => step.isSelected()))).toEqual([ true, false, false, false, ]); }); it('should get whether a step has errors', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#three-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.hasErrors()))).toEqual([false, false]); await steps[1].select(); expect(await parallel(() => steps.map(step => step.hasErrors()))).toEqual([true, false]); }); it('should get whether a step has been completed', async () => { const stepper = await loader.getHarness(MatStepperHarness.with({selector: '#three-stepper'})); const steps = await stepper.getSteps(); expect(await parallel(() => steps.map(step => step.isCompleted()))).toEqual([false, false]); fixture.componentInstance.oneGroup.setValue({oneCtrl: 'done'}); await steps[1].select(); expect(await parallel(() => steps.map(step => step.isCompleted()))).toEqual([true, false]); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 8969, "start_byte": 730, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/stepper-harness.spec.ts" }
components/src/material/stepper/testing/stepper-harness.spec.ts_8971_10677
@Component({ template: ` <mat-stepper orientation="vertical" id="one-stepper"> <mat-step label="One"> <button matStepperNext>Next</button> </mat-step> <mat-step label="Two"> <button matStepperPrevious>Previous</button> <button matStepperNext>Next</button> </mat-step> <mat-step label="Three" aria-labelledby="some-label"> <button matStepperPrevious>Previous</button> <button matStepperNext>Next</button> </mat-step> <mat-step label="Four" aria-label="Fourth step"> <button matStepperPrevious>Previous</button> </mat-step> </mat-stepper> <mat-stepper id="two-stepper"> <mat-step> <ng-template matStepLabel>One</ng-template> </mat-step> <mat-step optional> <ng-template matStepLabel>Two</ng-template> </mat-step> <mat-step optional> <ng-template matStepLabel>Three</ng-template> </mat-step> </mat-stepper> <mat-stepper orientation="vertical" id="three-stepper"> <mat-step [stepControl]="oneGroup" label="One"> <form [formGroup]="oneGroup"> <input formControlName="oneCtrl" required> </form> </mat-step> <mat-step [stepControl]="twoGroup" label="Two"> <form [formGroup]="twoGroup"> <input formControlName="twoCtrl" required> </form> </mat-step> </mat-stepper> `, standalone: true, imports: [MatStepperModule, ReactiveFormsModule], }) class StepperHarnessTest { oneGroup = new FormGroup({ oneCtrl: new FormControl('', Validators.required), }); twoGroup = new FormGroup({ twoCtrl: new FormControl('', Validators.required), }); }
{ "commit_id": "ea0d1ba7b", "end_byte": 10677, "start_byte": 8971, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/stepper-harness.spec.ts" }
components/src/material/stepper/testing/BUILD.bazel_0_820
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/stepper", "//src/cdk/testing", "//src/cdk/testing/private", "//src/cdk/testing/testbed", "//src/material/stepper", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 820, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/BUILD.bazel" }
components/src/material/stepper/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';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/index.ts" }
components/src/material/stepper/testing/step-harness.ts_0_4554
/** * @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 { ContentContainerComponentHarness, HarnessPredicate, HarnessLoader, } from '@angular/cdk/testing'; import {StepHarnessFilters} from './step-harness-filters'; /** Harness for interacting with a standard Angular Material step in tests. */ export class MatStepHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatStep` instance. */ static hostSelector = '.mat-step-header'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatStepHarness` that meets * certain criteria. * @param options Options for filtering which steps are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: StepHarnessFilters = {}): HarnessPredicate<MatStepHarness> { return new HarnessPredicate(MatStepHarness, options) .addOption('label', options.label, (harness, label) => HarnessPredicate.stringMatches(harness.getLabel(), label), ) .addOption( 'selected', options.selected, async (harness, selected) => (await harness.isSelected()) === selected, ) .addOption( 'completed', options.completed, async (harness, completed) => (await harness.isCompleted()) === completed, ) .addOption( 'invalid', options.invalid, async (harness, invalid) => (await harness.hasErrors()) === invalid, ); } /** Gets the label of the step. */ async getLabel(): Promise<string> { return (await this.locatorFor('.mat-step-text-label')()).text(); } /** Gets the `aria-label` of the step. */ async getAriaLabel(): Promise<string | null> { return (await this.host()).getAttribute('aria-label'); } /** Gets the value of the `aria-labelledby` attribute. */ async getAriaLabelledby(): Promise<string | null> { return (await this.host()).getAttribute('aria-labelledby'); } /** Whether the step is selected. */ async isSelected(): Promise<boolean> { const host = await this.host(); return (await host.getAttribute('aria-selected')) === 'true'; } /** Whether the step has been filled out. */ async isCompleted(): Promise<boolean> { const state = await this._getIconState(); return state === 'done' || (state === 'edit' && !(await this.isSelected())); } /** * Whether the step is currently showing its error state. Note that this doesn't mean that there * are or aren't any invalid form controls inside the step, but that the step is showing its * error-specific styling which depends on there being invalid controls, as well as the * `ErrorStateMatcher` determining that an error should be shown and that the `showErrors` * option was enabled through the `STEPPER_GLOBAL_OPTIONS` injection token. */ async hasErrors(): Promise<boolean> { return (await this._getIconState()) === 'error'; } /** Whether the step is optional. */ async isOptional(): Promise<boolean> { // If the node with the optional text is present, it means that the step is optional. const optionalNode = await this.locatorForOptional('.mat-step-optional')(); return !!optionalNode; } /** * Selects the given step by clicking on the label. The step may not be selected * if the stepper doesn't allow it (e.g. if there are validation errors). */ async select(): Promise<void> { await (await this.host()).click(); } protected override async getRootHarnessLoader(): Promise<HarnessLoader> { const contentId = await (await this.host()).getAttribute('aria-controls'); return this.documentRootLocatorFactory().harnessLoaderFor(`#${contentId}`); } /** * Gets the state of the step. Note that we have a `StepState` which we could use to type the * return value, but it's basically the same as `string`, because the type has `| string`. */ private async _getIconState(): Promise<string> { // The state is exposed on the icon with a class that looks like `mat-step-icon-state-{{state}}` const icon = await this.locatorFor('.mat-step-icon')(); const classes = (await icon.getAttribute('class'))!; const match = classes.match(/mat-step-icon-state-([a-z]+)/); if (!match) { throw Error(`Could not determine step state from "${classes}".`); } return match[1]; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 4554, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/step-harness.ts" }
components/src/material/stepper/testing/step-harness-filters.ts_0_1394
/** * @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'; /** Possible orientations for a stepper. */ export enum StepperOrientation { HORIZONTAL, VERTICAL, } /** A set of criteria that can be used to filter a list of `MatStepHarness` instances. */ export interface StepHarnessFilters extends BaseHarnessFilters { /** Only find instances whose label matches the given value. */ label?: string | RegExp; /** Only find steps with the given selected state. */ selected?: boolean; /** Only find completed steps. */ completed?: boolean; /** Only find steps that have errors. */ invalid?: boolean; } /** A set of criteria that can be used to filter a list of `MatStepperHarness` instances. */ export interface StepperHarnessFilters extends BaseHarnessFilters { /** Only find instances whose orientation matches the given value. */ orientation?: StepperOrientation; } /** * A set of criteria that can be used to filter a list of * `MatStepperNextHarness` and `MatStepperPreviousHarness` instances. */ export interface StepperButtonHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; }
{ "commit_id": "ea0d1ba7b", "end_byte": 1394, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/stepper/testing/step-harness-filters.ts" }
components/src/material/progress-spinner/module.ts_0_531
/** * @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 '@angular/material/core'; import {MatProgressSpinner, MatSpinner} from './progress-spinner'; @NgModule({ imports: [MatProgressSpinner, MatSpinner], exports: [MatProgressSpinner, MatSpinner, MatCommonModule], }) export class MatProgressSpinnerModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 531, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/module.ts" }
components/src/material/progress-spinner/progress-spinner.spec.ts_0_341
import {waitForAsync, TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {Component, ElementRef, ViewChild, ViewEncapsulation, signal} from '@angular/core'; import {MatProgressSpinnerModule} from './module'; import {MatProgressSpinner, MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS} from './progress-spinner';
{ "commit_id": "ea0d1ba7b", "end_byte": 341, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.spec.ts" }
components/src/material/progress-spinner/progress-spinner.spec.ts_343_10353
describe('MatProgressSpinner', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatProgressSpinnerModule, BasicProgressSpinner, IndeterminateProgressSpinner, ProgressSpinnerWithValueAndBoundMode, ProgressSpinnerWithColor, ProgressSpinnerCustomStrokeWidth, ProgressSpinnerCustomDiameter, SpinnerWithColor, ProgressSpinnerWithStringValues, IndeterminateSpinnerInShadowDom, IndeterminateSpinnerInShadowDomWithNgIf, SpinnerWithMode, ], }); })); it('should apply a mode of "determinate" if no mode is provided.', () => { let fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.mode).toBe('determinate'); }); it('should not modify the mode if a valid mode is provided.', () => { let fixture = TestBed.createComponent(IndeterminateProgressSpinner); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.mode).toBe('indeterminate'); }); it('should define a default value of zero for the value attribute', () => { let fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.value).toBe(0); }); it('should set the value to 0 when the mode is set to indeterminate', () => { let fixture = TestBed.createComponent(ProgressSpinnerWithValueAndBoundMode); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; fixture.componentInstance.mode.set('determinate'); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(50); fixture.componentInstance.mode.set('indeterminate'); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(0); }); it('should retain the value if it updates while indeterminate', () => { let fixture = TestBed.createComponent(ProgressSpinnerWithValueAndBoundMode); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; fixture.componentInstance.mode.set('determinate'); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(50); fixture.componentInstance.mode.set('indeterminate'); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(0); fixture.componentInstance.value.set(75); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(0); fixture.componentInstance.mode.set('determinate'); fixture.detectChanges(); expect(progressElement.componentInstance.value).toBe(75); }); it('should clamp the value of the progress between 0 and 100', () => { let fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; let progressComponent = progressElement.componentInstance; progressComponent.value = 50; expect(progressComponent.value).toBe(50); progressComponent.value = 0; expect(progressComponent.value).toBe(0); progressComponent.value = 100; expect(progressComponent.value).toBe(100); progressComponent.value = 999; expect(progressComponent.value).toBe(100); progressComponent.value = -10; expect(progressComponent.value).toBe(0); }); it('should default to a stroke width that is 10% of the diameter', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomDiameter); const spinner = fixture.debugElement.query(By.directive(MatProgressSpinner))!; fixture.componentInstance.diameter = 67; fixture.detectChanges(); expect(spinner.componentInstance.strokeWidth).toBe(6.7); }); it('should allow a custom diameter', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomDiameter); const spinner = fixture.debugElement.query(By.css('mat-progress-spinner'))!.nativeElement; const svgElement = fixture.nativeElement.querySelector('svg'); fixture.componentInstance.diameter = 32; fixture.detectChanges(); expect(parseInt(spinner.style.width)) .withContext('Expected the custom diameter to be applied to the host element width.') .toBe(32); expect(parseInt(spinner.style.height)) .withContext('Expected the custom diameter to be applied to the host element height.') .toBe(32); expect(parseInt(svgElement.clientWidth)) .withContext('Expected the custom diameter to be applied to the svg element width.') .toBe(32); expect(parseInt(svgElement.clientHeight)) .withContext('Expected the custom diameter to be applied to the svg element height.') .toBe(32); expect(svgElement.getAttribute('viewBox')) .withContext('Expected the custom diameter to be applied to the svg viewBox.') .toBe('0 0 25.2 25.2'); }); it('should allow a custom stroke width', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomStrokeWidth); fixture.componentInstance.strokeWidth = 40; fixture.detectChanges(); const circleElement = fixture.nativeElement.querySelector('circle'); const svgElement = fixture.nativeElement.querySelector('svg'); expect(parseInt(circleElement.style.strokeWidth)) .withContext( 'Expected the custom stroke ' + 'width to be applied to the circle element as a percentage of the element size.', ) .toBe(40); expect(svgElement.getAttribute('viewBox')) .withContext('Expected the viewBox to be adjusted based on the stroke width.') .toBe('0 0 130 130'); }); it('should allow floating point values for custom diameter', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomDiameter); fixture.componentInstance.diameter = 32.5; fixture.detectChanges(); const spinner = fixture.debugElement.query(By.css('mat-progress-spinner'))!.nativeElement; const svgElement: HTMLElement = fixture.nativeElement.querySelector('svg'); expect(parseFloat(spinner.style.width)) .withContext('Expected the custom diameter to be applied to the host element width.') .toBe(32.5); expect(parseFloat(spinner.style.height)) .withContext('Expected the custom diameter to be applied to the host element height.') .toBe(32.5); expect(Math.ceil(svgElement.clientWidth)) .withContext('Expected the custom diameter to be applied to the svg element width.') .toBe(33); expect(Math.ceil(svgElement.clientHeight)) .withContext('Expected the custom diameter to be applied to the svg element height.') .toBe(33); expect(svgElement.getAttribute('viewBox')) .withContext('Expected the custom diameter to be applied to the svg viewBox.') .toBe('0 0 25.75 25.75'); }); it('should allow floating point values for custom stroke width', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomStrokeWidth); fixture.componentInstance.strokeWidth = 40.5; fixture.detectChanges(); const circleElement = fixture.nativeElement.querySelector('circle'); const svgElement = fixture.nativeElement.querySelector('svg'); expect(parseFloat(circleElement.style.strokeWidth)) .withContext( 'Expected the custom stroke ' + 'width to be applied to the circle element as a percentage of the element size.', ) .toBe(40.5); expect(svgElement.getAttribute('viewBox')) .withContext('Expected the viewBox to be adjusted based on the stroke width.') .toBe('0 0 130.5 130.5'); }); it('should expand the host element if the stroke width is greater than the default', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomStrokeWidth); const element = fixture.debugElement.nativeElement.querySelector('.mat-mdc-progress-spinner'); fixture.componentInstance.strokeWidth = 40; fixture.detectChanges(); expect(element.style.width).toBe('100px'); expect(element.style.height).toBe('100px'); }); it('should not collapse the host element if the stroke width is less than the default', () => { const fixture = TestBed.createComponent(ProgressSpinnerCustomStrokeWidth); const element = fixture.debugElement.nativeElement.querySelector('.mat-mdc-progress-spinner'); fixture.componentInstance.strokeWidth = 5; fixture.detectChanges(); expect(element.style.width).toBe('100px'); expect(element.style.height).toBe('100px'); }); it('should set the color class on the mat-spinner', () => { let fixture = TestBed.createComponent(SpinnerWithColor); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-spinner'))!; expect(progressElement.nativeElement.classList).toContain('mat-primary'); fixture.componentInstance.color.set('accent'); fixture.detectChanges(); expect(progressElement.nativeElement.classList).toContain('mat-accent'); expect(progressElement.nativeElement.classList).not.toContain('mat-primary'); }); it('should set the color class on the mat-progress-spinner', () => { let fixture = TestBed.createComponent(ProgressSpinnerWithColor); fixture.detectChanges(); let progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.nativeElement.classList).toContain('mat-primary'); fixture.componentInstance.color.set('accent'); fixture.detectChanges(); expect(progressElement.nativeElement.classList).toContain('mat-accent'); expect(progressElement.nativeElement.classList).not.toContain('mat-primary'); });
{ "commit_id": "ea0d1ba7b", "end_byte": 10353, "start_byte": 343, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.spec.ts" }
components/src/material/progress-spinner/progress-spinner.spec.ts_10357_18262
it('should remove the underlying SVG element from the tab order explicitly', () => { const fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('svg').getAttribute('focusable')).toBe('false'); }); it('should handle the number inputs being passed in as strings', () => { const fixture = TestBed.createComponent(ProgressSpinnerWithStringValues); const spinner = fixture.debugElement.query(By.directive(MatProgressSpinner))!; const svgElement = spinner.nativeElement.querySelector('svg'); fixture.detectChanges(); expect(spinner.componentInstance.diameter).toBe(37); expect(spinner.componentInstance.strokeWidth).toBe(11); expect(spinner.componentInstance.value).toBe(25); expect(spinner.nativeElement.style.width).toBe('37px'); expect(spinner.nativeElement.style.height).toBe('37px'); expect(svgElement.clientWidth).toBe(37); expect(svgElement.clientHeight).toBe(37); expect(svgElement.getAttribute('viewBox')).toBe('0 0 38 38'); }); it('should update the element size when changed dynamically', () => { let fixture = TestBed.createComponent(BasicProgressSpinner); let spinner = fixture.debugElement.query(By.directive(MatProgressSpinner))!; spinner.componentInstance.diameter = 32; fixture.detectChanges(); expect(spinner.nativeElement.style.width).toBe('32px'); expect(spinner.nativeElement.style.height).toBe('32px'); }); it('should be able to set a default diameter', () => { TestBed.resetTestingModule().configureTestingModule({ imports: [MatProgressSpinnerModule, BasicProgressSpinner], providers: [ { provide: MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS, useValue: {diameter: 23}, }, ], }); const fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); const progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.diameter).toBe(23); }); it('should be able to set a default stroke width', () => { TestBed.resetTestingModule().configureTestingModule({ imports: [MatProgressSpinnerModule, BasicProgressSpinner], providers: [ { provide: MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS, useValue: {strokeWidth: 7}, }, ], }); const fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); const progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.strokeWidth).toBe(7); }); it('should be able to set a default color', () => { TestBed.resetTestingModule().configureTestingModule({ imports: [MatProgressSpinnerModule, BasicProgressSpinner], providers: [ { provide: MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS, useValue: {color: 'warn'}, }, ], }); const fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); const progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; expect(progressElement.componentInstance.color).toBe('warn'); expect(progressElement.nativeElement.classList).toContain('mat-warn'); }); it('should set `aria-valuenow` to the current value in determinate mode', () => { const fixture = TestBed.createComponent(ProgressSpinnerWithValueAndBoundMode); const progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; fixture.componentInstance.mode.set('determinate'); fixture.componentInstance.value.set(37); fixture.detectChanges(); expect(progressElement.nativeElement.getAttribute('aria-valuenow')).toBe('37'); }); it('should clear `aria-valuenow` in indeterminate mode', () => { const fixture = TestBed.createComponent(ProgressSpinnerWithValueAndBoundMode); const progressElement = fixture.debugElement.query(By.css('mat-progress-spinner'))!; fixture.componentInstance.mode.set('determinate'); fixture.componentInstance.value.set(89); fixture.detectChanges(); expect(progressElement.nativeElement.hasAttribute('aria-valuenow')).toBe(true); fixture.componentInstance.mode.set('indeterminate'); fixture.detectChanges(); expect(progressElement.nativeElement.hasAttribute('aria-valuenow')).toBe(false); }); it('should apply aria-hidden to child nodes', () => { const fixture = TestBed.createComponent(BasicProgressSpinner); fixture.detectChanges(); const progressElement = fixture.nativeElement.querySelector('mat-progress-spinner'); const children = Array.from<HTMLElement>(progressElement.children); expect(children.length).toBeGreaterThan(0); expect(children.every(child => child.getAttribute('aria-hidden') === 'true')).toBe(true); }); it('should be able to change the mode on a mat-spinner', () => { const fixture = TestBed.createComponent(SpinnerWithMode); fixture.detectChanges(); const progressElement = fixture.debugElement.query(By.css('mat-spinner')).nativeElement; expect(progressElement.getAttribute('mode')).toBe('determinate'); }); }); @Component({ template: '<mat-progress-spinner></mat-progress-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class BasicProgressSpinner {} @Component({ template: '<mat-progress-spinner [strokeWidth]="strokeWidth"></mat-progress-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerCustomStrokeWidth { strokeWidth: number; } @Component({ template: '<mat-progress-spinner [diameter]="diameter"></mat-progress-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerCustomDiameter { diameter: number; } @Component({ template: '<mat-progress-spinner mode="indeterminate"></mat-progress-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class IndeterminateProgressSpinner {} @Component({ template: '<mat-progress-spinner [value]="value()" [mode]="mode()"></mat-progress-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerWithValueAndBoundMode { mode = signal('indeterminate'); value = signal(50); } @Component({ template: ` <mat-spinner [color]="color()"></mat-spinner>`, standalone: true, imports: [MatProgressSpinnerModule], }) class SpinnerWithColor { color = signal('primary'); } @Component({ template: ` <mat-progress-spinner value="50" [color]="color()"></mat-progress-spinner>`, standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerWithColor { color = signal('primary'); } @Component({ template: ` <mat-progress-spinner value="25" diameter="37" strokeWidth="11"></mat-progress-spinner> `, standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerWithStringValues {} @Component({ template: ` <mat-progress-spinner mode="indeterminate" [diameter]="diameter"></mat-progress-spinner> `, encapsulation: ViewEncapsulation.ShadowDom, standalone: true, imports: [MatProgressSpinnerModule], }) class IndeterminateSpinnerInShadowDom { diameter: number; } @Component({ template: ` @if (true) { <div> <mat-progress-spinner mode="indeterminate" [diameter]="diameter"></mat-progress-spinner> </div> } `, encapsulation: ViewEncapsulation.ShadowDom, standalone: true, imports: [MatProgressSpinnerModule], }) class IndeterminateSpinnerInShadowDomWithNgIf { @ViewChild(MatProgressSpinner, {read: ElementRef}) spinner: ElementRef<HTMLElement>; diameter: number; } @Component({ template: '<mat-spinner mode="determinate"></mat-spinner>', standalone: true, imports: [MatProgressSpinnerModule], }) class SpinnerWithMode {}
{ "commit_id": "ea0d1ba7b", "end_byte": 18262, "start_byte": 10357, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.spec.ts" }
components/src/material/progress-spinner/public-api.ts_0_266
/** * @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 './progress-spinner'; export * from './module';
{ "commit_id": "ea0d1ba7b", "end_byte": 266, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/public-api.ts" }
components/src/material/progress-spinner/README.md_0_107
Please see the official documentation at https://material.angular.io/components/component/progress-spinner
{ "commit_id": "ea0d1ba7b", "end_byte": 107, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/README.md" }
components/src/material/progress-spinner/_progress-spinner-theme.scss_0_4340
@use '../core/style/sass-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mdc/circular-progress' as tokens-mdc-circular-progress; /// Outputs base theme styles (styles not dependent on the color, typography, or density settings) /// for the mat-progress-spinner. /// @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 { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-unthemable-tokens() ); } } } /// Outputs color theme styles for the mat-progress-spinner. /// @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 spinner: primary, secondary, tertiary, /// or error (If not specified, default primary 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-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-color-tokens($theme, primary) ); .mat-accent { @include token-utils.create-token-values( tokens-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-color-tokens($theme, accent) ); } .mat-warn { @include token-utils.create-token-values( tokens-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-color-tokens($theme, warn) ); } } } } /// Outputs typography theme styles for the mat-progress-spinner. /// @param {Map} $theme The theme to generate typography styles for. @mixin typography($theme) { } /// Outputs density theme styles for the mat-progress-spinner. /// @param {Map} $theme The theme to generate density styles for. @mixin density($theme) { } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mdc-circular-progress.$prefix, tokens: tokens-mdc-circular-progress.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-progress-spinner. /// @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 spinner: primary, secondary, tertiary, /// or error (If not specified, default primary color will be used). @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-progress-spinner') { @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' ); $mdc-circular-progress-tokens: token-utils.get-tokens-for( $tokens, tokens-mdc-circular-progress.$prefix, $options... ); @include token-utils.create-token-values( tokens-mdc-circular-progress.$prefix, $mdc-circular-progress-tokens ); }
{ "commit_id": "ea0d1ba7b", "end_byte": 4340, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/_progress-spinner-theme.scss" }
components/src/material/progress-spinner/progress-spinner.ts_0_7044
/** * @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, ElementRef, InjectionToken, Input, ViewChild, ViewEncapsulation, numberAttribute, ANIMATION_MODULE_TYPE, inject, } from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {NgTemplateOutlet} from '@angular/common'; /** Possible mode for a progress spinner. */ export type ProgressSpinnerMode = 'determinate' | 'indeterminate'; /** Default `mat-progress-spinner` options that can be overridden. */ export interface MatProgressSpinnerDefaultOptions { /** * Default theme color of the progress spinner. This API is supported in M2 themes only, it * has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ color?: ThemePalette; /** Diameter of the spinner. */ diameter?: number; /** Width of the spinner's stroke. */ strokeWidth?: number; /** * Whether the animations should be force to be enabled, ignoring if the current environment is * using NoopAnimationsModule. */ _forceAnimations?: boolean; } /** Injection token to be used to override the default options for `mat-progress-spinner`. */ export const MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS = new InjectionToken<MatProgressSpinnerDefaultOptions>('mat-progress-spinner-default-options', { providedIn: 'root', factory: MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS_FACTORY, }); /** @docs-private */ export function MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS_FACTORY(): MatProgressSpinnerDefaultOptions { return {diameter: BASE_SIZE}; } /** * Base reference size of the spinner. */ const BASE_SIZE = 100; /** * Base reference stroke width of the spinner. */ const BASE_STROKE_WIDTH = 10; @Component({ selector: 'mat-progress-spinner, mat-spinner', exportAs: 'matProgressSpinner', host: { 'role': 'progressbar', 'class': 'mat-mdc-progress-spinner mdc-circular-progress', // set tab index to -1 so screen readers will read the aria-label // Note: there is a known issue with JAWS that does not read progressbar aria labels on FireFox 'tabindex': '-1', '[class]': '"mat-" + color', '[class._mat-animation-noopable]': `_noopAnimations`, '[class.mdc-circular-progress--indeterminate]': 'mode === "indeterminate"', '[style.width.px]': 'diameter', '[style.height.px]': 'diameter', '[style.--mdc-circular-progress-size]': 'diameter + "px"', '[style.--mdc-circular-progress-active-indicator-width]': 'diameter + "px"', '[attr.aria-valuemin]': '0', '[attr.aria-valuemax]': '100', '[attr.aria-valuenow]': 'mode === "determinate" ? value : null', '[attr.mode]': 'mode', }, templateUrl: 'progress-spinner.html', styleUrl: 'progress-spinner.css', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [NgTemplateOutlet], }) export class MatProgressSpinner { readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); /** Whether the _mat-animation-noopable class should be applied, disabling animations. */ _noopAnimations: boolean; // TODO: should be typed as `ThemePalette` but internal apps pass in arbitrary strings. /** * Theme color of the progress spinner. This API is supported in M2 themes only, it * has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() get color() { return this._color || this._defaultColor; } set color(value: string | null | undefined) { this._color = value; } private _color: string | null | undefined; private _defaultColor: ThemePalette = 'primary'; /** The element of the determinate spinner. */ @ViewChild('determinateSpinner') _determinateCircle: ElementRef<HTMLElement>; constructor(...args: unknown[]); constructor() { const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); const defaults = inject<MatProgressSpinnerDefaultOptions>(MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS); this._noopAnimations = animationMode === 'NoopAnimations' && !!defaults && !defaults._forceAnimations; this.mode = this._elementRef.nativeElement.nodeName.toLowerCase() === 'mat-spinner' ? 'indeterminate' : 'determinate'; if (defaults) { if (defaults.color) { this.color = this._defaultColor = defaults.color; } if (defaults.diameter) { this.diameter = defaults.diameter; } if (defaults.strokeWidth) { this.strokeWidth = defaults.strokeWidth; } } } /** * Mode of the progress bar. * * Input must be one of these values: determinate, indeterminate, buffer, query, defaults to * 'determinate'. * Mirrored to mode attribute. */ @Input() mode: ProgressSpinnerMode; /** Value of the progress bar. Defaults to zero. Mirrored to aria-valuenow. */ @Input({transform: numberAttribute}) get value(): number { return this.mode === 'determinate' ? this._value : 0; } set value(v: number) { this._value = Math.max(0, Math.min(100, v || 0)); } private _value = 0; /** The diameter of the progress spinner (will set width and height of svg). */ @Input({transform: numberAttribute}) get diameter(): number { return this._diameter; } set diameter(size: number) { this._diameter = size || 0; } private _diameter = BASE_SIZE; /** Stroke width of the progress spinner. */ @Input({transform: numberAttribute}) get strokeWidth(): number { return this._strokeWidth ?? this.diameter / 10; } set strokeWidth(value: number) { this._strokeWidth = value || 0; } private _strokeWidth: number; /** The radius of the spinner, adjusted for stroke width. */ _circleRadius(): number { return (this.diameter - BASE_STROKE_WIDTH) / 2; } /** The view box of the spinner's svg element. */ _viewBox() { const viewBox = this._circleRadius() * 2 + this.strokeWidth; return `0 0 ${viewBox} ${viewBox}`; } /** The stroke circumference of the svg circle. */ _strokeCircumference(): number { return 2 * Math.PI * this._circleRadius(); } /** The dash offset of the svg circle. */ _strokeDashOffset() { if (this.mode === 'determinate') { return (this._strokeCircumference() * (100 - this._value)) / 100; } return null; } /** Stroke width of the circle in percent. */ _circleStrokeWidth() { return (this.strokeWidth / this.diameter) * 100; } } /** * @deprecated Import Progress Spinner instead. Note that the * `mat-spinner` selector isn't deprecated. * @breaking-change 16.0.0 */ // tslint:disable-next-line:variable-name export const MatSpinner = MatProgressSpinner;
{ "commit_id": "ea0d1ba7b", "end_byte": 7044, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.ts" }
components/src/material/progress-spinner/BUILD.bazel_0_1547
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"]) ng_module( name = "progress-spinner", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", ], ), assets = [":progress_spinner_scss"] + glob(["**/*.html"]), deps = [ "//src/cdk/platform", "//src/material/core", "@npm//@angular/common", "@npm//@angular/core", ], ) sass_library( name = "progress_spinner_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "progress_spinner_scss", src = "progress-spinner.scss", deps = [ "//src/material:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "progress_spinner_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":progress-spinner", "//src/cdk/platform", "@npm//@angular/common", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":progress_spinner_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":progress-spinner.md"], ) extract_tokens( name = "tokens", srcs = [":progress_spinner_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1547, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/BUILD.bazel" }
components/src/material/progress-spinner/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';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/index.ts" }
components/src/material/progress-spinner/progress-spinner.scss_0_5447
@use '@angular/cdk'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mdc/circular-progress' as tokens-mdc-circular-progress; .mat-mdc-progress-spinner { // Explicitly set to `block` since the browser defaults custom elements to `inline`. display: block; // Prevents the spinning of the inner element from affecting layout outside of the spinner. overflow: hidden; // Spinners with a diameter less than half the existing line-height will become distorted. // Explicitly set the line-height to 0px to avoid this issue. line-height: 0; position: relative; direction: ltr; transition: opacity 250ms cubic-bezier(0.4, 0, 0.6, 1); circle { @include token-utils.use-tokens( tokens-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-token-slots() ) { @include token-utils.create-token-slot(stroke-width, active-indicator-width); } } &._mat-animation-noopable { &, .mdc-circular-progress__determinate-circle { // The spinner itself has a transition on `opacity`. transition: none !important; } .mdc-circular-progress__indeterminate-circle-graphic, .mdc-circular-progress__spinner-layer, .mdc-circular-progress__indeterminate-container { // Disables the rotation animations. animation: none !important; } .mdc-circular-progress__indeterminate-container circle { // Render the indeterminate spinner as a complete circle when animations are off stroke-dasharray: 0 !important; } } @include cdk.high-contrast { .mdc-circular-progress__indeterminate-circle-graphic, .mdc-circular-progress__determinate-circle { // SVG colors aren't inverted automatically in high contrast mode. Set the // stroke to currentColor in order to respect the user's color settings. stroke: currentColor; // currentColor blends in with the background in Chromium-based browsers // so we have to fall back to `CanvasText` which isn't supported on IE. stroke: CanvasText; } } } .mdc-circular-progress__determinate-container, .mdc-circular-progress__indeterminate-circle-graphic, .mdc-circular-progress__indeterminate-container, .mdc-circular-progress__spinner-layer { position: absolute; width: 100%; height: 100%; } .mdc-circular-progress__determinate-container { transform: rotate(-90deg); .mdc-circular-progress--indeterminate & { opacity: 0; } } .mdc-circular-progress__indeterminate-container { font-size: 0; letter-spacing: 0; white-space: nowrap; opacity: 0; .mdc-circular-progress--indeterminate & { opacity: 1; animation: mdc-circular-progress-container-rotate 1568.2352941176ms linear infinite; } } .mdc-circular-progress__determinate-circle-graphic, .mdc-circular-progress__indeterminate-circle-graphic { fill: transparent; } .mat-mdc-progress-spinner .mdc-circular-progress__determinate-circle, .mat-mdc-progress-spinner .mdc-circular-progress__indeterminate-circle-graphic { @include token-utils.use-tokens( tokens-mdc-circular-progress.$prefix, tokens-mdc-circular-progress.get-token-slots() ) { @include token-utils.create-token-slot(stroke, active-indicator-color); } @include cdk.high-contrast { stroke: CanvasText; } } .mdc-circular-progress__determinate-circle { transition: stroke-dashoffset 500ms cubic-bezier(0, 0, 0.2, 1); } .mdc-circular-progress__gap-patch { position: absolute; top: 0; left: 47.5%; box-sizing: border-box; width: 5%; height: 100%; overflow: hidden; } .mdc-circular-progress__indeterminate-circle-graphic { .mdc-circular-progress__gap-patch & { left: -900%; width: 2000%; transform: rotate(180deg); } .mdc-circular-progress__circle-clipper & { width: 200%; } .mdc-circular-progress__circle-right & { left: -100%; } .mdc-circular-progress--indeterminate .mdc-circular-progress__circle-left & { animation: mdc-circular-progress-left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } .mdc-circular-progress--indeterminate .mdc-circular-progress__circle-right & { animation: mdc-circular-progress-right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } } .mdc-circular-progress__circle-clipper { display: inline-flex; position: relative; width: 50%; height: 100%; overflow: hidden; } .mdc-circular-progress__spinner-layer { .mdc-circular-progress--indeterminate & { animation: mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both; } } @keyframes mdc-circular-progress-container-rotate { to { transform: rotate(360deg); } } @keyframes mdc-circular-progress-spinner-layer-rotate { 12.5% { transform: rotate(135deg); } 25% { transform: rotate(270deg); } 37.5% { transform: rotate(405deg); } 50% { transform: rotate(540deg); } 62.5% { transform: rotate(675deg); } 75% { transform: rotate(810deg); } 87.5% { transform: rotate(945deg); } 100% { transform: rotate(1080deg); } } @keyframes mdc-circular-progress-left-spin { from { transform: rotate(265deg); } 50% { transform: rotate(130deg); } to { transform: rotate(265deg); } } @keyframes mdc-circular-progress-right-spin { from { transform: rotate(-265deg); } 50% { transform: rotate(-130deg); } to { transform: rotate(-265deg); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 5447, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.scss" }
components/src/material/progress-spinner/progress-spinner.html_0_1889
<ng-template #circle> <svg [attr.viewBox]="_viewBox()" class="mdc-circular-progress__indeterminate-circle-graphic" xmlns="http://www.w3.org/2000/svg" focusable="false"> <circle [attr.r]="_circleRadius()" [style.stroke-dasharray.px]="_strokeCircumference()" [style.stroke-dashoffset.px]="_strokeCircumference() / 2" [style.stroke-width.%]="_circleStrokeWidth()" cx="50%" cy="50%"/> </svg> </ng-template> <!-- All children need to be hidden for screen readers in order to support ChromeVox. More context in the issue: https://github.com/angular/components/issues/22165. --> <div class="mdc-circular-progress__determinate-container" aria-hidden="true" #determinateSpinner> <svg [attr.viewBox]="_viewBox()" class="mdc-circular-progress__determinate-circle-graphic" xmlns="http://www.w3.org/2000/svg" focusable="false"> <circle [attr.r]="_circleRadius()" [style.stroke-dasharray.px]="_strokeCircumference()" [style.stroke-dashoffset.px]="_strokeDashOffset()" [style.stroke-width.%]="_circleStrokeWidth()" class="mdc-circular-progress__determinate-circle" cx="50%" cy="50%"/> </svg> </div> <!--TODO: figure out why there are 3 separate svgs--> <div class="mdc-circular-progress__indeterminate-container" aria-hidden="true"> <div class="mdc-circular-progress__spinner-layer"> <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-left"> <ng-container [ngTemplateOutlet]="circle"></ng-container> </div> <div class="mdc-circular-progress__gap-patch"> <ng-container [ngTemplateOutlet]="circle"></ng-container> </div> <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-right"> <ng-container [ngTemplateOutlet]="circle"></ng-container> </div> </div> </div>
{ "commit_id": "ea0d1ba7b", "end_byte": 1889, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.html" }
components/src/material/progress-spinner/progress-spinner.md_0_1298
`<mat-progress-spinner>` and `<mat-spinner>` are a circular indicators of progress and activity. <!-- example(progress-spinner-overview) --> ### Progress mode The progress-spinner supports two modes, "determinate" and "indeterminate". The `<mat-spinner>` component is an alias for `<mat-progress-spinner mode="indeterminate">`. | Mode | Description | |---------------|----------------------------------------------------------------------------------| | determinate | Standard progress indicator, fills from 0% to 100% | | indeterminate | Indicates that something is happening without conveying a discrete progress | The default mode is "determinate". In this mode, the progress is set via the `value` property, which can be a whole number between 0 and 100. In "indeterminate" mode, the `value` property is ignored. ### Accessibility `MatProgressSpinner` implements the ARIA `role="progressbar"` pattern. By default, the spinner sets `aria-valuemin` to `0` and `aria-valuemax` to `100`. Avoid changing these values, as this may cause incompatibility with some assistive technology. Always provide an accessible label via `aria-label` or `aria-labelledby` for each spinner.
{ "commit_id": "ea0d1ba7b", "end_byte": 1298, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/progress-spinner.md" }
components/src/material/progress-spinner/testing/progress-spinner-harness.ts_0_1795
/** * @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 {coerceNumberProperty} from '@angular/cdk/coercion'; import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, } from '@angular/cdk/testing'; import {ProgressSpinnerMode} from '@angular/material/progress-spinner'; import {ProgressSpinnerHarnessFilters} from './progress-spinner-harness-filters'; /** Harness for interacting with a MDC based mat-progress-spinner in tests. */ export class MatProgressSpinnerHarness extends ComponentHarness { /** The selector for the host element of a `MatProgressSpinner` instance. */ static hostSelector = '.mat-mdc-progress-spinner'; /** * Gets a `HarnessPredicate` that can be used to search for a progress spinnner with specific * attributes. * @param options Options for filtering which progress spinner instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatProgressSpinnerHarness>( this: ComponentHarnessConstructor<T>, options: ProgressSpinnerHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } /** Gets the progress spinner's value. */ async getValue(): Promise<number | null> { const host = await this.host(); const ariaValue = await host.getAttribute('aria-valuenow'); return ariaValue ? coerceNumberProperty(ariaValue) : null; } /** Gets the progress spinner's mode. */ async getMode(): Promise<ProgressSpinnerMode> { const modeAttr = (await this.host()).getAttribute('mode'); return (await modeAttr) as ProgressSpinnerMode; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1795, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/progress-spinner-harness.ts" }
components/src/material/progress-spinner/testing/public-api.ts_0_300
/** * @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 './progress-spinner-harness'; export * from './progress-spinner-harness-filters';
{ "commit_id": "ea0d1ba7b", "end_byte": 300, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/public-api.ts" }
components/src/material/progress-spinner/testing/BUILD.bazel_0_817
load("//tools:defaults.bzl", "ng_module", "ng_test_library", "ng_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/coercion", "//src/cdk/testing", "//src/material/progress-spinner", ], ) 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/progress-spinner", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 817, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/BUILD.bazel" }
components/src/material/progress-spinner/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';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/index.ts" }
components/src/material/progress-spinner/testing/progress-spinner-harness-filters.ts_0_440
/** * @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'; /** A set of criteria that can be used to filter a list of `MatProgressSpinnerHarness` instances. */ export interface ProgressSpinnerHarnessFilters extends BaseHarnessFilters {}
{ "commit_id": "ea0d1ba7b", "end_byte": 440, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/progress-spinner-harness-filters.ts" }
components/src/material/progress-spinner/testing/progress-spinner-harness.spec.ts_0_2131
import {Component, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatProgressSpinnerModule} from '@angular/material/progress-spinner'; import {MatProgressSpinnerHarness} from './progress-spinner-harness'; describe('MatProgressSpinnerHarness', () => { let fixture: ComponentFixture<ProgressSpinnerHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatProgressSpinnerModule, ProgressSpinnerHarnessTest], }); fixture = TestBed.createComponent(ProgressSpinnerHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all progress spinner harnesses', async () => { const progressSpinners = await loader.getAllHarnesses(MatProgressSpinnerHarness); expect(progressSpinners.length).toBe(3); }); it('should get the value', async () => { fixture.componentInstance.value.set(50); const [determinate, indeterminate, impliedIndeterminate] = await loader.getAllHarnesses(MatProgressSpinnerHarness); expect(await determinate.getValue()).toBe(50); expect(await indeterminate.getValue()).toBe(null); expect(await impliedIndeterminate.getValue()).toBe(null); }); it('should get the mode', async () => { const [determinate, indeterminate, impliedIndeterminate] = await loader.getAllHarnesses(MatProgressSpinnerHarness); expect(await determinate.getMode()).toBe('determinate'); expect(await indeterminate.getMode()).toBe('indeterminate'); expect(await impliedIndeterminate.getMode()).toBe('indeterminate'); }); }); @Component({ template: ` <mat-progress-spinner mode="determinate" [value]="value()"></mat-progress-spinner> <mat-progress-spinner mode="indeterminate"></mat-progress-spinner> <mat-spinner></mat-spinner> `, standalone: true, imports: [MatProgressSpinnerModule], }) class ProgressSpinnerHarnessTest { value = signal(0); }
{ "commit_id": "ea0d1ba7b", "end_byte": 2131, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/progress-spinner/testing/progress-spinner-harness.spec.ts" }
components/src/material/dialog/dialog.zone.spec.ts_0_3163
import {Directionality} from '@angular/cdk/bidi'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import {SpyLocation} from '@angular/common/testing'; import { Component, Directive, Injector, NgZone, ViewChild, ViewContainerRef, provideZoneChangeDetection, inject, } from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, flush} from '@angular/core/testing'; import {MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subject} from 'rxjs'; describe('MatDialog', () => { let dialog: MatDialog; let zone: NgZone; let scrolledSubject = new Subject(); let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatDialogModule, NoopAnimationsModule, ComponentWithChildViewContainer, PizzaMsg, DirectiveWithViewContainer, ], providers: [ provideZoneChangeDetection(), {provide: Location, useClass: SpyLocation}, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject, register: () => {}, deregister: () => {}, }), }, ], }); dialog = TestBed.inject(MatDialog); zone = TestBed.inject(NgZone); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; })); it('should invoke the afterClosed callback inside the NgZone', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const afterCloseCallback = jasmine.createSpy('afterClose callback'); dialogRef.afterClosed().subscribe(() => { afterCloseCallback(NgZone.isInAngularZone()); }); zone.run(() => { dialogRef.close(); viewContainerFixture.detectChanges(); flush(); }); expect(afterCloseCallback).toHaveBeenCalledWith(true); })); }); @Directive({ selector: 'dir-with-view-container', standalone: true, }) class DirectiveWithViewContainer { viewContainerRef = inject(ViewContainerRef); } @Component({ selector: 'arbitrary-component', template: `@if (showChildView) {<dir-with-view-container></dir-with-view-container>}`, standalone: true, imports: [DirectiveWithViewContainer], }) class ComponentWithChildViewContainer { showChildView = true; @ViewChild(DirectiveWithViewContainer) childWithViewContainer: DirectiveWithViewContainer; get childViewContainer() { return this.childWithViewContainer.viewContainerRef; } } /** Simple component for testing ComponentPortal. */ @Component({ template: '<p>Pizza</p> <input> <button>Close</button>', standalone: true, }) class PizzaMsg { dialogRef = inject<MatDialogRef<PizzaMsg>>(MatDialogRef); dialogInjector = inject(Injector); directionality = inject(Directionality); }
{ "commit_id": "ea0d1ba7b", "end_byte": 3163, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.zone.spec.ts" }
components/src/material/dialog/dialog-content-directives.ts_0_6284
/** * @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 { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, inject, } from '@angular/core'; import {CdkScrollable} from '@angular/cdk/scrolling'; import {MatDialog} from './dialog'; import {_closeDialogVia, MatDialogRef} from './dialog-ref'; /** Counter used to generate unique IDs for dialog elements. */ let dialogElementUid = 0; /** * Button that will close the current dialog. */ @Directive({ selector: '[mat-dialog-close], [matDialogClose]', exportAs: 'matDialogClose', host: { '(click)': '_onButtonClick($event)', '[attr.aria-label]': 'ariaLabel || null', '[attr.type]': 'type', }, }) export class MatDialogClose implements OnInit, OnChanges { dialogRef = inject<MatDialogRef<any>>(MatDialogRef, {optional: true})!; private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _dialog = inject(MatDialog); /** Screen-reader label for the button. */ @Input('aria-label') ariaLabel: string; /** Default to "button" to prevents accidental form submits. */ @Input() type: 'submit' | 'button' | 'reset' = 'button'; /** Dialog close input. */ @Input('mat-dialog-close') dialogResult: any; @Input('matDialogClose') _matDialogClose: any; constructor(...args: unknown[]); constructor() {} ngOnInit() { if (!this.dialogRef) { // When this directive is included in a dialog via TemplateRef (rather than being // in a Component), the DialogRef isn't available via injection because embedded // views cannot be given a custom injector. Instead, we look up the DialogRef by // ID. This must occur in `onInit`, as the ID binding for the dialog container won't // be resolved at constructor time. this.dialogRef = getClosestDialog(this._elementRef, this._dialog.openDialogs)!; } } ngOnChanges(changes: SimpleChanges) { const proxiedChange = changes['_matDialogClose'] || changes['_matDialogCloseResult']; if (proxiedChange) { this.dialogResult = proxiedChange.currentValue; } } _onButtonClick(event: MouseEvent) { // Determinate the focus origin using the click event, because using the FocusMonitor will // result in incorrect origins. Most of the time, close buttons will be auto focused in the // dialog, and therefore clicking the button won't result in a focus change. This means that // the FocusMonitor won't detect any origin change, and will always output `program`. _closeDialogVia( this.dialogRef, event.screenX === 0 && event.screenY === 0 ? 'keyboard' : 'mouse', this.dialogResult, ); } } @Directive() export abstract class MatDialogLayoutSection implements OnInit, OnDestroy { protected _dialogRef = inject<MatDialogRef<any>>(MatDialogRef, {optional: true})!; private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _dialog = inject(MatDialog); constructor(...args: unknown[]); constructor() {} protected abstract _onAdd(): void; protected abstract _onRemove(): void; ngOnInit() { if (!this._dialogRef) { this._dialogRef = getClosestDialog(this._elementRef, this._dialog.openDialogs)!; } if (this._dialogRef) { Promise.resolve().then(() => { this._onAdd(); }); } } ngOnDestroy() { // Note: we null check because there are some internal // tests that are mocking out `MatDialogRef` incorrectly. const instance = this._dialogRef?._containerInstance; if (instance) { Promise.resolve().then(() => { this._onRemove(); }); } } } /** * Title of a dialog element. Stays fixed to the top of the dialog when scrolling. */ @Directive({ selector: '[mat-dialog-title], [matDialogTitle]', exportAs: 'matDialogTitle', host: { 'class': 'mat-mdc-dialog-title mdc-dialog__title', '[id]': 'id', }, }) export class MatDialogTitle extends MatDialogLayoutSection { @Input() id: string = `mat-mdc-dialog-title-${dialogElementUid++}`; protected _onAdd() { // Note: we null check the queue, because there are some internal // tests that are mocking out `MatDialogRef` incorrectly. this._dialogRef._containerInstance?._addAriaLabelledBy?.(this.id); } protected override _onRemove(): void { this._dialogRef?._containerInstance?._removeAriaLabelledBy?.(this.id); } } /** * Scrollable content container of a dialog. */ @Directive({ selector: `[mat-dialog-content], mat-dialog-content, [matDialogContent]`, host: {'class': 'mat-mdc-dialog-content mdc-dialog__content'}, hostDirectives: [CdkScrollable], }) export class MatDialogContent {} /** * Container for the bottom action buttons in a dialog. * Stays fixed to the bottom when scrolling. */ @Directive({ selector: `[mat-dialog-actions], mat-dialog-actions, [matDialogActions]`, host: { 'class': 'mat-mdc-dialog-actions mdc-dialog__actions', '[class.mat-mdc-dialog-actions-align-start]': 'align === "start"', '[class.mat-mdc-dialog-actions-align-center]': 'align === "center"', '[class.mat-mdc-dialog-actions-align-end]': 'align === "end"', }, }) export class MatDialogActions extends MatDialogLayoutSection { /** * Horizontal alignment of action buttons. */ @Input() align?: 'start' | 'center' | 'end'; protected _onAdd() { this._dialogRef._containerInstance?._updateActionSectionCount?.(1); } protected override _onRemove(): void { this._dialogRef._containerInstance?._updateActionSectionCount?.(-1); } } /** * Finds the closest MatDialogRef to an element by looking at the DOM. * @param element Element relative to which to look for a dialog. * @param openDialogs References to the currently-open dialogs. */ function getClosestDialog(element: ElementRef<HTMLElement>, openDialogs: MatDialogRef<any>[]) { let parent: HTMLElement | null = element.nativeElement.parentElement; while (parent && !parent.classList.contains('mat-mdc-dialog-container')) { parent = parent.parentElement; } return parent ? openDialogs.find(dialog => dialog.id === parent!.id) : null; }
{ "commit_id": "ea0d1ba7b", "end_byte": 6284, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-content-directives.ts" }
components/src/material/dialog/dialog-animations.ts_0_1774
/** * @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 { animate, state, style, transition, trigger, AnimationTriggerMetadata, query, animateChild, group, } from '@angular/animations'; /** * Default parameters for the animation for backwards compatibility. * @docs-private */ export const _defaultParams = { params: {enterAnimationDuration: '150ms', exitAnimationDuration: '75ms'}, }; /** * Animations used by MatDialog. * @docs-private */ export const matDialogAnimations: { readonly dialogContainer: AnimationTriggerMetadata; } = { /** Animation that is applied on the dialog container by default. */ dialogContainer: trigger('dialogContainer', [ // Note: The `enter` animation transitions to `transform: none`, because for some reason // specifying the transform explicitly, causes IE both to blur the dialog content and // decimate the animation performance. Leaving it as `none` solves both issues. state('void, exit', style({opacity: 0, transform: 'scale(0.7)'})), state('enter', style({transform: 'none'})), transition( '* => enter', group([ animate( '{{enterAnimationDuration}} cubic-bezier(0, 0, 0.2, 1)', style({transform: 'none', opacity: 1}), ), query('@*', animateChild(), {optional: true}), ]), _defaultParams, ), transition( '* => void, * => exit', group([ animate('{{exitAnimationDuration}} cubic-bezier(0.4, 0.0, 0.2, 1)', style({opacity: 0})), query('@*', animateChild(), {optional: true}), ]), _defaultParams, ), ]), };
{ "commit_id": "ea0d1ba7b", "end_byte": 1774, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-animations.ts" }
components/src/material/dialog/module.ts_0_996
/** * @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 {DialogModule} from '@angular/cdk/dialog'; import {OverlayModule} from '@angular/cdk/overlay'; import {PortalModule} from '@angular/cdk/portal'; import {NgModule} from '@angular/core'; import {MatCommonModule} from '@angular/material/core'; import {MatDialog} from './dialog'; import {MatDialogContainer} from './dialog-container'; import { MatDialogActions, MatDialogClose, MatDialogContent, MatDialogTitle, } from './dialog-content-directives'; const DIRECTIVES = [ MatDialogContainer, MatDialogClose, MatDialogTitle, MatDialogActions, MatDialogContent, ]; @NgModule({ imports: [DialogModule, OverlayModule, PortalModule, MatCommonModule, ...DIRECTIVES], exports: [MatCommonModule, ...DIRECTIVES], providers: [MatDialog], }) export class MatDialogModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 996, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/module.ts" }
components/src/material/dialog/dialog.scss_0_1928
@use '@angular/cdk'; @use '../core/tokens/m2/mdc/dialog' as tokens-mdc-dialog; @use '../core/tokens/m2/mat/dialog' as tokens-mat-dialog; @use '../core/tokens/token-utils'; @use '../core/style/variables'; // Dialog content max height. This has been copied from the standard dialog // and is needed to make the dialog content scrollable. $mat-dialog-content-max-height: 65vh !default; // Dialog button horizontal margin. This has been extracted from MDC as they // don't expose this value as variable. $mat-dialog-button-horizontal-margin: 8px !default; // Dialog container max height. This has been given a default value so the // flex-children can be calculated and not overflow on smaller screens. // Fixes b/323588333 $mat-dialog-container-max-height: 95vh !default; // Whether to emit fallback values for the structural styles. Previously MDC was emitting // paddings in the static styles which meant that users would get them even if they didn't // include the `dialog-base`. Eventually we should clean up the usages of this flag. $_emit-fallbacks: true; @mixin _use-mat-tokens { @include token-utils.use-tokens(tokens-mat-dialog.$prefix, tokens-mat-dialog.get-token-slots()) { @content; } } @mixin _use-mdc-tokens { @include token-utils.use-tokens(tokens-mdc-dialog.$prefix, tokens-mdc-dialog.get-token-slots()) { @content; } } // Note that we disable fallback declarations, but we don't disable fallback // values, because there are a lot of internal apps that don't include a proper // theme in their tests. .mat-mdc-dialog-container { width: 100%; height: 100%; display: block; box-sizing: border-box; max-height: inherit; min-height: inherit; min-width: inherit; max-width: inherit; // The dialog container is focusable. We remove the default outline shown in browsers. outline: 0; } // This needs extra specificity so it doesn't get overwritten by the CDK structural styles.
{ "commit_id": "ea0d1ba7b", "end_byte": 1928, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.scss" }
components/src/material/dialog/dialog.scss_1929_9337
.cdk-overlay-pane.mat-mdc-dialog-panel { @include _use-mat-tokens { @include token-utils.create-token-slot(max-width, container-max-width, $_emit-fallbacks); @include token-utils.create-token-slot(min-width, container-min-width, $_emit-fallbacks); @media (variables.$xsmall) { @include token-utils.create-token-slot(max-width, container-small-max-width, $_emit-fallbacks); } } } .mat-mdc-dialog-inner-container { display: flex; flex-direction: row; align-items: center; justify-content: space-around; box-sizing: border-box; height: 100%; opacity: 0; transition: opacity linear var(--mat-dialog-transition-duration, 0ms); max-height: inherit; min-height: inherit; min-width: inherit; max-width: inherit; .mdc-dialog--closing & { transition: opacity 75ms linear; transform: none; } .mdc-dialog--open & { opacity: 1; } ._mat-animation-noopable & { transition: none; } } .mat-mdc-dialog-surface { display: flex; flex-direction: column; flex-grow: 0; flex-shrink: 0; box-sizing: border-box; width: 100%; height: 100%; position: relative; overflow-y: auto; outline: 0; transform: scale(0.8); transition: transform var(--mat-dialog-transition-duration, 0ms) cubic-bezier(0, 0, 0.2, 1); max-height: inherit; min-height: inherit; min-width: inherit; max-width: inherit; @include _use-mat-tokens { @include token-utils.create-token-slot(box-shadow, container-elevation-shadow, $_emit-fallbacks); } @include _use-mdc-tokens { @include token-utils.create-token-slot(border-radius, container-shape, $_emit-fallbacks); @include token-utils.create-token-slot(background-color, container-color, $_emit-fallbacks); } [dir='rtl'] & { text-align: right; } .mdc-dialog--open &, .mdc-dialog--closing & { transform: none; } ._mat-animation-noopable & { transition: none; } &::before { // Renders an outline in high contrast mode. position: absolute; box-sizing: border-box; width: 100%; height: 100%; top: 0; left: 0; border: 2px solid transparent; border-radius: inherit; content: ''; pointer-events: none; } } .mat-mdc-dialog-title { display: block; position: relative; flex-shrink: 0; box-sizing: border-box; margin: 0 0 1px; @include _use-mat-tokens { @include token-utils.create-token-slot(padding, headline-padding, $_emit-fallbacks); } // This was used by MDC to set the text baseline. We should figure out a way to // remove it, because it can introduce unnecessary whitespace at the beginning // of the element. &::before { display: inline-block; width: 0; height: 40px; content: ''; vertical-align: 0; } [dir='rtl'] & { text-align: right; } // Nested to maintain the old specificity. .mat-mdc-dialog-container & { @include _use-mdc-tokens { @include token-utils.create-token-slot(color, subhead-color, $_emit-fallbacks); @include token-utils.create-token-slot(font-family, subhead-font, if($_emit-fallbacks, inherit, null)); @include token-utils.create-token-slot(line-height, subhead-line-height, $_emit-fallbacks); @include token-utils.create-token-slot(font-size, subhead-size, $_emit-fallbacks); @include token-utils.create-token-slot(font-weight, subhead-weight, $_emit-fallbacks); @include token-utils.create-token-slot(letter-spacing, subhead-tracking, $_emit-fallbacks); } } } .mat-mdc-dialog-content { display: block; flex-grow: 1; box-sizing: border-box; margin: 0; overflow: auto; max-height: $mat-dialog-content-max-height; > :first-child { margin-top: 0; } > :last-child { margin-bottom: 0; } // Nested to maintain the old specificity. .mat-mdc-dialog-container & { @include _use-mdc-tokens { @include token-utils.create-token-slot(color, supporting-text-color, $_emit-fallbacks); @include token-utils.create-token-slot(font-family, supporting-text-font, if($_emit-fallbacks, inherit, null)); @include token-utils.create-token-slot(line-height, supporting-text-line-height, $_emit-fallbacks); @include token-utils.create-token-slot(font-size, supporting-text-size, $_emit-fallbacks); @include token-utils.create-token-slot(font-weight, supporting-text-weight, $_emit-fallbacks); @include token-utils.create-token-slot(letter-spacing, supporting-text-tracking, $_emit-fallbacks); } } @include _use-mat-tokens { // These styles need a bit more specificity. .mat-mdc-dialog-container & { @include token-utils.create-token-slot(padding, content-padding, $_emit-fallbacks); } // Note: we can achieve this with a `:has` selector, but it results in an // increased specificity which breaks a lot of internal clients. .mat-mdc-dialog-container-with-actions & { @include token-utils.create-token-slot(padding, with-actions-content-padding, $_emit-fallbacks); } } .mat-mdc-dialog-container .mat-mdc-dialog-title + & { padding-top: 0; } } .mat-mdc-dialog-actions { display: flex; position: relative; flex-shrink: 0; flex-wrap: wrap; align-items: center; justify-content: flex-end; box-sizing: border-box; min-height: 52px; margin: 0; padding: 8px; border-top: 1px solid transparent; // For backwards compatibility, actions align at start by default. MDC usually // aligns actions at the end of the container. @include _use-mat-tokens { @include token-utils.create-token-slot(padding, actions-padding, $_emit-fallbacks); @include token-utils.create-token-slot(justify-content, actions-alignment, $_emit-fallbacks); } @include cdk.high-contrast { border-top-color: CanvasText; } // .mat-mdc-dialog-actions-align-{start|center|end} are set by directive input "align" // [align='start'], [align='center'] and [align='right'] are kept for backwards compability &.mat-mdc-dialog-actions-align-start, &[align='start'] { justify-content: start; } &.mat-mdc-dialog-actions-align-center, &[align='center'] { justify-content: center; } &.mat-mdc-dialog-actions-align-end, &[align='end'] { justify-content: flex-end; } // MDC applies horizontal margin to buttons that have an explicit `mdc-dialog__button` // class applied. We can't set this class for projected buttons that consumers of the // dialog create. To workaround this, we select all Material Design buttons we know and // add the necessary spacing similar to how MDC applies spacing. .mat-button-base + .mat-button-base, .mat-mdc-button-base + .mat-mdc-button-base { margin-left: $mat-dialog-button-horizontal-margin; [dir='rtl'] & { margin-left: 0; margin-right: $mat-dialog-button-horizontal-margin; } } } // When a component is passed into the dialog, the host element interrupts // the `display:flex` from affecting the dialog title, content, and // actions. To fix this, we make the component host `display: contents` by // marking its host with the `mat-mdc-dialog-component-host` class. // // Note that this problem does not exist when a template ref is used since // the title, contents, and actions are then nested directly under the // dialog surface. .mat-mdc-dialog-component-host { display: contents; }
{ "commit_id": "ea0d1ba7b", "end_byte": 9337, "start_byte": 1929, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.scss" }
components/src/material/dialog/public-api.ts_0_570
/** * @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 './dialog'; export * from './dialog-config'; export * from './dialog-ref'; export { MatDialogActions, MatDialogClose, MatDialogTitle, MatDialogContent, } from './dialog-content-directives'; export {MatDialogContainer} from './dialog-container'; export * from './module'; export {matDialogAnimations, _defaultParams} from './dialog-animations';
{ "commit_id": "ea0d1ba7b", "end_byte": 570, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/public-api.ts" }
components/src/material/dialog/README.md_0_97
Please see the official documentation at https://material.angular.io/components/component/dialog
{ "commit_id": "ea0d1ba7b", "end_byte": 97, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/README.md" }
components/src/material/dialog/dialog.md_0_7108
The `MatDialog` service can be used to open modal dialogs with Material Design styling and animations. <!-- example(dialog-overview) --> A dialog is opened by calling the `open` method with a component to be loaded and an optional config object. The `open` method will return an instance of `MatDialogRef`: ```ts let dialogRef = dialog.open(UserProfileComponent, { height: '400px', width: '600px', }); ``` The `MatDialogRef` provides a handle on the opened dialog. It can be used to close the dialog and to receive notifications when the dialog has been closed. Any notification Observables will complete when the dialog closes. ```ts dialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); // Pizza! }); dialogRef.close('Pizza!'); ``` Components created via `MatDialog` can _inject_ `MatDialogRef` and use it to close the dialog in which they are contained. When closing, an optional result value can be provided. This result value is forwarded as the result of the `afterClosed` Observable. ```ts @Component({/* ... */}) export class YourDialog { constructor(public dialogRef: MatDialogRef<YourDialog>) { } closeDialog() { this.dialogRef.close('Pizza!'); } } ``` ### Specifying global configuration defaults Default dialog options can be specified by providing an instance of `MatDialogConfig` for MAT_DIALOG_DEFAULT_OPTIONS in your application's root module. ```ts @NgModule({ providers: [ {provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: {hasBackdrop: false}} ] }) ``` ### Sharing data with the Dialog component. If you want to share data with your dialog, you can use the `data` option to pass information to the dialog component. ```ts let dialogRef = dialog.open(YourDialog, { data: { name: 'austin' }, }); ``` To access the data in your dialog component, you have to use the MAT_DIALOG_DATA injection token: ```ts import {Component, Inject} from '@angular/core'; import {MAT_DIALOG_DATA} from '@angular/material/dialog'; @Component({ selector: 'your-dialog', template: 'passed in {{ data.name }}', }) export class YourDialog { constructor(@Inject(MAT_DIALOG_DATA) public data: {name: string}) { } } ``` Note that if you're using a template dialog (one that was opened with a `TemplateRef`), the data will be available implicitly in the template: ```html <ng-template let-data> Hello, {{data.name}} </ng-template> ``` <!-- example(dialog-data) --> ### Dialog content Several directives are available to make it easier to structure your dialog content: | Name | Description | |------------------------|---------------------------------------------------------------------------------------------------------------| | `mat-dialog-title` | \[Attr] Dialog title, applied to a heading element (e.g., `<h1>`, `<h2>`) | | `<mat-dialog-content>` | Primary scrollable content of the dialog. | | `<mat-dialog-actions>` | Container for action buttons at the bottom of the dialog. Button alignment can be controlled via the `align` attribute which can be set to `end` and `center`. | | `mat-dialog-close` | \[Attr] Added to a `<button>`, makes the button close the dialog with an optional result from the bound value.| For example: ```html <h2 mat-dialog-title>Delete all elements?</h2> <mat-dialog-content>This will delete all elements that are currently on this page and cannot be undone.</mat-dialog-content> <mat-dialog-actions> <button mat-button mat-dialog-close>Cancel</button> <!-- The mat-dialog-close directive optionally accepts a value as a result for the dialog. --> <button mat-button [mat-dialog-close]="true">Delete</button> </mat-dialog-actions> ``` Once a dialog opens, the dialog will automatically focus the first tabbable element. You can control which elements are tab stops with the `tabindex` attribute ```html <button mat-button tabindex="-1">Not Tabbable</button> ``` <!-- example(dialog-content) --> ### Controlling the dialog animation You can control the duration of the dialog's enter and exit animations using the `enterAnimationDuration` and `exitAnimationDuration` options. If you want to disable the dialog's animation completely, you can do so by setting the properties to `0ms`. <!-- example(dialog-animations) --> ### Accessibility `MatDialog` creates modal dialogs that implements the ARIA `role="dialog"` pattern by default. You can change the dialog's role to `alertdialog` via `MatDialogConfig`. You should provide an accessible label to this root dialog element by setting the `ariaLabel` or `ariaLabelledBy` properties of `MatDialogConfig`. You can additionally specify a description element ID via the `ariaDescribedBy` property of `MatDialogConfig`. #### Keyboard interaction By default, the escape key closes `MatDialog`. While you can disable this behavior via the `disableClose` property of `MatDialogConfig`, doing this breaks the expected interaction pattern for the ARIA `role="dialog"` pattern. #### Focus management When opened, `MatDialog` traps browser focus such that it cannot escape the root `role="dialog"` element. By default, the first tabbable element in the dialog receives focus. You can customize which element receives focus with the `autoFocus` property of `MatDialogConfig`, which supports the following values. | Value | Behavior | |------------------|--------------------------------------------------------------------------| | `first-tabbable` | Focus the first tabbable element. This is the default setting. | | `first-header` | Focus the first header element (`role="heading"`, `h1` through `h6`) | | `dialog` | Focus the root `role="dialog"` element. | | Any CSS selector | Focus the first element matching the given selector. | While the default setting applies the best behavior for most applications, special cases may benefit from these alternatives. Always test your application to verify the behavior that works best for your users. #### Focus restoration When closed, `MatDialog` restores focus to the element that previously held focus when the dialog opened. However, if that previously focused element no longer exists, you must add additional handling to return focus to an element that makes sense for the user's workflow. Opening a dialog from a menu is one common pattern that causes this situation. The menu closes upon clicking an item, thus the focused menu item is no longer in the DOM when the bottom sheet attempts to restore focus. You can add handling for this situation with the `afterClosed()` observable from `MatDialogRef`. <!-- example({"example":"dialog-from-menu", "file":"dialog-from-menu-example.ts", "region":"focus-restoration"}) -->
{ "commit_id": "ea0d1ba7b", "end_byte": 7108, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.md" }
components/src/material/dialog/_dialog-theme.scss_0_3675
@use 'sass:map'; @use '../core/style/sass-utils'; @use '../core/tokens/m2/mdc/dialog' as tokens-mdc-dialog; @use '../core/tokens/m2/mat/dialog' as tokens-mat-dialog; @use '../core/tokens/token-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/typography/typography'; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { // Add default values for tokens not related to color, typography, or density. @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-dialog.$prefix, tokens-mdc-dialog.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-dialog.$prefix, tokens-mat-dialog.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 sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-dialog.$prefix, tokens-mdc-dialog.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-dialog.$prefix, tokens-mat-dialog.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-mdc-dialog.$prefix, tokens-mdc-dialog.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-dialog.$prefix, tokens-mat-dialog.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-mdc-dialog.$prefix, tokens: tokens-mdc-dialog.get-token-slots(), ), ( namespace: tokens-mat-dialog.$prefix, tokens: tokens-mat-dialog.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-dialog') { @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-mdc-dialog.$prefix, map.get($tokens, tokens-mdc-dialog.$prefix) ); @include token-utils.create-token-values( tokens-mat-dialog.$prefix, map.get($tokens, tokens-mat-dialog.$prefix) ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3675, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/_dialog-theme.scss" }
components/src/material/dialog/dialog-config.ts_0_4980
/** * @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 {ViewContainerRef, Injector} from '@angular/core'; import {Direction} from '@angular/cdk/bidi'; import {ScrollStrategy} from '@angular/cdk/overlay'; import {_defaultParams} from './dialog-animations'; /** Options for where to set focus to automatically on dialog open */ export type AutoFocusTarget = 'dialog' | 'first-tabbable' | 'first-heading'; /** Valid ARIA roles for a dialog element. */ export type DialogRole = 'dialog' | 'alertdialog'; /** Possible overrides for a dialog's position. */ export interface DialogPosition { /** Override for the dialog's top position. */ top?: string; /** Override for the dialog's bottom position. */ bottom?: string; /** Override for the dialog's left position. */ left?: string; /** Override for the dialog's right position. */ right?: string; } /** * Configuration for opening a modal dialog with the MatDialog service. */ export class MatDialogConfig<D = any> { /** * Where the attached component should live in Angular's *logical* component tree. * This affects what is available for injection and the change detection order for the * component instantiated inside of the dialog. This does not affect where the dialog * content will be rendered. */ viewContainerRef?: ViewContainerRef; /** * Injector used for the instantiation of the component to be attached. If provided, * takes precedence over the injector indirectly provided by `ViewContainerRef`. */ injector?: Injector; /** ID for the dialog. If omitted, a unique one will be generated. */ id?: string; /** The ARIA role of the dialog element. */ role?: DialogRole = 'dialog'; /** Custom class for the overlay pane. */ panelClass?: string | string[] = ''; /** Whether the dialog has a backdrop. */ hasBackdrop?: boolean = true; /** Custom class for the backdrop. */ backdropClass?: string | string[] = ''; /** Whether the user can use escape or clicking on the backdrop to close the modal. */ disableClose?: boolean = false; /** Width of the dialog. */ width?: string = ''; /** Height of the dialog. */ height?: string = ''; /** Min-width of the dialog. If a number is provided, assumes pixel units. */ minWidth?: number | string; /** Min-height of the dialog. If a number is provided, assumes pixel units. */ minHeight?: number | string; /** Max-width of the dialog. If a number is provided, assumes pixel units. Defaults to 80vw. */ maxWidth?: number | string; /** Max-height of the dialog. If a number is provided, assumes pixel units. */ maxHeight?: number | string; /** Position overrides. */ position?: DialogPosition; /** Data being injected into the child component. */ data?: D | null = null; /** Layout direction for the dialog's content. */ direction?: Direction; /** ID of the element that describes the dialog. */ ariaDescribedBy?: string | null = null; /** ID of the element that labels the dialog. */ ariaLabelledBy?: string | null = null; /** Aria label to assign to the dialog element. */ ariaLabel?: string | null = null; /** Whether this is a modal dialog. Used to set the `aria-modal` attribute. */ ariaModal?: boolean = true; /** * Where the dialog should focus on open. * @breaking-change 14.0.0 Remove boolean option from autoFocus. Use string or * AutoFocusTarget instead. */ autoFocus?: AutoFocusTarget | string | boolean = 'first-tabbable'; /** * Whether the dialog should restore focus to the * previously-focused element, after it's closed. */ restoreFocus?: boolean = true; /** Whether to wait for the opening animation to finish before trapping focus. */ delayFocusTrap?: boolean = true; /** Scroll strategy to be used for the dialog. */ scrollStrategy?: ScrollStrategy; /** * Whether the dialog should close when the user goes backwards/forwards in history. * Note that this usually doesn't include clicking on links (unless the user is using * the `HashLocationStrategy`). */ closeOnNavigation?: boolean = true; /** * Alternate `ComponentFactoryResolver` to use when resolving the associated component. * @deprecated No longer used. Will be removed. * @breaking-change 20.0.0 */ componentFactoryResolver?: unknown; /** * Duration of the enter animation in ms. * Should be a number, string type is deprecated. * @breaking-change 17.0.0 Remove string signature. */ enterAnimationDuration?: string | number; /** * Duration of the exit animation in ms. * Should be a number, string type is deprecated. * @breaking-change 17.0.0 Remove string signature. */ exitAnimationDuration?: string | number; // TODO(jelbourn): add configuration for lifecycle hooks, ARIA labelling. }
{ "commit_id": "ea0d1ba7b", "end_byte": 4980, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-config.ts" }
components/src/material/dialog/BUILD.bazel_0_1672
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"]) ng_module( name = "dialog", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":dialog_scss"] + glob(["**/*.html"]), deps = [ "//src/cdk/dialog", "//src/cdk/overlay", "//src/cdk/portal", "//src/material/core", ], ) sass_library( name = "dialog_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "dialog_scss", src = "dialog.scss", deps = [ ":dialog_scss_lib", "//src/material/core:core_scss_lib", ], ) ########### # Testing ########### ng_test_library( name = "dialog_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":dialog", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/dialog", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/platform", "//src/cdk/scrolling", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":dialog_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":dialog.md"], ) extract_tokens( name = "tokens", srcs = [":dialog_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1672, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/BUILD.bazel" }
components/src/material/dialog/dialog-container.ts_0_2174
/** * @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, ComponentRef, EventEmitter, OnDestroy, ViewEncapsulation, ANIMATION_MODULE_TYPE, inject, } from '@angular/core'; import {MatDialogConfig} from './dialog-config'; import {CdkDialogContainer} from '@angular/cdk/dialog'; import {coerceNumberProperty} from '@angular/cdk/coercion'; import {CdkPortalOutlet, ComponentPortal} from '@angular/cdk/portal'; /** Event that captures the state of dialog container animations. */ interface LegacyDialogAnimationEvent { state: 'opened' | 'opening' | 'closing' | 'closed'; totalTime: number; } /** Class added when the dialog is open. */ const OPEN_CLASS = 'mdc-dialog--open'; /** Class added while the dialog is opening. */ const OPENING_CLASS = 'mdc-dialog--opening'; /** Class added while the dialog is closing. */ const CLOSING_CLASS = 'mdc-dialog--closing'; /** Duration of the opening animation in milliseconds. */ export const OPEN_ANIMATION_DURATION = 150; /** Duration of the closing animation in milliseconds. */ export const CLOSE_ANIMATION_DURATION = 75; @Component({ selector: 'mat-dialog-container', templateUrl: 'dialog-container.html', styleUrl: 'dialog.css', encapsulation: ViewEncapsulation.None, // Disabled for consistency with the non-MDC dialog container. // tslint:disable-next-line:validate-decorators changeDetection: ChangeDetectionStrategy.Default, imports: [CdkPortalOutlet], host: { 'class': 'mat-mdc-dialog-container mdc-dialog', 'tabindex': '-1', '[attr.aria-modal]': '_config.ariaModal', '[id]': '_config.id', '[attr.role]': '_config.role', '[attr.aria-labelledby]': '_config.ariaLabel ? null : _ariaLabelledByQueue[0]', '[attr.aria-label]': '_config.ariaLabel', '[attr.aria-describedby]': '_config.ariaDescribedBy || null', '[class._mat-animation-noopable]': '!_animationsEnabled', '[class.mat-mdc-dialog-container-with-actions]': '_actionSectionCount > 0', }, }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 2174, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-container.ts" }
components/src/material/dialog/dialog-container.ts_2175_11093
class MatDialogContainer extends CdkDialogContainer<MatDialogConfig> implements OnDestroy { private _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); /** Emits when an animation state changes. */ _animationStateChanged = new EventEmitter<LegacyDialogAnimationEvent>(); /** Whether animations are enabled. */ _animationsEnabled: boolean = this._animationMode !== 'NoopAnimations'; /** Number of actions projected in the dialog. */ protected _actionSectionCount = 0; /** Host element of the dialog container component. */ private _hostElement: HTMLElement = this._elementRef.nativeElement; /** Duration of the dialog open animation. */ private _enterAnimationDuration = this._animationsEnabled ? parseCssTime(this._config.enterAnimationDuration) ?? OPEN_ANIMATION_DURATION : 0; /** Duration of the dialog close animation. */ private _exitAnimationDuration = this._animationsEnabled ? parseCssTime(this._config.exitAnimationDuration) ?? CLOSE_ANIMATION_DURATION : 0; /** Current timer for dialog animations. */ private _animationTimer: ReturnType<typeof setTimeout> | null = null; protected override _contentAttached(): void { // Delegate to the original dialog-container initialization (i.e. saving the // previous element, setting up the focus trap and moving focus to the container). super._contentAttached(); // Note: Usually we would be able to use the MDC dialog foundation here to handle // the dialog animation for us, but there are a few reasons why we just leverage // their styles and not use the runtime foundation code: // 1. Foundation does not allow us to disable animations. // 2. Foundation contains unnecessary features we don't need and aren't // tree-shakeable. e.g. background scrim, keyboard event handlers for ESC button. this._startOpenAnimation(); } /** Starts the dialog open animation if enabled. */ private _startOpenAnimation() { this._animationStateChanged.emit({state: 'opening', totalTime: this._enterAnimationDuration}); if (this._animationsEnabled) { this._hostElement.style.setProperty( TRANSITION_DURATION_PROPERTY, `${this._enterAnimationDuration}ms`, ); // We need to give the `setProperty` call from above some time to be applied. // One would expect that the open class is added once the animation finished, but MDC // uses the open class in combination with the opening class to start the animation. this._requestAnimationFrame(() => this._hostElement.classList.add(OPENING_CLASS, OPEN_CLASS)); this._waitForAnimationToComplete(this._enterAnimationDuration, this._finishDialogOpen); } else { this._hostElement.classList.add(OPEN_CLASS); // Note: We could immediately finish the dialog opening here with noop animations, // but we defer until next tick so that consumers can subscribe to `afterOpened`. // Executing this immediately would mean that `afterOpened` emits synchronously // on `dialog.open` before the consumer had a change to subscribe to `afterOpened`. Promise.resolve().then(() => this._finishDialogOpen()); } } /** * Starts the exit animation of the dialog if enabled. This method is * called by the dialog ref. */ _startExitAnimation(): void { this._animationStateChanged.emit({state: 'closing', totalTime: this._exitAnimationDuration}); this._hostElement.classList.remove(OPEN_CLASS); if (this._animationsEnabled) { this._hostElement.style.setProperty( TRANSITION_DURATION_PROPERTY, `${this._exitAnimationDuration}ms`, ); // We need to give the `setProperty` call from above some time to be applied. this._requestAnimationFrame(() => this._hostElement.classList.add(CLOSING_CLASS)); this._waitForAnimationToComplete(this._exitAnimationDuration, this._finishDialogClose); } else { // This subscription to the `OverlayRef#backdropClick` observable in the `DialogRef` is // set up before any user can subscribe to the backdrop click. The subscription triggers // the dialog close and this method synchronously. If we'd synchronously emit the `CLOSED` // animation state event if animations are disabled, the overlay would be disposed // immediately and all other subscriptions to `DialogRef#backdropClick` would be silently // skipped. We work around this by waiting with the dialog close until the next tick when // all subscriptions have been fired as expected. This is not an ideal solution, but // there doesn't seem to be any other good way. Alternatives that have been considered: // 1. Deferring `DialogRef.close`. This could be a breaking change due to a new microtask. // Also this issue is specific to the MDC implementation where the dialog could // technically be closed synchronously. In the non-MDC one, Angular animations are used // and closing always takes at least a tick. // 2. Ensuring that user subscriptions to `backdropClick`, `keydownEvents` in the dialog // ref are first. This would solve the issue, but has the risk of memory leaks and also // doesn't solve the case where consumers call `DialogRef.close` in their subscriptions. // Based on the fact that this is specific to the MDC-based implementation of the dialog // animations, the defer is applied here. Promise.resolve().then(() => this._finishDialogClose()); } } /** * Updates the number action sections. * @param delta Increase/decrease in the number of sections. */ _updateActionSectionCount(delta: number) { this._actionSectionCount += delta; this._changeDetectorRef.markForCheck(); } /** * Completes the dialog open by clearing potential animation classes, trapping * focus and emitting an opened event. */ private _finishDialogOpen = () => { this._clearAnimationClasses(); this._openAnimationDone(this._enterAnimationDuration); }; /** * Completes the dialog close by clearing potential animation classes, restoring * focus and emitting a closed event. */ private _finishDialogClose = () => { this._clearAnimationClasses(); this._animationStateChanged.emit({state: 'closed', totalTime: this._exitAnimationDuration}); }; /** Clears all dialog animation classes. */ private _clearAnimationClasses() { this._hostElement.classList.remove(OPENING_CLASS, CLOSING_CLASS); } private _waitForAnimationToComplete(duration: number, callback: () => void) { if (this._animationTimer !== null) { clearTimeout(this._animationTimer); } // Note that we want this timer to run inside the NgZone, because we want // the related events like `afterClosed` to be inside the zone as well. this._animationTimer = setTimeout(callback, duration); } /** Runs a callback in `requestAnimationFrame`, if available. */ private _requestAnimationFrame(callback: () => void) { this._ngZone.runOutsideAngular(() => { if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(callback); } else { callback(); } }); } protected override _captureInitialFocus(): void { if (!this._config.delayFocusTrap) { this._trapFocus(); } } /** * Callback for when the open dialog animation has finished. Intended to * be called by sub-classes that use different animation implementations. */ protected _openAnimationDone(totalTime: number) { if (this._config.delayFocusTrap) { this._trapFocus(); } this._animationStateChanged.next({state: 'opened', totalTime}); } override ngOnDestroy() { super.ngOnDestroy(); if (this._animationTimer !== null) { clearTimeout(this._animationTimer); } } override attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> { // When a component is passed into the dialog, the host element interrupts // the `display:flex` from affecting the dialog title, content, and // actions. To fix this, we make the component host `display: contents` by // marking its host with the `mat-mdc-dialog-component-host` class. // // Note that this problem does not exist when a template ref is used since // the title, contents, and actions are then nested directly under the // dialog surface. const ref = super.attachComponentPortal(portal); ref.location.nativeElement.classList.add('mat-mdc-dialog-component-host'); return ref; } } const TRANSITION_DURATION_PROPERTY = '--mat-dialog-transition-duration'; // TODO(mmalerba): Remove this function after animation durations are required // to be numbers. /** * Converts a CSS time string to a number in ms. If the given time is already a * number, it is assumed to be in ms. */
{ "commit_id": "ea0d1ba7b", "end_byte": 11093, "start_byte": 2175, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-container.ts" }
components/src/material/dialog/dialog-container.ts_11094_11561
function parseCssTime(time: string | number | undefined): number | null { if (time == null) { return null; } if (typeof time === 'number') { return time; } if (time.endsWith('ms')) { return coerceNumberProperty(time.substring(0, time.length - 2)); } if (time.endsWith('s')) { return coerceNumberProperty(time.substring(0, time.length - 1)) * 1000; } if (time === '0') { return 0; } return null; // anything else is invalid. }
{ "commit_id": "ea0d1ba7b", "end_byte": 11561, "start_byte": 11094, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-container.ts" }
components/src/material/dialog/dialog.ts_0_8557
/** * @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 {ComponentType, Overlay, ScrollStrategy} from '@angular/cdk/overlay'; import { ComponentRef, Injectable, InjectionToken, OnDestroy, TemplateRef, Type, inject, } from '@angular/core'; import {MatDialogConfig} from './dialog-config'; import {MatDialogContainer} from './dialog-container'; import {MatDialogRef} from './dialog-ref'; import {defer, Observable, Subject} from 'rxjs'; import {Dialog, DialogConfig} from '@angular/cdk/dialog'; import {startWith} from 'rxjs/operators'; /** Injection token that can be used to access the data that was passed in to a dialog. */ export const MAT_DIALOG_DATA = new InjectionToken<any>('MatMdcDialogData'); /** Injection token that can be used to specify default dialog options. */ export const MAT_DIALOG_DEFAULT_OPTIONS = new InjectionToken<MatDialogConfig>( 'mat-mdc-dialog-default-options', ); /** Injection token that determines the scroll handling while the dialog is open. */ export const MAT_DIALOG_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>( 'mat-mdc-dialog-scroll-strategy', { providedIn: 'root', factory: () => { const overlay = inject(Overlay); return () => overlay.scrollStrategies.block(); }, }, ); /** * @docs-private * @deprecated No longer used. To be removed. * @breaking-change 19.0.0 */ export function MAT_DIALOG_SCROLL_STRATEGY_PROVIDER_FACTORY( overlay: Overlay, ): () => ScrollStrategy { return () => overlay.scrollStrategies.block(); } /** * @docs-private * @deprecated No longer used. To be removed. * @breaking-change 19.0.0 */ export const MAT_DIALOG_SCROLL_STRATEGY_PROVIDER = { provide: MAT_DIALOG_SCROLL_STRATEGY, deps: [Overlay], useFactory: MAT_DIALOG_SCROLL_STRATEGY_PROVIDER_FACTORY, }; // Counter for unique dialog ids. let uniqueId = 0; /** * Service to open Material Design modal dialogs. */ @Injectable({providedIn: 'root'}) export class MatDialog implements OnDestroy { private _overlay = inject(Overlay); private _defaultOptions = inject<MatDialogConfig>(MAT_DIALOG_DEFAULT_OPTIONS, {optional: true}); private _scrollStrategy = inject(MAT_DIALOG_SCROLL_STRATEGY); private _parentDialog = inject(MatDialog, {optional: true, skipSelf: true}); protected _dialog = inject(Dialog); private readonly _openDialogsAtThisLevel: MatDialogRef<any>[] = []; private readonly _afterAllClosedAtThisLevel = new Subject<void>(); private readonly _afterOpenedAtThisLevel = new Subject<MatDialogRef<any>>(); protected dialogConfigClass = MatDialogConfig; private readonly _dialogRefConstructor: Type<MatDialogRef<any>>; private readonly _dialogContainerType: Type<MatDialogContainer>; private readonly _dialogDataToken: InjectionToken<any>; /** Keeps track of the currently-open dialogs. */ get openDialogs(): MatDialogRef<any>[] { return this._parentDialog ? this._parentDialog.openDialogs : this._openDialogsAtThisLevel; } /** Stream that emits when a dialog has been opened. */ get afterOpened(): Subject<MatDialogRef<any>> { return this._parentDialog ? this._parentDialog.afterOpened : this._afterOpenedAtThisLevel; } private _getAfterAllClosed(): Subject<void> { const parent = this._parentDialog; return parent ? parent._getAfterAllClosed() : this._afterAllClosedAtThisLevel; } /** * Stream that emits when all open dialog have finished closing. * Will emit on subscribe if there are no open dialogs to begin with. */ readonly afterAllClosed: Observable<void> = defer(() => this.openDialogs.length ? this._getAfterAllClosed() : this._getAfterAllClosed().pipe(startWith(undefined)), ) as Observable<any>; constructor(...args: unknown[]); constructor() { this._dialogRefConstructor = MatDialogRef; this._dialogContainerType = MatDialogContainer; this._dialogDataToken = MAT_DIALOG_DATA; } /** * Opens a modal dialog containing the given component. * @param component Type of the component to load into the dialog. * @param config Extra configuration options. * @returns Reference to the newly-opened dialog. */ open<T, D = any, R = any>( component: ComponentType<T>, config?: MatDialogConfig<D>, ): MatDialogRef<T, R>; /** * Opens a modal dialog containing the given template. * @param template TemplateRef to instantiate as the dialog content. * @param config Extra configuration options. * @returns Reference to the newly-opened dialog. */ open<T, D = any, R = any>( template: TemplateRef<T>, config?: MatDialogConfig<D>, ): MatDialogRef<T, R>; open<T, D = any, R = any>( template: ComponentType<T> | TemplateRef<T>, config?: MatDialogConfig<D>, ): MatDialogRef<T, R>; open<T, D = any, R = any>( componentOrTemplateRef: ComponentType<T> | TemplateRef<T>, config?: MatDialogConfig<D>, ): MatDialogRef<T, R> { let dialogRef: MatDialogRef<T, R>; config = {...(this._defaultOptions || new MatDialogConfig()), ...config}; config.id = config.id || `mat-mdc-dialog-${uniqueId++}`; config.scrollStrategy = config.scrollStrategy || this._scrollStrategy(); const cdkRef = this._dialog.open<R, D, T>(componentOrTemplateRef, { ...config, positionStrategy: this._overlay.position().global().centerHorizontally().centerVertically(), // Disable closing since we need to sync it up to the animation ourselves. disableClose: true, // Disable closing on destroy, because this service cleans up its open dialogs as well. // We want to do the cleanup here, rather than the CDK service, because the CDK destroys // the dialogs immediately whereas we want it to wait for the animations to finish. closeOnDestroy: false, // Disable closing on detachments so that we can sync up the animation. // The Material dialog ref handles this manually. closeOnOverlayDetachments: false, container: { type: this._dialogContainerType, providers: () => [ // Provide our config as the CDK config as well since it has the same interface as the // CDK one, but it contains the actual values passed in by the user for things like // `disableClose` which we disable for the CDK dialog since we handle it ourselves. {provide: this.dialogConfigClass, useValue: config}, {provide: DialogConfig, useValue: config}, ], }, templateContext: () => ({dialogRef}), providers: (ref, cdkConfig, dialogContainer) => { dialogRef = new this._dialogRefConstructor(ref, config, dialogContainer); dialogRef.updatePosition(config?.position); return [ {provide: this._dialogContainerType, useValue: dialogContainer}, {provide: this._dialogDataToken, useValue: cdkConfig.data}, {provide: this._dialogRefConstructor, useValue: dialogRef}, ]; }, }); // This can't be assigned in the `providers` callback, because // the instance hasn't been assigned to the CDK ref yet. (dialogRef! as {componentRef: ComponentRef<T>}).componentRef = cdkRef.componentRef!; dialogRef!.componentInstance = cdkRef.componentInstance!; this.openDialogs.push(dialogRef!); this.afterOpened.next(dialogRef!); dialogRef!.afterClosed().subscribe(() => { const index = this.openDialogs.indexOf(dialogRef); if (index > -1) { this.openDialogs.splice(index, 1); if (!this.openDialogs.length) { this._getAfterAllClosed().next(); } } }); return dialogRef!; } /** * Closes all of the currently-open dialogs. */ closeAll(): void { this._closeDialogs(this.openDialogs); } /** * Finds an open dialog by its id. * @param id ID to use when looking up the dialog. */ getDialogById(id: string): MatDialogRef<any> | undefined { return this.openDialogs.find(dialog => dialog.id === id); } ngOnDestroy() { // Only close the dialogs at this level on destroy // since the parent service may still be active. this._closeDialogs(this._openDialogsAtThisLevel); this._afterAllClosedAtThisLevel.complete(); this._afterOpenedAtThisLevel.complete(); } private _closeDialogs(dialogs: MatDialogRef<any>[]) { let i = dialogs.length; while (i--) { dialogs[i].close(); } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 8557, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.ts" }
components/src/material/dialog/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';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/index.ts" }
components/src/material/dialog/dialog.spec.ts_0_1454
import {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; import {A, ESCAPE} from '@angular/cdk/keycodes'; import {Overlay, OverlayContainer, ScrollStrategy} from '@angular/cdk/overlay'; import {_supportsShadowDom} from '@angular/cdk/platform'; import {ScrollDispatcher} from '@angular/cdk/scrolling'; import { createKeyboardEvent, dispatchEvent, dispatchKeyboardEvent, dispatchMouseEvent, patchElementFocus, } from '@angular/cdk/testing/private'; import {Location} from '@angular/common'; import {SpyLocation} from '@angular/common/testing'; import { ChangeDetectionStrategy, Component, createNgModuleRef, Directive, Injectable, Injector, NgModule, TemplateRef, ViewChild, ViewContainerRef, ViewEncapsulation, forwardRef, signal, inject, } from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, flush, flushMicrotasks, tick, } from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subject} from 'rxjs'; import {CLOSE_ANIMATION_DURATION, OPEN_ANIMATION_DURATION} from './dialog-container'; import { MAT_DIALOG_DATA, MAT_DIALOG_DEFAULT_OPTIONS, MatDialog, MatDialogActions, MatDialogClose, MatDialogContent, MatDialogModule, MatDialogRef, MatDialogState, MatDialogTitle, } from './index';
{ "commit_id": "ea0d1ba7b", "end_byte": 1454, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_1456_11331
describe('MatDialog', () => { let dialog: MatDialog; let overlayContainerElement: HTMLElement; let scrolledSubject = new Subject(); let focusMonitor: FocusMonitor; let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; let mockLocation: SpyLocation; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatDialogModule, NoopAnimationsModule, ComponentWithChildViewContainer, ComponentWithTemplateRef, PizzaMsg, ContentElementDialog, DialogWithInjectedData, DialogWithoutFocusableElements, DirectiveWithViewContainer, ComponentWithContentElementTemplateRef, ], providers: [ {provide: Location, useClass: SpyLocation}, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject, register: () => {}, deregister: () => {}, }), }, ], }); dialog = TestBed.inject(MatDialog); mockLocation = TestBed.inject(Location) as SpyLocation; overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); focusMonitor = TestBed.inject(FocusMonitor); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; })); it('should open a dialog with a component', () => { let dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('Pizza'); expect(dialogRef.componentInstance instanceof PizzaMsg).toBe(true); expect(dialogRef.componentInstance.dialogRef).toBe(dialogRef); viewContainerFixture.detectChanges(); let dialogContainerElement = overlayContainerElement.querySelector('mat-dialog-container')!; expect(dialogContainerElement.getAttribute('role')).toBe('dialog'); expect(dialogContainerElement.getAttribute('aria-modal')).toBe('true'); }); it('should open a dialog with a template', () => { const templateRefFixture = TestBed.createComponent(ComponentWithTemplateRef); templateRefFixture.componentInstance.localValue = 'Bees'; templateRefFixture.changeDetectorRef.markForCheck(); templateRefFixture.detectChanges(); const data = {value: 'Knees'}; let dialogRef = dialog.open(templateRefFixture.componentInstance.templateRef, {data}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('Cheese Bees Knees'); expect(templateRefFixture.componentInstance.dialogRef).toBe(dialogRef); viewContainerFixture.detectChanges(); let dialogContainerElement = overlayContainerElement.querySelector('mat-dialog-container')!; expect(dialogContainerElement.getAttribute('role')).toBe('dialog'); expect(dialogContainerElement.getAttribute('aria-modal')).toBe('true'); dialogRef.close(); }); it('should emit when dialog opening animation is complete', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const spy = jasmine.createSpy('afterOpen spy'); dialogRef.afterOpened().subscribe(spy); viewContainerFixture.detectChanges(); // callback should not be called before animation is complete expect(spy).not.toHaveBeenCalled(); flush(); expect(spy).toHaveBeenCalled(); })); it('should use injector from viewContainerRef for DialogInjector', () => { let dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); let dialogInjector = dialogRef.componentInstance.dialogInjector; expect(dialogRef.componentInstance.dialogRef).toBe(dialogRef); expect(dialogInjector.get<DirectiveWithViewContainer>(DirectiveWithViewContainer)) .withContext( 'Expected the dialog component to be created with the injector from ' + 'the viewContainerRef.', ) .toBeTruthy(); }); it('should open a dialog with a component and no ViewContainerRef', () => { let dialogRef = dialog.open(PizzaMsg); viewContainerFixture.detectChanges(); expect(overlayContainerElement.textContent).toContain('Pizza'); expect(dialogRef.componentInstance instanceof PizzaMsg).toBe(true); expect(dialogRef.componentInstance.dialogRef).toBe(dialogRef); viewContainerFixture.detectChanges(); let dialogContainerElement = overlayContainerElement.querySelector('mat-dialog-container')!; expect(dialogContainerElement.getAttribute('role')).toBe('dialog'); }); it('should apply the configured role to the dialog element', () => { dialog.open(PizzaMsg, {role: 'alertdialog'}); viewContainerFixture.detectChanges(); let dialogContainerElement = overlayContainerElement.querySelector('mat-dialog-container')!; expect(dialogContainerElement.getAttribute('role')).toBe('alertdialog'); }); it('should apply the specified `aria-describedby`', () => { dialog.open(PizzaMsg, {ariaDescribedBy: 'description-element'}); viewContainerFixture.detectChanges(); let dialogContainerElement = overlayContainerElement.querySelector('mat-dialog-container')!; expect(dialogContainerElement.getAttribute('aria-describedby')).toBe('description-element'); }); it('should close a dialog and get back a result', fakeAsync(() => { let dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); let afterCloseCallback = jasmine.createSpy('afterClose callback'); dialogRef.afterClosed().subscribe(afterCloseCallback); dialogRef.close('Charmander'); viewContainerFixture.detectChanges(); flush(); expect(afterCloseCallback).toHaveBeenCalledWith('Charmander'); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull(); })); it('should dispose of dialog if view container is destroyed while animating', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); dialogRef.close(); viewContainerFixture.detectChanges(); viewContainerFixture.destroy(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull(); })); it('should dispatch the beforeClosed and afterClosed events when the overlay is detached externally', fakeAsync(() => { const overlay = TestBed.inject(Overlay); const dialogRef = dialog.open(PizzaMsg, { viewContainerRef: testViewContainerRef, scrollStrategy: overlay.scrollStrategies.close(), }); const beforeClosedCallback = jasmine.createSpy('beforeClosed callback'); const afterCloseCallback = jasmine.createSpy('afterClosed callback'); dialogRef.beforeClosed().subscribe(beforeClosedCallback); dialogRef.afterClosed().subscribe(afterCloseCallback); scrolledSubject.next(); viewContainerFixture.detectChanges(); flush(); expect(beforeClosedCallback).toHaveBeenCalledTimes(1); expect(afterCloseCallback).toHaveBeenCalledTimes(1); })); it('should close a dialog and get back a result before it is closed', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); flush(); viewContainerFixture.detectChanges(); // beforeClose should emit before dialog container is destroyed const beforeCloseHandler = jasmine.createSpy('beforeClose callback').and.callFake(() => { expect(overlayContainerElement.querySelector('mat-dialog-container')) .not.withContext('dialog container exists when beforeClose is called') .toBeNull(); }); dialogRef.beforeClosed().subscribe(beforeCloseHandler); dialogRef.close('Bulbasaur'); viewContainerFixture.detectChanges(); flush(); expect(beforeCloseHandler).toHaveBeenCalledWith('Bulbasaur'); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull(); })); it('should close a dialog via the escape key', fakeAsync(() => { dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull(); expect(event.defaultPrevented).toBe(true); })); it('should not close a dialog via the escape key with a modifier', fakeAsync(() => { dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true}); dispatchEvent(document.body, event); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeTruthy(); expect(event.defaultPrevented).toBe(false); })); it('should close from a ViewContainerRef with OnPush change detection', fakeAsync(() => { const onPushFixture = TestBed.createComponent(ComponentWithOnPushViewContainer); onPushFixture.detectChanges(); const dialogRef = dialog.open(PizzaMsg, { viewContainerRef: onPushFixture.componentInstance.viewContainerRef, }); flushMicrotasks(); onPushFixture.detectChanges(); flushMicrotasks(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length) .withContext('Expected one open dialog.') .toBe(1); dialogRef.close(); flushMicrotasks(); onPushFixture.detectChanges(); tick(500); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length) .withContext('Expected no open dialogs.') .toBe(0); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 11331, "start_byte": 1456, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_11335_20221
it('should close when clicking on the overlay backdrop', fakeAsync(() => { dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeFalsy(); })); it('should emit the backdropClick stream when clicking on the overlay backdrop', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const spy = jasmine.createSpy('backdropClick spy'); dialogRef.backdropClick().subscribe(spy); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; backdrop.click(); expect(spy).toHaveBeenCalledTimes(1); viewContainerFixture.detectChanges(); flush(); // Additional clicks after the dialog has closed should not be emitted backdrop.click(); expect(spy).toHaveBeenCalledTimes(1); })); it('should emit the keyboardEvent stream when key events target the overlay', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const spy = jasmine.createSpy('keyboardEvent spy'); dialogRef.keydownEvents().subscribe(spy); viewContainerFixture.detectChanges(); flush(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; let container = overlayContainerElement.querySelector('mat-dialog-container') as HTMLElement; dispatchKeyboardEvent(document.body, 'keydown', A); dispatchKeyboardEvent(backdrop, 'keydown', A); dispatchKeyboardEvent(container, 'keydown', A); expect(spy).toHaveBeenCalledTimes(3); })); it('should notify the observers if a dialog has been opened', () => { dialog.afterOpened.subscribe(ref => { expect(dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef})).toBe(ref); }); }); it('should notify the observers if all open dialogs have finished closing', fakeAsync(() => { const ref1 = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const ref2 = dialog.open(ContentElementDialog, {viewContainerRef: testViewContainerRef}); const spy = jasmine.createSpy('afterAllClosed spy'); dialog.afterAllClosed.subscribe(spy); ref1.close(); viewContainerFixture.detectChanges(); flush(); expect(spy).not.toHaveBeenCalled(); ref2.close(); viewContainerFixture.detectChanges(); flush(); expect(spy).toHaveBeenCalled(); })); it('should emit the afterAllClosed stream on subscribe if there are no open dialogs', () => { const spy = jasmine.createSpy('afterAllClosed spy'); dialog.afterAllClosed.subscribe(spy); expect(spy).toHaveBeenCalled(); }); it('should override the width of the overlay pane', () => { dialog.open(PizzaMsg, {width: '500px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.width).toBe('500px'); }); it('should override the height of the overlay pane', () => { dialog.open(PizzaMsg, {height: '100px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.height).toBe('100px'); }); it('should override the min-width of the overlay pane', () => { dialog.open(PizzaMsg, {minWidth: '500px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.minWidth).toBe('500px'); }); it('should override the max-width of the overlay pane', fakeAsync(() => { let dialogRef = dialog.open(PizzaMsg); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.maxWidth).toBe(''); dialogRef.close(); tick(500); viewContainerFixture.detectChanges(); dialogRef = dialog.open(PizzaMsg, {maxWidth: '100px'}); viewContainerFixture.detectChanges(); flush(); overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.maxWidth).toBe('100px'); })); it('should override the min-height of the overlay pane', () => { dialog.open(PizzaMsg, {minHeight: '300px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.minHeight).toBe('300px'); }); it('should override the max-height of the overlay pane', () => { dialog.open(PizzaMsg, {maxHeight: '100px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.maxHeight).toBe('100px'); }); it('should override the top offset of the overlay pane', () => { dialog.open(PizzaMsg, {position: {top: '100px'}}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.marginTop).toBe('100px'); }); it('should override the bottom offset of the overlay pane', () => { dialog.open(PizzaMsg, {position: {bottom: '200px'}}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.marginBottom).toBe('200px'); }); it('should override the left offset of the overlay pane', () => { dialog.open(PizzaMsg, {position: {left: '250px'}}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.marginLeft).toBe('250px'); }); it('should override the right offset of the overlay pane', () => { dialog.open(PizzaMsg, {position: {right: '125px'}}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.marginRight).toBe('125px'); }); it('should allow for the position to be updated', () => { let dialogRef = dialog.open(PizzaMsg, {position: {left: '250px'}}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.marginLeft).toBe('250px'); dialogRef.updatePosition({left: '500px'}); expect(overlayPane.style.marginLeft).toBe('500px'); }); it('should allow for the dimensions to be updated', () => { let dialogRef = dialog.open(PizzaMsg, {width: '100px'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.width).toBe('100px'); dialogRef.updateSize('200px'); expect(overlayPane.style.width).toBe('200px'); }); it('should reset the overlay dimensions to their initial size', () => { let dialogRef = dialog.open(PizzaMsg); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.width).toBeFalsy(); expect(overlayPane.style.height).toBeFalsy(); dialogRef.updateSize('200px', '200px'); expect(overlayPane.style.width).toBe('200px'); expect(overlayPane.style.height).toBe('200px'); dialogRef.updateSize(); expect(overlayPane.style.width).toBeFalsy(); expect(overlayPane.style.height).toBeFalsy(); }); it('should allow setting the layout direction', () => { dialog.open(PizzaMsg, {direction: 'rtl'}); viewContainerFixture.detectChanges(); let overlayPane = overlayContainerElement.querySelector('.cdk-global-overlay-wrapper')!; expect(overlayPane.getAttribute('dir')).toBe('rtl'); }); it('should inject the correct layout direction in the component instance', () => { const dialogRef = dialog.open(PizzaMsg, {direction: 'rtl'}); viewContainerFixture.detectChanges(); expect(dialogRef.componentInstance.directionality.value).toBe('rtl'); }); it('should fall back to injecting the global direction if none is passed by the config', () => { const dialogRef = dialog.open(PizzaMsg, {}); viewContainerFixture.detectChanges(); expect(dialogRef.componentInstance.directionality.value).toBe('ltr'); });
{ "commit_id": "ea0d1ba7b", "end_byte": 20221, "start_byte": 11335, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_20225_29381
it('should use the passed in ViewContainerRef from the config', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); // One view ref is for the container and one more for the component with the content. expect(testViewContainerRef.length).toBe(2); dialogRef.close(); viewContainerFixture.detectChanges(); flush(); expect(testViewContainerRef.length).toBe(0); })); it('should close all of the dialogs', fakeAsync(() => { dialog.open(PizzaMsg); dialog.open(PizzaMsg); dialog.open(PizzaMsg); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(3); dialog.closeAll(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(0); })); it('should close all dialogs when the user goes forwards/backwards in history', fakeAsync(() => { dialog.open(PizzaMsg); dialog.open(PizzaMsg); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(2); mockLocation.simulateUrlPop(''); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(0); })); it('should close all open dialogs when the location hash changes', fakeAsync(() => { dialog.open(PizzaMsg); dialog.open(PizzaMsg); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(2); mockLocation.simulateHashChange(''); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(0); })); it('should close all of the dialogs when the injectable is destroyed', fakeAsync(() => { dialog.open(PizzaMsg); dialog.open(PizzaMsg); dialog.open(PizzaMsg); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(3); dialog.ngOnDestroy(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(0); })); it('should complete open and close streams when the injectable is destroyed', fakeAsync(() => { const afterOpenedSpy = jasmine.createSpy('after opened spy'); const afterAllClosedSpy = jasmine.createSpy('after all closed spy'); const afterOpenedSubscription = dialog.afterOpened.subscribe({complete: afterOpenedSpy}); const afterAllClosedSubscription = dialog.afterAllClosed.subscribe({ complete: afterAllClosedSpy, }); dialog.ngOnDestroy(); expect(afterOpenedSpy).toHaveBeenCalled(); expect(afterAllClosedSpy).toHaveBeenCalled(); afterOpenedSubscription.unsubscribe(); afterAllClosedSubscription.unsubscribe(); })); it('should allow the consumer to disable closing a dialog on navigation', fakeAsync(() => { dialog.open(PizzaMsg); dialog.open(PizzaMsg, {closeOnNavigation: false}); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(2); mockLocation.simulateUrlPop(''); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('mat-dialog-container').length).toBe(1); })); it('should have the componentInstance available in the afterClosed callback', fakeAsync(() => { let dialogRef = dialog.open(PizzaMsg); let spy = jasmine.createSpy('afterClosed spy'); flushMicrotasks(); viewContainerFixture.detectChanges(); flushMicrotasks(); dialogRef.afterClosed().subscribe(() => { spy(); expect(dialogRef.componentInstance) .withContext('Expected component instance to be defined.') .toBeTruthy(); }); dialogRef.close(); flushMicrotasks(); viewContainerFixture.detectChanges(); tick(500); // Ensure that the callback actually fires. expect(spy).toHaveBeenCalled(); })); it('should be able to attach a custom scroll strategy', fakeAsync(() => { const scrollStrategy: ScrollStrategy = { attach: () => {}, enable: jasmine.createSpy('scroll strategy enable spy'), disable: () => {}, }; dialog.open(PizzaMsg, {scrollStrategy}); flush(); expect(scrollStrategy.enable).toHaveBeenCalled(); })); describe('passing in data', () => { it('should be able to pass in data', () => { let config = {data: {stringParam: 'hello', dateParam: new Date()}}; let instance = dialog.open(DialogWithInjectedData, config).componentInstance; expect(instance.data.stringParam).toBe(config.data.stringParam); expect(instance.data.dateParam).toBe(config.data.dateParam); }); it('should default to null if no data is passed', () => { expect(() => { let dialogRef = dialog.open(DialogWithInjectedData); expect(dialogRef.componentInstance.data).toBeNull(); }).not.toThrow(); }); }); it('should not keep a reference to the component after the dialog is closed', fakeAsync(() => { let dialogRef = dialog.open(PizzaMsg); expect(dialogRef.componentInstance).toBeTruthy(); dialogRef.close(); viewContainerFixture.detectChanges(); flush(); expect(dialogRef.componentInstance) .withContext('Expected reference to have been cleared.') .toBeFalsy(); })); it('should assign a unique id to each dialog', fakeAsync(() => { const one = dialog.open(PizzaMsg); const two = dialog.open(PizzaMsg); flush(); expect(one.id).toBeTruthy(); expect(two.id).toBeTruthy(); expect(one.id).not.toBe(two.id); })); it('should allow for the id to be overwritten', () => { const dialogRef = dialog.open(PizzaMsg, {id: 'pizza'}); expect(dialogRef.id).toBe('pizza'); }); it('should throw when trying to open a dialog with the same id as another dialog', () => { dialog.open(PizzaMsg, {id: 'pizza'}); expect(() => dialog.open(PizzaMsg, {id: 'pizza'})).toThrowError(/must be unique/g); }); it('should be able to find a dialog by id', () => { const dialogRef = dialog.open(PizzaMsg, {id: 'pizza'}); expect(dialog.getDialogById('pizza')).toBe(dialogRef); }); it('should toggle `aria-hidden` on the overlay container siblings', fakeAsync(() => { const sibling = document.createElement('div'); overlayContainerElement.parentNode!.appendChild(sibling); const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); expect(sibling.getAttribute('aria-hidden')) .withContext('Expected sibling to be hidden') .toBe('true'); expect(overlayContainerElement.hasAttribute('aria-hidden')) .withContext('Expected overlay container not to be hidden.') .toBe(false); dialogRef.close(); viewContainerFixture.detectChanges(); flush(); expect(sibling.hasAttribute('aria-hidden')) .withContext('Expected sibling to no longer be hidden.') .toBe(false); sibling.remove(); })); it('should restore `aria-hidden` to the overlay container siblings on close', fakeAsync(() => { const sibling = document.createElement('div'); sibling.setAttribute('aria-hidden', 'true'); overlayContainerElement.parentNode!.appendChild(sibling); const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); expect(sibling.getAttribute('aria-hidden')) .withContext('Expected sibling to be hidden.') .toBe('true'); dialogRef.close(); viewContainerFixture.detectChanges(); flush(); expect(sibling.getAttribute('aria-hidden')) .withContext('Expected sibling to remain hidden.') .toBe('true'); sibling.remove(); })); it('should not set `aria-hidden` on `aria-live` elements', fakeAsync(() => { const sibling = document.createElement('div'); sibling.setAttribute('aria-live', 'polite'); overlayContainerElement.parentNode!.appendChild(sibling); dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); expect(sibling.hasAttribute('aria-hidden')) .withContext('Expected live element not to be hidden.') .toBe(false); sibling.remove(); })); it('should add and remove classes while open', () => { let dialogRef = dialog.open(PizzaMsg, { disableClose: true, viewContainerRef: testViewContainerRef, }); const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(pane.classList).not.toContain( 'custom-class-one', 'Expected class to be initially missing', ); dialogRef.addPanelClass('custom-class-one'); expect(pane.classList).withContext('Expected class to be added').toContain('custom-class-one'); dialogRef.removePanelClass('custom-class-one'); expect(pane.classList).not.toContain('custom-class-one', 'Expected class to be removed'); });
{ "commit_id": "ea0d1ba7b", "end_byte": 29381, "start_byte": 20225, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_29385_38048
describe('disableClose option', () => { it('should prevent closing via clicks on the backdrop', fakeAsync(() => { dialog.open(PizzaMsg, {disableClose: true, viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeTruthy(); })); it('should prevent closing via the escape key', fakeAsync(() => { dialog.open(PizzaMsg, {disableClose: true, viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeTruthy(); })); it('should allow for the disableClose option to be updated while open', fakeAsync(() => { let dialogRef = dialog.open(PizzaMsg, { disableClose: true, viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; backdrop.click(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeTruthy(); dialogRef.disableClose = false; backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeFalsy(); })); it('should recapture focus when clicking on the backdrop', fakeAsync(() => { dialog.open(PizzaMsg, {disableClose: true, viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); flush(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; let input = overlayContainerElement.querySelector('input') as HTMLInputElement; expect(document.activeElement) .withContext('Expected input to be focused on open') .toBe(input); input.blur(); // Programmatic clicks might not move focus so we simulate it. backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected input to stay focused after click') .toBe(input); })); it( 'should recapture focus to the first tabbable element when clicking on the backdrop with ' + 'autoFocus set to "first-tabbable" (the default)', fakeAsync(() => { dialog.open(PizzaMsg, { disableClose: true, viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); flush(); let backdrop = overlayContainerElement.querySelector( '.cdk-overlay-backdrop', ) as HTMLElement; let input = overlayContainerElement.querySelector('input') as HTMLInputElement; expect(document.activeElement) .withContext('Expected input to be focused on open') .toBe(input); input.blur(); // Programmatic clicks might not move focus so we simulate it. backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected input to stay focused after click') .toBe(input); }), ); it( 'should recapture focus to the container when clicking on the backdrop with ' + 'autoFocus set to "dialog"', fakeAsync(() => { dialog.open(PizzaMsg, { disableClose: true, viewContainerRef: testViewContainerRef, autoFocus: 'dialog', }); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector( '.cdk-overlay-backdrop', ) as HTMLElement; let container = overlayContainerElement.querySelector( '.mat-mdc-dialog-container', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected container to be focused on open') .toBe(container); container.blur(); // Programmatic clicks might not move focus so we simulate it. backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected container to stay focused after click') .toBe(container); }), ); }); it( 'should recapture focus to the first header when clicking on the backdrop with ' + 'autoFocus set to "first-heading"', fakeAsync(() => { dialog.open(ContentElementDialog, { disableClose: true, viewContainerRef: testViewContainerRef, autoFocus: 'first-heading', }); flush(); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; let firstHeader = overlayContainerElement.querySelector( '.mat-mdc-dialog-title[tabindex="-1"]', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected first header to be focused on open') .toBe(firstHeader); firstHeader.blur(); // Programmatic clicks might not move focus so we simulate it. backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected first header to stay focused after click') .toBe(firstHeader); }), ); it( 'should recapture focus to the first element that matches the css selector when ' + 'clicking on the backdrop with autoFocus set to a css selector', fakeAsync(() => { dialog.open(ContentElementDialog, { disableClose: true, viewContainerRef: testViewContainerRef, autoFocus: 'button', }); flush(); viewContainerFixture.detectChanges(); let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement; let firstButton = overlayContainerElement.querySelector( '[mat-dialog-close]', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected first button to be focused on open') .toBe(firstButton); firstButton.blur(); // Programmatic clicks might not move focus so we simulate it. backdrop.click(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected first button to stay focused after click') .toBe(firstButton); }), ); describe('hasBackdrop option', () => { it('should have a backdrop', () => { dialog.open(PizzaMsg, {hasBackdrop: true, viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeTruthy(); }); it('should not have a backdrop', () => { dialog.open(PizzaMsg, {hasBackdrop: false, viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy(); }); }); describe('panelClass option', () => { it('should have custom panel class', () => { dialog.open(PizzaMsg, { panelClass: 'custom-panel-class', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.custom-panel-class')).toBeTruthy(); }); }); describe('backdropClass option', () => { it('should have default backdrop class', () => { dialog.open(PizzaMsg, {backdropClass: '', viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.cdk-overlay-dark-backdrop')).toBeTruthy(); }); it('should have custom backdrop class', () => { dialog.open(PizzaMsg, { backdropClass: 'custom-backdrop-class', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.custom-backdrop-class')).toBeTruthy(); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 38048, "start_byte": 29385, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_38052_46631
describe('focus management', () => { // When testing focus, all of the elements must be in the DOM. beforeEach(() => document.body.appendChild(overlayContainerElement)); afterEach(() => overlayContainerElement.remove()); it('should focus the first tabbable element of the dialog on open (the default)', fakeAsync(() => { dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement!.tagName) .withContext('Expected first tabbable element (input) in the dialog to be focused.') .toBe('INPUT'); })); it('should focus the dialog element on open', fakeAsync(() => { dialog.open(PizzaMsg, { viewContainerRef: testViewContainerRef, autoFocus: 'dialog', }); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); let container = overlayContainerElement.querySelector( '.mat-mdc-dialog-container', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected container to be focused on open') .toBe(container); })); it('should focus the first header element on open', fakeAsync(() => { dialog.open(ContentElementDialog, { viewContainerRef: testViewContainerRef, autoFocus: 'first-heading', }); flush(); viewContainerFixture.detectChanges(); let firstHeader = overlayContainerElement.querySelector( 'h2[tabindex="-1"]', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected first header to be focused on open') .toBe(firstHeader); })); it('should focus the first element that matches the css selector from autoFocus on open', fakeAsync(() => { dialog.open(PizzaMsg, { viewContainerRef: testViewContainerRef, autoFocus: 'p', }); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); let firstParagraph = overlayContainerElement.querySelector( 'p[tabindex="-1"]', ) as HTMLInputElement; expect(document.activeElement) .withContext('Expected first paragraph to be focused on open') .toBe(firstParagraph); })); it('should attach the focus trap even if automatic focus is disabled', fakeAsync(() => { dialog.open(PizzaMsg, { viewContainerRef: testViewContainerRef, autoFocus: 'false', }); viewContainerFixture.detectChanges(); flush(); expect( overlayContainerElement.querySelectorAll('.cdk-focus-trap-anchor').length, ).toBeGreaterThan(0); })); it('should re-focus trigger element when dialog closes', fakeAsync(() => { // Create a element that has focus before the dialog is opened. let button = document.createElement('button'); button.id = 'dialog-trigger'; document.body.appendChild(button); button.focus(); const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); flush(); viewContainerFixture.detectChanges(); expect(document.activeElement!.id).not.toBe( 'dialog-trigger', 'Expected the focus to change when dialog was opened.', ); dialogRef.close(); expect(document.activeElement!.id).not.toBe( 'dialog-trigger', 'Expected the focus not to have changed before the animation finishes.', ); viewContainerFixture.detectChanges(); tick(500); expect(document.activeElement!.id) .withContext('Expected that the trigger was refocused after the dialog is closed.') .toBe('dialog-trigger'); button.remove(); })); it('should re-focus trigger element inside the shadow DOM when dialog closes', fakeAsync(() => { if (!_supportsShadowDom()) { return; } viewContainerFixture.destroy(); const fixture = TestBed.createComponent(ShadowDomComponent); fixture.detectChanges(); flush(); const button = fixture.debugElement.query(By.css('button'))!.nativeElement; button.focus(); const dialogRef = dialog.open(PizzaMsg); fixture.detectChanges(); flush(); const spy = spyOn(button, 'focus').and.callThrough(); dialogRef.close(); fixture.detectChanges(); tick(500); expect(spy).toHaveBeenCalled(); })); it('should re-focus the trigger via keyboard when closed via escape key', fakeAsync(() => { const button = document.createElement('button'); let lastFocusOrigin: FocusOrigin = null; focusMonitor.monitor(button, false).subscribe(focusOrigin => (lastFocusOrigin = focusOrigin)); document.body.appendChild(button); button.focus(); // Patch the element focus after the initial and real focus, because otherwise the // `activeElement` won't be set, and the dialog won't be able to restore focus to an // element. patchElementFocus(button); dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); tick(500); viewContainerFixture.detectChanges(); flushMicrotasks(); expect(lastFocusOrigin!).withContext('Expected the trigger button to be blurred').toBeNull(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); flushMicrotasks(); viewContainerFixture.detectChanges(); tick(500); expect(lastFocusOrigin!) .withContext('Expected the trigger button to be focused via keyboard') .toBe('keyboard'); focusMonitor.stopMonitoring(button); button.remove(); })); it('should re-focus the trigger via mouse when backdrop has been clicked', fakeAsync(() => { const button = document.createElement('button'); let lastFocusOrigin: FocusOrigin = null; focusMonitor.monitor(button, false).subscribe(focusOrigin => (lastFocusOrigin = focusOrigin)); document.body.appendChild(button); button.focus(); // Patch the element focus after the initial and real focus, because otherwise the // `activeElement` won't be set, and the dialog won't be able to restore focus to an // element. patchElementFocus(button); dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); tick(500); viewContainerFixture.detectChanges(); flushMicrotasks(); expect(lastFocusOrigin!).withContext('Expected the trigger button to be blurred').toBeNull(); const backdrop = overlayContainerElement.querySelector( '.cdk-overlay-backdrop', ) as HTMLElement; backdrop.click(); viewContainerFixture.detectChanges(); tick(500); expect(lastFocusOrigin!) .withContext('Expected the trigger button to be focused via mouse') .toBe('mouse'); focusMonitor.stopMonitoring(button); button.remove(); })); it('should re-focus via keyboard if the close button has been triggered through keyboard', fakeAsync(() => { const button = document.createElement('button'); let lastFocusOrigin: FocusOrigin = null; focusMonitor.monitor(button, false).subscribe(focusOrigin => (lastFocusOrigin = focusOrigin)); document.body.appendChild(button); button.focus(); // Patch the element focus after the initial and real focus, because otherwise the // `activeElement` won't be set, and the dialog won't be able to restore focus to an // element. patchElementFocus(button); dialog.open(ContentElementDialog, {viewContainerRef: testViewContainerRef}); tick(500); viewContainerFixture.detectChanges(); flushMicrotasks(); expect(lastFocusOrigin!).withContext('Expected the trigger button to be blurred').toBeNull(); const closeButton = overlayContainerElement.querySelector( 'button[mat-dialog-close]', ) as HTMLElement; // Fake the behavior of pressing the SPACE key on a button element. Browsers fire a `click` // event with a MouseEvent, which has coordinates that are out of the element boundaries. dispatchMouseEvent(closeButton, 'click', 0, 0); viewContainerFixture.detectChanges(); tick(500); expect(lastFocusOrigin!) .withContext('Expected the trigger button to be focused via keyboard') .toBe('keyboard'); focusMonitor.stopMonitoring(button); button.remove(); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 46631, "start_byte": 38052, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_46637_51823
it('should re-focus via mouse if the close button has been clicked', fakeAsync(() => { const button = document.createElement('button'); let lastFocusOrigin: FocusOrigin = null; focusMonitor.monitor(button, false).subscribe(focusOrigin => (lastFocusOrigin = focusOrigin)); document.body.appendChild(button); button.focus(); // Patch the element focus after the initial and real focus, because otherwise the // `activeElement` won't be set, and the dialog won't be able to restore focus to an // element. patchElementFocus(button); dialog.open(ContentElementDialog, {viewContainerRef: testViewContainerRef}); tick(500); viewContainerFixture.detectChanges(); flushMicrotasks(); expect(lastFocusOrigin!).withContext('Expected the trigger button to be blurred').toBeNull(); const closeButton = overlayContainerElement.querySelector( 'button[mat-dialog-close]', ) as HTMLElement; // The dialog close button detects the focus origin by inspecting the click event. If // coordinates of the click are not present, it assumes that the click has been triggered // by keyboard. dispatchMouseEvent(closeButton, 'click', 10, 10); viewContainerFixture.detectChanges(); tick(500); expect(lastFocusOrigin!) .withContext('Expected the trigger button to be focused via mouse') .toBe('mouse'); focusMonitor.stopMonitoring(button); button.remove(); })); it('should allow the consumer to shift focus in afterClosed', fakeAsync(() => { // Create a element that has focus before the dialog is opened. let button = document.createElement('button'); let input = document.createElement('input'); button.id = 'dialog-trigger'; input.id = 'input-to-be-focused'; document.body.appendChild(button); document.body.appendChild(input); button.focus(); let dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); tick(500); viewContainerFixture.detectChanges(); dialogRef.afterClosed().subscribe(() => input.focus()); dialogRef.close(); tick(500); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement!.id) .withContext('Expected that the trigger was refocused after the dialog is closed.') .toBe('input-to-be-focused'); button.remove(); input.remove(); flush(); })); it('should move focus to the container if there are no focusable elements in the dialog', fakeAsync(() => { dialog.open(DialogWithoutFocusableElements); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement!.tagName) .withContext('Expected dialog container to be focused.') .toBe('MAT-DIALOG-CONTAINER'); })); it('should be able to disable focus restoration', fakeAsync(() => { // Create a element that has focus before the dialog is opened. const button = document.createElement('button'); button.id = 'dialog-trigger'; document.body.appendChild(button); button.focus(); const dialogRef = dialog.open(PizzaMsg, { viewContainerRef: testViewContainerRef, restoreFocus: false, }); flush(); viewContainerFixture.detectChanges(); expect(document.activeElement!.id).not.toBe( 'dialog-trigger', 'Expected the focus to change when dialog was opened.', ); dialogRef.close(); viewContainerFixture.detectChanges(); tick(500); expect(document.activeElement!.id).not.toBe( 'dialog-trigger', 'Expected focus not to have been restored.', ); button.remove(); })); it('should not move focus if it was moved outside the dialog while animating', fakeAsync(() => { // Create a element that has focus before the dialog is opened. const button = document.createElement('button'); const otherButton = document.createElement('button'); const body = document.body; button.id = 'dialog-trigger'; otherButton.id = 'other-button'; body.appendChild(button); body.appendChild(otherButton); button.focus(); const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); flush(); viewContainerFixture.detectChanges(); expect(document.activeElement!.id).not.toBe( 'dialog-trigger', 'Expected the focus to change when dialog was opened.', ); // Start the closing sequence and move focus out of dialog. dialogRef.close(); otherButton.focus(); expect(document.activeElement!.id) .withContext('Expected focus to be on the alternate button.') .toBe('other-button'); viewContainerFixture.detectChanges(); flush(); expect(document.activeElement!.id) .withContext('Expected focus to stay on the alternate button.') .toBe('other-button'); button.remove(); otherButton.remove(); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 51823, "start_byte": 46637, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_51827_62006
describe('dialog content elements', () => { let dialogRef: MatDialogRef<any>; let hostInstance: ContentElementDialog | ComponentWithContentElementTemplateRef; describe('inside component dialog', () => { beforeEach(fakeAsync(() => { dialogRef = dialog.open(ContentElementDialog, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); hostInstance = dialogRef.componentInstance; })); runContentElementTests(); }); describe('inside template portal', () => { beforeEach(fakeAsync(() => { const fixture = TestBed.createComponent(ComponentWithContentElementTemplateRef); fixture.detectChanges(); dialogRef = dialog.open(fixture.componentInstance.templateRef, { viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); flush(); hostInstance = fixture.componentInstance; })); runContentElementTests(); }); it('should set the aria-labelledby attribute to the id of the title under OnPush host', fakeAsync(() => { @Component({ standalone: true, imports: [MatDialogTitle], template: `@if (showTitle()) { <h2 mat-dialog-title>This is the first title</h2> }`, }) class DialogCmp { showTitle = signal(true); } @Component({ template: '', selector: 'child', standalone: true, }) class Child { readonly viewContainerRef = inject(ViewContainerRef); readonly dialog = inject(MatDialog); dialogRef?: MatDialogRef<DialogCmp>; open() { this.dialogRef = this.dialog.open(DialogCmp, {viewContainerRef: this.viewContainerRef}); } } @Component({ standalone: true, imports: [Child], template: `<child></child>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class OnPushHost { @ViewChild(Child, {static: true}) child: Child; } const hostFixture = TestBed.createComponent(OnPushHost); hostFixture.componentInstance.child.open(); hostFixture.detectChanges(); flush(); hostFixture.detectChanges(); const overlayContainer = TestBed.inject(OverlayContainer); const title = overlayContainer.getContainerElement().querySelector('[mat-dialog-title]')!; const container = overlayContainerElement.querySelector('mat-dialog-container')!; expect(title.id).withContext('Expected title element to have an id.').toBeTruthy(); expect(container.getAttribute('aria-labelledby')) .withContext('Expected the aria-labelledby to match the title id.') .toBe(title.id); hostFixture.componentInstance.child.dialogRef?.componentInstance.showTitle.set(false); hostFixture.detectChanges(); flush(); hostFixture.detectChanges(); expect(container.getAttribute('aria-labelledby')).toBe(null); })); function runContentElementTests() { it('should close the dialog when clicking on the close button', fakeAsync(() => { expect(overlayContainerElement.querySelectorAll('.mat-mdc-dialog-container').length).toBe( 1, ); (overlayContainerElement.querySelector('button[mat-dialog-close]') as HTMLElement).click(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelectorAll('.mat-mdc-dialog-container').length).toBe( 0, ); })); it('should not close if [mat-dialog-close] is applied on a non-button node', () => { expect(overlayContainerElement.querySelectorAll('.mat-mdc-dialog-container').length).toBe( 1, ); (overlayContainerElement.querySelector('div[mat-dialog-close]') as HTMLElement).click(); expect(overlayContainerElement.querySelectorAll('.mat-mdc-dialog-container').length).toBe( 1, ); }); it('should allow for a user-specified aria-label on the close button', fakeAsync(() => { let button = overlayContainerElement.querySelector('.close-with-aria-label')!; expect(button.getAttribute('aria-label')).toBe('Best close button ever'); })); it('should set the "type" attribute of the close button if not set manually', () => { let button = overlayContainerElement.querySelector('button[mat-dialog-close]')!; expect(button.getAttribute('type')).toBe('button'); }); it('should not override type attribute of the close button if set manually', () => { let button = overlayContainerElement.querySelector('button.with-submit')!; expect(button.getAttribute('type')).toBe('submit'); }); it('should return the [mat-dialog-close] result when clicking the close button', fakeAsync(() => { let afterCloseCallback = jasmine.createSpy('afterClose callback'); dialogRef.afterClosed().subscribe(afterCloseCallback); (overlayContainerElement.querySelector('button.close-with-true') as HTMLElement).click(); viewContainerFixture.detectChanges(); flush(); expect(afterCloseCallback).toHaveBeenCalledWith(true); })); it('should set the aria-labelledby attribute to the id of the title', fakeAsync(() => { let title = overlayContainerElement.querySelector('[mat-dialog-title]')!; let container = overlayContainerElement.querySelector('mat-dialog-container')!; flush(); viewContainerFixture.detectChanges(); expect(title.id).withContext('Expected title element to have an id.').toBeTruthy(); expect(container.getAttribute('aria-labelledby')) .withContext('Expected the aria-labelledby to match the title id.') .toBe(title.id); })); it('should update the aria-labelledby attribute if two titles are swapped', fakeAsync(() => { const container = overlayContainerElement.querySelector('mat-dialog-container')!; let title = overlayContainerElement.querySelector('[mat-dialog-title]')!; flush(); viewContainerFixture.detectChanges(); const previousId = title.id; expect(title.id).toBeTruthy(); expect(container.getAttribute('aria-labelledby')).toBe(title.id); hostInstance.shownTitle = 'second'; viewContainerFixture.changeDetectorRef.markForCheck(); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); title = overlayContainerElement.querySelector('[mat-dialog-title]')!; expect(title.id).toBeTruthy(); expect(title.id).not.toBe(previousId); expect(container.getAttribute('aria-labelledby')).toBe(title.id); })); it('should update the aria-labelledby attribute if multiple titles are present and one is removed', fakeAsync(() => { const container = overlayContainerElement.querySelector('mat-dialog-container')!; hostInstance.shownTitle = 'all'; viewContainerFixture.changeDetectorRef.markForCheck(); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); const titles = overlayContainerElement.querySelectorAll('[mat-dialog-title]'); expect(titles.length).toBe(3); expect(container.getAttribute('aria-labelledby')).toBe(titles[0].id); hostInstance.shownTitle = 'second'; viewContainerFixture.changeDetectorRef.markForCheck(); viewContainerFixture.detectChanges(); flush(); viewContainerFixture.detectChanges(); expect(container.getAttribute('aria-labelledby')).toBe(titles[1].id); })); it('should add correct css class according to given [align] input in [mat-dialog-actions]', () => { let actions = overlayContainerElement.querySelector('mat-dialog-actions')!; expect(actions) .withContext('Expected action buttons to not have class align-center') .not.toHaveClass('mat-mdc-dialog-actions-align-center'); expect(actions) .withContext('Expected action buttons to have class align-end') .toHaveClass('mat-mdc-dialog-actions-align-end'); }); } }); describe('aria-labelledby', () => { it('should be able to set a custom aria-labelledby', () => { dialog.open(PizzaMsg, { ariaLabelledBy: 'Labelled By', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); const container = overlayContainerElement.querySelector('mat-dialog-container')!; expect(container.getAttribute('aria-labelledby')).toBe('Labelled By'); }); it( 'should not set the aria-labelledby automatically if it has an aria-label ' + 'and an aria-labelledby', fakeAsync(() => { dialog.open(ContentElementDialog, { ariaLabel: 'Hello there', ariaLabelledBy: 'Labelled By', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); tick(); viewContainerFixture.detectChanges(); const container = overlayContainerElement.querySelector('mat-dialog-container')!; expect(container.hasAttribute('aria-labelledby')).toBe(false); }), ); it( 'should set the aria-labelledby attribute to the config provided aria-labelledby ' + 'instead of the mat-dialog-title id', fakeAsync(() => { dialog.open(ContentElementDialog, { ariaLabelledBy: 'Labelled By', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); flush(); let title = overlayContainerElement.querySelector('[mat-dialog-title]')!; let container = overlayContainerElement.querySelector('mat-dialog-container')!; flush(); viewContainerFixture.detectChanges(); expect(title.id).withContext('Expected title element to have an id.').toBeTruthy(); expect(container.getAttribute('aria-labelledby')).toBe('Labelled By'); }), ); });
{ "commit_id": "ea0d1ba7b", "end_byte": 62006, "start_byte": 51827, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_62010_72014
describe('aria-label', () => { it('should be able to set a custom aria-label', () => { dialog.open(PizzaMsg, {ariaLabel: 'Hello there', viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); const container = overlayContainerElement.querySelector('mat-dialog-container')!; expect(container.getAttribute('aria-label')).toBe('Hello there'); }); it('should not set the aria-labelledby automatically if it has an aria-label', fakeAsync(() => { dialog.open(ContentElementDialog, { ariaLabel: 'Hello there', viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); tick(); viewContainerFixture.detectChanges(); const container = overlayContainerElement.querySelector('mat-dialog-container')!; expect(container.hasAttribute('aria-labelledby')).toBe(false); })); }); it('should dispose backdrop if containing dialog view is destroyed', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeDefined(); dialogRef.close(); viewContainerFixture.componentInstance.showChildView = false; viewContainerFixture.changeDetectorRef.markForCheck(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBe(null); })); }); describe('MatDialog with a parent MatDialog', () => { let parentDialog: MatDialog; let childDialog: MatDialog; let overlayContainerElement: HTMLElement; let fixture: ComponentFixture<ComponentThatProvidesMatDialog>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatDialogModule, NoopAnimationsModule, ComponentThatProvidesMatDialog], providers: [ { provide: OverlayContainer, useFactory: () => { overlayContainerElement = document.createElement('div'); return {getContainerElement: () => overlayContainerElement}; }, }, {provide: Location, useClass: SpyLocation}, ], }); parentDialog = TestBed.inject(MatDialog); fixture = TestBed.createComponent(ComponentThatProvidesMatDialog); childDialog = fixture.componentInstance.dialog; fixture.detectChanges(); })); afterEach(() => { overlayContainerElement.innerHTML = ''; }); it('should close dialogs opened by a parent when calling closeAll on a child MatDialog', fakeAsync(() => { parentDialog.open(PizzaMsg); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .withContext('Expected a dialog to be opened') .toContain('Pizza'); childDialog.closeAll(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent!.trim()) .withContext('Expected closeAll on child MatDialog to close dialog opened by parent') .toBe(''); })); it('should close dialogs opened by a child when calling closeAll on a parent MatDialog', fakeAsync(() => { childDialog.open(PizzaMsg); fixture.detectChanges(); expect(overlayContainerElement.textContent) .withContext('Expected a dialog to be opened') .toContain('Pizza'); parentDialog.closeAll(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent!.trim()) .withContext('Expected closeAll on parent MatDialog to close dialog opened by child') .toBe(''); })); it('should close the top dialog via the escape key', fakeAsync(() => { childDialog.open(PizzaMsg); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); fixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull(); })); it('should not close the parent dialogs when a child is destroyed', fakeAsync(() => { parentDialog.open(PizzaMsg); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .withContext('Expected a dialog to be opened') .toContain('Pizza'); childDialog.ngOnDestroy(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .withContext('Expected a dialog to be opened') .toContain('Pizza'); })); }); describe('MatDialog with default options', () => { let dialog: MatDialog; let overlayContainerElement: HTMLElement; let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; beforeEach(fakeAsync(() => { const defaultConfig = { hasBackdrop: false, disableClose: true, width: '100px', height: '100px', minWidth: '50px', minHeight: '50px', maxWidth: '150px', maxHeight: '150px', autoFocus: 'dialog', }; TestBed.configureTestingModule({ imports: [ MatDialogModule, NoopAnimationsModule, ComponentWithChildViewContainer, DirectiveWithViewContainer, ], providers: [{provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: defaultConfig}], }); dialog = TestBed.inject(MatDialog); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; })); it('should use the provided defaults', () => { dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeTruthy(); expect(document.activeElement!.tagName).not.toBe('INPUT'); let overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(overlayPane.style.width).toBe('100px'); expect(overlayPane.style.height).toBe('100px'); expect(overlayPane.style.minWidth).toBe('50px'); expect(overlayPane.style.minHeight).toBe('50px'); expect(overlayPane.style.maxWidth).toBe('150px'); expect(overlayPane.style.maxHeight).toBe('150px'); }); it('should be overridable by open() options', fakeAsync(() => { dialog.open(PizzaMsg, { hasBackdrop: true, disableClose: false, viewContainerRef: testViewContainerRef, }); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeTruthy(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeFalsy(); })); }); describe('MatDialog with animations enabled', () => { let dialog: MatDialog; let testViewContainerRef: ViewContainerRef; let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ MatDialogModule, BrowserAnimationsModule, ComponentWithChildViewContainer, DirectiveWithViewContainer, ], }); dialog = TestBed.inject(MatDialog); viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer); viewContainerFixture.detectChanges(); testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer; })); it('should emit when dialog opening animation is complete', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); const spy = jasmine.createSpy('afterOpen spy'); dialogRef.afterOpened().subscribe(spy); viewContainerFixture.detectChanges(); // callback should not be called before animation is complete expect(spy).not.toHaveBeenCalled(); tick(OPEN_ANIMATION_DURATION); flush(); expect(spy).toHaveBeenCalled(); })); it('should return the current state of the dialog', fakeAsync(() => { const dialogRef = dialog.open(PizzaMsg, {viewContainerRef: testViewContainerRef}); expect(dialogRef.getState()).toBe(MatDialogState.OPEN); dialogRef.close(); viewContainerFixture.detectChanges(); expect(dialogRef.getState()).toBe(MatDialogState.CLOSING); // Ensure that the closing state is still set if half of the animation has // passed by. The dialog state should be only set to `closed` when the dialog // finished the close animation. tick(CLOSE_ANIMATION_DURATION / 2); expect(dialogRef.getState()).toBe(MatDialogState.CLOSING); // Flush the remaining duration of the closing animation. We flush all other remaining // tasks (e.g. the fallback close timeout) to avoid fakeAsync pending timer failures. flush(); expect(dialogRef.getState()).toBe(MatDialogState.CLOSED); })); }); describe('MatDialog with explicit injector provided', () => { let overlayContainerElement: HTMLElement; let fixture: ComponentFixture<ModuleBoundDialogParentComponent>; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatDialogModule, BrowserAnimationsModule, ModuleBoundDialogParentComponent], }); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); fixture = TestBed.createComponent(ModuleBoundDialogParentComponent); })); it('should use the standalone injector and render the dialog successfully', () => { fixture.componentInstance.openDialog(); fixture.detectChanges(); expect( overlayContainerElement.querySelector('module-bound-dialog-child-component')!.innerHTML, ).toEqual('<p>Pasta</p>'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 72014, "start_byte": 62010, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog.spec.ts_72016_77842
@Directive({ selector: 'dir-with-view-container', standalone: true, }) class DirectiveWithViewContainer { viewContainerRef = inject(ViewContainerRef); } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: 'hello', standalone: false, }) class ComponentWithOnPushViewContainer { viewContainerRef = inject(ViewContainerRef); } @Component({ selector: 'arbitrary-component', template: `@if (showChildView) {<dir-with-view-container></dir-with-view-container>}`, standalone: true, imports: [DirectiveWithViewContainer], }) class ComponentWithChildViewContainer { showChildView = true; @ViewChild(DirectiveWithViewContainer) childWithViewContainer: DirectiveWithViewContainer; get childViewContainer() { return this.childWithViewContainer.viewContainerRef; } } @Component({ selector: 'arbitrary-component-with-template-ref', template: `<ng-template let-data let-dialogRef="dialogRef"> Cheese {{localValue}} {{data?.value}}{{setDialogRef(dialogRef)}}</ng-template>`, standalone: true, }) class ComponentWithTemplateRef { localValue: string; dialogRef: MatDialogRef<any>; @ViewChild(TemplateRef) templateRef: TemplateRef<any>; setDialogRef(dialogRef: MatDialogRef<any>): string { this.dialogRef = dialogRef; return ''; } } /** Simple component for testing ComponentPortal. */ @Component({ template: '<p>Pizza</p> <input> <button>Close</button>', standalone: true, }) class PizzaMsg { dialogRef = inject<MatDialogRef<PizzaMsg>>(MatDialogRef); dialogInjector = inject(Injector); directionality = inject(Directionality); } @Component({ template: ` @if (shouldShowTitle('first')) { <h2 mat-dialog-title>This is the first title</h2> } @if (shouldShowTitle('second')) { <h2 mat-dialog-title>This is the second title</h2> } @if (shouldShowTitle('third')) { <h2 mat-dialog-title>This is the third title</h2> } <mat-dialog-content>Lorem ipsum dolor sit amet.</mat-dialog-content> <mat-dialog-actions align="end"> <button mat-dialog-close>Close</button> <button class="close-with-true" [mat-dialog-close]="true">Close and return true</button> <button class="close-with-aria-label" aria-label="Best close button ever" [mat-dialog-close]="true"></button> <div mat-dialog-close>Should not close</div> <button class="with-submit" type="submit" mat-dialog-close>Should have submit</button> </mat-dialog-actions> `, standalone: true, imports: [MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose], }) class ContentElementDialog { shownTitle: 'first' | 'second' | 'third' | 'all' = 'first'; shouldShowTitle(name: string) { return this.shownTitle === 'all' || this.shownTitle === name; } } @Component({ template: ` <ng-template> @if (shouldShowTitle('first')) { <h2 mat-dialog-title>This is the first title</h2> } @if (shouldShowTitle('second')) { <h2 mat-dialog-title>This is the second title</h2> } @if (shouldShowTitle('third')) { <h2 mat-dialog-title>This is the third title</h2> } <mat-dialog-content>Lorem ipsum dolor sit amet.</mat-dialog-content> <mat-dialog-actions align="end"> <button mat-dialog-close>Close</button> <button class="close-with-true" [mat-dialog-close]="true">Close and return true</button> <button class="close-with-aria-label" aria-label="Best close button ever" [mat-dialog-close]="true"></button> <div mat-dialog-close>Should not close</div> <button class="with-submit" type="submit" mat-dialog-close>Should have submit</button> </mat-dialog-actions> </ng-template> `, standalone: true, imports: [MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose], }) class ComponentWithContentElementTemplateRef { @ViewChild(TemplateRef) templateRef: TemplateRef<any>; shownTitle: 'first' | 'second' | 'third' | 'all' = 'first'; shouldShowTitle(name: string) { return this.shownTitle === 'all' || this.shownTitle === name; } } @Component({ template: '', providers: [MatDialog], standalone: true, }) class ComponentThatProvidesMatDialog { dialog = inject(MatDialog); } /** Simple component for testing ComponentPortal. */ @Component({ template: '', standalone: true, }) class DialogWithInjectedData { data = inject(MAT_DIALOG_DATA); } @Component({ template: '<p>Pasta</p>', standalone: true, }) class DialogWithoutFocusableElements {} @Component({ template: `<button>I'm a button</button>`, encapsulation: ViewEncapsulation.ShadowDom, standalone: false, }) class ShadowDomComponent {} @Component({ template: '', standalone: true, }) class ModuleBoundDialogParentComponent { private _injector = inject(Injector); private _dialog = inject(MatDialog); openDialog(): void { const ngModuleRef = createNgModuleRef( ModuleBoundDialogModule, /* parentInjector */ this._injector, ); this._dialog.open(ModuleBoundDialogComponent, {injector: ngModuleRef.injector}); } } @Injectable() class ModuleBoundDialogService { name = 'Pasta'; } @Component({ template: '<module-bound-dialog-child-component></module-bound-dialog-child-component>', standalone: true, imports: [forwardRef(() => ModuleBoundDialogChildComponent)], }) class ModuleBoundDialogComponent {} @Component({ selector: 'module-bound-dialog-child-component', template: '<p>{{service.name}}</p>', standalone: true, }) class ModuleBoundDialogChildComponent { service = inject(ModuleBoundDialogService); } @NgModule({ imports: [ModuleBoundDialogComponent, ModuleBoundDialogChildComponent], providers: [ModuleBoundDialogService], }) class ModuleBoundDialogModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 77842, "start_byte": 72016, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog.spec.ts" }
components/src/material/dialog/dialog-container.html_0_178
<div class="mat-mdc-dialog-inner-container mdc-dialog__container"> <div class="mat-mdc-dialog-surface mdc-dialog__surface"> <ng-template cdkPortalOutlet /> </div> </div>
{ "commit_id": "ea0d1ba7b", "end_byte": 178, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-container.html" }
components/src/material/dialog/_dialog-legacy-padding.scss_0_1174
// Legacy padding for the dialog. Copied from the non-MDC dialog styles. $legacy-padding: 24px !default; /// Mixin that applies creates styles for MDC-based dialog's to have legacy outer /// padding. By default, the dialog does not have any padding. The individual directives /// such as `matDialogContent`, `matDialogActions` or `matDialogTitle` set the padding. @mixin legacy-padding() { // Sets the outer padding for the projected dialog user-content. .mat-mdc-dialog-surface { padding: $legacy-padding; } // Updates the MDC title, content and action elements to account for the legacy outer // padding. The elements will be shifted so that they behave as if there is no margin. // This allows us to still rely on MDC's dialog spacing while maintaining a default outer // padding for backwards compatibility. .mat-mdc-dialog-container { .mat-mdc-dialog-title { margin-top: -$legacy-padding; } .mat-mdc-dialog-actions { margin-bottom: -$legacy-padding; } .mat-mdc-dialog-title, .mat-mdc-dialog-content, .mat-mdc-dialog-actions { margin-left: -$legacy-padding; margin-right: -$legacy-padding; } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1174, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/_dialog-legacy-padding.scss" }
components/src/material/dialog/dialog-ref.ts_0_8332
/** * @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 of the lifecycle of a dialog. */ import {FocusOrigin} from '@angular/cdk/a11y'; import {merge, Observable, Subject} from 'rxjs'; import {DialogRef} from '@angular/cdk/dialog'; import {DialogPosition, MatDialogConfig} from './dialog-config'; import {MatDialogContainer} from './dialog-container'; import {filter, take} from 'rxjs/operators'; import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes'; import {GlobalPositionStrategy} from '@angular/cdk/overlay'; import {ComponentRef} from '@angular/core'; export enum MatDialogState { OPEN, CLOSING, CLOSED, } /** * Reference to a dialog opened via the MatDialog service. */ export class MatDialogRef<T, R = any> { /** The instance of component opened into the dialog. */ componentInstance: T; /** * `ComponentRef` of the component opened into the dialog. Will be * null when the dialog is opened using a `TemplateRef`. */ readonly componentRef: ComponentRef<T> | null; /** Whether the user is allowed to close the dialog. */ disableClose: boolean | undefined; /** Unique ID for the dialog. */ id: string; /** Subject for notifying the user that the dialog has finished opening. */ private readonly _afterOpened = new Subject<void>(); /** Subject for notifying the user that the dialog has started closing. */ private readonly _beforeClosed = new Subject<R | undefined>(); /** Result to be passed to afterClosed. */ private _result: R | undefined; /** Handle to the timeout that's running as a fallback in case the exit animation doesn't fire. */ private _closeFallbackTimeout: number; /** Current state of the dialog. */ private _state = MatDialogState.OPEN; // TODO(crisbeto): we shouldn't have to declare this property, because `DialogRef.close` // already has a second `options` parameter that we can use. The problem is that internal tests // have assertions like `expect(MatDialogRef.close).toHaveBeenCalledWith(foo)` which will break, // because it'll be called with two arguments by things like `MatDialogClose`. /** Interaction that caused the dialog to close. */ private _closeInteractionType: FocusOrigin | undefined; constructor( private _ref: DialogRef<R, T>, config: MatDialogConfig, public _containerInstance: MatDialogContainer, ) { this.disableClose = config.disableClose; this.id = _ref.id; // Used to target panels specifically tied to dialogs. _ref.addPanelClass('mat-mdc-dialog-panel'); // Emit when opening animation completes _containerInstance._animationStateChanged .pipe( filter(event => event.state === 'opened'), take(1), ) .subscribe(() => { this._afterOpened.next(); this._afterOpened.complete(); }); // Dispose overlay when closing animation is complete _containerInstance._animationStateChanged .pipe( filter(event => event.state === 'closed'), take(1), ) .subscribe(() => { clearTimeout(this._closeFallbackTimeout); this._finishDialogClose(); }); _ref.overlayRef.detachments().subscribe(() => { this._beforeClosed.next(this._result); this._beforeClosed.complete(); this._finishDialogClose(); }); merge( this.backdropClick(), this.keydownEvents().pipe( filter(event => event.keyCode === ESCAPE && !this.disableClose && !hasModifierKey(event)), ), ).subscribe(event => { if (!this.disableClose) { event.preventDefault(); _closeDialogVia(this, event.type === 'keydown' ? 'keyboard' : 'mouse'); } }); } /** * Close the dialog. * @param dialogResult Optional result to return to the dialog opener. */ close(dialogResult?: R): void { this._result = dialogResult; // Transition the backdrop in parallel to the dialog. this._containerInstance._animationStateChanged .pipe( filter(event => event.state === 'closing'), take(1), ) .subscribe(event => { this._beforeClosed.next(dialogResult); this._beforeClosed.complete(); this._ref.overlayRef.detachBackdrop(); // The logic that disposes of the overlay depends on the exit animation completing, however // it isn't guaranteed if the parent view is destroyed while it's running. Add a fallback // timeout which will clean everything up if the animation hasn't fired within the specified // amount of time plus 100ms. We don't need to run this outside the NgZone, because for the // vast majority of cases the timeout will have been cleared before it has the chance to fire. this._closeFallbackTimeout = setTimeout( () => this._finishDialogClose(), event.totalTime + 100, ); }); this._state = MatDialogState.CLOSING; this._containerInstance._startExitAnimation(); } /** * Gets an observable that is notified when the dialog is finished opening. */ afterOpened(): Observable<void> { return this._afterOpened; } /** * Gets an observable that is notified when the dialog is finished closing. */ afterClosed(): Observable<R | undefined> { return this._ref.closed; } /** * Gets an observable that is notified when the dialog has started closing. */ beforeClosed(): Observable<R | undefined> { return this._beforeClosed; } /** * Gets an observable that emits when the overlay's backdrop has been clicked. */ backdropClick(): Observable<MouseEvent> { return this._ref.backdropClick; } /** * Gets an observable that emits when keydown events are targeted on the overlay. */ keydownEvents(): Observable<KeyboardEvent> { return this._ref.keydownEvents; } /** * Updates the dialog's position. * @param position New dialog position. */ updatePosition(position?: DialogPosition): this { let strategy = this._ref.config.positionStrategy as GlobalPositionStrategy; if (position && (position.left || position.right)) { position.left ? strategy.left(position.left) : strategy.right(position.right); } else { strategy.centerHorizontally(); } if (position && (position.top || position.bottom)) { position.top ? strategy.top(position.top) : strategy.bottom(position.bottom); } else { strategy.centerVertically(); } this._ref.updatePosition(); return this; } /** * Updates the dialog's width and height. * @param width New width of the dialog. * @param height New height of the dialog. */ updateSize(width: string = '', height: string = ''): this { this._ref.updateSize(width, height); return this; } /** Add a CSS class or an array of classes to the overlay pane. */ addPanelClass(classes: string | string[]): this { this._ref.addPanelClass(classes); return this; } /** Remove a CSS class or an array of classes from the overlay pane. */ removePanelClass(classes: string | string[]): this { this._ref.removePanelClass(classes); return this; } /** Gets the current state of the dialog's lifecycle. */ getState(): MatDialogState { return this._state; } /** * Finishes the dialog close by updating the state of the dialog * and disposing the overlay. */ private _finishDialogClose() { this._state = MatDialogState.CLOSED; this._ref.close(this._result, {focusOrigin: this._closeInteractionType}); this.componentInstance = null!; } } /** * Closes the dialog with the specified interaction type. This is currently not part of * `MatDialogRef` as that would conflict with custom dialog ref mocks provided in tests. * More details. See: https://github.com/angular/components/pull/9257#issuecomment-651342226. */ // TODO: Move this back into `MatDialogRef` when we provide an official mock dialog ref. export function _closeDialogVia<R>(ref: MatDialogRef<R>, interactionType: FocusOrigin, result?: R) { (ref as unknown as {_closeInteractionType: FocusOrigin})._closeInteractionType = interactionType; return ref.close(result); }
{ "commit_id": "ea0d1ba7b", "end_byte": 8332, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/dialog-ref.ts" }
components/src/material/dialog/testing/public-api.ts_0_369
/** * @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 {DialogHarnessFilters} from './dialog-harness-filters'; export {MatDialogHarness, MatDialogSection} from './dialog-harness'; export * from './dialog-opener';
{ "commit_id": "ea0d1ba7b", "end_byte": 369, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/public-api.ts" }
components/src/material/dialog/testing/dialog-opener.spec.ts_0_2521
import {Component, inject} from '@angular/core'; import {TestBed, fakeAsync, flush} from '@angular/core/testing'; import {MAT_DIALOG_DATA, MatDialogRef, MatDialogState} from '@angular/material/dialog'; import {MatTestDialogOpener, MatTestDialogOpenerModule} from '@angular/material/dialog/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; describe('MatTestDialogOpener', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatTestDialogOpenerModule, NoopAnimationsModule, ExampleComponent], }); })); it('should open a dialog when created', fakeAsync(() => { const fixture = TestBed.createComponent(MatTestDialogOpener.withComponent(ExampleComponent)); flush(); expect(fixture.componentInstance.dialogRef.getState()).toBe(MatDialogState.OPEN); expect(document.querySelector('mat-dialog-container')).toBeTruthy(); })); it('should throw an error if no dialog component is provided', () => { expect(() => TestBed.createComponent(MatTestDialogOpener)).toThrow( Error('MatTestDialogOpener does not have a component provided.'), ); }); it('should pass data to the component', async () => { const config = {data: 'test'}; const fixture = TestBed.createComponent( MatTestDialogOpener.withComponent(ExampleComponent, config), ); fixture.detectChanges(); await fixture.whenStable(); const dialogContainer = document.querySelector('mat-dialog-container'); expect(dialogContainer!.innerHTML).toContain('Data: test'); }); it('should get closed result data', fakeAsync(() => { const config = {data: 'test'}; const fixture = TestBed.createComponent( MatTestDialogOpener.withComponent<ExampleComponent, ExampleDialogResult>( ExampleComponent, config, ), ); flush(); const closeButton = document.querySelector('#close-btn') as HTMLElement; closeButton.click(); flush(); expect(fixture.componentInstance.closedResult).toEqual({reason: 'closed'}); })); }); interface ExampleDialogResult { reason: string; } /** Simple component for testing MatTestDialogOpener. */ @Component({ template: ` Data: {{data}} <button id="close-btn" (click)="close()">Close</button> `, standalone: true, }) class ExampleComponent { dialogRef = inject<MatDialogRef<ExampleComponent, ExampleDialogResult>>(MatDialogRef); data = inject(MAT_DIALOG_DATA); close() { this.dialogRef.close({reason: 'closed'}); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2521, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/dialog-opener.spec.ts" }
components/src/material/dialog/testing/dialog-harness.ts_0_3698
/** * @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, TestKey, } from '@angular/cdk/testing'; import {DialogHarnessFilters} from './dialog-harness-filters'; import {DialogRole} from '@angular/material/dialog'; /** Selectors for different sections of the mat-dialog that can contain user content. */ export enum MatDialogSection { TITLE = '.mat-mdc-dialog-title', CONTENT = '.mat-mdc-dialog-content', ACTIONS = '.mat-mdc-dialog-actions', } /** Harness for interacting with a standard `MatDialog` in tests. */ export class MatDialogHarness // @breaking-change 14.0.0 change generic type to MatDialogSection. extends ContentContainerComponentHarness<MatDialogSection | string> { /** The selector for the host element of a `MatDialog` instance. */ static hostSelector = '.mat-mdc-dialog-container'; /** * Gets a `HarnessPredicate` that can be used to search for a dialog with specific attributes. * @param options Options for filtering which dialog instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatDialogHarness>( this: ComponentHarnessConstructor<T>, options: DialogHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } protected _title = this.locatorForOptional(MatDialogSection.TITLE); protected _content = this.locatorForOptional(MatDialogSection.CONTENT); protected _actions = this.locatorForOptional(MatDialogSection.ACTIONS); /** Gets the id of the dialog. */ async getId(): Promise<string | null> { const id = await (await this.host()).getAttribute('id'); // In case no id has been specified, the "id" property always returns // an empty string. To make this method more explicit, we return null. return id !== '' ? id : null; } /** Gets the role of the dialog. */ async getRole(): Promise<DialogRole | null> { return (await this.host()).getAttribute('role') as Promise<DialogRole | null>; } /** Gets the value of the dialog's "aria-label" attribute. */ async getAriaLabel(): Promise<string | null> { return (await this.host()).getAttribute('aria-label'); } /** Gets the value of the dialog's "aria-labelledby" attribute. */ async getAriaLabelledby(): Promise<string | null> { return (await this.host()).getAttribute('aria-labelledby'); } /** Gets the value of the dialog's "aria-describedby" attribute. */ async getAriaDescribedby(): Promise<string | null> { return (await this.host()).getAttribute('aria-describedby'); } /** * Closes the dialog by pressing escape. * * Note: this method does nothing if `disableClose` has been set to `true` for the dialog. */ async close(): Promise<void> { await (await this.host()).sendKeys(TestKey.ESCAPE); } /** Gets te dialog's text. */ async getText() { return (await this.host()).text(); } /** Gets the dialog's title text. This only works if the dialog is using mat-dialog-title. */ async getTitleText() { return (await this._title())?.text() ?? ''; } /** Gets the dialog's content text. This only works if the dialog is using mat-dialog-content. */ async getContentText() { return (await this._content())?.text() ?? ''; } /** Gets the dialog's actions text. This only works if the dialog is using mat-dialog-actions. */ async getActionsText() { return (await this._actions())?.text() ?? ''; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3698, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/dialog-harness.ts" }
components/src/material/dialog/testing/dialog-harness-filters.ts_0_422
/** * @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'; /** A set of criteria that can be used to filter a list of `MatDialogHarness` instances. */ export interface DialogHarnessFilters extends BaseHarnessFilters {}
{ "commit_id": "ea0d1ba7b", "end_byte": 422, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/dialog-harness-filters.ts" }
components/src/material/dialog/testing/dialog-harness.spec.ts_0_5147
import {Component, TemplateRef, ViewChild, inject} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import { MatDialog, MatDialogActions, MatDialogConfig, MatDialogContent, MatDialogTitle, } from '@angular/material/dialog'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatDialogHarness} from './dialog-harness'; describe('MatDialogHarness', () => { let fixture: ComponentFixture<DialogHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule], }); fixture = TestBed.createComponent(DialogHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); it('should load harness for dialog', async () => { fixture.componentInstance.open(); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(dialogs.length).toBe(1); }); it('should load harness for dialog with specific id', async () => { fixture.componentInstance.open({id: 'my-dialog'}); fixture.componentInstance.open({id: 'other'}); let dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(dialogs.length).toBe(2); dialogs = await loader.getAllHarnesses(MatDialogHarness.with({selector: '#my-dialog'})); expect(dialogs.length).toBe(1); }); it('should be able to get id of dialog', async () => { fixture.componentInstance.open({id: 'my-dialog'}); fixture.componentInstance.open({id: 'other'}); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(await dialogs[0].getId()).toBe('my-dialog'); expect(await dialogs[1].getId()).toBe('other'); }); it('should be able to get role of dialog', async () => { fixture.componentInstance.open({role: 'alertdialog'}); fixture.componentInstance.open({role: 'dialog'}); fixture.componentInstance.open({role: undefined}); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(await dialogs[0].getRole()).toBe('alertdialog'); expect(await dialogs[1].getRole()).toBe('dialog'); expect(await dialogs[2].getRole()).toBe(null); }); it('should be able to get aria-label of dialog', async () => { fixture.componentInstance.open(); fixture.componentInstance.open({ariaLabel: 'Confirm purchase.'}); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(await dialogs[0].getAriaLabel()).toBe(null); expect(await dialogs[1].getAriaLabel()).toBe('Confirm purchase.'); }); it('should be able to get aria-labelledby of dialog', async () => { fixture.componentInstance.open(); fixture.componentInstance.open({ariaLabelledBy: 'dialog-label'}); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(await dialogs[0].getAriaLabelledby()).toMatch(/-dialog-title-\d+/); expect(await dialogs[1].getAriaLabelledby()).toBe('dialog-label'); }); it('should be able to get aria-describedby of dialog', async () => { fixture.componentInstance.open(); fixture.componentInstance.open({ariaDescribedBy: 'dialog-description'}); const dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(await dialogs[0].getAriaDescribedby()).toBe(null); expect(await dialogs[1].getAriaDescribedby()).toBe('dialog-description'); }); it('should be able to close dialog', async () => { fixture.componentInstance.open({disableClose: true}); fixture.componentInstance.open(); let dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(dialogs.length).toBe(2); await dialogs[0].close(); dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(dialogs.length).toBe(1); // should be a noop since "disableClose" is set to "true". await dialogs[0].close(); dialogs = await loader.getAllHarnesses(MatDialogHarness); expect(dialogs.length).toBe(1); }); it('should get the text content of each section', async () => { fixture.componentInstance.open(); const dialog = await loader.getHarness(MatDialogHarness); expect(await dialog.getText()).toBe(`I'm the dialog titleI'm the dialog contentCancelOk`); expect(await dialog.getTitleText()).toBe(`I'm the dialog title`); expect(await dialog.getContentText()).toBe(`I'm the dialog content`); expect(await dialog.getActionsText()).toBe(`CancelOk`); }); }); @Component({ template: ` <ng-template> <div matDialogTitle>I'm the dialog title</div> <div matDialogContent>I'm the dialog content</div> <div matDialogActions> <button>Cancel</button> <button>Ok</button> </div> </ng-template> `, standalone: true, imports: [MatDialogTitle, MatDialogContent, MatDialogActions], }) class DialogHarnessTest { readonly dialog = inject(MatDialog); @ViewChild(TemplateRef) dialogTmpl: TemplateRef<any>; open(config?: MatDialogConfig) { return this.dialog.open(this.dialogTmpl, config); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 5147, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/dialog-harness.spec.ts" }
components/src/material/dialog/testing/BUILD.bazel_0_923
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/overlay", "//src/cdk/testing", "//src/material/dialog", "@npm//@angular/core", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/overlay", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/dialog", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 923, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/BUILD.bazel" }
components/src/material/dialog/testing/dialog-opener.ts_0_2689
/** * @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 {ComponentType} from '@angular/cdk/overlay'; import { ChangeDetectionStrategy, Component, NgModule, NgZone, OnDestroy, ViewEncapsulation, inject, } from '@angular/core'; import {MatDialog, MatDialogConfig, MatDialogModule, MatDialogRef} from '@angular/material/dialog'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subscription} from 'rxjs'; /** Test component that immediately opens a dialog when bootstrapped. */ @Component({ selector: 'mat-test-dialog-opener', template: '', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class MatTestDialogOpener<T = unknown, R = unknown> implements OnDestroy { dialog = inject(MatDialog); /** Component that should be opened with the MatDialog `open` method. */ protected static component: ComponentType<unknown> | undefined; /** Config that should be provided to the MatDialog `open` method. */ protected static config: MatDialogConfig | undefined; /** MatDialogRef returned from the MatDialog `open` method. */ dialogRef: MatDialogRef<T, R>; /** Data passed to the `MatDialog` close method. */ closedResult: R | undefined; private readonly _afterClosedSubscription: Subscription; private readonly _ngZone = inject(NgZone); /** Static method that prepares this class to open the provided component. */ static withComponent<T = unknown, R = unknown>( component: ComponentType<T>, config?: MatDialogConfig, ) { MatTestDialogOpener.component = component; MatTestDialogOpener.config = config; return MatTestDialogOpener as ComponentType<MatTestDialogOpener<T, R>>; } constructor(...args: unknown[]); constructor() { if (!MatTestDialogOpener.component) { throw new Error(`MatTestDialogOpener does not have a component provided.`); } this.dialogRef = this._ngZone.run(() => this.dialog.open<T, R>( MatTestDialogOpener.component as ComponentType<T>, MatTestDialogOpener.config || {}, ), ); this._afterClosedSubscription = this.dialogRef.afterClosed().subscribe(result => { this.closedResult = result; }); } ngOnDestroy() { this._afterClosedSubscription.unsubscribe(); MatTestDialogOpener.component = undefined; MatTestDialogOpener.config = undefined; } } @NgModule({ imports: [MatDialogModule, NoopAnimationsModule, MatTestDialogOpener], }) export class MatTestDialogOpenerModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 2689, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/dialog-opener.ts" }
components/src/material/dialog/testing/index.ts_0_285
/** * @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'; export {MatDialogHarness} from './dialog-harness';
{ "commit_id": "ea0d1ba7b", "end_byte": 285, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/dialog/testing/index.ts" }
components/src/material/form-field/form-field-errors.ts_0_700
/** * @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 function getMatFormFieldPlaceholderConflictError(): Error { return Error('Placeholder attribute and child element were both specified.'); } /** @docs-private */ export function getMatFormFieldDuplicatedHintError(align: string): Error { return Error(`A hint was already declared for 'align="${align}"'.`); } /** @docs-private */ export function getMatFormFieldMissingControlError(): Error { return Error('mat-form-field must contain a MatFormFieldControl.'); }
{ "commit_id": "ea0d1ba7b", "end_byte": 700, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field-errors.ts" }
components/src/material/form-field/form-field.ts_0_7255
/** * @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 {Directionality} from '@angular/cdk/bidi'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {Platform} from '@angular/cdk/platform'; import {NgTemplateOutlet} from '@angular/common'; import { ANIMATION_MODULE_TYPE, AfterContentChecked, AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, ElementRef, InjectionToken, Injector, Input, OnDestroy, QueryList, ViewChild, ViewEncapsulation, afterRender, computed, contentChild, inject, } from '@angular/core'; import {AbstractControlDirective} from '@angular/forms'; import {ThemePalette} from '@angular/material/core'; import {Subject, Subscription, merge} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {MAT_ERROR, MatError} from './directives/error'; import { FLOATING_LABEL_PARENT, FloatingLabelParent, MatFormFieldFloatingLabel, } from './directives/floating-label'; import {MatHint} from './directives/hint'; import {MatLabel} from './directives/label'; import {MatFormFieldLineRipple} from './directives/line-ripple'; import {MatFormFieldNotchedOutline} from './directives/notched-outline'; import {MAT_PREFIX, MatPrefix} from './directives/prefix'; import {MAT_SUFFIX, MatSuffix} from './directives/suffix'; import {matFormFieldAnimations} from './form-field-animations'; import {MatFormFieldControl as _MatFormFieldControl} from './form-field-control'; import { getMatFormFieldDuplicatedHintError, getMatFormFieldMissingControlError, } from './form-field-errors'; /** Type for the available floatLabel values. */ export type FloatLabelType = 'always' | 'auto'; /** Possible appearance styles for the form field. */ export type MatFormFieldAppearance = 'fill' | 'outline'; /** Behaviors for how the subscript height is set. */ export type SubscriptSizing = 'fixed' | 'dynamic'; /** * Represents the default options for the form field that can be configured * using the `MAT_FORM_FIELD_DEFAULT_OPTIONS` injection token. */ export interface MatFormFieldDefaultOptions { /** Default form field appearance style. */ appearance?: MatFormFieldAppearance; /** * Default theme color of the form field. This API is supported in M2 themes only, it has no * effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants */ color?: ThemePalette; /** Whether the required marker should be hidden by default. */ hideRequiredMarker?: boolean; /** * Whether the label for form fields should by default float `always`, * `never`, or `auto` (only when necessary). */ floatLabel?: FloatLabelType; /** Whether the form field should reserve space for one line by default. */ subscriptSizing?: SubscriptSizing; } /** * Injection token that can be used to inject an instances of `MatFormField`. It serves * as alternative token to the actual `MatFormField` class which would cause unnecessary * retention of the `MatFormField` class and its component metadata. */ export const MAT_FORM_FIELD = new InjectionToken<MatFormField>('MatFormField'); /** * Injection token that can be used to configure the * default options for all form field within an app. */ export const MAT_FORM_FIELD_DEFAULT_OPTIONS = new InjectionToken<MatFormFieldDefaultOptions>( 'MAT_FORM_FIELD_DEFAULT_OPTIONS', ); let nextUniqueId = 0; /** Default appearance used by the form field. */ const DEFAULT_APPEARANCE: MatFormFieldAppearance = 'fill'; /** * Whether the label for form fields should by default float `always`, * `never`, or `auto`. */ const DEFAULT_FLOAT_LABEL: FloatLabelType = 'auto'; /** Default way that the subscript element height is set. */ const DEFAULT_SUBSCRIPT_SIZING: SubscriptSizing = 'fixed'; /** * Default transform for docked floating labels in a MDC text-field. This value has been * extracted from the MDC text-field styles because we programmatically modify the docked * label transform, but do not want to accidentally discard the default label transform. */ const FLOATING_LABEL_DEFAULT_DOCKED_TRANSFORM = `translateY(-50%)`; /** * Despite `MatFormFieldControl` being an abstract class, most of our usages enforce its shape * using `implements` instead of `extends`. This appears to be problematic when Closure compiler * is configured to use type information to rename properties, because it can't figure out which * class properties are coming from. This interface seems to work around the issue while preserving * our type safety (alternative being using `any` everywhere). * @docs-private */ interface MatFormFieldControl<T> extends _MatFormFieldControl<T> {} /** Container for form controls that applies Material Design styling and behavior. */ @Component({ selector: 'mat-form-field', exportAs: 'matFormField', templateUrl: './form-field.html', styleUrl: './form-field.css', animations: [matFormFieldAnimations.transitionMessages], host: { 'class': 'mat-mdc-form-field', '[class.mat-mdc-form-field-label-always-float]': '_shouldAlwaysFloat()', '[class.mat-mdc-form-field-has-icon-prefix]': '_hasIconPrefix', '[class.mat-mdc-form-field-has-icon-suffix]': '_hasIconSuffix', // Note that these classes reuse the same names as the non-MDC version, because they can be // considered a public API since custom form controls may use them to style themselves. // See https://github.com/angular/components/pull/20502#discussion_r486124901. '[class.mat-form-field-invalid]': '_control.errorState', '[class.mat-form-field-disabled]': '_control.disabled', '[class.mat-form-field-autofilled]': '_control.autofilled', '[class.mat-form-field-no-animations]': '_animationMode === "NoopAnimations"', '[class.mat-form-field-appearance-fill]': 'appearance == "fill"', '[class.mat-form-field-appearance-outline]': 'appearance == "outline"', '[class.mat-form-field-hide-placeholder]': '_hasFloatingLabel() && !_shouldLabelFloat()', '[class.mat-focused]': '_control.focused', '[class.mat-primary]': 'color !== "accent" && color !== "warn"', '[class.mat-accent]': 'color === "accent"', '[class.mat-warn]': 'color === "warn"', '[class.ng-untouched]': '_shouldForward("untouched")', '[class.ng-touched]': '_shouldForward("touched")', '[class.ng-pristine]': '_shouldForward("pristine")', '[class.ng-dirty]': '_shouldForward("dirty")', '[class.ng-valid]': '_shouldForward("valid")', '[class.ng-invalid]': '_shouldForward("invalid")', '[class.ng-pending]': '_shouldForward("pending")', }, encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ {provide: MAT_FORM_FIELD, useExisting: MatFormField}, {provide: FLOATING_LABEL_PARENT, useExisting: MatFormField}, ], imports: [ MatFormFieldFloatingLabel, MatFormFieldNotchedOutline, NgTemplateOutlet, MatFormFieldLineRipple, MatHint, ], }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 7255, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.ts" }
components/src/material/form-field/form-field.ts_7256_15331
class MatFormField implements FloatingLabelParent, AfterContentInit, AfterContentChecked, AfterViewInit, OnDestroy { _elementRef = inject(ElementRef); private _changeDetectorRef = inject(ChangeDetectorRef); private _dir = inject(Directionality); private _platform = inject(Platform); private _defaults = inject<MatFormFieldDefaultOptions>(MAT_FORM_FIELD_DEFAULT_OPTIONS, { optional: true, }); _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); @ViewChild('textField') _textField: ElementRef<HTMLElement>; @ViewChild('iconPrefixContainer') _iconPrefixContainer: ElementRef<HTMLElement>; @ViewChild('textPrefixContainer') _textPrefixContainer: ElementRef<HTMLElement>; @ViewChild('iconSuffixContainer') _iconSuffixContainer: ElementRef<HTMLElement>; @ViewChild('textSuffixContainer') _textSuffixContainer: ElementRef<HTMLElement>; @ViewChild(MatFormFieldFloatingLabel) _floatingLabel: MatFormFieldFloatingLabel | undefined; @ViewChild(MatFormFieldNotchedOutline) _notchedOutline: MatFormFieldNotchedOutline | undefined; @ViewChild(MatFormFieldLineRipple) _lineRipple: MatFormFieldLineRipple | undefined; @ContentChild(_MatFormFieldControl) _formFieldControl: MatFormFieldControl<any>; @ContentChildren(MAT_PREFIX, {descendants: true}) _prefixChildren: QueryList<MatPrefix>; @ContentChildren(MAT_SUFFIX, {descendants: true}) _suffixChildren: QueryList<MatSuffix>; @ContentChildren(MAT_ERROR, {descendants: true}) _errorChildren: QueryList<MatError>; @ContentChildren(MatHint, {descendants: true}) _hintChildren: QueryList<MatHint>; private readonly _labelChild = contentChild(MatLabel); /** Whether the required marker should be hidden. */ @Input() get hideRequiredMarker(): boolean { return this._hideRequiredMarker; } set hideRequiredMarker(value: BooleanInput) { this._hideRequiredMarker = coerceBooleanProperty(value); } private _hideRequiredMarker = false; /** * Theme color of the form field. This API is supported in M2 themes only, it * has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: ThemePalette = 'primary'; /** Whether the label should always float or float as the user types. */ @Input() get floatLabel(): FloatLabelType { return this._floatLabel || this._defaults?.floatLabel || DEFAULT_FLOAT_LABEL; } set floatLabel(value: FloatLabelType) { if (value !== this._floatLabel) { this._floatLabel = value; // For backwards compatibility. Custom form field controls or directives might set // the "floatLabel" input and expect the form field view to be updated automatically. // e.g. autocomplete trigger. Ideally we'd get rid of this and the consumers would just // emit the "stateChanges" observable. TODO(devversion): consider removing. this._changeDetectorRef.markForCheck(); } } private _floatLabel: FloatLabelType; /** The form field appearance style. */ @Input() get appearance(): MatFormFieldAppearance { return this._appearance; } set appearance(value: MatFormFieldAppearance) { const oldValue = this._appearance; const newAppearance = value || this._defaults?.appearance || DEFAULT_APPEARANCE; if (typeof ngDevMode === 'undefined' || ngDevMode) { if (newAppearance !== 'fill' && newAppearance !== 'outline') { throw new Error( `MatFormField: Invalid appearance "${newAppearance}", valid values are "fill" or "outline".`, ); } } this._appearance = newAppearance; if (this._appearance === 'outline' && this._appearance !== oldValue) { // If the appearance has been switched to `outline`, the label offset needs to be updated. // The update can happen once the view has been re-checked, but not immediately because // the view has not been updated and the notched-outline floating label is not present. this._needsOutlineLabelOffsetUpdate = true; } } private _appearance: MatFormFieldAppearance = DEFAULT_APPEARANCE; /** * Whether the form field should reserve space for one line of hint/error text (default) * or to have the spacing grow from 0px as needed based on the size of the hint/error content. * Note that when using dynamic sizing, layout shifts will occur when hint/error text changes. */ @Input() get subscriptSizing(): SubscriptSizing { return this._subscriptSizing || this._defaults?.subscriptSizing || DEFAULT_SUBSCRIPT_SIZING; } set subscriptSizing(value: SubscriptSizing) { this._subscriptSizing = value || this._defaults?.subscriptSizing || DEFAULT_SUBSCRIPT_SIZING; } private _subscriptSizing: SubscriptSizing | null = null; /** Text for the form field hint. */ @Input() get hintLabel(): string { return this._hintLabel; } set hintLabel(value: string) { this._hintLabel = value; this._processHints(); } private _hintLabel = ''; _hasIconPrefix = false; _hasTextPrefix = false; _hasIconSuffix = false; _hasTextSuffix = false; // Unique id for the internal form field label. readonly _labelId = `mat-mdc-form-field-label-${nextUniqueId++}`; // Unique id for the hint label. readonly _hintLabelId = `mat-mdc-hint-${nextUniqueId++}`; /** State of the mat-hint and mat-error animations. */ _subscriptAnimationState = ''; /** Gets the current form field control */ get _control(): MatFormFieldControl<any> { return this._explicitFormFieldControl || this._formFieldControl; } set _control(value) { this._explicitFormFieldControl = value; } private _destroyed = new Subject<void>(); private _isFocused: boolean | null = null; private _explicitFormFieldControl: MatFormFieldControl<any>; private _needsOutlineLabelOffsetUpdate = false; private _previousControl: MatFormFieldControl<unknown> | null = null; private _stateChanges: Subscription | undefined; private _valueChanges: Subscription | undefined; private _injector = inject(Injector); constructor(...args: unknown[]); constructor() { const defaults = this._defaults; if (defaults) { if (defaults.appearance) { this.appearance = defaults.appearance; } this._hideRequiredMarker = Boolean(defaults?.hideRequiredMarker); if (defaults.color) { this.color = defaults.color; } } } ngAfterViewInit() { // Initial focus state sync. This happens rarely, but we want to account for // it in case the form field control has "focused" set to true on init. this._updateFocusState(); // Enable animations now. This ensures we don't animate on initial render. this._subscriptAnimationState = 'enter'; // Because the above changes a value used in the template after it was checked, we need // to trigger CD or the change might not be reflected if there is no other CD scheduled. this._changeDetectorRef.detectChanges(); } ngAfterContentInit() { this._assertFormFieldControl(); this._initializeSubscript(); this._initializePrefixAndSuffix(); this._initializeOutlineLabelOffsetSubscriptions(); } ngAfterContentChecked() { this._assertFormFieldControl(); if (this._control !== this._previousControl) { this._initializeControl(this._previousControl); this._previousControl = this._control; } } ngOnDestroy() { this._stateChanges?.unsubscribe(); this._valueChanges?.unsubscribe(); this._destroyed.next(); this._destroyed.complete(); } /** * Gets the id of the label element. If no label is present, returns `null`. */ getLabelId = computed(() => (this._hasFloatingLabel() ? this._labelId : null)); /** * Gets an ElementRef for the element that a overlay attached to the form field * should be positioned relative to. */ getConnectedOverlayOrigin(): ElementRef { return this._textField || this._elementRef; } /** Animates the placeholder up and locks it in position. */
{ "commit_id": "ea0d1ba7b", "end_byte": 15331, "start_byte": 7256, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.ts" }
components/src/material/form-field/form-field.ts_15334_23828
_animateAndLockLabel(): void { // This is for backwards compatibility only. Consumers of the form field might use // this method. e.g. the autocomplete trigger. This method has been added to the non-MDC // form field because setting "floatLabel" to "always" caused the label to float without // animation. This is different in MDC where the label always animates, so this method // is no longer necessary. There doesn't seem any benefit in adding logic to allow changing // the floating label state without animations. The non-MDC implementation was inconsistent // because it always animates if "floatLabel" is set away from "always". // TODO(devversion): consider removing this method when releasing the MDC form field. if (this._hasFloatingLabel()) { this.floatLabel = 'always'; } } /** Initializes the registered form field control. */ private _initializeControl(previousControl: MatFormFieldControl<unknown> | null) { const control = this._control; const classPrefix = 'mat-mdc-form-field-type-'; if (previousControl) { this._elementRef.nativeElement.classList.remove(classPrefix + previousControl.controlType); } if (control.controlType) { this._elementRef.nativeElement.classList.add(classPrefix + control.controlType); } // Subscribe to changes in the child control state in order to update the form field UI. this._stateChanges?.unsubscribe(); this._stateChanges = control.stateChanges.subscribe(() => { this._updateFocusState(); this._syncDescribedByIds(); this._changeDetectorRef.markForCheck(); }); this._valueChanges?.unsubscribe(); // Run change detection if the value changes. if (control.ngControl && control.ngControl.valueChanges) { this._valueChanges = control.ngControl.valueChanges .pipe(takeUntil(this._destroyed)) .subscribe(() => this._changeDetectorRef.markForCheck()); } } private _checkPrefixAndSuffixTypes() { this._hasIconPrefix = !!this._prefixChildren.find(p => !p._isText); this._hasTextPrefix = !!this._prefixChildren.find(p => p._isText); this._hasIconSuffix = !!this._suffixChildren.find(s => !s._isText); this._hasTextSuffix = !!this._suffixChildren.find(s => s._isText); } /** Initializes the prefix and suffix containers. */ private _initializePrefixAndSuffix() { this._checkPrefixAndSuffixTypes(); // Mark the form field as dirty whenever the prefix or suffix children change. This // is necessary because we conditionally display the prefix/suffix containers based // on whether there is projected content. merge(this._prefixChildren.changes, this._suffixChildren.changes).subscribe(() => { this._checkPrefixAndSuffixTypes(); this._changeDetectorRef.markForCheck(); }); } /** * Initializes the subscript by validating hints and synchronizing "aria-describedby" ids * with the custom form field control. Also subscribes to hint and error changes in order * to be able to validate and synchronize ids on change. */ private _initializeSubscript() { // Re-validate when the number of hints changes. this._hintChildren.changes.subscribe(() => { this._processHints(); this._changeDetectorRef.markForCheck(); }); // Update the aria-described by when the number of errors changes. this._errorChildren.changes.subscribe(() => { this._syncDescribedByIds(); this._changeDetectorRef.markForCheck(); }); // Initial mat-hint validation and subscript describedByIds sync. this._validateHints(); this._syncDescribedByIds(); } /** Throws an error if the form field's control is missing. */ private _assertFormFieldControl() { if (!this._control && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw getMatFormFieldMissingControlError(); } } private _updateFocusState() { // Usually the MDC foundation would call "activateFocus" and "deactivateFocus" whenever // certain DOM events are emitted. This is not possible in our implementation of the // form field because we support abstract form field controls which are not necessarily // of type input, nor do we have a reference to a native form field control element. Instead // we handle the focus by checking if the abstract form field control focused state changes. if (this._control.focused && !this._isFocused) { this._isFocused = true; this._lineRipple?.activate(); } else if (!this._control.focused && (this._isFocused || this._isFocused === null)) { this._isFocused = false; this._lineRipple?.deactivate(); } this._textField?.nativeElement.classList.toggle( 'mdc-text-field--focused', this._control.focused, ); } /** * The floating label in the docked state needs to account for prefixes. The horizontal offset * is calculated whenever the appearance changes to `outline`, the prefixes change, or when the * form field is added to the DOM. This method sets up all subscriptions which are needed to * trigger the label offset update. */ private _initializeOutlineLabelOffsetSubscriptions() { // Whenever the prefix changes, schedule an update of the label offset. // TODO(mmalerba): Use ResizeObserver to better support dynamically changing prefix content. this._prefixChildren.changes.subscribe(() => (this._needsOutlineLabelOffsetUpdate = true)); // TODO(mmalerba): Split this into separate `afterRender` calls using the `EarlyRead` and // `Write` phases. afterRender( () => { if (this._needsOutlineLabelOffsetUpdate) { this._needsOutlineLabelOffsetUpdate = false; this._updateOutlineLabelOffset(); } }, { injector: this._injector, }, ); this._dir.change .pipe(takeUntil(this._destroyed)) .subscribe(() => (this._needsOutlineLabelOffsetUpdate = true)); } /** Whether the floating label should always float or not. */ _shouldAlwaysFloat() { return this.floatLabel === 'always'; } _hasOutline() { return this.appearance === 'outline'; } /** * Whether the label should display in the infix. Labels in the outline appearance are * displayed as part of the notched-outline and are horizontally offset to account for * form field prefix content. This won't work in server side rendering since we cannot * measure the width of the prefix container. To make the docked label appear as if the * right offset has been calculated, we forcibly render the label inside the infix. Since * the label is part of the infix, the label cannot overflow the prefix content. */ _forceDisplayInfixLabel() { return !this._platform.isBrowser && this._prefixChildren.length && !this._shouldLabelFloat(); } _hasFloatingLabel = computed(() => !!this._labelChild()); _shouldLabelFloat(): boolean { if (!this._hasFloatingLabel()) { return false; } return this._control.shouldLabelFloat || this._shouldAlwaysFloat(); } /** * Determines whether a class from the AbstractControlDirective * should be forwarded to the host element. */ _shouldForward(prop: keyof AbstractControlDirective): boolean { const control = this._control ? this._control.ngControl : null; return control && control[prop]; } /** Determines whether to display hints or errors. */ _getDisplayedMessages(): 'error' | 'hint' { return this._errorChildren && this._errorChildren.length > 0 && this._control.errorState ? 'error' : 'hint'; } /** Handle label resize events. */ _handleLabelResized() { this._refreshOutlineNotchWidth(); } /** Refreshes the width of the outline-notch, if present. */ _refreshOutlineNotchWidth() { if (!this._hasOutline() || !this._floatingLabel || !this._shouldLabelFloat()) { this._notchedOutline?._setNotchWidth(0); } else { this._notchedOutline?._setNotchWidth(this._floatingLabel.getWidth()); } } /** Does any extra processing that is required when handling the hints. */ private _processHints() { this._validateHints(); this._syncDescribedByIds(); } /** * Ensure that there is a maximum of one of each "mat-hint" alignment specified. The hint * label specified set through the input is being considered as "start" aligned. * * This method is a noop if Angular runs in production mode. */
{ "commit_id": "ea0d1ba7b", "end_byte": 23828, "start_byte": 15334, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.ts" }
components/src/material/form-field/form-field.ts_23831_29619
private _validateHints() { if (this._hintChildren && (typeof ngDevMode === 'undefined' || ngDevMode)) { let startHint: MatHint; let endHint: MatHint; this._hintChildren.forEach((hint: MatHint) => { if (hint.align === 'start') { if (startHint || this.hintLabel) { throw getMatFormFieldDuplicatedHintError('start'); } startHint = hint; } else if (hint.align === 'end') { if (endHint) { throw getMatFormFieldDuplicatedHintError('end'); } endHint = hint; } }); } } /** * Sets the list of element IDs that describe the child control. This allows the control to update * its `aria-describedby` attribute accordingly. */ private _syncDescribedByIds() { if (this._control) { let ids: string[] = []; // TODO(wagnermaciel): Remove the type check when we find the root cause of this bug. if ( this._control.userAriaDescribedBy && typeof this._control.userAriaDescribedBy === 'string' ) { ids.push(...this._control.userAriaDescribedBy.split(' ')); } if (this._getDisplayedMessages() === 'hint') { const startHint = this._hintChildren ? this._hintChildren.find(hint => hint.align === 'start') : null; const endHint = this._hintChildren ? this._hintChildren.find(hint => hint.align === 'end') : null; if (startHint) { ids.push(startHint.id); } else if (this._hintLabel) { ids.push(this._hintLabelId); } if (endHint) { ids.push(endHint.id); } } else if (this._errorChildren) { ids.push(...this._errorChildren.map(error => error.id)); } this._control.setDescribedByIds(ids); } } /** * Updates the horizontal offset of the label in the outline appearance. In the outline * appearance, the notched-outline and label are not relative to the infix container because * the outline intends to surround prefixes, suffixes and the infix. This means that the * floating label by default overlaps prefixes in the docked state. To avoid this, we need to * horizontally offset the label by the width of the prefix container. The MDC text-field does * not need to do this because they use a fixed width for prefixes. Hence, they can simply * incorporate the horizontal offset into their default text-field styles. */ private _updateOutlineLabelOffset() { if (!this._hasOutline() || !this._floatingLabel) { return; } const floatingLabel = this._floatingLabel.element; // If no prefix is displayed, reset the outline label offset from potential // previous label offset updates. if (!(this._iconPrefixContainer || this._textPrefixContainer)) { floatingLabel.style.transform = ''; return; } // If the form field is not attached to the DOM yet (e.g. in a tab), we defer // the label offset update until the zone stabilizes. if (!this._isAttachedToDom()) { this._needsOutlineLabelOffsetUpdate = true; return; } const iconPrefixContainer = this._iconPrefixContainer?.nativeElement; const textPrefixContainer = this._textPrefixContainer?.nativeElement; const iconSuffixContainer = this._iconSuffixContainer?.nativeElement; const textSuffixContainer = this._textSuffixContainer?.nativeElement; const iconPrefixContainerWidth = iconPrefixContainer?.getBoundingClientRect().width ?? 0; const textPrefixContainerWidth = textPrefixContainer?.getBoundingClientRect().width ?? 0; const iconSuffixContainerWidth = iconSuffixContainer?.getBoundingClientRect().width ?? 0; const textSuffixContainerWidth = textSuffixContainer?.getBoundingClientRect().width ?? 0; // If the directionality is RTL, the x-axis transform needs to be inverted. This // is because `transformX` does not change based on the page directionality. const negate = this._dir.value === 'rtl' ? '-1' : '1'; const prefixWidth = `${iconPrefixContainerWidth + textPrefixContainerWidth}px`; const labelOffset = `var(--mat-mdc-form-field-label-offset-x, 0px)`; const labelHorizontalOffset = `calc(${negate} * (${prefixWidth} + ${labelOffset}))`; // Update the translateX of the floating label to account for the prefix container, // but allow the CSS to override this setting via a CSS variable when the label is // floating. floatingLabel.style.transform = `var( --mat-mdc-form-field-label-transform, ${FLOATING_LABEL_DEFAULT_DOCKED_TRANSFORM} translateX(${labelHorizontalOffset}) )`; // Prevent the label from overlapping the suffix when in resting position. const prefixAndSuffixWidth = iconPrefixContainerWidth + textPrefixContainerWidth + iconSuffixContainerWidth + textSuffixContainerWidth; this._elementRef.nativeElement.style.setProperty( '--mat-form-field-notch-max-width', `calc(100% - ${prefixAndSuffixWidth}px)`, ); } /** Checks whether the form field is attached to the DOM. */ private _isAttachedToDom(): boolean { const element: HTMLElement = this._elementRef.nativeElement; if (element.getRootNode) { const rootNode = element.getRootNode(); // If the element is inside the DOM the root node will be either the document // or the closest shadow root, otherwise it'll be the element itself. return rootNode && rootNode !== element; } // Otherwise fall back to checking if it's in the document. This doesn't account for // shadow DOM, however browser that support shadow DOM should support `getRootNode` as well. return document.documentElement!.contains(element); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 29619, "start_byte": 23831, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.ts" }
components/src/material/form-field/_mdc-text-field-textarea-overrides.scss_0_2028
// MDCs default textarea styles cannot be used because they only apply if a special // class is applied to the "mdc-text-field" wrapper. Since we cannot know whether the // registered form-field control is a textarea and MDC by default does not have styles // for textareas in the fill appearance, we add our own minimal textarea styles // which are scoped to the actual textarea element (i.e. not require a class in the // text-field wrapper) and integrate better with the any configured appearance. // Mixin that can be included to override the default MDC text-field styles // to properly support textareas. @mixin private-text-field-textarea-overrides() { // Ensures that textarea elements inside of the form-field have proper vertical spacing // to account for the floating label. Also ensures that there is no vertical text overflow. // **Note**: Before changing this selector, make sure the `cdk-textarea-autosize` class is // still able to override the `resize` property to `none`. .mat-mdc-form-field-textarea-control { // Set the vertical alignment for textareas inside form fields to be the middle. This // ensures that textareas do not stretch the infix container vertically without having // multiple rows of text. See: https://github.com/angular/components/pull/22089. vertical-align: middle; // Textareas by default also allow users to resize the textarea horizontally. This // causes the textarea to overflow the form-field. We only allow vertical resizing. resize: vertical; box-sizing: border-box; height: auto; // Using padding for textareas causes a bad user experience because the text outside // of the text box will overflow vertically. Also, the vertical spacing for controls // is set through the infix container to allow for arbitrary form-field controls. margin: 0; padding: 0; border: none; // By default IE always renders scrollbars on textarea. // This brings it in line with other browsers. overflow: auto; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2028, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-textarea-overrides.scss" }
components/src/material/form-field/module.ts_0_921
/** * @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 {ObserversModule} from '@angular/cdk/observers'; import {NgModule} from '@angular/core'; import {MatCommonModule} from '@angular/material/core'; import {MatError} from './directives/error'; import {MatHint} from './directives/hint'; import {MatLabel} from './directives/label'; import {MatPrefix} from './directives/prefix'; import {MatSuffix} from './directives/suffix'; import {MatFormField} from './form-field'; @NgModule({ imports: [ MatCommonModule, ObserversModule, MatFormField, MatLabel, MatError, MatHint, MatPrefix, MatSuffix, ], exports: [MatFormField, MatLabel, MatHint, MatError, MatPrefix, MatSuffix, MatCommonModule], }) export class MatFormFieldModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 921, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/module.ts" }
components/src/material/form-field/_user-agent-overrides.scss_0_845
// Mixin that resets user agent styles to make the form field behave consistently. @mixin private-form-field-user-agent-overrides() { .mat-mdc-form-field-input-control { // Due to the native input masking these inputs can be slightly taller than // the plain text inputs. We normalize it by resetting the line height. &[type='date'], &[type='datetime'], &[type='datetime-local'], &[type='month'], &[type='week'], &[type='time'] { line-height: 1; } // Native datetime inputs have an element in the shadow DOM that makes them taller than // other inputs. These changes reset the user agent styles to make them consistent. // via https://8yd.no/article/date-input-height-in-safari &::-webkit-datetime-edit { line-height: 1; padding: 0; margin-bottom: -2px; } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 845, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/_user-agent-overrides.scss" }
components/src/material/form-field/form-field.scss_0_1290
@use '../core/tokens/token-utils'; @use '../core/style/vendor-prefixes'; @use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field; @use './form-field-subscript'; @use './form-field-focus-overlay'; @use './form-field-high-contrast'; @use './form-field-native-select'; @use './user-agent-overrides'; @use './mdc-text-field-structure'; @use './mdc-text-field-textarea-overrides'; @use './mdc-text-field-structure-overrides'; @use './mdc-text-field-density-overrides'; // Base styles for MDC text-field, notched-outline, floating label and line-ripple. @include mdc-text-field-structure.private-text-field-structure(); // MDC text-field overwrites. @include mdc-text-field-textarea-overrides.private-text-field-textarea-overrides(); @include mdc-text-field-structure-overrides.private-text-field-structure-overrides(); @include mdc-text-field-density-overrides.private-text-field-density-overrides(); // Include the subscript, focus-overlay, native select and high-contrast styles. @include form-field-subscript.private-form-field-subscript(); @include form-field-focus-overlay.private-form-field-focus-overlay(); @include form-field-native-select.private-form-field-native-select(); @include form-field-high-contrast.private-form-field-high-contrast(); @include user-agent-overrides
{ "commit_id": "ea0d1ba7b", "end_byte": 1290, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.scss" }
components/src/material/form-field/form-field.scss_1290_8724
.private-form-field-user-agent-overrides(); // The amount of padding between the icon prefix/suffix and the infix. // This assumes that the icon will be a 24px square with 12px padding. $_icon-prefix-infix-padding: 4px; // Host element of the form-field. It contains the mdc-text-field wrapper // and the subscript wrapper. .mat-mdc-form-field { // The scale to use for the form-field's label when its in the floating position. --mat-mdc-form-field-floating-label-scale: 0.75; display: inline-flex; // This container contains the text-field and the subscript. The subscript // should be displayed below the text-field. Hence the column direction. flex-direction: column; // This allows the form-field to shrink down when used inside flex or grid layouts. min-width: 0; // To avoid problems with text-align. text-align: left; @include token-utils.use-tokens(tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) { @include vendor-prefixes.smooth-font(); @include token-utils.create-token-slot(font-family, container-text-font); @include token-utils.create-token-slot(line-height, container-text-line-height); @include token-utils.create-token-slot(font-size, container-text-size); @include token-utils.create-token-slot(letter-spacing, container-text-tracking); @include token-utils.create-token-slot(font-weight, container-text-weight); .mdc-text-field--outlined { $token-value: token-utils.get-token-variable(outlined-label-text-populated-size); // For the non-upgraded notch label (i.e. when rendered on the server), also // use the correct typography. .mdc-floating-label--float-above { font-size: calc(#{$token-value} * var(--mat-mdc-form-field-floating-label-scale)); } .mdc-notched-outline--upgraded .mdc-floating-label--float-above { font-size: $token-value; } } } [dir='rtl'] & { text-align: right; } } // Container that contains the prefixes, infix and suffixes. These elements should // be aligned vertically in the baseline and in a single row. .mat-mdc-form-field-flex { display: inline-flex; align-items: baseline; box-sizing: border-box; width: 100%; } .mat-mdc-text-field-wrapper { // The MDC text-field should stretch to the width of the host `<mat-form-field>` element. // This allows developers to control the width without needing custom CSS overrides. width: 100%; // Avoids stacking issues due to the absolutely-positioned // descendants of the form field (see #28708) z-index: 0; } .mat-mdc-form-field-icon-prefix, .mat-mdc-form-field-icon-suffix { // Vertically center icons. align-self: center; // The line-height can cause the prefix/suffix container to be taller than the actual icons, // breaking the vertical centering. To prevent this we set the line-height to 0. line-height: 0; // MDC applies `pointer-events: none` to the `.mdc-text-field--disabled`. This breaks clicking on // prefix and suffix buttons, so we override `pointer-events` to always allow clicking. pointer-events: auto; // Needs a z-index to ensure it's on top of other clickable content. See #27043. position: relative; z-index: 1; & > .mat-icon { padding: 0 12px; // It's common for apps to apply `box-sizing: border-box` // globally which will break the alignment. box-sizing: content-box; } } .mat-mdc-form-field-icon-prefix { @include token-utils.use-tokens(tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) { @include token-utils.create-token-slot(color, leading-icon-color); .mat-form-field-disabled & { @include token-utils.create-token-slot(color, disabled-leading-icon-color); } } } .mat-mdc-form-field-icon-suffix { @include token-utils.use-tokens(tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) { @include token-utils.create-token-slot(color, trailing-icon-color); .mat-form-field-disabled & { @include token-utils.create-token-slot(color, disabled-trailing-icon-color); } .mat-form-field-invalid & { @include token-utils.create-token-slot(color, error-trailing-icon-color); } .mat-form-field-invalid:not(.mat-focused):not(.mat-form-field-disabled) .mat-mdc-text-field-wrapper:hover & { @include token-utils.create-token-slot(color, error-hover-trailing-icon-color); } .mat-form-field-invalid.mat-focused .mat-mdc-text-field-wrapper & { @include token-utils.create-token-slot(color, error-focus-trailing-icon-color); } } } // The prefix/suffix needs a little extra padding between the icon and the infix. Because we need to // support arbitrary height input elements, we use a different DOM structure for prefix and suffix // icons, and therefore can't rely on MDC for these styles. .mat-mdc-form-field-icon-prefix, [dir='rtl'] .mat-mdc-form-field-icon-suffix { padding: 0 $_icon-prefix-infix-padding 0 0; } .mat-mdc-form-field-icon-suffix, [dir='rtl'] .mat-mdc-form-field-icon-prefix { padding: 0 0 0 $_icon-prefix-infix-padding; } // Scale down icons in the subscript and floating label to be the same size // as the text. .mat-mdc-form-field-subscript-wrapper, .mat-mdc-form-field label { .mat-icon { width: 1em; height: 1em; font-size: inherit; } } // Infix that contains the projected content (usually an input or a textarea). We ensure // that the projected form-field control and content can stretch as needed, but we also // apply a default infix width to make the form-field's look natural. .mat-mdc-form-field-infix { flex: auto; min-width: 0; // Infix stretches to fit the container, but naturally wants to be this wide. We set // this in order to have a consistent natural size for the various types of controls // that can go in a form field. width: 180px; // Needed so that the floating label does not overlap with prefixes or suffixes. position: relative; box-sizing: border-box; // We do not want to set fixed width on textarea with cols attribute as it makes different // columns look same width. &:has(textarea[cols]) { width: auto; } } // In the form-field theme, we add a 1px left margin to the notch to fix a rendering bug in Chrome. // Here we apply negative margin to offset the effect on the layout and a clip-path to ensure the // left border is completely hidden. (Though the border is transparent, it still creates a triangle // shaped artifact where it meets the top and bottom borders.) .mat-mdc-form-field .mdc-notched-outline__notch { margin-left: -1px; @include vendor-prefixes.clip-path(inset(-9em -999em -9em 1px)); [dir='rtl'] & { margin-left: 0; margin-right: -1px; @include vendor-prefixes.clip-path(inset(-9em 1px -9em -999em)); } } // In order to make it possible for developers to disable animations for form-fields, // we only activate the animation styles if animations are not explicitly disabled. .mat-mdc-form-field:not(.mat-form-field-no-animations) { @include mdc-text-field-structure.private-text-field-animations; } // Allow the label to grow 1px bigger than the notch. // If we see this actually happen we know we need to resize the notch. .mdc-notched-outline .mdc-floating-label { max-width: calc(100% + 1px); } .mdc-notched-outline--upgraded .mdc-floating-label--float-above { max-width: calc(100% * 4 / 3 + 1px); }
{ "commit_id": "ea0d1ba7b", "end_byte": 8724, "start_byte": 1290, "url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.scss" }
components/src/material/form-field/_mdc-text-field-structure-overrides.scss_0_811
@use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field; @use '../core/tokens/token-utils'; @use '../core/style/vendor-prefixes'; // TODO(b/263527625): should be removed when this is addressed on the MDC side. // MDC sets a will-change on this element, because of the animation. This can cause // scrolling performance degradation on pages with a lot of form fields so we reset it. // The animation is on a `transform` which is hardware-accelerated already. // This flag is used to re-add the `will-change` internally since removing it causes a // lot of screenshot diffs. $_enable-form-field-will-change-reset: true; // Mixin that can be included to override the default MDC text-field // styles to fit our needs. See individual comments for context on why // certain MDC styles need to be modified.
{ "commit_id": "ea0d1ba7b", "end_byte": 811, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-structure-overrides.scss" }