_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/input/input.spec.ts_30194_39995 | it('should not throw if a native select does not have options', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithoutOptions);
expect(() => fixture.detectChanges()).not.toThrow();
}));
it('should be able to toggle the floating label programmatically', fakeAsync(() => {
const fixture = createComponent(MatInputWithId);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.directive(MatFormField))!;
const containerInstance = formField.componentInstance as MatFormField;
const label = formField.nativeElement.querySelector('label');
expect(containerInstance.floatLabel).toBe('auto');
expect(label.classList).not.toContain('mdc-floating-label--float-above');
fixture.componentInstance.floatLabel = 'always';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(containerInstance.floatLabel).toBe('always');
expect(label.classList).toContain('mdc-floating-label--float-above');
}));
it('should not have prefix and suffix elements when none are specified', fakeAsync(() => {
let fixture = createComponent(MatInputWithId);
fixture.detectChanges();
let prefixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-prefix'));
let suffixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-suffix'));
expect(prefixEl).toBeNull();
expect(suffixEl).toBeNull();
}));
it('should add prefix and suffix elements when specified', fakeAsync(() => {
const fixture = createComponent(MatInputWithPrefixAndSuffix);
fixture.detectChanges();
const textPrefixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-text-prefix'))!;
const textSuffixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-text-suffix'))!;
const iconPrefixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-icon-prefix'))!;
const iconSuffixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-icon-suffix'))!;
expect(textPrefixEl).not.toBeNull();
expect(textSuffixEl).not.toBeNull();
expect(iconPrefixEl).not.toBeNull();
expect(iconSuffixEl).not.toBeNull();
expect(textPrefixEl.nativeElement.innerText.trim()).toEqual('Prefix');
expect(textSuffixEl.nativeElement.innerText.trim()).toEqual('Suffix');
expect(iconPrefixEl.nativeElement.innerText.trim()).toEqual('favorite');
expect(iconSuffixEl.nativeElement.innerText.trim()).toEqual('favorite');
}));
it('should allow ng-container as prefix and suffix', () => {
const fixture = createComponent(InputWithNgContainerPrefixAndSuffix);
fixture.detectChanges();
const textPrefixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-text-prefix'))!;
const textSuffixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-text-suffix'))!;
const iconPrefixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-icon-prefix'))!;
const iconSuffixEl = fixture.debugElement.query(By.css('.mat-mdc-form-field-icon-suffix'))!;
expect(textPrefixEl.nativeElement.innerText.trim()).toEqual('text-prefix');
expect(textSuffixEl.nativeElement.innerText.trim()).toEqual('text-suffix');
expect(iconPrefixEl.nativeElement.innerText.trim()).toEqual('icon-prefix');
expect(iconSuffixEl.nativeElement.innerText.trim()).toEqual('icon-suffix');
});
it('should update empty class when value changes programmatically and OnPush', fakeAsync(() => {
let fixture = createComponent(MatInputOnPush);
fixture.detectChanges();
let component = fixture.componentInstance;
let label = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(label.classList).not.toContain('mdc-floating-label--float-above');
component.formControl.setValue('something');
fixture.detectChanges();
expect(label.classList).toContain('mdc-floating-label--float-above');
}));
it('should set the focused class when the input is focused', fakeAsync(() => {
let fixture = createComponent(MatInputTextTestController);
fixture.detectChanges();
let input = fixture.debugElement
.query(By.directive(MatInput))!
.injector.get<MatInput>(MatInput);
let container = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
// Call the focus handler directly to avoid flakyness where
// browsers don't focus elements if the window is minimized.
input._focusChanged(true);
fixture.detectChanges();
expect(container.classList).toContain('mat-focused');
}));
it('should remove the focused class if the input becomes disabled while focused', fakeAsync(() => {
const fixture = createComponent(MatInputTextTestController);
fixture.detectChanges();
const input = fixture.debugElement
.query(By.directive(MatInput))!
.injector.get<MatInput>(MatInput);
const container = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
// Call the focus handler directly to avoid flakyness where
// browsers don't focus elements if the window is minimized.
input._focusChanged(true);
fixture.detectChanges();
expect(container.classList).toContain('mat-focused');
input.disabled = true;
fixture.detectChanges();
expect(container.classList).not.toContain('mat-focused');
}));
it('should only show the native control placeholder, when there is a label, on focus', () => {
const fixture = createComponent(MatInputWithLabelAndPlaceholder);
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('mat-form-field'))!.nativeElement;
const label = fixture.debugElement.query(By.css('label'))!.nativeElement;
const input = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(container.classList).toContain('mat-form-field-hide-placeholder');
expect(label.textContent.trim()).toBe('Label');
input.value = 'Value';
dispatchFakeEvent(input, 'input');
fixture.detectChanges();
expect(container.classList).not.toContain('mat-form-field-hide-placeholder');
});
it('should always show the native control placeholder when floatLabel is set to "always"', () => {
const fixture = createComponent(MatInputWithLabelAndPlaceholder);
fixture.componentInstance.floatLabel = 'always';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('mat-form-field'))!.nativeElement;
expect(container.classList).not.toContain('mat-form-field-hide-placeholder');
});
it('should not add the `placeholder` attribute if there is no placeholder', () => {
const fixture = createComponent(MatInputWithoutPlaceholder);
fixture.detectChanges();
const input = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(input.hasAttribute('placeholder')).toBe(false);
});
it('should not add the native select class if the control is not a native select', () => {
const fixture = createComponent(MatInputWithId);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
expect(formField.classList).not.toContain('mat-mdc-form-field-type-mat-native-select');
});
it('should preserve the native placeholder on a non-legacy appearance', fakeAsync(() => {
const fixture = createComponent(MatInputWithLabelAndPlaceholder);
fixture.componentInstance.floatLabel = 'auto';
fixture.componentInstance.appearance = 'outline';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('input').getAttribute('placeholder')).toBe(
'Placeholder',
);
}));
it(
'should use the native input value when determining whether ' +
'the element is empty with a custom accessor',
fakeAsync(() => {
let fixture = createComponent(MatInputWithCustomAccessor, [], [], [CustomMatInputAccessor]);
fixture.detectChanges();
let formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField._control.empty).toBe(true);
fixture.nativeElement.querySelector('input').value = 'abc';
fixture.detectChanges();
expect(formField._control.empty).toBe(false);
}),
);
it('should default the form field color to primary', fakeAsync(() => {
const fixture = createComponent(MatInputWithColor);
fixture.detectChanges();
const formField = fixture.nativeElement.querySelector('.mat-mdc-form-field');
expect(formField.classList).toContain('mat-primary');
}));
it('should be able to change the form field color', fakeAsync(() => {
const fixture = createComponent(MatInputWithColor);
fixture.componentInstance.color = 'accent';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const formField = fixture.nativeElement.querySelector('.mat-mdc-form-field');
expect(formField.classList).toContain('mat-accent');
fixture.componentInstance.color = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(formField.classList).toContain('mat-warn');
}));
it('should set a class on the input depending on whether it is in a form field', fakeAsync(() => {
const fixture = createComponent(MatInputInsideOutsideFormField);
fixture.detectChanges();
const inFormField = fixture.nativeElement.querySelector('.inside');
const outsideFormField = fixture.nativeElement.querySelector('.outside');
expect(inFormField.classList).toContain('mat-mdc-form-field-input-control');
expect(outsideFormField.classList).not.toContain('mat-mdc-form-field-input-control');
}));
});
describe('MatMdcInput with forms', | {
"end_byte": 39995,
"start_byte": 30194,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_39996_49725 | () => {
describe('error messages', () => {
let fixture: ComponentFixture<MatInputWithFormErrorMessages>;
let testComponent: MatInputWithFormErrorMessages;
let containerEl: HTMLElement;
let inputEl: HTMLInputElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(MatInputWithFormErrorMessages);
fixture.detectChanges();
testComponent = fixture.componentInstance;
containerEl = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
}));
it('should not show any errors if the user has not interacted', fakeAsync(() => {
expect(testComponent.formControl.untouched)
.withContext('Expected untouched form control')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "false".')
.toBe('false');
}));
it('should display an error message when the input is touched and invalid', fakeAsync(() => {
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
inputEl.value = 'not valid';
testComponent.formControl.markAsTouched();
fixture.detectChanges();
flush();
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
}));
it('should not reset text-field validity if focus changes for an invalid input', fakeAsync(() => {
// Mark the control as touched, so that the form-field displays as invalid.
testComponent.formControl.markAsTouched();
fixture.detectChanges();
flush();
const wrapperEl = containerEl.querySelector('.mdc-text-field')!;
expect(wrapperEl.classList).toContain('mdc-text-field--invalid');
dispatchFakeEvent(inputEl, 'focus');
dispatchFakeEvent(inputEl, 'blur');
flush();
expect(wrapperEl.classList).toContain('mdc-text-field--invalid');
}));
it('should display an error message when the parent form is submitted', fakeAsync(() => {
expect(testComponent.form.submitted)
.withContext('Expected form not to have been submitted')
.toBe(false);
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
inputEl.value = 'not valid';
dispatchFakeEvent(fixture.debugElement.query(By.css('form'))!.nativeElement, 'submit');
fixture.detectChanges();
flush();
expect(testComponent.form.submitted)
.withContext('Expected form to have been submitted')
.toBe(true);
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
}));
it('should display an error message when the parent form group is submitted', fakeAsync(() => {
fixture.destroy();
TestBed.resetTestingModule();
let groupFixture = createComponent(MatInputWithFormGroupErrorMessages);
let component: MatInputWithFormGroupErrorMessages;
groupFixture.detectChanges();
component = groupFixture.componentInstance;
containerEl = groupFixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
inputEl = groupFixture.debugElement.query(By.css('input'))!.nativeElement;
expect(component.formGroup.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "false".')
.toBe('false');
expect(component.formGroupDirective.submitted)
.withContext('Expected form not to have been submitted')
.toBe(false);
inputEl.value = 'not valid';
dispatchFakeEvent(groupFixture.debugElement.query(By.css('form'))!.nativeElement, 'submit');
groupFixture.detectChanges();
flush();
expect(component.formGroupDirective.submitted)
.withContext('Expected form to have been submitted')
.toBe(true);
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
}));
it('should hide the errors and show the hints once the input becomes valid', fakeAsync(() => {
testComponent.formControl.markAsTouched();
fixture.detectChanges();
flush();
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected no hints to be shown.')
.toBe(0);
testComponent.formControl.setValue('valid value');
fixture.detectChanges();
flush();
expect(containerEl.classList).not.toContain(
'mat-form-field-invalid',
'Expected container not to have the invalid class when valid.',
);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages when the input is valid.')
.toBe(0);
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected one hint to be shown once the input is valid.')
.toBe(1);
}));
it('should not hide the hint if there are no error messages', fakeAsync(() => {
testComponent.renderError = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected one hint to be shown on load.')
.toBe(1);
testComponent.formControl.markAsTouched();
fixture.detectChanges();
flush();
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected one hint to still be shown.')
.toBe(1);
}));
it('should set the proper aria-live attribute on the error messages', fakeAsync(() => {
testComponent.formControl.markAsTouched();
fixture.detectChanges();
expect(containerEl.querySelector('mat-error')!.getAttribute('aria-live')).toBe('polite');
}));
it('sets the aria-describedby to reference errors when in error state', fakeAsync(() => {
let hintId = fixture.debugElement
.query(By.css('.mat-mdc-form-field-hint'))!
.nativeElement.getAttribute('id');
let describedBy = inputEl.getAttribute('aria-describedby');
expect(hintId).withContext('hint should be shown').toBeTruthy();
expect(describedBy).toBe(hintId);
fixture.componentInstance.formControl.markAsTouched();
fixture.detectChanges();
let errorIds = fixture.debugElement
.queryAll(By.css('.mat-mdc-form-field-error'))
.map(el => el.nativeElement.getAttribute('id'))
.join(' ');
describedBy = inputEl.getAttribute('aria-describedby');
expect(errorIds).withContext('errors should be shown').toBeTruthy();
expect(describedBy).toBe(errorIds);
}));
it('should set `aria-invalid` to true if the input is empty', fakeAsync(() => {
// Submit the form since it's the one that triggers the default error state matcher.
dispatchFakeEvent(fixture.nativeElement.querySelector('form'), 'submit');
fixture.detectChanges();
flush();
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(inputEl.value).toBe('incorrect');
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true"')
.toBe('true');
inputEl.value = 'not valid';
fixture.detectChanges();
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(inputEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
}));
}); | {
"end_byte": 49725,
"start_byte": 39996,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_49729_55970 | describe('custom error behavior', () => {
it('should display an error message when a custom error matcher returns true', fakeAsync(() => {
let fixture = createComponent(InputInFormGroup);
fixture.detectChanges();
let component = fixture.componentInstance;
let containerEl = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
const control = component.formGroup.get('name')!;
expect(control.invalid).withContext('Expected form control to be invalid').toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages')
.toBe(0);
control.markAsTouched();
fixture.detectChanges();
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages after being touched.')
.toBe(0);
component.errorState = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error messages to have been rendered.')
.toBe(1);
}));
it('should display an error message when global error matcher returns true', fakeAsync(() => {
let fixture = createComponent(MatInputWithFormErrorMessages, [
{
provide: ErrorStateMatcher,
useValue: {isErrorState: () => true},
},
]);
fixture.detectChanges();
let containerEl = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
let testComponent = fixture.componentInstance;
// Expect the control to still be untouched but the error to show due to the global setting
// Expect the control to still be untouched but the error to show due to the global setting
expect(testComponent.formControl.untouched)
.withContext('Expected untouched form control')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected an error message')
.toBe(1);
}));
it('should display an error message when using ShowOnDirtyErrorStateMatcher', fakeAsync(() => {
let fixture = createComponent(MatInputWithFormErrorMessages, [
{
provide: ErrorStateMatcher,
useClass: ShowOnDirtyErrorStateMatcher,
},
]);
fixture.detectChanges();
let containerEl = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
let testComponent = fixture.componentInstance;
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
testComponent.formControl.markAsTouched();
fixture.detectChanges();
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages when touched')
.toBe(0);
testComponent.formControl.markAsDirty();
fixture.detectChanges();
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message when dirty')
.toBe(1);
}));
});
it('should update the value when using FormControl.setValue', () => {
let fixture = createComponent(MatInputWithFormControl);
fixture.detectChanges();
let input = fixture.debugElement
.query(By.directive(MatInput))!
.injector.get<MatInput>(MatInput);
expect(input.value).toBeFalsy();
fixture.componentInstance.formControl.setValue('something');
expect(input.value).toBe('something');
});
it('should display disabled styles when using FormControl.disable()', fakeAsync(() => {
const fixture = createComponent(MatInputWithFormControl);
fixture.detectChanges();
const formFieldEl = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(formFieldEl.classList).not.toContain(
'mat-form-field-disabled',
`Expected form field not to start out disabled.`,
);
expect(inputEl.disabled).toBe(false);
fixture.componentInstance.formControl.disable();
fixture.detectChanges();
expect(formFieldEl.classList)
.withContext(`Expected form field to look disabled after disable() is called.`)
.toContain('mat-form-field-disabled');
expect(inputEl.disabled).toBe(true);
}));
it('should not treat the number 0 as empty', fakeAsync(() => {
let fixture = createComponent(MatInputZeroTestController);
fixture.detectChanges();
flush();
fixture.detectChanges();
let formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).not.toBeNull();
expect(formField._control.empty).toBe(false);
}));
it('should update when the form field value is patched without emitting', fakeAsync(() => {
const fixture = createComponent(MatInputWithFormControl);
fixture.detectChanges();
let formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField._control.empty).toBe(true);
fixture.componentInstance.formControl.patchValue('value', {emitEvent: false});
fixture.detectChanges();
expect(formField._control.empty).toBe(false);
}));
it('should update notch size after changing appearance to outline', fakeAsync(() => {
const fixture = createComponent(MatInputWithAppearance);
fixture.detectChanges();
tick(16);
expect(fixture.nativeElement.querySelector('.mdc-notched-outline__notch')).toBe(null);
fixture.componentInstance.appearance = 'outline';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(16);
let notch = fixture.nativeElement.querySelector('.mdc-notched-outline__notch')! as HTMLElement;
expect(notch.style.width).toBeFalsy();
fixture.nativeElement.querySelector('input')!.focus();
fixture.detectChanges();
tick(16);
expect(notch.style.width).toBeTruthy();
}));
}); | {
"end_byte": 55970,
"start_byte": 49729,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_55972_65320 | describe('MatFormField default options', () => {
it('should be fill appearance if no default options provided', () => {
const fixture = createComponent(MatInputWithAppearance);
fixture.detectChanges();
expect(fixture.componentInstance.formField.appearance).toBe('fill');
});
it('should be fill appearance if empty default options provided', () => {
const fixture = createComponent(MatInputWithAppearance, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.appearance).toBe('fill');
});
it('should be able to change the default appearance', () => {
const fixture = createComponent(MatInputWithAppearance, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {appearance: 'outline'},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.appearance).toBe('outline');
});
it('should default hideRequiredMarker to false', () => {
const fixture = createComponent(MatInputWithAppearance, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.hideRequiredMarker).toBe(false);
});
it('should be able to change the default value of hideRequiredMarker and appearance', () => {
const fixture = createComponent(MatInputWithAppearance, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {
hideRequiredMarker: true,
appearance: 'outline',
},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.hideRequiredMarker).toBe(true);
expect(fixture.componentInstance.formField.appearance).toBe('outline');
});
it('should be able to change the default color', () => {
const fixture = createComponent(MatInputSimple, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {color: 'accent'},
},
]);
fixture.detectChanges();
const formField = fixture.nativeElement.querySelector('.mat-mdc-form-field');
expect(formField.classList).toContain('mat-accent');
});
it('defaults subscriptSizing to false', () => {
const fixture = createComponent(MatInputWithSubscriptSizing);
fixture.detectChanges();
const subscriptElement = fixture.nativeElement.querySelector(
'.mat-mdc-form-field-subscript-wrapper',
);
expect(fixture.componentInstance.formField.subscriptSizing).toBe('fixed');
expect(subscriptElement.classList.contains('mat-mdc-form-field-subscript-dynamic-size')).toBe(
false,
);
fixture.componentInstance.sizing = 'dynamic';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.formField.subscriptSizing).toBe('dynamic');
expect(subscriptElement.classList.contains('mat-mdc-form-field-subscript-dynamic-size')).toBe(
true,
);
});
it('changes the default value of subscriptSizing (undefined input)', () => {
const fixture = createComponent(MatInputWithSubscriptSizing, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {
subscriptSizing: 'dynamic',
},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.subscriptSizing).toBe('dynamic');
expect(
fixture.nativeElement
.querySelector('.mat-mdc-form-field-subscript-wrapper')
.classList.contains('mat-mdc-form-field-subscript-dynamic-size'),
).toBe(true);
});
it('changes the default value of subscriptSizing (no input)', () => {
const fixture = createComponent(MatInputWithAppearance, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {
subscriptSizing: 'dynamic',
},
},
]);
fixture.detectChanges();
expect(fixture.componentInstance.formField.subscriptSizing).toBe('dynamic');
expect(
fixture.nativeElement
.querySelector('.mat-mdc-form-field-subscript-wrapper')
.classList.contains('mat-mdc-form-field-subscript-dynamic-size'),
).toBe(true);
});
});
describe('MatFormField without label', () => {
it('should not float the label when no label is defined.', () => {
let fixture = createComponent(MatInputWithoutDefinedLabel);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'))!;
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
// Update the value of the input and set focus.
inputEl.nativeElement.value = 'Text';
fixture.detectChanges();
// should not float label if there is no label
expect(formField._shouldLabelFloat()).toBe(false);
});
it('should not float the label when the label is removed after it has been shown', () => {
let fixture = createComponent(MatInputWithCondictionalLabel);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'))!;
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
// initially, label is present
expect(fixture.nativeElement.querySelector('label')).not.toBeNull();
// removing label after it has been shown
fixture.componentInstance.hasLabel = false;
inputEl.nativeElement.value = 'Text';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// now expected to not have a label
expect(fixture.nativeElement.querySelector('label')).toBeNull();
// should not float label since there is no label
expect(formField._shouldLabelFloat()).toBe(false);
});
it('should float the label when the label is not removed', () => {
let fixture = createComponent(MatInputWithCondictionalLabel);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'))!;
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
inputEl.nativeElement.value = 'Text';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Expected to have a label
expect(fixture.nativeElement.querySelector('label')).not.toBeNull();
// should float label since there is a label
expect(formField._shouldLabelFloat()).toBe(true);
});
});
function configureTestingModule(
component: Type<any>,
options: {
providers?: Provider[];
imports?: any[];
declarations?: any[];
animations?: boolean;
} = {},
) {
const {providers = [], imports = [], declarations = [], animations = true} = options;
TestBed.configureTestingModule({
imports: [
FormsModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
animations ? BrowserAnimationsModule : NoopAnimationsModule,
ReactiveFormsModule,
...imports,
],
declarations: [component, ...declarations],
providers: [
// Custom error handler that re-throws the error. Errors happening within
// change detection phase will be reported through the handler and thrown
// in Ivy. Since we do not want to pollute the "console.error", but rather
// just rely on the actual error interrupting the test, we re-throw here.
{
provide: ErrorHandler,
useValue: {
handleError: (err: any) => {
throw err;
},
},
},
...providers,
],
});
}
function createComponent<T>(
component: Type<T>,
providers: Provider[] = [],
imports: any[] = [],
declarations: any[] = [],
): ComponentFixture<T> {
configureTestingModule(component, {providers, imports, declarations});
return TestBed.createComponent<T>(component);
}
@Component({
template: `
<mat-form-field [floatLabel]="floatLabel">
<mat-label>Label</mat-label>
<input matNativeControl id="test-id" placeholder="test">
</mat-form-field>`,
standalone: false,
})
class MatInputWithId {
floatLabel: 'always' | 'auto' = 'auto';
}
@Component({
template: `
<mat-form-field>
<input matInput [disabled]="disabled" [disabledInteractive]="disabledInteractive">
</mat-form-field>
`,
standalone: false,
})
class MatInputWithDisabled {
disabled = false;
disabledInteractive = false;
}
@Component({
template: `<mat-form-field><input matInput [required]="required"></mat-form-field>`,
standalone: false,
})
class MatInputWithRequired {
required: boolean;
}
@Component({
template: `<mat-form-field><input matInput [type]="type"></mat-form-field>`,
standalone: false,
})
class MatInputWithType {
type: string;
}
@Component({
template: `
<mat-form-field [hideRequiredMarker]="hideRequiredMarker">
<mat-label>hello</mat-label>
<input matInput required [disabled]="disabled">
</mat-form-field>`,
standalone: false,
})
class MatInputLabelRequiredTestComponent {
hideRequiredMarker: boolean = false;
disabled: boolean = false;
}
@Component({
template: `
<mat-form-field>
<input matInput placeholder="Hello" [formControl]="formControl">
</mat-form-field>`,
standalone: false,
})
class MatInputWithFormControl {
formControl = new FormControl('');
} | {
"end_byte": 65320,
"start_byte": 55972,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_65322_73083 | @Component({
template: `<mat-form-field><input matInput><mat-hint>{{label}}</mat-hint></mat-form-field>`,
standalone: false,
})
class MatInputHintLabel2TestController {
label: string = '';
}
@Component({
template: `
<mat-form-field [hintLabel]="label">
<input matInput aria-describedby="initial">
</mat-form-field>`,
standalone: false,
})
class MatInputHintLabelTestController {
label: string = '';
}
@Component({
template: `
<mat-form-field [hintLabel]="label">
<input matInput [formControl]="formControl" [aria-describedby]="userDescribedByValue">
@if (showError) {
<mat-error>Some error</mat-error>
}
</mat-form-field>`,
standalone: false,
})
class MatInputWithSubscriptAndAriaDescribedBy {
label: string = '';
userDescribedByValue: string = '';
showError = false;
formControl = new FormControl('');
}
@Component({
template: `<mat-form-field><input matInput [type]="t"></mat-form-field>`,
standalone: false,
})
class MatInputInvalidTypeTestController {
t = 'file';
}
@Component({
template: `
<mat-form-field hintLabel="Hello">
<input matInput>
<mat-hint>World</mat-hint>
</mat-form-field>`,
standalone: false,
})
class MatInputInvalidHint2TestController {}
@Component({
template: `
<mat-form-field>
<input matInput>
<mat-hint>Hello</mat-hint>
<mat-hint>World</mat-hint>
</mat-form-field>`,
standalone: false,
})
class MatInputInvalidHintTestController {}
@Component({
template: `
<mat-form-field>
<input matInput>
<mat-hint align="start" [id]="startId">Hello</mat-hint>
<mat-hint align="end" [id]="endId">World</mat-hint>
</mat-form-field>`,
standalone: false,
})
class MatInputMultipleHintTestController {
startId: string;
endId: string;
}
@Component({
template: `
<mat-form-field hintLabel="Hello">
<input matInput>
<mat-hint align="end">World</mat-hint>
</mat-form-field>`,
standalone: false,
})
class MatInputMultipleHintMixedTestController {}
@Component({
template: `
<mat-form-field>
<input matInput type="date" placeholder="Placeholder">
</mat-form-field>`,
standalone: false,
})
class MatInputDateTestController {}
@Component({
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<input
matInput
type="text"
placeholder="Placeholder"
[disabled]="disabled"
[disabledInteractive]="disabledInteractive">
</mat-form-field>`,
standalone: false,
})
class MatInputTextTestController {
disabled = false;
disabledInteractive = false;
}
@Component({
template: `
<mat-form-field>
<input matInput type="password" placeholder="Placeholder">
</mat-form-field>`,
standalone: false,
})
class MatInputPasswordTestController {}
@Component({
template: `
<mat-form-field>
<input matInput type="number" placeholder="Placeholder">
</mat-form-field>`,
standalone: false,
})
class MatInputNumberTestController {}
@Component({
template: `
<mat-form-field>
<input matInput type="number" placeholder="Placeholder" [(ngModel)]="value">
</mat-form-field>`,
standalone: false,
})
class MatInputZeroTestController {
value = 0;
}
@Component({
template: `
<mat-form-field>
<input matInput placeholder="Label" [value]="value">
</mat-form-field>`,
standalone: false,
})
class MatInputWithValueBinding {
value: string = 'Initial';
}
@Component({
template: `
<mat-form-field>
<input matInput placeholder="Label">
</mat-form-field>
`,
standalone: false,
})
class MatInputWithStaticLabel {}
@Component({
template: `
<mat-form-field [floatLabel]="shouldFloat">
<mat-label>Label</mat-label>
<input
matInput
placeholder="Placeholder"
[disabled]="disabled"
[disabledInteractive]="disabledInteractive">
</mat-form-field>`,
standalone: false,
})
class MatInputWithDynamicLabel {
shouldFloat: 'always' | 'auto' = 'always';
disabled = false;
disabledInteractive = false;
}
@Component({
template: `
<mat-form-field>
<input matInput placeholder="Label">
</mat-form-field>
`,
standalone: false,
})
class MatInputWithoutDefinedLabel {}
@Component({
template: `
<mat-form-field>
@if (hasLabel) {
<mat-label>Label</mat-label>
}
<input matInput>
</mat-form-field>`,
standalone: false,
})
class MatInputWithCondictionalLabel {
hasLabel = true;
}
@Component({
template: `
<mat-form-field>
<textarea matNativeControl [rows]="rows" [cols]="cols" [wrap]="wrap" placeholder="Snacks">
</textarea>
</mat-form-field>`,
standalone: false,
})
class MatInputTextareaWithBindings {
rows: number = 4;
cols: number = 8;
wrap: string = 'hard';
}
@Component({
template: `<mat-form-field><input></mat-form-field>`,
standalone: false,
})
class MatInputMissingMatInputTestController {}
@Component({
template: `
<form #form="ngForm" novalidate>
<mat-form-field>
<input matInput [formControl]="formControl">
<mat-hint>Please type something</mat-hint>
@if (renderError) {
<mat-error>This field is required</mat-error>
}
</mat-form-field>
</form>
`,
standalone: false,
})
class MatInputWithFormErrorMessages {
@ViewChild('form') form: NgForm;
formControl = new FormControl('incorrect', [
Validators.required,
Validators.pattern(/valid value/),
]);
renderError = true;
}
@Component({
template: `
<form [formGroup]="formGroup">
<mat-form-field>
<input matInput
formControlName="name"
[errorStateMatcher]="customErrorStateMatcher">
<mat-hint>Please type something</mat-hint>
<mat-error>This field is required</mat-error>
</mat-form-field>
</form>
`,
standalone: false,
})
class InputInFormGroup {
formGroup = new FormGroup({
name: new FormControl('', [Validators.required, Validators.pattern(/valid value/)]),
});
errorState = false;
customErrorStateMatcher = {
isErrorState: () => this.errorState,
};
}
@Component({
template: `
<form [formGroup]="formGroup" novalidate>
<mat-form-field>
<input matInput formControlName="name">
<mat-hint>Please type something</mat-hint>
<mat-error>This field is required</mat-error>
</mat-form-field>
</form>
`,
standalone: false,
})
class MatInputWithFormGroupErrorMessages {
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
formGroup = new FormGroup({
name: new FormControl('incorrect', [Validators.required, Validators.pattern(/valid value/)]),
});
}
@Component({
template: `
<mat-form-field>
<mat-icon matIconPrefix>favorite</mat-icon>
<div matTextPrefix>Prefix</div>
<input matInput>
<div matTextSuffix>Suffix</div>
<mat-icon matIconSuffix>favorite</mat-icon>
</mat-form-field>
`,
standalone: false,
})
class MatInputWithPrefixAndSuffix {}
@Component({
template: `
<mat-form-field>
@if (renderInput) {
<input matInput>
}
</mat-form-field>
`,
standalone: false,
})
class MatInputWithNgIf {
renderInput = true;
}
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<input matInput [formControl]="formControl">
</mat-form-field>
`,
standalone: false,
})
class MatInputOnPush {
formControl = new FormControl('');
}
@Component({
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<input matInput>
</mat-form-field>
`,
standalone: false,
})
class MatInputWithLabel {} | {
"end_byte": 73083,
"start_byte": 65322,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_73085_78060 | @Component({
template: `
<mat-form-field [floatLabel]="floatLabel" [appearance]="appearance">
<mat-label>Label</mat-label>
<input matInput placeholder="Placeholder">
</mat-form-field>
`,
standalone: false,
})
class MatInputWithLabelAndPlaceholder {
floatLabel: FloatLabelType;
appearance: MatFormFieldAppearance;
}
@Component({
template: `
<mat-form-field [appearance]="appearance">
<mat-label>My Label</mat-label>
<input matInput placeholder="Placeholder">
</mat-form-field>
`,
standalone: false,
})
class MatInputWithAppearance {
@ViewChild(MatFormField) formField: MatFormField;
appearance: MatFormFieldAppearance;
}
@Component({
template: `
<mat-form-field [subscriptSizing]="sizing">
<mat-label>My Label</mat-label>
<input matInput placeholder="Placeholder" required>
</mat-form-field>
`,
standalone: false,
})
class MatInputWithSubscriptSizing {
@ViewChild(MatFormField) formField: MatFormField;
sizing: SubscriptSizing;
}
@Component({
template: `
<mat-form-field>
<input matInput>
</mat-form-field>
`,
standalone: false,
})
class MatInputWithoutPlaceholder {}
@Component({
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<select matNativeControl id="test-id" [disabled]="disabled" [required]="required">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>`,
standalone: false,
})
class MatInputSelect {
disabled: boolean;
required: boolean;
}
@Component({
template: `
<mat-form-field>
<mat-label>Form-field label</mat-label>
<select matNativeControl>
<option value="" disabled selected></option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>`,
standalone: false,
})
class MatInputSelectWithNoLabelNoValue {}
@Component({
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<select matNativeControl>
<option value="" label="select a car"></option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>`,
standalone: false,
})
class MatInputSelectWithLabel {}
@Component({
template: `
<mat-form-field>
<mat-label>Label</mat-label>
<select matNativeControl>
<option value="">select a car</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>`,
standalone: false,
})
class MatInputSelectWithInnerHtml {}
@Component({
template: `
<mat-form-field>
<input matInput customInputAccessor placeholder="Placeholder">
</mat-form-field>`,
standalone: false,
})
class MatInputWithCustomAccessor {}
@Component({
template: `
<mat-form-field>
<select matNativeControl>
</select>
</mat-form-field>`,
standalone: false,
})
class MatInputSelectWithoutOptions {}
/** Custom component that never has a value. Used for testing the `MAT_INPUT_VALUE_ACCESSOR`. */
@Directive({
selector: 'input[customInputAccessor]',
providers: [
{
provide: MAT_INPUT_VALUE_ACCESSOR,
useExisting: CustomMatInputAccessor,
},
],
standalone: false,
})
class CustomMatInputAccessor {
get value() {
return this._value;
}
set value(_value: any) {}
private _value = null;
}
@Component({
template: `
<mat-form-field [color]="color">
<input matNativeControl>
</mat-form-field>`,
standalone: false,
})
class MatInputWithColor {
color: ThemePalette;
}
@Component({
template: `
<mat-form-field>
<input class="inside" matNativeControl>
</mat-form-field>
<input class="outside" matNativeControl>
`,
standalone: false,
})
class MatInputInsideOutsideFormField {}
@Component({
template: `
<mat-form-field>
<mat-label>Hello</mat-label>
<input matInput [formControl]="formControl">
</mat-form-field>`,
standalone: false,
})
class MatInputWithRequiredFormControl {
formControl = new FormControl('', [Validators.required]);
}
@Component({
template: `
<mat-form-field>
<input matInput>
</mat-form-field>
`,
standalone: false,
})
class MatInputSimple {}
@Component({
template: `
<mat-form-field>
<ng-container matIconPrefix>icon-prefix</ng-container>
<ng-container matTextPrefix>text-prefix</ng-container>
<input matInput>
<ng-container matTextSuffix>text-suffix</ng-container>
<ng-container matIconSuffix>icon-suffix</ng-container>
</mat-form-field>
`,
standalone: false,
})
class InputWithNgContainerPrefixAndSuffix {} | {
"end_byte": 78060,
"start_byte": 73085,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/README.md_0_96 | Please see the official documentation at https://material.angular.io/components/component/input
| {
"end_byte": 96,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/README.md"
} |
components/src/material/input/BUILD.bazel_0_1414 | load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_module",
"ng_test_library",
"ng_web_test_suite",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "input",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = glob(["**/*.html"]),
deps = [
"//src/cdk/text-field",
"//src/material/core",
"//src/material/form-field",
"@npm//@angular/forms",
],
)
sass_library(
name = "input_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
###########
# Testing
###########
ng_test_library(
name = "input_tests_lib",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":input",
"//src/cdk/platform",
"//src/cdk/testing/private",
"//src/material/core",
"//src/material/form-field",
"//src/material/icon",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":input_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":input.md"],
)
extract_tokens(
name = "tokens",
srcs = [":input_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1414,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/BUILD.bazel"
} |
components/src/material/input/_input-theme.scss_0_1918 | @use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/tokens/token-utils';
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
}
}
@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: (),
),
);
}
@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-input') {
@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'
);
}
| {
"end_byte": 1918,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/_input-theme.scss"
} |
components/src/material/input/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/index.ts"
} |
components/src/material/input/testing/input-harness.ts_0_4963 | /**
* @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 {HarnessPredicate, parallel} from '@angular/cdk/testing';
import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {InputHarnessFilters} from './input-harness-filters';
/** Harness for interacting with a standard Material inputs in tests. */
export class MatInputHarness extends MatFormFieldControlHarness {
// TODO: We do not want to handle `select` elements with `matNativeControl` because
// not all methods of this harness work reasonably for native select elements.
// For more details. See: https://github.com/angular/components/pull/18221.
static hostSelector = '[matInput], input[matNativeControl], textarea[matNativeControl]';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatInputHarness` that meets
* certain criteria.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: InputHarnessFilters = {}): HarnessPredicate<MatInputHarness> {
return new HarnessPredicate(MatInputHarness, options)
.addOption('value', options.value, (harness, value) => {
return HarnessPredicate.stringMatches(harness.getValue(), value);
})
.addOption('placeholder', options.placeholder, (harness, placeholder) => {
return HarnessPredicate.stringMatches(harness.getPlaceholder(), placeholder);
});
}
/** Whether the input is disabled. */
async isDisabled(): Promise<boolean> {
const host = await this.host();
const disabled = await host.getAttribute('disabled');
if (disabled !== null) {
return coerceBooleanProperty(disabled);
}
return (await host.getAttribute('aria-disabled')) === 'true';
}
/** Whether the input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('required');
}
/** Whether the input is readonly. */
async isReadonly(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('readOnly');
}
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is never undefined.
return await (await this.host()).getProperty<string>('value');
}
/** Gets the name of the input. */
async getName(): Promise<string> {
// The "name" property of the native input is never undefined.
return await (await this.host()).getProperty<string>('name');
}
/**
* Gets the type of the input. Returns "textarea" if the input is
* a textarea.
*/
async getType(): Promise<string> {
// The "type" property of the native input is never undefined.
return await (await this.host()).getProperty<string>('type');
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
const host = await this.host();
const [nativePlaceholder, fallback] = await parallel(() => [
host.getProperty('placeholder'),
host.getAttribute('data-placeholder'),
]);
return nativePlaceholder || fallback || '';
}
/** Gets the id of the input. */
async getId(): Promise<string> {
// The input directive always assigns a unique id to the input in
// case no id has been explicitly specified.
return await (await this.host()).getProperty<string>('id');
}
/**
* Focuses the input and returns a promise that indicates when the
* action is complete.
*/
async focus(): Promise<void> {
return (await this.host()).focus();
}
/**
* Blurs the input and returns a promise that indicates when the
* action is complete.
*/
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the input is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/**
* Sets the value of the input. The value will be set by simulating
* keypresses that correspond to the given value.
*/
async setValue(newValue: string): Promise<void> {
const inputEl = await this.host();
await inputEl.clear();
// We don't want to send keys for the value if the value is an empty
// string in order to clear the value. Sending keys with an empty string
// still results in unnecessary focus events.
if (newValue) {
await inputEl.sendKeys(newValue);
}
// Some input types won't respond to key presses (e.g. `color`) so to be sure that the
// value is set, we also set the property after the keyboard sequence. Note that we don't
// want to do it before, because it can cause the value to be entered twice.
await inputEl.setInputValue(newValue);
}
}
| {
"end_byte": 4963,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/input-harness.ts"
} |
components/src/material/input/testing/native-option-harness.ts_0_2083 | /**
* @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 {NativeOptionHarnessFilters} from './native-select-harness-filters';
/** Harness for interacting with a native `option` in tests. */
export class MatNativeOptionHarness extends ComponentHarness {
/** Selector used to locate option instances. */
static hostSelector = 'select[matNativeControl] option';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatNativeOptionHarness` that meets
* certain criteria.
* @param options Options for filtering which option instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: NativeOptionHarnessFilters = {}) {
return new HarnessPredicate(MatNativeOptionHarness, options)
.addOption('text', options.text, async (harness, title) =>
HarnessPredicate.stringMatches(await harness.getText(), title),
)
.addOption(
'index',
options.index,
async (harness, index) => (await harness.getIndex()) === index,
)
.addOption(
'isSelected',
options.isSelected,
async (harness, isSelected) => (await harness.isSelected()) === isSelected,
);
}
/** Gets the option's label text. */
async getText(): Promise<string> {
return (await this.host()).getProperty<string>('label');
}
/** Index of the option within the native `select` element. */
async getIndex(): Promise<number> {
return (await this.host()).getProperty<number>('index');
}
/** Gets whether the option is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Gets whether the option is selected. */
async isSelected(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('selected');
}
}
| {
"end_byte": 2083,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/native-option-harness.ts"
} |
components/src/material/input/testing/native-select-harness.ts_0_3661 | /**
* @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 {HarnessPredicate, parallel} from '@angular/cdk/testing';
import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
import {MatNativeOptionHarness} from './native-option-harness';
import {
NativeOptionHarnessFilters,
NativeSelectHarnessFilters,
} from './native-select-harness-filters';
/** Harness for interacting with a native `select` in tests. */
export class MatNativeSelectHarness extends MatFormFieldControlHarness {
static hostSelector = 'select[matNativeControl]';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatNativeSelectHarness` that meets
* certain criteria.
* @param options Options for filtering which select instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: NativeSelectHarnessFilters = {}): HarnessPredicate<MatNativeSelectHarness> {
return new HarnessPredicate(MatNativeSelectHarness, options);
}
/** Gets a boolean promise indicating if the select is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Gets a boolean promise indicating if the select is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('required');
}
/** Gets a boolean promise indicating if the select is in multi-selection mode. */
async isMultiple(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('multiple');
}
/** Gets the name of the select. */
async getName(): Promise<string> {
// The "name" property of the native select is never undefined.
return await (await this.host()).getProperty<string>('name');
}
/** Gets the id of the select. */
async getId(): Promise<string> {
// We're guaranteed to have an id, because the `matNativeControl` always assigns one.
return await (await this.host()).getProperty<string>('id');
}
/** Focuses the select and returns a void promise that indicates when the action is complete. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the select and returns a void promise that indicates when the action is complete. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the select is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Gets the options inside the select panel. */
async getOptions(filter: NativeOptionHarnessFilters = {}): Promise<MatNativeOptionHarness[]> {
return this.locatorForAll(MatNativeOptionHarness.with(filter))();
}
/**
* Selects the options that match the passed-in filter. If the select is in multi-selection
* mode all options will be clicked, otherwise the harness will pick the first matching option.
*/
async selectOptions(filter: NativeOptionHarnessFilters = {}): Promise<void> {
const [isMultiple, options] = await parallel(() => {
return [this.isMultiple(), this.getOptions(filter)];
});
if (options.length === 0) {
throw Error('Select does not have options matching the specified filter');
}
const [host, optionIndexes] = await parallel(() => [
this.host(),
parallel(() => options.slice(0, isMultiple ? undefined : 1).map(option => option.getIndex())),
]);
await host.selectOptions(...optionIndexes);
}
}
| {
"end_byte": 3661,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/native-select-harness.ts"
} |
components/src/material/input/testing/input-harness.spec.ts_0_523 | 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 {FormsModule} from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {getSupportedInputTypes} from '@angular/cdk/platform';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatInputHarness} from './input-harness'; | {
"end_byte": 523,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/input-harness.spec.ts"
} |
components/src/material/input/testing/input-harness.spec.ts_525_9277 | describe('MatInputHarness', () => {
let fixture: ComponentFixture<InputHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NoopAnimationsModule, MatInputModule, FormsModule, InputHarnessTest],
});
fixture = TestBed.createComponent(InputHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all input harnesses', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
});
it('should load input with specific id', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness.with({selector: '#myTextarea'}));
expect(inputs.length).toBe(1);
});
it('should load input with specific name', async () => {
const inputs = await loader.getAllHarnesses(
MatInputHarness.with({selector: '[name="favorite-food"]'}),
);
expect(inputs.length).toBe(1);
});
it('should load input with a specific value', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness.with({value: 'Sushi'}));
expect(inputs.length).toBe(1);
});
it('should load input with a value that matches a regex', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness.with({value: /shi$/}));
expect(inputs.length).toBe(1);
expect(await inputs[0].getValue()).toBe('Sushi');
});
it('should load input with a specific placeholder', async () => {
const inputs = await loader.getAllHarnesses(
MatInputHarness.with({placeholder: 'Favorite food'}),
);
expect(inputs.length).toBe(1);
});
it('should load input with a placeholder that matches a regex', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness.with({placeholder: / food$/}));
expect(inputs.length).toBe(1);
expect(await inputs[0].getPlaceholder()).toBe('Favorite food');
});
it('should be able to get id of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getId()).toMatch(/mat-input-\d+/);
expect(await inputs[1].getId()).toMatch(/mat-input-\d+/);
expect(await inputs[2].getId()).toBe('myTextarea');
expect(await inputs[3].getId()).toBe('nativeControl');
expect(await inputs[4].getId()).toMatch(/mat-input-\d+/);
expect(await inputs[5].getId()).toBe('has-ng-model');
});
it('should be able to get name of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getName()).toBe('favorite-food');
expect(await inputs[1].getName()).toBe('');
expect(await inputs[2].getName()).toBe('');
expect(await inputs[3].getName()).toBe('');
expect(await inputs[4].getName()).toBe('');
expect(await inputs[5].getName()).toBe('has-ng-model');
});
it('should be able to get value of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getValue()).toBe('Sushi');
expect(await inputs[1].getValue()).toBe('');
expect(await inputs[2].getValue()).toBe('');
expect(await inputs[3].getValue()).toBe('');
expect(await inputs[4].getValue()).toBe('');
expect(await inputs[5].getValue()).toBe('');
});
it('should be able to set value of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getValue()).toBe('Sushi');
expect(await inputs[1].getValue()).toBe('');
expect(await inputs[3].getValue()).toBe('');
expect(await inputs[4].getValue()).toBe('');
await inputs[0].setValue('');
await inputs[2].setValue('new-value');
await inputs[3].setValue('new-value');
await inputs[4].setValue('new-value');
expect(await inputs[0].getValue()).toBe('');
expect(await inputs[2].getValue()).toBe('new-value');
expect(await inputs[3].getValue()).toBe('new-value');
expect(await inputs[4].getValue()).toBe('new-value');
});
it('should be able to get disabled state', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].isDisabled()).toBe(false);
expect(await inputs[1].isDisabled()).toBe(false);
expect(await inputs[2].isDisabled()).toBe(false);
expect(await inputs[3].isDisabled()).toBe(false);
expect(await inputs[4].isDisabled()).toBe(false);
expect(await inputs[5].isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await inputs[1].isDisabled()).toBe(true);
});
it('should be able to get readonly state', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].isReadonly()).toBe(false);
expect(await inputs[1].isReadonly()).toBe(false);
expect(await inputs[2].isReadonly()).toBe(false);
expect(await inputs[3].isReadonly()).toBe(false);
expect(await inputs[4].isReadonly()).toBe(false);
expect(await inputs[5].isReadonly()).toBe(false);
fixture.componentInstance.readonly.set(true);
expect(await inputs[1].isReadonly()).toBe(true);
});
it('should be able to get required state', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].isRequired()).toBe(false);
expect(await inputs[1].isRequired()).toBe(false);
expect(await inputs[2].isRequired()).toBe(false);
expect(await inputs[3].isRequired()).toBe(false);
expect(await inputs[4].isRequired()).toBe(false);
expect(await inputs[5].isRequired()).toBe(false);
fixture.componentInstance.required.set(true);
expect(await inputs[1].isRequired()).toBe(true);
});
it('should be able to get placeholder of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getPlaceholder()).toBe('Favorite food');
expect(await inputs[1].getPlaceholder()).toBe('');
expect(await inputs[2].getPlaceholder()).toBe('Leave a comment');
expect(await inputs[3].getPlaceholder()).toBe('Native control');
expect(await inputs[4].getPlaceholder()).toBe('');
expect(await inputs[5].getPlaceholder()).toBe('');
});
it('should be able to get type of input', async () => {
const inputs = await loader.getAllHarnesses(MatInputHarness);
expect(inputs.length).toBe(7);
expect(await inputs[0].getType()).toBe('text');
expect(await inputs[1].getType()).toBe('number');
expect(await inputs[2].getType()).toBe('textarea');
expect(await inputs[3].getType()).toBe('text');
expect(await inputs[4].getType()).toBe('textarea');
expect(await inputs[5].getType()).toBe('text');
fixture.componentInstance.inputType.set('text');
expect(await inputs[1].getType()).toBe('text');
});
it('should be able to focus input', async () => {
const input = await loader.getHarness(
MatInputHarness.with({selector: '[name="favorite-food"]'}),
);
expect(await input.isFocused()).toBe(false);
await input.focus();
expect(await input.isFocused()).toBe(true);
});
it('should be able to blur input', async () => {
const input = await loader.getHarness(
MatInputHarness.with({selector: '[name="favorite-food"]'}),
);
expect(await input.isFocused()).toBe(false);
await input.focus();
expect(await input.isFocused()).toBe(true);
await input.blur();
expect(await input.isFocused()).toBe(false);
});
it('should be able to set the value of a control that cannot be typed in', async () => {
// We can't test this against browsers that don't support color inputs.
if (!getSupportedInputTypes().has('color')) {
return;
}
const input = await loader.getHarness(MatInputHarness.with({selector: '#colorControl'}));
expect(await input.getValue()).toBe('#000000'); // Color inputs default to black.
await input.setValue('#00ff00');
expect((await input.getValue()).toLowerCase()).toBe('#00ff00');
});
it('should be able to get disabled state when disabledInteractive is enabled', async () => {
const input = (await loader.getAllHarnesses(MatInputHarness))[1];
fixture.componentInstance.disabled.set(false);
fixture.componentInstance.disabledInteractive.set(true);
expect(await input.isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await input.isDisabled()).toBe(true);
});
}); | {
"end_byte": 9277,
"start_byte": 525,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/input-harness.spec.ts"
} |
components/src/material/input/testing/input-harness.spec.ts_9279_10927 | @Component({
template: `
<mat-form-field>
<input matInput placeholder="Favorite food" value="Sushi" name="favorite-food">
</mat-form-field>
<mat-form-field>
<input
matInput
[type]="inputType()"
[readonly]="readonly()"
[disabled]="disabled()"
[disabledInteractive]="disabledInteractive()"
[required]="required()">
</mat-form-field>
<mat-form-field>
<textarea id="myTextarea" matInput placeholder="Leave a comment"></textarea>
</mat-form-field>
<mat-form-field>
<input matNativeControl placeholder="Native control" id="nativeControl">
</mat-form-field>
<mat-form-field>
<textarea matNativeControl></textarea>
</mat-form-field>
<mat-form-field>
<!--
Select native controls should not be handled as part of the input harness. We add this
to assert that the harness does not accidentally match it.
-->
<select matNativeControl>
<option value="first">First</option>
</select>
</mat-form-field>
<mat-form-field>
<input [(ngModel)]="ngModelValue" [name]="ngModelName" id="has-ng-model" matNativeControl>
</mat-form-field>
<mat-form-field>
<input matNativeControl placeholder="Color control" id="colorControl" type="color">
</mat-form-field>
`,
standalone: true,
imports: [MatInputModule, FormsModule],
})
class InputHarnessTest {
inputType = signal('number');
readonly = signal(false);
disabled = signal(false);
disabledInteractive = signal(false);
required = signal(false);
ngModelValue = '';
ngModelName = 'has-ng-model';
} | {
"end_byte": 10927,
"start_byte": 9279,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/input-harness.spec.ts"
} |
components/src/material/input/testing/public-api.ts_0_409 | /**
* @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 './input-harness';
export * from './input-harness-filters';
export * from './native-select-harness';
export * from './native-select-harness-filters';
export * from './native-option-harness';
| {
"end_byte": 409,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/public-api.ts"
} |
components/src/material/input/testing/native-select-harness-filters.ts_0_676 | /**
* @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 `MatNativeSelectHarness` instances. */
export interface NativeSelectHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of `MatNativeOptionHarness` instances. */
export interface NativeOptionHarnessFilters extends BaseHarnessFilters {
text?: string | RegExp;
index?: number;
isSelected?: boolean;
}
| {
"end_byte": 676,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/native-select-harness-filters.ts"
} |
components/src/material/input/testing/BUILD.bazel_0_865 | 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/coercion",
"//src/cdk/testing",
"//src/material/form-field/testing/control",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/platform",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/input",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 865,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/BUILD.bazel"
} |
components/src/material/input/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/index.ts"
} |
components/src/material/input/testing/native-select-harness.spec.ts_0_7948 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {FormsModule} from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatNativeSelectHarness} from './native-select-harness';
describe('MatNativeSelectHarness', () => {
let fixture: ComponentFixture<SelectHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [NoopAnimationsModule, MatInputModule, FormsModule, SelectHarnessTest],
});
fixture = TestBed.createComponent(SelectHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all select harnesses', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(selects.length).toBe(2);
});
it('should get the id of a select', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(await parallel(() => selects.map(select => select.getId()))).toEqual(['food', 'drink']);
});
it('should get the name of a select', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(await parallel(() => selects.map(select => select.getName()))).toEqual([
'favorite-food',
'favorite-drink',
]);
});
it('should get whether a select is disabled', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(
await parallel(() => {
return selects.map(select => select.isDisabled());
}),
).toEqual([false, false]);
fixture.componentInstance.favoriteDrinkDisabled.set(true);
expect(await parallel(() => selects.map(select => select.isDisabled()))).toEqual([false, true]);
});
it('should get whether the select is in multi-selection mode', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(await parallel(() => selects.map(select => select.isMultiple()))).toEqual([false, true]);
});
it('should get whether a select is required', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
expect(
await parallel(() => {
return selects.map(select => select.isRequired());
}),
).toEqual([false, false]);
fixture.componentInstance.favoriteFoodRequired.set(true);
expect(await parallel(() => selects.map(select => select.isRequired()))).toEqual([true, false]);
});
it('should be able to focus a select', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
expect(await select.isFocused()).toBe(false);
await select.focus();
expect(await select.isFocused()).toBe(true);
});
it('should be able to blur a select', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
expect(await select.isFocused()).toBe(false);
await select.focus();
expect(await select.isFocused()).toBe(true);
await select.blur();
expect(await select.isFocused()).toBe(false);
});
it('should get the options of a select', async () => {
const selects = await loader.getAllHarnesses(MatNativeSelectHarness);
const options = await parallel(() => selects.map(select => select.getOptions()));
expect(options.length).toBe(2);
expect(options[0].length).toBe(3);
expect(options[1].length).toBe(4);
});
it('should select an option inside of a single-selection select', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
expect(fixture.componentInstance.favoriteFood).toBeFalsy();
await select.selectOptions({text: 'Ramen'});
expect(fixture.componentInstance.favoriteFood).toBe('ramen');
});
it('should select an option inside of a multi-selection select', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#drink'}));
expect(fixture.componentInstance.favoriteDrink).toEqual([]);
await select.selectOptions({text: /Water|Juice/});
expect(fixture.componentInstance.favoriteDrink).toEqual(['water', 'juice']);
});
it('should get the text of select options', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#drink'}));
const options = await select.getOptions();
expect(await parallel(() => options.map(option => option.getText()))).toEqual([
'Water',
'Soda',
'Coffee',
'Juice',
]);
});
it('should get the index of select options', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
const options = await select.getOptions();
expect(await parallel(() => options.map(option => option.getIndex()))).toEqual([0, 1, 2]);
});
it('should get the disabled state of select options', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
const options = await select.getOptions();
expect(await parallel(() => options.map(option => option.isDisabled()))).toEqual([
false,
false,
false,
]);
fixture.componentInstance.pastaDisabled.set(true);
expect(await parallel(() => options.map(option => option.isDisabled()))).toEqual([
false,
true,
false,
]);
});
it('should get the selected state of an option in a single-selection list', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#food'}));
const options = await select.getOptions();
expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([
false,
false,
false,
]);
await select.selectOptions({index: 2});
expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([
false,
false,
true,
]);
});
it('should get the selected state of an option in a multi-selection list', async () => {
const select = await loader.getHarness(MatNativeSelectHarness.with({selector: '#drink'}));
const options = await select.getOptions();
expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([
false,
false,
false,
false,
]);
await select.selectOptions({text: /Water|Coffee/});
expect(await parallel(() => options.map(option => option.isSelected()))).toEqual([
true,
false,
true,
false,
]);
});
});
@Component({
template: `
<mat-form-field>
<select
id="food"
matNativeControl
name="favorite-food"
[(ngModel)]="favoriteFood"
[required]="favoriteFoodRequired()">
<option value="pizza">Pizza</option>
<option value="pasta" [disabled]="pastaDisabled()">Pasta</option>
<option value="ramen">Ramen</option>
</select>
</mat-form-field>
<mat-form-field>
<select
id="drink"
matNativeControl
name="favorite-drink"
[(ngModel)]="favoriteDrink"
[disabled]="favoriteDrinkDisabled()"
multiple>
<option value="water">Water</option>
<option value="soda">Soda</option>
<option value="coffee">Coffee</option>
<option value="juice">Juice</option>
</select>
</mat-form-field>
`,
standalone: true,
imports: [MatInputModule, FormsModule],
})
class SelectHarnessTest {
favoriteFood: string;
favoriteDrink: string[] = [];
favoriteFoodRequired = signal(false);
favoriteDrinkDisabled = signal(false);
pastaDisabled = signal(false);
}
| {
"end_byte": 7948,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/native-select-harness.spec.ts"
} |
components/src/material/input/testing/input-harness-filters.ts_0_592 | /**
* @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 `MatInputHarness` instances. */
export interface InputHarnessFilters extends BaseHarnessFilters {
/** Filters based on the value of the input. */
value?: string | RegExp;
/** Filters based on the placeholder text of the input. */
placeholder?: string | RegExp;
}
| {
"end_byte": 592,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/testing/input-harness-filters.ts"
} |
components/src/material/progress-bar/module.ts_0_475 | /**
* @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 {MatProgressBar} from './progress-bar';
@NgModule({
imports: [MatProgressBar],
exports: [MatProgressBar, MatCommonModule],
})
export class MatProgressBarModule {}
| {
"end_byte": 475,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/module.ts"
} |
components/src/material/progress-bar/public-api.ts_0_262 | /**
* @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-bar';
export * from './module';
| {
"end_byte": 262,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/public-api.ts"
} |
components/src/material/progress-bar/README.md_0_103 | Please see the official documentation at https://material.angular.io/components/component/progress-bar
| {
"end_byte": 103,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/README.md"
} |
components/src/material/progress-bar/progress-bar.ts_0_7966 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
Component,
ViewEncapsulation,
ElementRef,
NgZone,
Input,
Output,
EventEmitter,
AfterViewInit,
OnDestroy,
ChangeDetectorRef,
InjectionToken,
inject,
numberAttribute,
ANIMATION_MODULE_TYPE,
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {ThemePalette} from '@angular/material/core';
/** Last animation end data. */
export interface ProgressAnimationEnd {
value: number;
}
/** Default `mat-progress-bar` options that can be overridden. */
export interface MatProgressBarDefaultOptions {
/**
* Default theme color of the progress bar. 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;
/** Default mode of the progress bar. */
mode?: ProgressBarMode;
}
/** Injection token to be used to override the default options for `mat-progress-bar`. */
export const MAT_PROGRESS_BAR_DEFAULT_OPTIONS = new InjectionToken<MatProgressBarDefaultOptions>(
'MAT_PROGRESS_BAR_DEFAULT_OPTIONS',
);
/**
* Injection token used to provide the current location to `MatProgressBar`.
* Used to handle server-side rendering and to stub out during unit tests.
* @docs-private
*/
export const MAT_PROGRESS_BAR_LOCATION = new InjectionToken<MatProgressBarLocation>(
'mat-progress-bar-location',
{providedIn: 'root', factory: MAT_PROGRESS_BAR_LOCATION_FACTORY},
);
/**
* Stubbed out location for `MatProgressBar`.
* @docs-private
*/
export interface MatProgressBarLocation {
getPathname: () => string;
}
/** @docs-private */
export function MAT_PROGRESS_BAR_LOCATION_FACTORY(): MatProgressBarLocation {
const _document = inject(DOCUMENT);
const _location = _document ? _document.location : null;
return {
// Note that this needs to be a function, rather than a property, because Angular
// will only resolve it once, but we want the current path on each call.
getPathname: () => (_location ? _location.pathname + _location.search : ''),
};
}
export type ProgressBarMode = 'determinate' | 'indeterminate' | 'buffer' | 'query';
@Component({
selector: 'mat-progress-bar',
exportAs: 'matProgressBar',
host: {
'role': 'progressbar',
'aria-valuemin': '0',
'aria-valuemax': '100',
// 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',
'[attr.aria-valuenow]': '_isIndeterminate() ? null : value',
'[attr.mode]': 'mode',
'class': 'mat-mdc-progress-bar mdc-linear-progress',
'[class]': '"mat-" + color',
'[class._mat-animation-noopable]': '_isNoopAnimation',
'[class.mdc-linear-progress--animation-ready]': '!_isNoopAnimation',
'[class.mdc-linear-progress--indeterminate]': '_isIndeterminate()',
},
templateUrl: 'progress-bar.html',
styleUrl: 'progress-bar.css',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatProgressBar implements AfterViewInit, OnDestroy {
readonly _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _ngZone = inject(NgZone);
private _changeDetectorRef = inject(ChangeDetectorRef);
_animationMode? = inject(ANIMATION_MODULE_TYPE, {optional: true});
constructor(...args: unknown[]);
constructor() {
const defaults = inject<MatProgressBarDefaultOptions>(MAT_PROGRESS_BAR_DEFAULT_OPTIONS, {
optional: true,
});
this._isNoopAnimation = this._animationMode === 'NoopAnimations';
if (defaults) {
if (defaults.color) {
this.color = this._defaultColor = defaults.color;
}
this.mode = defaults.mode || this.mode;
}
}
/** Flag that indicates whether NoopAnimations mode is set to true. */
_isNoopAnimation = false;
// TODO: should be typed as `ThemePalette` but internal apps pass in arbitrary strings.
/**
* Theme color of the progress bar. 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';
/** Value of the progress bar. Defaults to zero. Mirrored to aria-valuenow. */
@Input({transform: numberAttribute})
get value(): number {
return this._value;
}
set value(v: number) {
this._value = clamp(v || 0);
this._changeDetectorRef.markForCheck();
}
private _value = 0;
/** Buffer value of the progress bar. Defaults to zero. */
@Input({transform: numberAttribute})
get bufferValue(): number {
return this._bufferValue || 0;
}
set bufferValue(v: number) {
this._bufferValue = clamp(v || 0);
this._changeDetectorRef.markForCheck();
}
private _bufferValue = 0;
/**
* Event emitted when animation of the primary progress bar completes. This event will not
* be emitted when animations are disabled, nor will it be emitted for modes with continuous
* animations (indeterminate and query).
*/
@Output() readonly animationEnd = new EventEmitter<ProgressAnimationEnd>();
/**
* Mode of the progress bar.
*
* Input must be one of these values: determinate, indeterminate, buffer, query, defaults to
* 'determinate'.
* Mirrored to mode attribute.
*/
@Input()
get mode(): ProgressBarMode {
return this._mode;
}
set mode(value: ProgressBarMode) {
// Note that we don't technically need a getter and a setter here,
// but we use it to match the behavior of the existing mat-progress-bar.
this._mode = value;
this._changeDetectorRef.markForCheck();
}
private _mode: ProgressBarMode = 'determinate';
ngAfterViewInit() {
// Run outside angular so change detection didn't get triggered on every transition end
// instead only on the animation that we care about (primary value bar's transitionend)
this._ngZone.runOutsideAngular(() => {
this._elementRef.nativeElement.addEventListener('transitionend', this._transitionendHandler);
});
}
ngOnDestroy() {
this._elementRef.nativeElement.removeEventListener('transitionend', this._transitionendHandler);
}
/** Gets the transform style that should be applied to the primary bar. */
_getPrimaryBarTransform(): string {
return `scaleX(${this._isIndeterminate() ? 1 : this.value / 100})`;
}
/** Gets the `flex-basis` value that should be applied to the buffer bar. */
_getBufferBarFlexBasis(): string {
return `${this.mode === 'buffer' ? this.bufferValue : 100}%`;
}
/** Returns whether the progress bar is indeterminate. */
_isIndeterminate(): boolean {
return this.mode === 'indeterminate' || this.mode === 'query';
}
/** Event handler for `transitionend` events. */
private _transitionendHandler = (event: TransitionEvent) => {
if (
this.animationEnd.observers.length === 0 ||
!event.target ||
!(event.target as HTMLElement).classList.contains('mdc-linear-progress__primary-bar')
) {
return;
}
if (this.mode === 'determinate' || this.mode === 'buffer') {
this._ngZone.run(() => this.animationEnd.next({value: this.value}));
}
};
}
/** Clamps a value to be between two numbers, by default 0 and 100. */
function clamp(v: number, min = 0, max = 100) {
return Math.max(min, Math.min(max, v));
}
| {
"end_byte": 7966,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.ts"
} |
components/src/material/progress-bar/progress-bar.spec.ts_0_9818 | import {dispatchFakeEvent} from '@angular/cdk/testing/private';
import {
ApplicationRef,
Component,
DebugElement,
EnvironmentProviders,
Provider,
Type,
} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MAT_PROGRESS_BAR_DEFAULT_OPTIONS, MatProgressBarModule} from './index';
import {MatProgressBar} from './progress-bar';
describe('MatProgressBar', () => {
function createComponent<T>(
componentType: Type<T>,
providers: (Provider | EnvironmentProviders)[] = [],
): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [MatProgressBarModule, componentType],
providers,
});
return TestBed.createComponent<T>(componentType);
}
// 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.
it('should have elements wrapped in aria-hidden div', () => {
const fixture = createComponent(BasicProgressBar);
const host = fixture.nativeElement as Element;
const element = host.children[0];
const children = element.children;
expect(children.length).toBe(3);
const ariaHidden = Array.from(children).map(child => child.getAttribute('aria-hidden'));
expect(ariaHidden).toEqual(['true', 'true', 'true']);
});
describe('with animation', () => {
describe('basic progress-bar', () => {
it('should apply a mode of "determinate" if no mode is provided.', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
expect(progressElement.componentInstance.mode).toBe('determinate');
});
it('should define default values for value and bufferValue attributes', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
expect(progressElement.componentInstance.value).toBe(0);
expect(progressElement.componentInstance.bufferValue).toBe(0);
});
it('should clamp value and bufferValue between 0 and 100', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
progressComponent.value = 50;
expect(progressComponent.value).toBe(50);
progressComponent.value = 999;
expect(progressComponent.value).toBe(100);
progressComponent.value = -10;
expect(progressComponent.value).toBe(0);
progressComponent.bufferValue = -29;
expect(progressComponent.bufferValue).toBe(0);
progressComponent.bufferValue = 9;
expect(progressComponent.bufferValue).toBe(9);
progressComponent.bufferValue = 1320;
expect(progressComponent.bufferValue).toBe(100);
});
it('should set the proper transform based on the current value', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
const primaryStyles = progressElement.nativeElement.querySelector(
'.mdc-linear-progress__primary-bar',
).style;
const bufferStyles = progressElement.nativeElement.querySelector(
'.mdc-linear-progress__buffer-bar',
).style;
// Parse out and round the value since different
// browsers return the value with a different precision.
const getBufferValue = () => Math.floor(parseInt(bufferStyles.flexBasis));
expect(primaryStyles.transform).toBe('scaleX(0)');
expect(getBufferValue()).toBe(100);
progressComponent.value = 40;
fixture.detectChanges();
expect(primaryStyles.transform).toBe('scaleX(0.4)');
expect(getBufferValue()).toBe(100);
progressComponent.value = 35;
progressComponent.bufferValue = 55;
fixture.detectChanges();
expect(primaryStyles.transform).toBe('scaleX(0.35)');
expect(getBufferValue()).toBe(100);
progressComponent.mode = 'buffer';
fixture.detectChanges();
expect(primaryStyles.transform).toBe('scaleX(0.35)');
expect(getBufferValue()).toEqual(55);
progressComponent.value = 60;
progressComponent.bufferValue = 60;
fixture.detectChanges();
expect(primaryStyles.transform).toBe('scaleX(0.6)');
expect(getBufferValue()).toEqual(60);
});
it('should remove the `aria-valuenow` attribute in indeterminate mode', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
progressComponent.mode = 'determinate';
progressComponent.value = 50;
fixture.detectChanges();
expect(progressElement.nativeElement.getAttribute('aria-valuenow'))
.withContext('Expected aria-valuenow to be set in determinate mode.')
.toBe('50');
progressComponent.mode = 'indeterminate';
fixture.detectChanges();
expect(progressElement.nativeElement.hasAttribute('aria-valuenow'))
.withContext('Expect aria-valuenow to be cleared in indeterminate mode.')
.toBe(false);
});
it('should remove the `aria-valuenow` attribute in query mode', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
progressComponent.mode = 'determinate';
progressComponent.value = 50;
fixture.detectChanges();
expect(progressElement.nativeElement.getAttribute('aria-valuenow'))
.withContext('Expected aria-valuenow to be set in determinate mode.')
.toBe('50');
progressComponent.mode = 'query';
fixture.detectChanges();
expect(progressElement.nativeElement.hasAttribute('aria-valuenow'))
.withContext('Expect aria-valuenow to be cleared in query mode.')
.toBe(false);
});
it('should be able to configure the default progress bar options via DI', () => {
const fixture = createComponent(BasicProgressBar, [
{
provide: MAT_PROGRESS_BAR_DEFAULT_OPTIONS,
useValue: {
mode: 'buffer',
color: 'warn',
},
},
]);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
expect(progressElement.componentInstance.mode).toBe('buffer');
expect(progressElement.componentInstance.color).toBe('warn');
});
it('should update the DOM transform when the value has changed', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
const primaryBar = progressElement.nativeElement.querySelector(
'.mdc-linear-progress__primary-bar',
);
expect(primaryBar.style.transform).toBe('scaleX(0)');
progressComponent.value = 40;
fixture.detectChanges();
expect(primaryBar.style.transform).toBe('scaleX(0.4)');
});
it('should update the DOM transform when the bufferValue has changed', () => {
const fixture = createComponent(BasicProgressBar);
fixture.detectChanges();
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
const progressComponent = progressElement.componentInstance;
const bufferBar = progressElement.nativeElement.querySelector(
'.mdc-linear-progress__buffer-bar',
);
progressComponent.mode = 'buffer';
fixture.detectChanges();
expect(bufferBar.style.flexBasis).toBe('0%');
progressComponent.bufferValue = 40;
fixture.detectChanges();
expect(bufferBar.style.flexBasis).toBe('40%');
});
});
describe('animation trigger on determinate setting', () => {
let fixture: ComponentFixture<BasicProgressBar>;
let progressComponent: MatProgressBar;
let primaryValueBar: DebugElement;
beforeEach(() => {
fixture = createComponent(BasicProgressBar);
const progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
progressComponent = progressElement.componentInstance;
primaryValueBar = progressElement.query(By.css('.mdc-linear-progress__primary-bar'))!;
});
it('should trigger output event on primary value bar animation end', () => {
fixture.detectChanges();
const animationEndSpy = jasmine.createSpy();
progressComponent.animationEnd.subscribe(animationEndSpy);
progressComponent.value = 40;
expect(animationEndSpy).not.toHaveBeenCalled();
// On animation end, output should be emitted.
dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend', true);
expect(animationEndSpy).toHaveBeenCalledWith({value: 40});
});
}); | {
"end_byte": 9818,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.spec.ts"
} |
components/src/material/progress-bar/progress-bar.spec.ts_9824_13161 | describe('animation trigger on buffer setting', () => {
let fixture: ComponentFixture<BufferProgressBar>;
let progressElement: DebugElement;
let progressComponent: MatProgressBar;
let primaryValueBar: DebugElement;
beforeEach(() => {
fixture = createComponent(BufferProgressBar);
progressElement = fixture.debugElement.query(By.css('mat-progress-bar'))!;
progressComponent = progressElement.componentInstance;
primaryValueBar = progressElement.query(By.css('.mdc-linear-progress__primary-bar'))!;
});
it('should bind on transitionend eventListener on primaryBarValue', () => {
spyOn(progressElement.nativeElement, 'addEventListener');
fixture.detectChanges();
expect(progressElement.nativeElement.addEventListener).toHaveBeenCalled();
expect(progressElement.nativeElement.addEventListener.calls.mostRecent().args[0]).toBe(
'transitionend',
);
});
it('should trigger output event on primary value bar animation end', () => {
fixture.detectChanges();
const animationEndSpy = jasmine.createSpy();
progressComponent.animationEnd.subscribe(animationEndSpy);
progressComponent.value = 40;
expect(animationEndSpy).not.toHaveBeenCalled();
// On animation end, output should be emitted.
dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend', true);
expect(animationEndSpy).toHaveBeenCalledWith({value: 40});
});
it('should trigger output event with value not bufferValue', () => {
fixture.detectChanges();
const animationEndSpy = jasmine.createSpy();
progressComponent.animationEnd.subscribe(animationEndSpy);
progressComponent.value = 40;
progressComponent.bufferValue = 70;
expect(animationEndSpy).not.toHaveBeenCalled();
// On animation end, output should be emitted.
dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend', true);
expect(animationEndSpy).toHaveBeenCalledWith({value: 40});
});
it('should not run change detection if there are no `animationEnd` observers', () => {
fixture.detectChanges();
const animationEndSpy = jasmine.createSpy();
const appRef = TestBed.inject(ApplicationRef);
spyOn(appRef, 'tick');
progressComponent.value = 30;
progressComponent.bufferValue = 60;
// On animation end, output should be emitted.
dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend', true);
expect(appRef.tick).not.toHaveBeenCalled();
progressComponent.animationEnd.subscribe(animationEndSpy);
progressComponent.value = 40;
progressComponent.bufferValue = 70;
// On animation end, output should be emitted.
dispatchFakeEvent(primaryValueBar.nativeElement, 'transitionend', true);
expect(animationEndSpy).toHaveBeenCalledWith({value: 40});
});
});
});
});
@Component({
template: '<mat-progress-bar></mat-progress-bar>',
standalone: true,
imports: [MatProgressBar],
})
class BasicProgressBar {}
@Component({
template: '<mat-progress-bar mode="buffer"></mat-progress-bar>',
standalone: true,
imports: [MatProgressBar],
})
class BufferProgressBar {} | {
"end_byte": 13161,
"start_byte": 9824,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.spec.ts"
} |
components/src/material/progress-bar/progress-bar.html_0_893 | <!--
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-linear-progress__buffer" aria-hidden="true">
<div
class="mdc-linear-progress__buffer-bar"
[style.flex-basis]="_getBufferBarFlexBasis()"></div>
<!-- Remove the dots outside of buffer mode since they can cause CSP issues (see #28938) -->
@if (mode === 'buffer') {
<div class="mdc-linear-progress__buffer-dots"></div>
}
</div>
<div
class="mdc-linear-progress__bar mdc-linear-progress__primary-bar"
aria-hidden="true"
[style.transform]="_getPrimaryBarTransform()">
<span class="mdc-linear-progress__bar-inner"></span>
</div>
<div class="mdc-linear-progress__bar mdc-linear-progress__secondary-bar" aria-hidden="true">
<span class="mdc-linear-progress__bar-inner"></span>
</div>
| {
"end_byte": 893,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.html"
} |
components/src/material/progress-bar/progress-bar.scss_0_1750 | @use '@angular/cdk';
@use '../core/tokens/m2/mdc/linear-progress' as tokens-mdc-linear-progress;
@use '../core/tokens/token-utils';
@use '../core/style/vendor-prefixes';
.mat-mdc-progress-bar {
// Explicitly set to `block` since the browser defaults custom elements to `inline`.
display: block;
// Explicitly set a `text-align` so that the content isn't affected by the parent (see #27613).
text-align: start;
// Inverts the progress bar horizontally in `query` mode.
&[mode='query'] {
transform: scaleX(-1);
}
&._mat-animation-noopable {
.mdc-linear-progress__buffer-dots,
.mdc-linear-progress__primary-bar,
.mdc-linear-progress__secondary-bar,
.mdc-linear-progress__bar-inner.mdc-linear-progress__bar-inner {
// Disable the loading animations.
animation: none;
}
.mdc-linear-progress__primary-bar,
.mdc-linear-progress__buffer-bar {
// There's a `transitionend` event that depends on this element. Add a very short
// transition when animations are disabled so that the event can still fire.
transition: transform 1ms;
}
}
}
.mdc-linear-progress {
position: relative;
width: 100%;
transform: translateZ(0);
outline: 1px solid transparent;
overflow-x: hidden;
transition: opacity 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1);
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
$track-variable: token-utils.get-token-variable(track-height);
$indicator-height-variable: token-utils.get-token-variable(active-indicator-height);
height: max(#{$track-variable}, #{$indicator-height-variable});
}
@include cdk.high-contrast {
outline-color: CanvasText;
}
} | {
"end_byte": 1750,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.scss"
} |
components/src/material/progress-bar/progress-bar.scss_1752_8265 | .mdc-linear-progress__bar {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
width: 100%;
animation: none;
transform-origin: top left;
transition: transform 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1);
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
@include token-utils.create-token-slot(height, active-indicator-height);
}
.mdc-linear-progress--indeterminate & {
transition: none;
}
[dir='rtl'] & {
right: 0;
transform-origin: center right;
}
}
.mdc-linear-progress__bar-inner {
display: inline-block;
position: absolute;
width: 100%;
animation: none;
border-top-style: solid;
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
@include token-utils.create-token-slot(border-color, active-indicator-color);
@include token-utils.create-token-slot(border-top-width, active-indicator-height);
}
}
.mdc-linear-progress__buffer {
display: flex;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
width: 100%;
overflow: hidden;
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
@include token-utils.create-token-slot(height, track-height);
@include token-utils.create-token-slot(border-radius, track-shape);
}
}
.mdc-linear-progress__buffer-dots {
$mask: "data:image/svg+xml,%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' " +
"xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' " +
"enable-background='new 0 0 5 2' xml:space='preserve' viewBox='0 0 5 2' " +
"preserveAspectRatio='xMinYMin slice'%3E%3Ccircle cx='1' cy='1' r='1'/%3E%3C/svg%3E";
@include vendor-prefixes.mask-image(url($mask));
background-repeat: repeat-x;
flex: auto;
transform: rotate(180deg);
animation: mdc-linear-progress-buffering 250ms infinite linear;
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, track-color);
}
@include cdk.high-contrast {
background-color: ButtonBorder;
}
[dir='rtl'] & {
animation: mdc-linear-progress-buffering-reverse 250ms infinite linear;
transform: rotate(0);
}
}
.mdc-linear-progress__buffer-bar {
flex: 0 1 100%;
transition: flex-basis 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1);
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
@include token-utils.create-token-slot(background-color, track-color);
}
}
.mdc-linear-progress__primary-bar {
transform: scaleX(0);
.mdc-linear-progress--indeterminate & {
left: -145.166611%;
}
.mdc-linear-progress--indeterminate.mdc-linear-progress--animation-ready & {
animation: mdc-linear-progress-primary-indeterminate-translate 2s infinite linear;
}
.mdc-linear-progress--indeterminate.mdc-linear-progress--animation-ready & {
> .mdc-linear-progress__bar-inner {
animation: mdc-linear-progress-primary-indeterminate-scale 2s infinite linear;
}
}
[dir='rtl'] .mdc-linear-progress.mdc-linear-progress--animation-ready & {
animation-name: mdc-linear-progress-primary-indeterminate-translate-reverse;
}
[dir='rtl'] .mdc-linear-progress.mdc-linear-progress--indeterminate & {
right: -145.166611%;
left: auto;
}
}
.mdc-linear-progress__secondary-bar {
display: none;
.mdc-linear-progress--indeterminate & {
left: -54.888891%;
display: block;
}
.mdc-linear-progress--indeterminate.mdc-linear-progress--animation-ready & {
animation: mdc-linear-progress-secondary-indeterminate-translate 2s infinite linear;
}
.mdc-linear-progress--indeterminate.mdc-linear-progress--animation-ready & {
> .mdc-linear-progress__bar-inner {
animation: mdc-linear-progress-secondary-indeterminate-scale 2s infinite linear;
}
}
[dir='rtl'] .mdc-linear-progress.mdc-linear-progress--animation-ready & {
animation-name: mdc-linear-progress-secondary-indeterminate-translate-reverse;
}
[dir='rtl'] .mdc-linear-progress.mdc-linear-progress--indeterminate & {
right: -54.888891%;
left: auto;
}
}
@keyframes mdc-linear-progress-buffering {
from {
@include token-utils.use-tokens(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-token-slots()
) {
$track-variable: token-utils.get-token-variable(track-height);
transform: rotate(180deg) translateX(calc(#{$track-variable} * -2.5));
}
}
}
@keyframes mdc-linear-progress-primary-indeterminate-translate {
0% {
transform: translateX(0);
}
20% {
animation-timing-function: cubic-bezier(0.5, 0, 0.701732, 0.495819);
transform: translateX(0);
}
59.15% {
animation-timing-function: cubic-bezier(0.302435, 0.381352, 0.55, 0.956352);
transform: translateX(83.67142%);
}
100% {
transform: translateX(200.611057%);
}
}
@keyframes mdc-linear-progress-primary-indeterminate-scale {
0% {
transform: scaleX(0.08);
}
36.65% {
animation-timing-function: cubic-bezier(0.334731, 0.12482, 0.785844, 1);
transform: scaleX(0.08);
}
69.15% {
animation-timing-function: cubic-bezier(0.06, 0.11, 0.6, 1);
transform: scaleX(0.661479);
}
100% {
transform: scaleX(0.08);
}
}
@keyframes mdc-linear-progress-secondary-indeterminate-translate {
0% {
animation-timing-function: cubic-bezier(0.15, 0, 0.515058, 0.409685);
transform: translateX(0);
}
25% {
animation-timing-function: cubic-bezier(0.31033, 0.284058, 0.8, 0.733712);
transform: translateX(37.651913%);
}
48.35% {
animation-timing-function: cubic-bezier(0.4, 0.627035, 0.6, 0.902026);
transform: translateX(84.386165%);
}
100% {
transform: translateX(160.277782%);
}
}
@keyframes mdc-linear-progress-secondary-indeterminate-scale {
0% {
animation-timing-function: cubic-bezier(0.205028, 0.057051, 0.57661, 0.453971);
transform: scaleX(0.08);
}
19.15% {
animation-timing-function: cubic-bezier(0.152313, 0.196432, 0.648374, 1.004315);
transform: scaleX(0.457104);
}
44.15% {
animation-timing-function: cubic-bezier(0.257759, -0.003163, 0.211762, 1.38179);
transform: scaleX(0.72796);
}
100% {
transform: scaleX(0.08);
}
} | {
"end_byte": 8265,
"start_byte": 1752,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.scss"
} |
components/src/material/progress-bar/progress-bar.scss_8267_9295 | @keyframes mdc-linear-progress-primary-indeterminate-translate-reverse {
0% {
transform: translateX(0);
}
20% {
animation-timing-function: cubic-bezier(0.5, 0, 0.701732, 0.495819);
transform: translateX(0);
}
59.15% {
animation-timing-function: cubic-bezier(0.302435, 0.381352, 0.55, 0.956352);
transform: translateX(-83.67142%);
}
100% {
transform: translateX(-200.611057%);
}
}
@keyframes mdc-linear-progress-secondary-indeterminate-translate-reverse {
0% {
animation-timing-function: cubic-bezier(0.15, 0, 0.515058, 0.409685);
transform: translateX(0);
}
25% {
animation-timing-function: cubic-bezier(0.31033, 0.284058, 0.8, 0.733712);
transform: translateX(-37.651913%);
}
48.35% {
animation-timing-function: cubic-bezier(0.4, 0.627035, 0.6, 0.902026);
transform: translateX(-84.386165%);
}
100% {
transform: translateX(-160.277782%);
}
}
@keyframes mdc-linear-progress-buffering-reverse {
from {
transform: translateX(-10px);
}
} | {
"end_byte": 9295,
"start_byte": 8267,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.scss"
} |
components/src/material/progress-bar/BUILD.bazel_0_1383 | 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-bar",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
assets = [":progress_bar_scss"] + glob(["**/*.html"]),
deps = [
"//src/material/core",
"@npm//@angular/core",
],
)
sass_library(
name = "progress_bar_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "progress_bar_scss",
src = "progress-bar.scss",
deps = [
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "progress_bar_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":progress-bar",
"//src/cdk/testing/private",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":progress_bar_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":progress-bar.md"],
)
extract_tokens(
name = "tokens",
srcs = [":progress_bar_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1383,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/BUILD.bazel"
} |
components/src/material/progress-bar/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/index.ts"
} |
components/src/material/progress-bar/_progress-bar-theme.scss_0_4122 | @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/linear-progress' as tokens-mdc-linear-progress;
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-progress-bar.
/// @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 {
// 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-linear-progress.$prefix,
tokens-mdc-linear-progress.get-unthemable-tokens()
);
}
}
}
@mixin _palette-styles($theme, $palette-name) {
@include token-utils.create-token-values(
tokens-mdc-linear-progress.$prefix,
tokens-mdc-linear-progress.get-color-tokens($theme, $palette-name)
);
}
/// Outputs color theme styles for the mat-progress-bar.
/// @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 progress bar: 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 {
.mat-mdc-progress-bar {
@include _palette-styles($theme, primary);
&.mat-accent {
@include _palette-styles($theme, accent);
}
&.mat-warn {
@include _palette-styles($theme, warn);
}
}
}
}
/// Outputs typography theme styles for the mat-progress-bar.
/// @param {Map} $theme The theme to generate typography styles for.
@mixin typography($theme) {
}
/// Outputs density theme styles for the mat-progress-bar.
/// @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-linear-progress.$prefix,
tokens: tokens-mdc-linear-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-bar.
/// @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 progress bar: 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-bar') {
@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'
);
$tokens: token-utils.get-tokens-for($tokens, tokens-mdc-linear-progress.$prefix, $options...);
@include token-utils.create-token-values(tokens-mdc-linear-progress.$prefix, $tokens);
}
| {
"end_byte": 4122,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/_progress-bar-theme.scss"
} |
components/src/material/progress-bar/progress-bar.md_0_1764 | `<mat-progress-bar>` is a horizontal progress-bar for indicating progress and activity.
### Progress mode
The progress-bar supports four modes: determinate, indeterminate, buffer and query.
#### Determinate
Operations where the percentage of the operation complete is known should use the
determinate indicator.
<!-- example(progress-bar-determinate) -->
This is the default mode and the progress is represented by the `value` property.
#### Indeterminate
Operations where the user is asked to wait while something finishes and it’s
not necessary to indicate how long it will take should use the indeterminate indicator.
<!-- example(progress-bar-indeterminate) -->
In this mode the `value` property is ignored.
#### Buffer
Use the `buffer` mode of the progress-bar to indicate some activity or loading from the server.
<!-- example(progress-bar-buffer) -->
In "buffer" mode, `value` determines the progress of the primary bar while the `bufferValue` is
used to show the additional buffering progress.
#### Query
Use the `query` mode of the progress-bar to indicate pre-loading before the actual loading starts.
<!-- example(progress-bar-query) -->
In "query" mode, the progress-bar renders as an inverted "indeterminate" bar. Once the response
progress is available, the `mode` should be changed to determinate to convey the progress. In
this mode the `value` property is ignored.
### Accessibility
`MatProgressBar` implements the ARIA `role="progressbar"` pattern. By default, the progress bar
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 progress bar.
| {
"end_byte": 1764,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/progress-bar.md"
} |
components/src/material/progress-bar/testing/public-api.ts_0_292 | /**
* @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-bar-harness';
export * from './progress-bar-harness-filters';
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/public-api.ts"
} |
components/src/material/progress-bar/testing/progress-bar-harness-filters.ts_0_432 | /**
* @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 `MatProgressBarHarness` instances. */
export interface ProgressBarHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 432,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/progress-bar-harness-filters.ts"
} |
components/src/material/progress-bar/testing/progress-bar-harness.ts_0_1551 | /**
* @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 {ProgressBarHarnessFilters} from './progress-bar-harness-filters';
/** Harness for interacting with a `mat-progress-bar` in tests. */
export class MatProgressBarHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-progress-bar';
/**
* Gets a `HarnessPredicate` that can be used to search for a progress bar with specific
* attributes.
* @param options Options for filtering which progress bar instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatProgressBarHarness>(
this: ComponentHarnessConstructor<T>,
options: ProgressBarHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Gets a promise for the progress bar'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 a promise for the progress bar's mode. */
async getMode(): Promise<string | null> {
return (await this.host()).getAttribute('mode');
}
}
| {
"end_byte": 1551,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/progress-bar-harness.ts"
} |
components/src/material/progress-bar/testing/BUILD.bazel_0_770 | 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",
],
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/progress-bar",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 770,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/BUILD.bazel"
} |
components/src/material/progress-bar/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/index.ts"
} |
components/src/material/progress-bar/testing/progress-bar-harness.spec.ts_0_1922 | 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 {MatProgressBarModule} from '@angular/material/progress-bar';
import {MatProgressBarHarness} from './progress-bar-harness';
describe('MatProgressBarHarness', () => {
let fixture: ComponentFixture<ProgressBarHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatProgressBarModule, ProgressBarHarnessTest],
});
fixture = TestBed.createComponent(ProgressBarHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all progress bar harnesses', async () => {
const progressBars = await loader.getAllHarnesses(MatProgressBarHarness);
expect(progressBars.length).toBe(2);
});
it('should get the value', async () => {
fixture.componentInstance.value.set(50);
const [determinate, indeterminate] = await loader.getAllHarnesses(MatProgressBarHarness);
expect(await determinate.getValue()).toBe(50);
expect(await indeterminate.getValue()).toBe(null);
});
it('should get the mode', async () => {
const [determinate, indeterminate] = await loader.getAllHarnesses(MatProgressBarHarness);
expect(await determinate.getMode()).toBe('determinate');
expect(await indeterminate.getMode()).toBe('indeterminate');
});
});
// TODO: Add and test progress bars with modes `buffer` and `query`.
@Component({
template: `
<mat-progress-bar mode="determinate" [value]="value()"></mat-progress-bar>
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
`,
standalone: true,
imports: [MatProgressBarModule],
})
class ProgressBarHarnessTest {
value = signal<number | undefined>(undefined);
}
| {
"end_byte": 1922,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/progress-bar/testing/progress-bar-harness.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle.ts_0_2559 | /**
* @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 {
AfterContentInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
numberAttribute,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
ViewChild,
ViewEncapsulation,
ANIMATION_MODULE_TYPE,
inject,
HostAttributeToken,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
} from '@angular/forms';
import {FocusMonitor} from '@angular/cdk/a11y';
import {
MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS,
MatSlideToggleDefaultOptions,
} from './slide-toggle-config';
import {_MatInternalFormField, _StructuralStylesLoader, MatRipple} from '@angular/material/core';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
/**
* @deprecated Will stop being exported.
* @breaking-change 19.0.0
*/
export const MAT_SLIDE_TOGGLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatSlideToggle),
multi: true,
};
/** Change event object emitted by a slide toggle. */
export class MatSlideToggleChange {
constructor(
/** The source slide toggle of the event. */
public source: MatSlideToggle,
/** The new `checked` value of the slide toggle. */
public checked: boolean,
) {}
}
// Increasing integer for generating unique ids for slide-toggle components.
let nextUniqueId = 0;
@Component({
selector: 'mat-slide-toggle',
templateUrl: 'slide-toggle.html',
styleUrl: 'slide-toggle.css',
host: {
'class': 'mat-mdc-slide-toggle',
'[id]': 'id',
// Needs to be removed since it causes some a11y issues (see #21266).
'[attr.tabindex]': 'null',
'[attr.aria-label]': 'null',
'[attr.name]': 'null',
'[attr.aria-labelledby]': 'null',
'[class.mat-mdc-slide-toggle-focused]': '_focused',
'[class.mat-mdc-slide-toggle-checked]': 'checked',
'[class._mat-animation-noopable]': '_noopAnimations',
'[class]': 'color ? "mat-" + color : ""',
},
exportAs: 'matSlideToggle',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
MAT_SLIDE_TOGGLE_VALUE_ACCESSOR,
{
provide: NG_VALIDATORS,
useExisting: MatSlideToggle,
multi: true,
},
],
imports: [MatRipple, _MatInternalFormField],
})
export | {
"end_byte": 2559,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.ts"
} |
components/src/material/slide-toggle/slide-toggle.ts_2560_10543 | class MatSlideToggle
implements OnDestroy, AfterContentInit, OnChanges, ControlValueAccessor, Validator
{
private _elementRef = inject(ElementRef);
protected _focusMonitor = inject(FocusMonitor);
protected _changeDetectorRef = inject(ChangeDetectorRef);
defaults = inject<MatSlideToggleDefaultOptions>(MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS);
private _onChange = (_: any) => {};
private _onTouched = () => {};
private _validatorOnChange = () => {};
private _uniqueId: string;
private _checked: boolean = false;
private _createChangeEvent(isChecked: boolean) {
return new MatSlideToggleChange(this, isChecked);
}
/** Unique ID for the label element. */
_labelId: string;
/** Returns the unique id for the visual hidden button. */
get buttonId(): string {
return `${this.id || this._uniqueId}-button`;
}
/** Reference to the MDC switch element. */
@ViewChild('switch') _switchElement: ElementRef<HTMLElement>;
/** Focuses the slide-toggle. */
focus(): void {
this._switchElement.nativeElement.focus();
}
/** Whether noop animations are enabled. */
_noopAnimations: boolean;
/** Whether the slide toggle is currently focused. */
_focused: boolean;
/** Name value will be applied to the input element if present. */
@Input() name: string | null = null;
/** A unique id for the slide-toggle input. If none is supplied, it will be auto-generated. */
@Input() id: string;
/** Whether the label should appear after or before the slide-toggle. Defaults to 'after'. */
@Input() labelPosition: 'before' | 'after' = 'after';
/** Used to set the aria-label attribute on the underlying input element. */
@Input('aria-label') ariaLabel: string | null = null;
/** Used to set the aria-labelledby attribute on the underlying input element. */
@Input('aria-labelledby') ariaLabelledby: string | null = null;
/** Used to set the aria-describedby attribute on the underlying input element. */
@Input('aria-describedby') ariaDescribedby: string;
/** Whether the slide-toggle is required. */
@Input({transform: booleanAttribute}) required: boolean;
// TODO(crisbeto): this should be a ThemePalette, but some internal apps were abusing
// the lack of type checking previously and assigning random strings.
/**
* Theme color of the slide toggle. 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: string | undefined;
/** Whether the slide toggle is disabled. */
@Input({transform: booleanAttribute}) disabled: boolean = false;
/** Whether the slide toggle has a ripple. */
@Input({transform: booleanAttribute}) disableRipple: boolean = false;
/** Tabindex of slide toggle. */
@Input({transform: (value: unknown) => (value == null ? 0 : numberAttribute(value))})
tabIndex: number = 0;
/** Whether the slide-toggle element is checked or not. */
@Input({transform: booleanAttribute})
get checked(): boolean {
return this._checked;
}
set checked(value: boolean) {
this._checked = value;
this._changeDetectorRef.markForCheck();
}
/** Whether to hide the icon inside of the slide toggle. */
@Input({transform: booleanAttribute}) hideIcon: boolean;
/** Whether the slide toggle should remain interactive when it is disabled. */
@Input({transform: booleanAttribute}) disabledInteractive: boolean;
/** An event will be dispatched each time the slide-toggle changes its value. */
@Output() readonly change = new EventEmitter<MatSlideToggleChange>();
/**
* An event will be dispatched each time the slide-toggle input is toggled.
* This event is always emitted when the user toggles the slide toggle, but this does not mean
* the slide toggle's value has changed.
*/
@Output() readonly toggleChange: EventEmitter<void> = new EventEmitter<void>();
/** Returns the unique id for the visual hidden input. */
get inputId(): string {
return `${this.id || this._uniqueId}-input`;
}
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
const defaults = this.defaults;
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0;
this.color = defaults.color || 'accent';
this._noopAnimations = animationMode === 'NoopAnimations';
this.id = this._uniqueId = `mat-mdc-slide-toggle-${++nextUniqueId}`;
this.hideIcon = defaults.hideIcon ?? false;
this.disabledInteractive = defaults.disabledInteractive ?? false;
this._labelId = this._uniqueId + '-label';
}
ngAfterContentInit() {
this._focusMonitor.monitor(this._elementRef, true).subscribe(focusOrigin => {
if (focusOrigin === 'keyboard' || focusOrigin === 'program') {
this._focused = true;
this._changeDetectorRef.markForCheck();
} else if (!focusOrigin) {
// When a focused element becomes disabled, the browser *immediately* fires a blur event.
// Angular does not expect events to be raised during change detection, so any state
// change (such as a form control's ng-touched) will cause a changed-after-checked error.
// See https://github.com/angular/angular/issues/17793. To work around this, we defer
// telling the form control it has been touched until the next tick.
Promise.resolve().then(() => {
this._focused = false;
this._onTouched();
this._changeDetectorRef.markForCheck();
});
}
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['required']) {
this._validatorOnChange();
}
}
ngOnDestroy() {
this._focusMonitor.stopMonitoring(this._elementRef);
}
/** Implemented as part of ControlValueAccessor. */
writeValue(value: any): void {
this.checked = !!value;
}
/** Implemented as part of ControlValueAccessor. */
registerOnChange(fn: any): void {
this._onChange = fn;
}
/** Implemented as part of ControlValueAccessor. */
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
/** Implemented as a part of Validator. */
validate(control: AbstractControl<boolean>): ValidationErrors | null {
return this.required && control.value !== true ? {'required': true} : null;
}
/** Implemented as a part of Validator. */
registerOnValidatorChange(fn: () => void): void {
this._validatorOnChange = fn;
}
/** Implemented as a part of ControlValueAccessor. */
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this._changeDetectorRef.markForCheck();
}
/** Toggles the checked state of the slide-toggle. */
toggle(): void {
this.checked = !this.checked;
this._onChange(this.checked);
}
/**
* Emits a change event on the `change` output. Also notifies the FormControl about the change.
*/
protected _emitChangeEvent() {
this._onChange(this.checked);
this.change.emit(this._createChangeEvent(this.checked));
}
/** Method being called whenever the underlying button is clicked. */
_handleClick() {
if (!this.disabled) {
this.toggleChange.emit();
if (!this.defaults.disableToggleValue) {
this.checked = !this.checked;
this._onChange(this.checked);
this.change.emit(new MatSlideToggleChange(this, this.checked));
}
}
}
_getAriaLabelledBy() {
if (this.ariaLabelledby) {
return this.ariaLabelledby;
}
// Even though we have a `label` element with a `for` pointing to the button, we need the
// `aria-labelledby`, because the button gets flagged as not having a label by tools like axe.
return this.ariaLabel ? null : this._labelId;
}
} | {
"end_byte": 10543,
"start_byte": 2560,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.ts"
} |
components/src/material/slide-toggle/slide-toggle.spec.ts_0_1076 | import {FocusMonitor} from '@angular/cdk/a11y';
import {BidiModule, Direction} from '@angular/cdk/bidi';
import {dispatchFakeEvent} from '@angular/cdk/testing/private';
import {Component} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
flushMicrotasks,
inject,
tick,
} from '@angular/core/testing';
import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {MatSlideToggle, MatSlideToggleChange, MatSlideToggleModule} from './index';
import {MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS} from './slide-toggle-config';
describe('MatSlideToggle without forms', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MatSlideToggleModule,
BidiModule,
SlideToggleBasic,
SlideToggleCheckedAndDisabledAttr,
SlideToggleWithTabindexAttr,
SlideToggleWithoutLabel,
SlideToggleProjectedLabel,
TextBindingComponent,
SlideToggleWithStaticAriaAttributes,
],
});
}); | {
"end_byte": 1076,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle.spec.ts_1080_10896 | describe('basic behavior', () => {
let fixture: ComponentFixture<any>;
let testComponent: SlideToggleBasic;
let slideToggle: MatSlideToggle;
let slideToggleElement: HTMLElement;
let labelElement: HTMLLabelElement;
let buttonElement: HTMLButtonElement;
beforeEach(() => {
fixture = TestBed.createComponent(SlideToggleBasic);
// Enable jasmine spies on event functions, which may trigger at initialization
// of the slide-toggle component.
spyOn(fixture.debugElement.componentInstance, 'onSlideChange').and.callThrough();
spyOn(fixture.debugElement.componentInstance, 'onSlideClick').and.callThrough();
// Initialize the slide-toggle component, by triggering the first change detection cycle.
fixture.detectChanges();
const slideToggleDebug = fixture.debugElement.query(By.css('mat-slide-toggle'))!;
testComponent = fixture.debugElement.componentInstance;
slideToggle = slideToggleDebug.componentInstance;
slideToggleElement = slideToggleDebug.nativeElement;
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement;
});
it('should apply class based on color attribute', () => {
testComponent.slideColor = 'primary';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.classList).toContain('mat-primary');
testComponent.slideColor = 'accent';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.classList).toContain('mat-accent');
});
it('should correctly update the disabled property', () => {
expect(buttonElement.disabled).toBeFalsy();
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.disabled).toBeTruthy();
});
it('should correctly update the checked property', () => {
expect(slideToggle.checked).toBeFalsy();
expect(buttonElement.getAttribute('aria-checked')).toBe('false');
testComponent.slideChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-checked')).toBe('true');
});
it('should set the toggle to checked on click', fakeAsync(() => {
expect(slideToggle.checked).toBe(false);
expect(buttonElement.getAttribute('aria-checked')).toBe('false');
expect(slideToggleElement.classList).not.toContain('mat-mdc-slide-toggle-checked');
labelElement.click();
fixture.detectChanges();
flush();
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
expect(slideToggle.checked).toBe(true);
expect(buttonElement.getAttribute('aria-checked')).toBe('true');
}));
it('should not trigger the click event multiple times', fakeAsync(() => {
// By default, when clicking on a label element, a generated click will be dispatched
// on the associated button element.
// Since we're using a label element and a visual hidden button, this behavior can led
// to an issue, where the click events on the slide-toggle are getting executed twice.
expect(slideToggle.checked).toBe(false);
expect(slideToggleElement.classList).not.toContain('mat-mdc-slide-toggle-checked');
labelElement.click();
fixture.detectChanges();
tick();
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
expect(slideToggle.checked).toBe(true);
expect(testComponent.onSlideClick).toHaveBeenCalledTimes(1);
}));
it('should trigger the change event properly', fakeAsync(() => {
expect(slideToggleElement.classList).not.toContain('mat-mdc-slide-toggle-checked');
labelElement.click();
fixture.detectChanges();
flush();
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
expect(testComponent.onSlideChange).toHaveBeenCalledTimes(1);
}));
it('should not trigger the change event by changing the native value', fakeAsync(() => {
expect(slideToggleElement.classList).not.toContain('mat-mdc-slide-toggle-checked');
testComponent.slideChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
tick();
expect(testComponent.onSlideChange).not.toHaveBeenCalled();
}));
it('should add a suffix to the element id', () => {
testComponent.slideId = 'myId';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.id).toBe('myId');
expect(buttonElement.id).toBe(`${slideToggleElement.id}-button`);
testComponent.slideId = 'nextId';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.id).toBe('nextId');
expect(buttonElement.id).toBe(`${slideToggleElement.id}-button`);
testComponent.slideId = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Once the id binding is set to null, the id property should auto-generate a unique id.
expect(buttonElement.id).toMatch(/mat-mdc-slide-toggle-\d+-button/);
});
it('should forward the tabIndex to the underlying element', () => {
fixture.detectChanges();
expect(buttonElement.tabIndex).toBe(0);
testComponent.slideTabindex = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.tabIndex).toBe(4);
});
it('should forward the specified name to the element', () => {
testComponent.slideName = 'myName';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.name).toBe('myName');
testComponent.slideName = 'nextName';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.name).toBe('nextName');
testComponent.slideName = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.name).toBe('');
});
it('should forward the aria-label attribute to the element', () => {
testComponent.slideLabel = 'ariaLabel';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-label')).toBe('ariaLabel');
testComponent.slideLabel = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.hasAttribute('aria-label')).toBeFalsy();
});
it('should forward the aria-labelledby attribute to the element', () => {
testComponent.slideLabelledBy = 'ariaLabelledBy';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-labelledby')).toBe('ariaLabelledBy');
testComponent.slideLabelledBy = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// We fall back to pointing to the label if a value isn't provided.
expect(buttonElement.getAttribute('aria-labelledby')).toMatch(
/mat-mdc-slide-toggle-\d+-label/,
);
});
it('should forward the aria-describedby attribute to the element', () => {
testComponent.slideAriaDescribedBy = 'some-element';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-describedby')).toBe('some-element');
testComponent.slideAriaDescribedBy = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.hasAttribute('aria-describedby')).toBe(false);
});
it('should set the `for` attribute to the id of the element', () => {
expect(labelElement.getAttribute('for')).toBeTruthy();
expect(buttonElement.getAttribute('id')).toBeTruthy();
expect(labelElement.getAttribute('for')).toBe(buttonElement.getAttribute('id'));
});
it('should emit the new values properly', fakeAsync(() => {
labelElement.click();
fixture.detectChanges();
tick();
// We're checking the arguments type / emitted value to be a boolean, because sometimes the
// emitted value can be a DOM Event, which is not valid.
// See angular/angular#4059
expect(testComponent.lastEvent.checked).toBe(true);
}));
it('should support subscription on the change observable', fakeAsync(() => {
const spy = jasmine.createSpy('change spy');
const subscription = slideToggle.change.subscribe(spy);
labelElement.click();
fixture.detectChanges();
tick();
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({checked: true}));
subscription.unsubscribe();
}));
it('should forward the required attribute', () => {
testComponent.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-required')).toBe('true');
testComponent.isRequired = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-required')).toBe(null);
});
it('should focus on underlying element when focus() is called', fakeAsync(() => {
expect(document.activeElement).not.toBe(buttonElement);
slideToggle.focus();
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(buttonElement);
})); | {
"end_byte": 10896,
"start_byte": 1080,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle.spec.ts_10902_20120 | it('should not manually move focus to underlying when focus comes from mouse or touch', fakeAsync(
inject([FocusMonitor], (focusMonitor: FocusMonitor) => {
expect(document.activeElement).not.toBe(buttonElement);
focusMonitor.focusVia(slideToggleElement, 'mouse');
fixture.detectChanges();
flush();
expect(document.activeElement).not.toBe(buttonElement);
focusMonitor.focusVia(slideToggleElement, 'touch');
fixture.detectChanges();
flush();
expect(document.activeElement).not.toBe(buttonElement);
}),
));
it('should set a element class if labelPosition is set to before', fakeAsync(() => {
const formField = slideToggleElement.querySelector('.mdc-form-field')!;
expect(formField.classList).not.toContain('mdc-form-field--align-end');
testComponent.labelPosition = 'before';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(formField.classList).toContain('mdc-form-field--align-end');
}));
it('should show ripples', fakeAsync(() => {
const rippleSelector = '.mat-ripple-element';
const switchElement = slideToggleElement.querySelector('.mdc-switch')!;
expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(0);
dispatchFakeEvent(switchElement, 'mousedown');
dispatchFakeEvent(switchElement, 'mouseup');
expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(1);
flush();
}));
it('should not show ripples when disableRipple is set', fakeAsync(() => {
const switchElement = slideToggleElement.querySelector('.mdc-switch')!;
const rippleSelector = '.mat-ripple-element';
testComponent.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(0);
dispatchFakeEvent(switchElement, 'mousedown');
dispatchFakeEvent(switchElement, 'mouseup');
expect(slideToggleElement.querySelectorAll(rippleSelector).length).toBe(0);
flush();
}));
it('should have a focus indicator', fakeAsync(() => {
const rippleElement = slideToggleElement.querySelector('.mat-mdc-slide-toggle-ripple')!;
expect(rippleElement.classList).toContain('mat-focus-indicator');
}));
it('should be able to hide the icon', fakeAsync(() => {
expect(slideToggleElement.querySelector('.mdc-switch__icons')).toBeTruthy();
testComponent.hideIcon = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleElement.querySelector('.mdc-switch__icons')).toBeFalsy();
}));
it('should be able to mark a slide toggle as interactive while it is disabled', fakeAsync(() => {
testComponent.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.disabled).toBe(true);
expect(buttonElement.hasAttribute('aria-disabled')).toBe(false);
expect(buttonElement.getAttribute('tabindex')).toBe('-1');
expect(buttonElement.classList).not.toContain('mat-mdc-slide-toggle-disabled-interactive');
testComponent.disabledInteractive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonElement.disabled).toBe(false);
expect(buttonElement.getAttribute('aria-disabled')).toBe('true');
expect(buttonElement.getAttribute('tabindex')).toBe('0');
expect(buttonElement.classList).toContain('mat-mdc-slide-toggle-disabled-interactive');
}));
it('should not change its state when clicked while disabled and interactive', fakeAsync(() => {
expect(slideToggle.checked).toBe(false);
testComponent.isDisabled = testComponent.disabledInteractive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
buttonElement.click();
fixture.detectChanges();
tick();
expect(slideToggle.checked).toBe(false);
}));
});
describe('custom template', () => {
it('should not trigger the change event on initialization', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleBasic);
fixture.componentInstance.slideChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.lastEvent).toBeFalsy();
}));
it('should be able to set the tabindex via the native attribute', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleWithTabindexAttr);
fixture.detectChanges();
const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!
.componentInstance as MatSlideToggle;
expect(slideToggle.tabIndex)
.withContext('Expected tabIndex property to have been set based on the native attribute')
.toBe(5);
}));
it('should add the disabled class if disabled through attribute', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleCheckedAndDisabledAttr);
fixture.detectChanges();
const switchEl = fixture.nativeElement.querySelector('.mdc-switch');
expect(switchEl.classList).toContain('mdc-switch--disabled');
}));
it('should add the checked class if checked through attribute', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleCheckedAndDisabledAttr);
fixture.detectChanges();
const switchEl = fixture.nativeElement.querySelector('.mdc-switch');
expect(switchEl.classList).toContain('mdc-switch--checked');
}));
it('should remove the tabindex from the host node', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleWithTabindexAttr);
fixture.detectChanges();
const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!.nativeElement;
expect(slideToggle.hasAttribute('tabindex')).toBe(false);
}));
it('should remove the tabindex from the host element when disabled', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleWithTabindexAttr);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!.nativeElement;
expect(slideToggle.hasAttribute('tabindex')).toBe(false);
}));
});
it(
'should not change value on click when click action is noop when using custom a ' +
'action configuration',
fakeAsync(() => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatSlideToggleModule, SlideToggleBasic],
providers: [
{
provide: MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS,
useValue: {disableToggleValue: true},
},
],
});
const fixture = TestBed.createComponent(SlideToggleBasic);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
const slideToggleDebug = fixture.debugElement.query(By.css('mat-slide-toggle'))!;
const slideToggle = slideToggleDebug.componentInstance;
const buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
const labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(testComponent.toggleTriggered).toBe(0);
expect(testComponent.dragTriggered).toBe(0);
expect(slideToggle.checked).withContext('Expect slide toggle value not changed').toBe(false);
labelElement.click();
fixture.detectChanges();
tick();
expect(slideToggle.checked).withContext('Expect slide toggle value not changed').toBe(false);
expect(testComponent.toggleTriggered).withContext('Expect toggle once').toBe(1);
expect(testComponent.dragTriggered).toBe(0);
buttonElement.click();
fixture.detectChanges();
tick();
expect(slideToggle.checked).withContext('Expect slide toggle value not changed').toBe(false);
expect(testComponent.toggleTriggered).withContext('Expect toggle twice').toBe(2);
expect(testComponent.dragTriggered).toBe(0);
}),
);
it('should be able to change the default color', () => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatSlideToggleModule, SlideToggleWithForm],
providers: [{provide: MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS, useValue: {color: 'warn'}}],
});
const fixture = TestBed.createComponent(SlideToggleWithForm);
fixture.detectChanges();
const slideToggle = fixture.nativeElement.querySelector('.mat-mdc-slide-toggle');
expect(slideToggle.classList).toContain('mat-warn');
});
it('should clear static aria attributes from the host node', () => {
const fixture = TestBed.createComponent(SlideToggleWithStaticAriaAttributes);
fixture.detectChanges();
const host: HTMLElement = fixture.nativeElement.querySelector('mat-slide-toggle');
expect(host.hasAttribute('aria-label')).toBe(false);
expect(host.hasAttribute('aria-labelledby')).toBe(false);
});
}); | {
"end_byte": 20120,
"start_byte": 10902,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle.spec.ts_20122_28876 | describe('MatSlideToggle with forms', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MatSlideToggleModule,
FormsModule,
ReactiveFormsModule,
SlideToggleWithForm,
SlideToggleWithModel,
SlideToggleWithFormControl,
SlideToggleWithModelAndChangeEvent,
],
});
});
describe('using ngModel', () => {
let fixture: ComponentFixture<SlideToggleWithModel>;
let testComponent: SlideToggleWithModel;
let slideToggle: MatSlideToggle;
let slideToggleElement: HTMLElement;
let slideToggleModel: NgModel;
let buttonElement: HTMLButtonElement;
let labelElement: HTMLLabelElement;
// This initialization is async() because it needs to wait for ngModel to set the initial value.
beforeEach(() => {
fixture = TestBed.createComponent(SlideToggleWithModel);
fixture.detectChanges();
const slideToggleDebug = fixture.debugElement.query(By.directive(MatSlideToggle))!;
testComponent = fixture.debugElement.componentInstance;
slideToggle = slideToggleDebug.componentInstance;
slideToggleElement = slideToggleDebug.nativeElement;
slideToggleModel = slideToggleDebug.injector.get<NgModel>(NgModel);
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement;
});
it('should be initially set to ng-pristine', () => {
expect(slideToggleElement.classList).toContain('ng-pristine');
expect(slideToggleElement.classList).not.toContain('ng-dirty');
});
it('should update the model programmatically', fakeAsync(() => {
expect(slideToggleElement.classList).not.toContain('mat-mdc-slide-toggle-checked');
testComponent.modelValue = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Flush the microtasks because the forms module updates the model state asynchronously.
flushMicrotasks();
fixture.detectChanges();
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
}));
it('should have the correct control state initially and after interaction', fakeAsync(() => {
// The control should start off valid, pristine, and untouched.
expect(slideToggleModel.valid).toBe(true);
expect(slideToggleModel.pristine).toBe(true);
expect(slideToggleModel.touched).toBe(false);
// After changing the value from the view, the control should
// become dirty (not pristine), but remain untouched if focus is still there.
slideToggle.checked = true;
dispatchFakeEvent(buttonElement, 'focus');
buttonElement.click();
flush();
expect(slideToggleModel.valid).toBe(true);
expect(slideToggleModel.pristine).toBe(false);
expect(slideToggleModel.touched).toBe(false);
// Once the button element loses focus, the control should remain dirty but should
// also turn touched.
dispatchFakeEvent(buttonElement, 'blur');
fixture.detectChanges();
flush();
expect(slideToggleModel.valid).toBe(true);
expect(slideToggleModel.pristine).toBe(false);
expect(slideToggleModel.touched).toBe(true);
}));
it('should not throw an error when disabling while focused', fakeAsync(() => {
expect(() => {
// Focus the button element because after disabling, the `blur` event should automatically
// fire and not result in a changed after checked exception. Related: #12323
buttonElement.focus();
tick();
fixture.componentInstance.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
}).not.toThrow();
}));
it('should not set the control to touched when changing the state programmatically', fakeAsync(() => {
// The control should start off with being untouched.
expect(slideToggleModel.touched).toBe(false);
testComponent.isChecked = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(slideToggleModel.touched).toBe(false);
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
// Once the button element loses focus, the control should remain dirty but should
// also turn touched.
dispatchFakeEvent(buttonElement, 'blur');
fixture.detectChanges();
flush();
expect(slideToggleModel.touched).toBe(true);
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
}));
it('should not set the control to touched when changing the model', fakeAsync(() => {
// The control should start off with being untouched.
expect(slideToggleModel.touched).toBe(false);
testComponent.modelValue = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Flush the microtasks because the forms module updates the model state asynchronously.
flushMicrotasks();
// The checked property has been updated from the model and now the view needs
// to reflect the state change.
fixture.detectChanges();
expect(slideToggleModel.touched).toBe(false);
expect(slideToggle.checked).toBe(true);
expect(slideToggleElement.classList).toContain('mat-mdc-slide-toggle-checked');
}));
it('should update checked state on click if control is checked initially', fakeAsync(() => {
fixture = TestBed.createComponent(SlideToggleWithModel);
slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!.componentInstance;
labelElement = fixture.debugElement.query(By.css('label'))!.nativeElement;
fixture.componentInstance.modelValue = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Flush the microtasks because the forms module updates the model state asynchronously.
flushMicrotasks();
// Now the new checked variable has been updated in the slide-toggle and the slide-toggle
// is marked for check because it still needs to update the underlying button.
fixture.detectChanges();
expect(slideToggle.checked)
.withContext('Expected slide-toggle to be checked initially')
.toBe(true);
labelElement.click();
fixture.detectChanges();
tick();
expect(slideToggle.checked)
.withContext('Expected slide-toggle to be no longer checked after label click.')
.toBe(false);
}));
it('should be pristine if initial value is set from NgModel', fakeAsync(() => {
fixture = TestBed.createComponent(SlideToggleWithModel);
fixture.componentInstance.modelValue = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
const debugElement = fixture.debugElement.query(By.directive(MatSlideToggle))!;
const modelInstance = debugElement.injector.get<NgModel>(NgModel);
// Flush the microtasks because the forms module updates the model state asynchronously.
flushMicrotasks();
expect(modelInstance.pristine).toBe(true);
}));
it('should set the model value when toggling via the `toggle` method', fakeAsync(() => {
expect(testComponent.modelValue).toBe(false);
fixture.debugElement.query(By.directive(MatSlideToggle))!.componentInstance.toggle();
fixture.detectChanges();
flushMicrotasks();
fixture.detectChanges();
expect(testComponent.modelValue).toBe(true);
}));
});
describe('with a FormControl', () => {
let fixture: ComponentFixture<SlideToggleWithFormControl>;
let testComponent: SlideToggleWithFormControl;
let slideToggle: MatSlideToggle;
let buttonElement: HTMLButtonElement;
beforeEach(() => {
fixture = TestBed.createComponent(SlideToggleWithFormControl);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
slideToggle = fixture.debugElement.query(By.directive(MatSlideToggle))!.componentInstance;
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
});
it('should toggle the disabled state', () => {
expect(slideToggle.disabled).toBe(false);
expect(buttonElement.disabled).toBe(false);
testComponent.formControl.disable();
fixture.detectChanges();
expect(slideToggle.disabled).toBe(true);
expect(buttonElement.disabled).toBe(true);
testComponent.formControl.enable();
fixture.detectChanges();
expect(slideToggle.disabled).toBe(false);
expect(buttonElement.disabled).toBe(false);
});
}); | {
"end_byte": 28876,
"start_byte": 20122,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle.spec.ts_28880_36053 | describe('with form element', () => {
let fixture: ComponentFixture<any>;
let testComponent: SlideToggleWithForm;
let buttonElement: HTMLButtonElement;
// This initialization is async() because it needs to wait for ngModel to set the initial value.
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(SlideToggleWithForm);
fixture.detectChanges();
flush();
testComponent = fixture.debugElement.componentInstance;
buttonElement = fixture.debugElement.query(By.css('button'))!.nativeElement;
}));
it('should not submit the form when clicked', fakeAsync(() => {
expect(testComponent.isSubmitted).toBe(false);
buttonElement.click();
fixture.detectChanges();
flush();
expect(testComponent.isSubmitted).toBe(false);
}));
it('should have proper invalid state if unchecked', fakeAsync(() => {
testComponent.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flushMicrotasks();
const slideToggleEl = fixture.nativeElement.querySelector('.mat-mdc-slide-toggle');
expect(slideToggleEl.classList).toContain('ng-invalid');
expect(slideToggleEl.classList).not.toContain('ng-valid');
// The required slide-toggle will be checked and the form control
// should become valid.
buttonElement.click();
fixture.detectChanges();
flush();
expect(slideToggleEl.classList).not.toContain('ng-invalid');
expect(slideToggleEl.classList).toContain('ng-valid');
// The required slide-toggle will be unchecked and the form control
// should become invalid.
buttonElement.click();
fixture.detectChanges();
flush();
expect(slideToggleEl.classList).toContain('ng-invalid');
expect(slideToggleEl.classList).not.toContain('ng-valid');
}));
it('should clear static name attribute from the slide toggle host node', () => {
const hostNode = fixture.nativeElement.querySelector('.mat-mdc-slide-toggle');
expect(buttonElement.getAttribute('name')).toBeTruthy();
expect(hostNode.hasAttribute('name')).toBe(false);
});
});
describe('with model and change event', () => {
it('should report changes to NgModel before emitting change event', fakeAsync(() => {
const fixture = TestBed.createComponent(SlideToggleWithModelAndChangeEvent);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
spyOn(fixture.componentInstance, 'onChange').and.callFake(() => {
expect(fixture.componentInstance.checked)
.withContext('Expected the model value to have changed before the change event fired.')
.toBe(true);
});
labelEl.click();
flush();
expect(fixture.componentInstance.onChange).toHaveBeenCalledTimes(1);
}));
});
});
@Component({
template: `
<mat-slide-toggle
[dir]="direction"
[required]="isRequired"
[disabled]="isDisabled"
[color]="slideColor"
[id]="slideId"
[checked]="slideChecked"
[name]="slideName"
[aria-label]="slideLabel"
[aria-labelledby]="slideLabelledBy"
[aria-describedby]="slideAriaDescribedBy"
[tabIndex]="slideTabindex"
[labelPosition]="labelPosition"
[disableRipple]="disableRipple"
[hideIcon]="hideIcon"
[disabledInteractive]="disabledInteractive"
(toggleChange)="onSlideToggleChange()"
(dragChange)="onSlideDragChange()"
(change)="onSlideChange($event)"
(click)="onSlideClick($event)">
<span>Test Slide Toggle</span>
</mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleBasic {
isDisabled = false;
isRequired = false;
disableRipple = false;
slideChecked = false;
slideColor: string;
slideId: string | null;
slideName: string | null;
slideLabel: string | null;
slideLabelledBy: string | null;
slideAriaDescribedBy: string | null;
slideTabindex: number;
lastEvent: MatSlideToggleChange;
labelPosition: string;
toggleTriggered = 0;
dragTriggered = 0;
direction: Direction = 'ltr';
hideIcon = false;
disabledInteractive = false;
onSlideClick: (event?: Event) => void = () => {};
onSlideChange = (event: MatSlideToggleChange) => (this.lastEvent = event);
onSlideToggleChange = () => this.toggleTriggered++;
onSlideDragChange = () => this.dragTriggered++;
}
@Component({
template: `
<form ngNativeValidate (ngSubmit)="isSubmitted = true">
<mat-slide-toggle name="slide" ngModel [required]="isRequired">Required</mat-slide-toggle>
<button type="submit"></button>
</form>`,
standalone: true,
imports: [MatSlideToggleModule, FormsModule, ReactiveFormsModule],
})
class SlideToggleWithForm {
isSubmitted: boolean = false;
isRequired: boolean = false;
}
@Component({
template: `<mat-slide-toggle [(ngModel)]="modelValue" [disabled]="isDisabled"
[checked]="isChecked"></mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, FormsModule, ReactiveFormsModule],
})
class SlideToggleWithModel {
modelValue = false;
isChecked = false;
isDisabled = false;
}
@Component({
template: `<mat-slide-toggle checked disabled>Label</mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleCheckedAndDisabledAttr {}
@Component({
template: `
<mat-slide-toggle [formControl]="formControl">
<span>Test Slide Toggle</span>
</mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, FormsModule, ReactiveFormsModule],
})
class SlideToggleWithFormControl {
formControl = new FormControl(false);
}
@Component({
template: `<mat-slide-toggle tabindex="5" [disabled]="disabled"></mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleWithTabindexAttr {
disabled = false;
}
@Component({
template: `<mat-slide-toggle>{{label}}</mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleWithoutLabel {
label: string;
}
@Component({
template: `<mat-slide-toggle [(ngModel)]="checked" (change)="onChange()"></mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, FormsModule, ReactiveFormsModule],
})
class SlideToggleWithModelAndChangeEvent {
checked: boolean;
onChange: () => void = () => {};
}
@Component({
template: `<mat-slide-toggle><some-text></some-text></mat-slide-toggle>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleProjectedLabel {}
@Component({
selector: 'some-text',
template: `<span>{{text}}</span>`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class TextBindingComponent {
text: string = 'Some text';
}
@Component({
template: `
<mat-slide-toggle aria-label="Slide toggle" aria-labelledby="something"></mat-slide-toggle>
`,
standalone: true,
imports: [MatSlideToggleModule, BidiModule],
})
class SlideToggleWithStaticAriaAttributes {} | {
"end_byte": 36053,
"start_byte": 28880,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.spec.ts"
} |
components/src/material/slide-toggle/slide-toggle-required-validator.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 {Directive, forwardRef, Provider} from '@angular/core';
import {CheckboxRequiredValidator, NG_VALIDATORS} from '@angular/forms';
/**
* @deprecated No longer used, `MatCheckbox` implements required validation directly.
* @breaking-change 19.0.0
*/
export const MAT_SLIDE_TOGGLE_REQUIRED_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MatSlideToggleRequiredValidator),
multi: true,
};
/**
* Validator for Material slide-toggle components with the required attribute in a
* template-driven form. The default validator for required form controls asserts
* that the control value is not undefined but that is not appropriate for a slide-toggle
* where the value is always defined.
*
* Required slide-toggle form controls are valid when checked.
*
* @deprecated No longer used, `MatCheckbox` implements required validation directly.
* @breaking-change 19.0.0
*/
@Directive({
selector: `mat-slide-toggle[required][formControlName],
mat-slide-toggle[required][formControl], mat-slide-toggle[required][ngModel]`,
providers: [MAT_SLIDE_TOGGLE_REQUIRED_VALIDATOR],
})
export class MatSlideToggleRequiredValidator extends CheckboxRequiredValidator {}
| {
"end_byte": 1419,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle-required-validator.ts"
} |
components/src/material/slide-toggle/module.ts_0_862 | /**
* @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 {MatSlideToggle} from './slide-toggle';
import {MatSlideToggleRequiredValidator} from './slide-toggle-required-validator';
/**
* @deprecated No longer used, `MatSlideToggle` implements required validation directly.
* @breaking-change 19.0.0
*/
@NgModule({
imports: [MatSlideToggleRequiredValidator],
exports: [MatSlideToggleRequiredValidator],
})
export class _MatSlideToggleRequiredValidatorModule {}
@NgModule({
imports: [MatSlideToggle, MatCommonModule],
exports: [MatSlideToggle, MatCommonModule],
})
export class MatSlideToggleModule {}
| {
"end_byte": 862,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/module.ts"
} |
components/src/material/slide-toggle/slide-toggle.md_0_1606 | `<mat-slide-toggle>` is an on/off control that can be toggled via clicking.
<!-- example(slide-toggle-overview) -->
The slide-toggle behaves similarly to a checkbox, though it does not support an `indeterminate`
state like `<mat-checkbox>`.
### Slide-toggle label
The slide-toggle label is provided as the content to the `<mat-slide-toggle>` element.
If you don't want the label to appear next to the slide-toggle, you can use
[`aria-label`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-label) or
[`aria-labelledby`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-labelledby) to
specify an appropriate label.
### Use with `@angular/forms`
`<mat-slide-toggle>` is compatible with `@angular/forms` and supports both `FormsModule`
and `ReactiveFormsModule`.
### Accessibility
`MatSlideToggle` uses an internal `<button role="switch">` to provide an accessible experience. This
internal button receives focus and is automatically labelled by the text content of the
`<mat-slide-toggle>` element. Avoid adding other interactive controls into the content of
`<mat-slide-toggle>`, as this degrades the experience for users of assistive technology.
Always provide an accessible label via `aria-label` or `aria-labelledby` for toggles without
descriptive text content. For dynamic labels, `MatSlideToggle` provides input properties for binding
`aria-label` and `aria-labelledby`. This means that you should not use the `attr.` prefix when
binding these properties, as demonstrated below.
```html
<mat-slide-toggle [aria-label]="isSubscribedToEmailsMessage">
</mat-slide-toggle>
```
| {
"end_byte": 1606,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.md"
} |
components/src/material/slide-toggle/public-api.ts_0_352 | /**
* @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 './slide-toggle';
export * from './slide-toggle-config';
export * from './module';
export * from './slide-toggle-required-validator';
| {
"end_byte": 352,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/public-api.ts"
} |
components/src/material/slide-toggle/README.md_0_103 | Please see the official documentation at https://material.angular.io/components/component/slide-toggle
| {
"end_byte": 103,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/README.md"
} |
components/src/material/slide-toggle/BUILD.bazel_0_1592 | 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 = "slide-toggle",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
"harness/**",
],
),
assets = [":slide_toggle_scss"] + glob(["**/*.html"]),
deps = [
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "slide_toggle_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "slide_toggle_scss",
src = "slide-toggle.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "slide_toggle_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":slide-toggle",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/testing/private",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":slide_toggle_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":slide-toggle.md"],
)
extract_tokens(
name = "tokens",
srcs = [":slide_toggle_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1592,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/BUILD.bazel"
} |
components/src/material/slide-toggle/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/index.ts"
} |
components/src/material/slide-toggle/slide-toggle.scss_0_7639 | @use '@angular/cdk';
@use '../core/style/layout-common';
@use '../core/tokens/m2/mat/switch' as tokens-mat-switch;
@use '../core/tokens/m2/mdc/switch' as tokens-mdc-switch;
@use '../core/tokens/token-utils';
@use '../core/style/vendor-prefixes';
$_mdc-slots: (tokens-mdc-switch.$prefix, tokens-mdc-switch.get-token-slots());
$_mat-slots: (tokens-mat-switch.$prefix, tokens-mat-switch.get-token-slots());
$_interactive-disabled-selector: '.mat-mdc-slide-toggle-disabled-interactive.mdc-switch--disabled';
.mdc-switch {
align-items: center;
background: none;
border: none;
cursor: pointer;
display: inline-flex;
flex-shrink: 0;
margin: 0;
outline: none;
overflow: visible;
padding: 0;
position: relative;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(width, track-width);
}
&.mdc-switch--disabled {
cursor: default;
pointer-events: none;
}
&.mat-mdc-slide-toggle-disabled-interactive {
pointer-events: auto;
}
}
.mdc-switch__track {
overflow: hidden;
position: relative;
width: 100%;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(height, track-height);
@include token-utils.create-token-slot(border-radius, track-shape);
.mdc-switch--disabled.mdc-switch & {
@include token-utils.create-token-slot(opacity, disabled-track-opacity);
}
}
&::before,
&::after {
border: 1px solid transparent;
border-radius: inherit;
box-sizing: border-box;
content: '';
height: 100%;
left: 0;
position: absolute;
width: 100%;
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(border-width, track-outline-width);
@include token-utils.create-token-slot(border-color, track-outline-color);
.mdc-switch--selected & {
@include token-utils.create-token-slot(border-width, selected-track-outline-width);
@include token-utils.create-token-slot(border-color, selected-track-outline-color);
}
.mdc-switch--disabled & {
@include token-utils.create-token-slot(border-width,
disabled-unselected-track-outline-width);
@include token-utils.create-token-slot(border-color,
disabled-unselected-track-outline-color);
}
}
}
@include cdk.high-contrast {
border-color: currentColor;
}
&::before {
transition: transform 75ms 0ms cubic-bezier(0, 0, 0.2, 1);
transform: translateX(0);
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(background, unselected-track-color);
}
.mdc-switch--selected & {
transition: transform 75ms 0ms cubic-bezier(0.4, 0, 0.6, 1);
transform: translateX(100%);
[dir='rtl'] .mdc-switch--selected & {
transform: translateX(-100%);
}
}
@include token-utils.use-tokens($_mat-slots...) {
.mdc-switch--selected & {
@include token-utils.create-token-slot(opacity, hidden-track-opacity);
@include token-utils.create-token-slot(transition, hidden-track-transition);
}
.mdc-switch--unselected & {
@include token-utils.create-token-slot(opacity, visible-track-opacity);
@include token-utils.create-token-slot(transition, visible-track-transition);
}
}
@include token-utils.use-tokens($_mdc-slots...) {
.mdc-switch:enabled:hover:not(:focus):not(:active) & {
@include token-utils.create-token-slot(background, unselected-hover-track-color);
}
.mdc-switch:enabled:focus:not(:active) & {
@include token-utils.create-token-slot(background, unselected-focus-track-color);
}
.mdc-switch:enabled:active & {
@include token-utils.create-token-slot(background, unselected-pressed-track-color);
}
#{$_interactive-disabled-selector}:hover:not(:focus):not(:active) &,
#{$_interactive-disabled-selector}:focus:not(:active) &,
#{$_interactive-disabled-selector}:active &,
.mdc-switch.mdc-switch--disabled & {
@include token-utils.create-token-slot(background, disabled-unselected-track-color);
}
}
}
&::after {
transform: translateX(-100%);
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(background, selected-track-color);
}
[dir='rtl'] & {
transform: translateX(100%);
}
.mdc-switch--selected & {
transform: translateX(0);
}
@include token-utils.use-tokens($_mat-slots...) {
.mdc-switch--selected & {
@include token-utils.create-token-slot(opacity, visible-track-opacity);
@include token-utils.create-token-slot(transition, visible-track-transition);
}
.mdc-switch--unselected & {
@include token-utils.create-token-slot(opacity, hidden-track-opacity);
@include token-utils.create-token-slot(transition, hidden-track-transition);
}
}
@include token-utils.use-tokens($_mdc-slots...) {
.mdc-switch:enabled:hover:not(:focus):not(:active) & {
@include token-utils.create-token-slot(background, selected-hover-track-color);
}
.mdc-switch:enabled:focus:not(:active) & {
@include token-utils.create-token-slot(background, selected-focus-track-color);
}
.mdc-switch:enabled:active & {
@include token-utils.create-token-slot(background, selected-pressed-track-color);
}
#{$_interactive-disabled-selector}:hover:not(:focus):not(:active) &,
#{$_interactive-disabled-selector}:focus:not(:active) &,
#{$_interactive-disabled-selector}:active &,
.mdc-switch.mdc-switch--disabled & {
@include token-utils.create-token-slot(background, disabled-selected-track-color);
}
}
}
}
.mdc-switch__handle-track {
height: 100%;
pointer-events: none;
position: absolute;
top: 0;
transition: transform 75ms 0ms cubic-bezier(0.4, 0, 0.2, 1);
left: 0;
right: auto;
transform: translateX(0);
@include token-utils.use-tokens($_mdc-slots...) {
width: calc(100% - #{token-utils.get-token-variable(handle-width)});
}
[dir='rtl'] & {
left: auto;
right: 0;
}
.mdc-switch--selected & {
transform: translateX(100%);
[dir='rtl'] & {
transform: translateX(-100%);
}
}
}
.mdc-switch__handle {
display: flex;
pointer-events: auto;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 0;
right: auto;
// Used for M3 animations. Does not affect the M2 slide-toggle
// because the width and height are static, and the margin is unused.
transition:
width 75ms cubic-bezier(0.4, 0, 0.2, 1),
height 75ms cubic-bezier(0.4, 0, 0.2, 1),
margin 75ms cubic-bezier(0.4, 0, 0.2, 1);
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(width, handle-width);
@include token-utils.create-token-slot(height, handle-height);
@include token-utils.create-token-slot(border-radius, handle-shape);
}
[dir='rtl'] & {
left: auto;
right: 0;
}
@include token-utils.use-tokens($_mat-slots...) {
.mat-mdc-slide-toggle .mdc-switch--unselected & {
@include token-utils.create-token-slot(width, unselected-handle-size);
@include token-utils.create-token-slot(height, unselected-handle-size);
@include token-utils.create-token-slot(margin, unselected-handle-horizontal-margin);
&:has(.mdc-switch__icons) {
@include token-utils.create-token-slot(margin,
unselected-with-icon-handle-horizontal-margin);
}
} | {
"end_byte": 7639,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.scss"
} |
components/src/material/slide-toggle/slide-toggle.scss_7645_15398 | .mat-mdc-slide-toggle .mdc-switch--selected & {
@include token-utils.create-token-slot(width, selected-handle-size);
@include token-utils.create-token-slot(height, selected-handle-size);
@include token-utils.create-token-slot(margin, selected-handle-horizontal-margin);
&:has(.mdc-switch__icons) {
@include token-utils.create-token-slot(margin, selected-with-icon-handle-horizontal-margin);
}
}
.mat-mdc-slide-toggle &:has(.mdc-switch__icons) {
@include token-utils.create-token-slot(width, with-icon-handle-size);
@include token-utils.create-token-slot(height, with-icon-handle-size);
}
.mat-mdc-slide-toggle .mdc-switch:active:not(.mdc-switch--disabled) & {
@include token-utils.create-token-slot(width, pressed-handle-size);
@include token-utils.create-token-slot(height, pressed-handle-size);
}
.mat-mdc-slide-toggle .mdc-switch--selected:active:not(.mdc-switch--disabled) & {
@include token-utils.create-token-slot(margin, selected-pressed-handle-horizontal-margin);
}
.mat-mdc-slide-toggle .mdc-switch--unselected:active:not(.mdc-switch--disabled) & {
@include token-utils.create-token-slot(margin, unselected-pressed-handle-horizontal-margin);
}
.mdc-switch--disabled.mdc-switch--selected &::after {
@include token-utils.create-token-slot(opacity, disabled-selected-handle-opacity);
}
.mdc-switch--disabled.mdc-switch--unselected &::after {
@include token-utils.create-token-slot(opacity, disabled-unselected-handle-opacity);
}
}
&::before,
&::after {
border: 1px solid transparent;
border-radius: inherit;
box-sizing: border-box;
content: '';
width: 100%;
height: 100%;
left: 0;
position: absolute;
top: 0;
transition: background-color 75ms 0ms cubic-bezier(0.4, 0, 0.2, 1),
border-color 75ms 0ms cubic-bezier(0.4, 0, 0.2, 1);
z-index: -1;
@include cdk.high-contrast {
border-color: currentColor;
}
}
@include token-utils.use-tokens($_mdc-slots...) {
&::after {
.mdc-switch--selected:enabled & {
@include token-utils.create-token-slot(background, selected-handle-color);
}
.mdc-switch--selected:enabled:hover:not(:focus):not(:active) & {
@include token-utils.create-token-slot(background, selected-hover-handle-color);
}
.mdc-switch--selected:enabled:focus:not(:active) & {
@include token-utils.create-token-slot(background, selected-focus-handle-color);
}
.mdc-switch--selected:enabled:active & {
@include token-utils.create-token-slot(background, selected-pressed-handle-color);
}
#{$_interactive-disabled-selector}.mdc-switch--selected:hover:not(:focus):not(:active) &,
#{$_interactive-disabled-selector}.mdc-switch--selected:focus:not(:active) &,
#{$_interactive-disabled-selector}.mdc-switch--selected:active &,
.mdc-switch--selected.mdc-switch--disabled & {
@include token-utils.create-token-slot(background, disabled-selected-handle-color);
}
.mdc-switch--unselected:enabled & {
@include token-utils.create-token-slot(background, unselected-handle-color);
}
.mdc-switch--unselected:enabled:hover:not(:focus):not(:active) & {
@include token-utils.create-token-slot(background, unselected-hover-handle-color);
}
.mdc-switch--unselected:enabled:focus:not(:active) & {
@include token-utils.create-token-slot(background, unselected-focus-handle-color);
}
.mdc-switch--unselected:enabled:active & {
@include token-utils.create-token-slot(background, unselected-pressed-handle-color);
}
.mdc-switch--unselected.mdc-switch--disabled & {
@include token-utils.create-token-slot(background, disabled-unselected-handle-color);
}
}
&::before {
@include token-utils.create-token-slot(background, handle-surface-color);
}
}
}
.mdc-switch__shadow {
border-radius: inherit;
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 0;
@include token-utils.use-tokens($_mdc-slots...) {
.mdc-switch:enabled & {
@include token-utils.create-token-slot(box-shadow, handle-elevation-shadow);
}
#{$_interactive-disabled-selector}:hover:not(:focus):not(:active) &,
#{$_interactive-disabled-selector}:focus:not(:active) &,
#{$_interactive-disabled-selector}:active &,
.mdc-switch.mdc-switch--disabled & {
@include token-utils.create-token-slot(box-shadow, disabled-handle-elevation-shadow);
}
}
}
.mdc-switch__ripple {
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
z-index: -1;
@include token-utils.use-tokens($_mdc-slots...) {
@include token-utils.create-token-slot(width, state-layer-size);
@include token-utils.create-token-slot(height, state-layer-size);
}
&::after {
content: '';
opacity: 0;
.mdc-switch--disabled & {
display: none;
}
.mat-mdc-slide-toggle-disabled-interactive & {
display: block;
}
.mdc-switch:hover & {
opacity: 0.04;
transition: 75ms opacity cubic-bezier(0, 0, 0.2, 1);
}
// Needs a little more specificity so the :hover styles don't override it.
.mat-mdc-slide-toggle.mat-mdc-slide-toggle-focused .mdc-switch & {
opacity: 0.12;
}
@include token-utils.use-tokens($_mdc-slots...) {
#{$_interactive-disabled-selector}:enabled:focus &,
#{$_interactive-disabled-selector}:enabled:active &,
#{$_interactive-disabled-selector}:enabled:hover:not(:focus) &,
.mdc-switch--unselected:enabled:hover:not(:focus) & {
@include token-utils.create-token-slot(background, unselected-hover-state-layer-color);
}
.mdc-switch--unselected:enabled:focus & {
@include token-utils.create-token-slot(background, unselected-focus-state-layer-color);
}
.mdc-switch--unselected:enabled:active & {
@include token-utils.create-token-slot(background, unselected-pressed-state-layer-color);
@include token-utils.create-token-slot(opacity, unselected-pressed-state-layer-opacity);
transition: opacity 75ms linear;
}
.mdc-switch--selected:enabled:hover:not(:focus) & {
@include token-utils.create-token-slot(background, selected-hover-state-layer-color);
}
.mdc-switch--selected:enabled:focus & {
@include token-utils.create-token-slot(background, selected-focus-state-layer-color);
}
.mdc-switch--selected:enabled:active & {
@include token-utils.create-token-slot(background, selected-pressed-state-layer-color);
@include token-utils.create-token-slot(opacity, selected-pressed-state-layer-opacity);
transition: opacity 75ms linear;
}
}
}
}
.mdc-switch__icons {
position: relative;
height: 100%;
width: 100%;
z-index: 1;
@include token-utils.use-tokens($_mdc-slots...) {
.mdc-switch--disabled.mdc-switch--unselected & {
@include token-utils.create-token-slot(opacity, disabled-unselected-icon-opacity);
}
.mdc-switch--disabled.mdc-switch--selected & {
@include token-utils.create-token-slot(opacity, disabled-selected-icon-opacity);
}
}
}
.mdc-switch__icon {
bottom: 0;
left: 0;
margin: auto;
position: absolute;
right: 0;
top: 0;
opacity: 0;
transition: opacity 30ms 0ms cubic-bezier(0.4, 0, 1, 1);
@include token-utils.use-tokens($_mdc-slots...) {
.mdc-switch--unselected & {
@include token-utils.create-token-slot(width, unselected-icon-size);
@include token-utils.create-token-slot(height, unselected-icon-size);
@include token-utils | {
"end_byte": 15398,
"start_byte": 7645,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.scss"
} |
components/src/material/slide-toggle/slide-toggle.scss_15398_18821 | .create-token-slot(fill, unselected-icon-color);
}
.mdc-switch--unselected.mdc-switch--disabled & {
@include token-utils.create-token-slot(fill, disabled-unselected-icon-color);
}
.mdc-switch--selected & {
@include token-utils.create-token-slot(width, selected-icon-size);
@include token-utils.create-token-slot(height, selected-icon-size);
@include token-utils.create-token-slot(fill, selected-icon-color);
}
.mdc-switch--selected.mdc-switch--disabled & {
@include token-utils.create-token-slot(fill, disabled-selected-icon-color);
}
}
}
.mdc-switch--selected .mdc-switch__icon--on,
.mdc-switch--unselected .mdc-switch__icon--off {
opacity: 1;
transition: opacity 45ms 30ms cubic-bezier(0, 0, 0.2, 1);
}
.mat-mdc-slide-toggle {
@include vendor-prefixes.user-select(none);
display: inline-block;
-webkit-tap-highlight-color: transparent;
// Remove the native outline since we use the ripple for focus indication.
outline: 0;
// The ripple needs extra specificity so the base ripple styling doesn't override its `position`.
.mat-mdc-slide-toggle-ripple,
.mdc-switch__ripple::after {
@include layout-common.fill();
border-radius: 50%;
// Disable pointer events for the ripple container so that it doesn't eat the mouse events meant
// for the input. Pointer events can be safely disabled because the ripple trigger element is
// the host element.
pointer-events: none;
// Fixes the ripples not clipping to the border radius on Safari. Uses `:not(:empty)`
// in order to avoid creating extra layers when there aren't any ripples.
&:not(:empty) {
transform: translateZ(0);
}
}
// Needs a little more specificity so the :hover styles don't override it.
// For slide-toggles render the focus indicator when we know
// the hidden input is focused (slightly different for each control).
&.mat-mdc-slide-toggle-focused .mat-focus-indicator::before {
content: '';
}
.mat-internal-form-field {
@include token-utils.use-tokens($_mat-slots...) {
@include token-utils.create-token-slot(color, label-text-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
@include token-utils.create-token-slot(font-weight, label-text-weight);
}
}
.mat-ripple-element {
opacity: 0.12;
}
// Slide-toggle components have to set `border-radius: 50%` in order to support density scaling
// which will clip a square focus indicator so we have to turn it into a circle.
.mat-focus-indicator::before {
border-radius: 50%;
}
&._mat-animation-noopable {
.mdc-switch__handle-track,
.mdc-switch__icon,
.mdc-switch__handle::before,
.mdc-switch__handle::after,
.mdc-switch__track::before,
.mdc-switch__track::after {
transition: none;
}
}
// If our slide-toggle is enabled the cursor on label should appear as a pointer.
.mdc-switch:enabled + .mdc-label {
cursor: pointer;
}
// TODO(wagnermaciel): Use our custom token system to emit this css rule.
.mdc-switch--disabled + label {
color: var(--mdc-switch-disabled-label-text-color);
}
} | {
"end_byte": 18821,
"start_byte": 15398,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.scss"
} |
components/src/material/slide-toggle/slide-toggle.html_0_2330 | <div mat-internal-form-field [labelPosition]="labelPosition">
<button
class="mdc-switch"
role="switch"
type="button"
[class.mdc-switch--selected]="checked"
[class.mdc-switch--unselected]="!checked"
[class.mdc-switch--checked]="checked"
[class.mdc-switch--disabled]="disabled"
[class.mat-mdc-slide-toggle-disabled-interactive]="disabledInteractive"
[tabIndex]="disabled && !disabledInteractive ? -1 : tabIndex"
[disabled]="disabled && !disabledInteractive"
[attr.id]="buttonId"
[attr.name]="name"
[attr.aria-label]="ariaLabel"
[attr.aria-labelledby]="_getAriaLabelledBy()"
[attr.aria-describedby]="ariaDescribedby"
[attr.aria-required]="required || null"
[attr.aria-checked]="checked"
[attr.aria-disabled]="disabled && disabledInteractive ? 'true' : null"
(click)="_handleClick()"
#switch>
<span class="mdc-switch__track"></span>
<span class="mdc-switch__handle-track">
<span class="mdc-switch__handle">
<span class="mdc-switch__shadow">
<span class="mdc-elevation-overlay"></span>
</span>
<span class="mdc-switch__ripple">
<span class="mat-mdc-slide-toggle-ripple mat-focus-indicator" mat-ripple
[matRippleTrigger]="switch"
[matRippleDisabled]="disableRipple || disabled"
[matRippleCentered]="true"></span>
</span>
@if (!hideIcon) {
<span class="mdc-switch__icons">
<svg
class="mdc-switch__icon mdc-switch__icon--on"
viewBox="0 0 24 24"
aria-hidden="true">
<path d="M19.69,5.23L8.96,15.96l-4.23-4.23L2.96,13.5l6,6L21.46,7L19.69,5.23z" />
</svg>
<svg
class="mdc-switch__icon mdc-switch__icon--off"
viewBox="0 0 24 24"
aria-hidden="true">
<path d="M20 13H4v-2h16v2z" />
</svg>
</span>
}
</span>
</span>
</button>
<!--
Clicking on the label will trigger another click event from the button.
Stop propagation here so other listeners further up in the DOM don't execute twice.
-->
<label class="mdc-label" [for]="buttonId" [attr.id]="_labelId" (click)="$event.stopPropagation()">
<ng-content></ng-content>
</label>
</div>
| {
"end_byte": 2330,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle.html"
} |
components/src/material/slide-toggle/slide-toggle-config.ts_0_1366 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '@angular/core';
import {ThemePalette} from '@angular/material/core';
/** Default `mat-slide-toggle` options that can be overridden. */
export interface MatSlideToggleDefaultOptions {
/** Whether toggle action triggers value changes in slide toggle. */
disableToggleValue?: boolean;
/**
* Default theme color of the slide toggle. 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 to hide the icon inside the slide toggle. */
hideIcon?: boolean;
/** Whether disabled slide toggles should remain interactive. */
disabledInteractive?: boolean;
}
/** Injection token to be used to override the default options for `mat-slide-toggle`. */
export const MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS = new InjectionToken<MatSlideToggleDefaultOptions>(
'mat-slide-toggle-default-options',
{
providedIn: 'root',
factory: () => ({disableToggleValue: false, hideIcon: false, disabledInteractive: false}),
},
);
| {
"end_byte": 1366,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/slide-toggle-config.ts"
} |
components/src/material/slide-toggle/_slide-toggle-theme.scss_0_6595 | @use '../core/style/sass-utils';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/tokens/token-utils';
@use '../core/typography/typography';
@use '../core/tokens/m2/mat/switch' as tokens-mat-switch;
@use '../core/tokens/m2/mdc/switch' as tokens-mdc-switch;
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-slide-toggle.
/// @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-switch.$prefix,
tokens-mdc-switch.get-unthemable-tokens()
);
.mat-mdc-slide-toggle {
@include token-utils.create-token-values(
tokens-mat-switch.$prefix,
tokens-mat-switch.get-unthemable-tokens()
);
}
}
}
}
/// Outputs color theme styles for the mat-slide-toggle.
/// @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 slide-toggle: 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 {
$mdc-tokens: tokens-mdc-switch.get-color-tokens($theme);
// Add values for MDC slide toggles tokens
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-switch.$prefix,
tokens-mdc-switch.get-color-tokens($theme)
);
& {
// TODO(wagnermaciel): Use our token system to define this css variable.
--mdc-switch-disabled-label-text-color: #{inspection.get-theme-color(
$theme,
foreground,
disabled-text
)};
}
.mat-mdc-slide-toggle {
@include token-utils.create-token-values(
tokens-mat-switch.$prefix,
tokens-mat-switch.get-color-tokens($theme)
);
// Change the color palette related tokens to accent or warn if applicable
&.mat-accent {
@include token-utils.create-token-values(
tokens-mdc-switch.$prefix,
tokens-mdc-switch.private-get-color-palette-color-tokens($theme, accent)
);
}
&.mat-warn {
@include token-utils.create-token-values(
tokens-mdc-switch.$prefix,
tokens-mdc-switch.private-get-color-palette-color-tokens($theme, warn)
);
}
}
}
}
}
/// Outputs typography theme styles for the mat-slide-toggle.
/// @param {Map} $theme The theme to generate typography styles for.
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-switch.$prefix,
tokens-mdc-switch.get-typography-tokens($theme)
);
.mat-mdc-slide-toggle {
@include token-utils.create-token-values(
tokens-mat-switch.$prefix,
tokens-mat-switch.get-typography-tokens($theme)
);
}
}
}
}
/// Outputs density theme styles for the mat-slide-toggle.
/// @param {Map} $theme The theme to generate density styles for.
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-switch.$prefix,
tokens-mdc-switch.get-density-tokens($theme)
);
.mat-mdc-slide-toggle {
@include token-utils.create-token-values(
tokens-mat-switch.$prefix,
tokens-mat-switch.get-density-tokens($theme)
);
}
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-switch.$prefix,
tokens: tokens-mat-switch.get-token-slots(),
),
(
namespace: tokens-mdc-switch.$prefix,
tokens: tokens-mdc-switch.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-icon.
/// @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 slide-toggle: 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-slide-toggle') {
@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-switch-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-switch.$prefix, $options...);
// Don't pass $options here, since the mat-switch doesn't support color options,
// only the mdc-switch does.
$mat-switch-tokens: token-utils.get-tokens-for($tokens, tokens-mat-switch.$prefix);
@include token-utils.create-token-values(tokens-mdc-switch.$prefix, $mdc-switch-tokens);
@include token-utils.create-token-values(tokens-mat-switch.$prefix, $mat-switch-tokens);
}
| {
"end_byte": 6595,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/_slide-toggle-theme.scss"
} |
components/src/material/slide-toggle/testing/slide-toggle-harness.spec.ts_0_7995 | 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 {FormControl, ReactiveFormsModule} from '@angular/forms';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatSlideToggleHarness} from './slide-toggle-harness';
describe('MatSlideToggleHarness', () => {
let fixture: ComponentFixture<SlideToggleHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatSlideToggleModule, ReactiveFormsModule, SlideToggleHarnessTest],
});
fixture = TestBed.createComponent(SlideToggleHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all slide-toggle harnesses', async () => {
const slideToggles = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(slideToggles.length).toBe(2);
});
it('should load slide-toggle with exact label', async () => {
const slideToggles = await loader.getAllHarnesses(MatSlideToggleHarness.with({label: 'First'}));
expect(slideToggles.length).toBe(1);
expect(await slideToggles[0].getLabelText()).toBe('First');
});
it('should load slide-toggle with disabled=true predicate', async () => {
const slideToggles = await loader.getAllHarnesses(MatSlideToggleHarness.with({disabled: true}));
expect(slideToggles.length).toBe(1);
expect(await slideToggles[0].isDisabled()).toBe(true);
});
it('should load slide-toggle with disabled=false predicate', async () => {
const slideToggles = await loader.getAllHarnesses(
MatSlideToggleHarness.with({disabled: false}),
);
expect(slideToggles.length).toBe(1);
expect(await slideToggles[0].isDisabled()).toBe(false);
});
it('should load slide-toggle with regex label match', async () => {
const slideToggles = await loader.getAllHarnesses(MatSlideToggleHarness.with({label: /^s/i}));
expect(slideToggles.length).toBe(1);
expect(await slideToggles[0].getLabelText()).toBe('Second');
});
it('should load slide-toggle with name', async () => {
const slideToggles = await loader.getAllHarnesses(
MatSlideToggleHarness.with({name: 'first-name'}),
);
expect(slideToggles.length).toBe(1);
expect(await slideToggles[0].getLabelText()).toBe('First');
});
it('should get checked state', async () => {
const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await checkedToggle.isChecked()).toBe(true);
expect(await uncheckedToggle.isChecked()).toBe(false);
});
it('should get disabled state', async () => {
const [enabledToggle, disabledToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await enabledToggle.isDisabled()).toBe(false);
expect(await disabledToggle.isDisabled()).toBe(true);
});
it('should get required state', async () => {
const [requiredToggle, optionalToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await requiredToggle.isRequired()).toBe(true);
expect(await optionalToggle.isRequired()).toBe(false);
});
it('should get valid state', async () => {
const [requiredToggle, optionalToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await optionalToggle.isValid())
.withContext('Expected optional toggle to be valid')
.toBe(true);
expect(await requiredToggle.isValid())
.withContext('Expected required checked toggle to be valid')
.toBe(true);
await requiredToggle.uncheck();
expect(await requiredToggle.isValid())
.withContext('Expected required unchecked toggle to be invalid')
.toBe(false);
});
it('should get name', async () => {
const slideToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'First'}));
expect(await slideToggle.getName()).toBe('first-name');
});
it('should get aria-label', async () => {
const slideToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'First'}));
expect(await slideToggle.getAriaLabel()).toBe('First slide-toggle');
});
it('should get aria-labelledby', async () => {
const slideToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'Second'}));
expect(await slideToggle.getAriaLabelledby()).toBe('second-label');
});
it('should get label text', async () => {
const [firstToggle, secondToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
expect(await firstToggle.getLabelText()).toBe('First');
expect(await secondToggle.getLabelText()).toBe('Second');
});
it('should focus slide-toggle', async () => {
const slideToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'First'}));
expect(await slideToggle.isFocused()).toBe(false);
await slideToggle.focus();
expect(await slideToggle.isFocused()).toBe(true);
});
it('should blur slide-toggle', async () => {
const slideToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'First'}));
await slideToggle.focus();
expect(await slideToggle.isFocused()).toBe(true);
await slideToggle.blur();
expect(await slideToggle.isFocused()).toBe(false);
});
it('should toggle slide-toggle', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
await checkedToggle.toggle();
await uncheckedToggle.toggle();
expect(await checkedToggle.isChecked()).toBe(false);
expect(await uncheckedToggle.isChecked()).toBe(true);
});
it('should check slide-toggle', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
await checkedToggle.check();
await uncheckedToggle.check();
expect(await checkedToggle.isChecked()).toBe(true);
expect(await uncheckedToggle.isChecked()).toBe(true);
});
it('should uncheck slide-toggle', async () => {
fixture.componentInstance.disabled.set(false);
const [checkedToggle, uncheckedToggle] = await loader.getAllHarnesses(MatSlideToggleHarness);
await checkedToggle.uncheck();
await uncheckedToggle.uncheck();
expect(await checkedToggle.isChecked()).toBe(false);
expect(await uncheckedToggle.isChecked()).toBe(false);
});
it('should not toggle disabled slide-toggle', async () => {
const disabledToggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'Second'}));
expect(await disabledToggle.isChecked()).toBe(false);
await disabledToggle.toggle();
expect(await disabledToggle.isChecked()).toBe(false);
});
it('should get disabled state when disabledInteractive is enabled', async () => {
fixture.componentInstance.disabled.set(false);
fixture.componentInstance.disabledInteractive.set(true);
const toggle = await loader.getHarness(MatSlideToggleHarness.with({label: 'Second'}));
expect(await toggle.isDisabled()).toBe(false);
fixture.componentInstance.disabled.set(true);
expect(await toggle.isDisabled()).toBe(true);
});
});
@Component({
template: `
<mat-slide-toggle
[formControl]="ctrl"
required
name="first-name"
aria-label="First slide-toggle">
First
</mat-slide-toggle>
<mat-slide-toggle
[disabled]="disabled()"
[disabledInteractive]="disabledInteractive()"
aria-labelledby="second-label">
Second
</mat-slide-toggle>
<span id="second-label">Second slide-toggle</span>
`,
standalone: true,
imports: [MatSlideToggleModule, ReactiveFormsModule],
})
class SlideToggleHarnessTest {
ctrl = new FormControl(true);
disabled = signal(true);
disabledInteractive = signal(false);
}
| {
"end_byte": 7995,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/slide-toggle-harness.spec.ts"
} |
components/src/material/slide-toggle/testing/public-api.ts_0_292 | /**
* @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 './slide-toggle-harness';
export * from './slide-toggle-harness-filters';
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/public-api.ts"
} |
components/src/material/slide-toggle/testing/slide-toggle-harness.ts_0_4906 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {SlideToggleHarnessFilters} from './slide-toggle-harness-filters';
/** Harness for interacting with a mat-slide-toggle in tests. */
export class MatSlideToggleHarness extends ComponentHarness {
private _label = this.locatorFor('label');
_nativeElement = this.locatorFor('button');
static hostSelector = '.mat-mdc-slide-toggle';
/**
* Gets a `HarnessPredicate` that can be used to search for a slide-toggle w/ specific attributes.
* @param options Options for narrowing the search:
* - `selector` finds a slide-toggle whose host element matches the given selector.
* - `label` finds a slide-toggle with specific label text.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatSlideToggleHarness>(
this: ComponentHarnessConstructor<T>,
options: SlideToggleHarnessFilters = {},
): HarnessPredicate<T> {
return (
new HarnessPredicate(this, options)
.addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabelText(), label),
)
// We want to provide a filter option for "name" because the name of the slide-toggle is
// only set on the underlying input. This means that it's not possible for developers
// to retrieve the harness of a specific checkbox with name through a CSS selector.
.addOption(
'name',
options.name,
async (harness, name) => (await harness.getName()) === name,
)
.addOption(
'checked',
options.checked,
async (harness, checked) => (await harness.isChecked()) == checked,
)
.addOption(
'disabled',
options.disabled,
async (harness, disabled) => (await harness.isDisabled()) == disabled,
)
);
}
/** Toggle the checked state of the slide-toggle. */
async toggle(): Promise<void> {
return (await this._nativeElement()).click();
}
/** Whether the slide-toggle is checked. */
async isChecked(): Promise<boolean> {
const checked = (await this._nativeElement()).getAttribute('aria-checked');
return coerceBooleanProperty(await checked);
}
/** Whether the slide-toggle is disabled. */
async isDisabled(): Promise<boolean> {
const nativeElement = await this._nativeElement();
const disabled = await nativeElement.getAttribute('disabled');
if (disabled !== null) {
return coerceBooleanProperty(disabled);
}
return (await nativeElement.getAttribute('aria-disabled')) === 'true';
}
/** Whether the slide-toggle is required. */
async isRequired(): Promise<boolean> {
const ariaRequired = await (await this._nativeElement()).getAttribute('aria-required');
return ariaRequired === 'true';
}
/** Whether the slide-toggle is valid. */
async isValid(): Promise<boolean> {
const invalid = (await this.host()).hasClass('ng-invalid');
return !(await invalid);
}
/** Gets the slide-toggle's name. */
async getName(): Promise<string | null> {
return (await this._nativeElement()).getAttribute('name');
}
/** Gets the slide-toggle's aria-label. */
async getAriaLabel(): Promise<string | null> {
return (await this._nativeElement()).getAttribute('aria-label');
}
/** Gets the slide-toggle's aria-labelledby. */
async getAriaLabelledby(): Promise<string | null> {
return (await this._nativeElement()).getAttribute('aria-labelledby');
}
/** Gets the slide-toggle's label text. */
async getLabelText(): Promise<string> {
return (await this._label()).text();
}
/** Focuses the slide-toggle. */
async focus(): Promise<void> {
return (await this._nativeElement()).focus();
}
/** Blurs the slide-toggle. */
async blur(): Promise<void> {
return (await this._nativeElement()).blur();
}
/** Whether the slide-toggle is focused. */
async isFocused(): Promise<boolean> {
return (await this._nativeElement()).isFocused();
}
/**
* Puts the slide-toggle in a checked state by toggling it if it is currently unchecked, or doing
* nothing if it is already checked.
*/
async check(): Promise<void> {
if (!(await this.isChecked())) {
await this.toggle();
}
}
/**
* Puts the slide-toggle in an unchecked state by toggling it if it is currently checked, or doing
* nothing if it is already unchecked.
*/
async uncheck(): Promise<void> {
if (await this.isChecked()) {
await this.toggle();
}
}
}
| {
"end_byte": 4906,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/slide-toggle-harness.ts"
} |
components/src/material/slide-toggle/testing/BUILD.bazel_0_804 | load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ts_library(
name = "testing",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
deps = [
"//src/cdk/coercion",
"//src/cdk/testing",
],
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/slide-toggle",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 804,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/BUILD.bazel"
} |
components/src/material/slide-toggle/testing/index.ts_0_234 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/index.ts"
} |
components/src/material/slide-toggle/testing/slide-toggle-harness-filters.ts_0_784 | /**
* @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 `MatSlideToggleHarness` instances. */
export interface SlideToggleHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose label matches the given value. */
label?: string | RegExp;
/** Only find instances whose name is the given value. */
name?: string;
/** Only find instances with the given checked value. */
checked?: boolean;
/** Only find instances where the disabled state matches the given value. */
disabled?: boolean;
}
| {
"end_byte": 784,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/slide-toggle/testing/slide-toggle-harness-filters.ts"
} |
components/src/material/datepicker/date-range-input-parts.ts_0_6909 | /**
* @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 {BACKSPACE, LEFT_ARROW, RIGHT_ARROW} from '@angular/cdk/keycodes';
import {
Directive,
DoCheck,
ElementRef,
InjectionToken,
Injector,
Input,
OnInit,
Signal,
inject,
} from '@angular/core';
import {
AbstractControl,
FormGroupDirective,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
NgControl,
NgForm,
ValidationErrors,
ValidatorFn,
Validators,
} from '@angular/forms';
import {ErrorStateMatcher, _ErrorStateTracker} from '@angular/material/core';
import {_computeAriaAccessibleName} from './aria-accessible-name';
import {DateRange, DateSelectionModelChange} from './date-selection-model';
import {DateFilterFn, MatDatepickerInputBase} from './datepicker-input-base';
/** Parent component that should be wrapped around `MatStartDate` and `MatEndDate`. */
export interface MatDateRangeInputParent<D> {
id: string;
min: D | null;
max: D | null;
dateFilter: DateFilterFn<D>;
rangePicker: {
opened: boolean;
id: string;
};
// @breaking-change 20.0.0 property to become required.
_ariaOwns?: Signal<string | null>;
_startInput: MatDateRangeInputPartBase<D>;
_endInput: MatDateRangeInputPartBase<D>;
_groupDisabled: boolean;
_handleChildValueChange(): void;
_openDatepicker(): void;
}
/**
* Used to provide the date range input wrapper component
* to the parts without circular dependencies.
*/
export const MAT_DATE_RANGE_INPUT_PARENT = new InjectionToken<MatDateRangeInputParent<unknown>>(
'MAT_DATE_RANGE_INPUT_PARENT',
);
/**
* Base class for the individual inputs that can be projected inside a `mat-date-range-input`.
*/
@Directive()
abstract class MatDateRangeInputPartBase<D>
extends MatDatepickerInputBase<DateRange<D>>
implements OnInit, DoCheck
{
_rangeInput = inject<MatDateRangeInputParent<D>>(MAT_DATE_RANGE_INPUT_PARENT);
override _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
_defaultErrorStateMatcher = inject(ErrorStateMatcher);
private _injector = inject(Injector);
_parentForm = inject(NgForm, {optional: true});
_parentFormGroup = inject(FormGroupDirective, {optional: true});
/**
* Form control bound to this input part.
* @docs-private
*/
ngControl: NgControl;
protected abstract override _validator: ValidatorFn | null;
protected abstract override _assignValueToModel(value: D | null): void;
protected abstract override _getValueFromModel(modelValue: DateRange<D>): D | null;
protected readonly _dir = inject(Directionality, {optional: true});
private _errorStateTracker: _ErrorStateTracker;
/** Object used to control when error messages are shown. */
@Input()
get errorStateMatcher() {
return this._errorStateTracker.matcher;
}
set errorStateMatcher(value: ErrorStateMatcher) {
this._errorStateTracker.matcher = value;
}
/** Whether the input is in an error state. */
get errorState() {
return this._errorStateTracker.errorState;
}
set errorState(value: boolean) {
this._errorStateTracker.errorState = value;
}
constructor(...args: unknown[]);
constructor() {
super();
this._errorStateTracker = new _ErrorStateTracker(
this._defaultErrorStateMatcher,
null,
this._parentFormGroup,
this._parentForm,
this.stateChanges,
);
}
ngOnInit() {
// We need the date input to provide itself as a `ControlValueAccessor` and a `Validator`, while
// injecting its `NgControl` so that the error state is handled correctly. This introduces a
// circular dependency, because both `ControlValueAccessor` and `Validator` depend on the input
// itself. Usually we can work around it for the CVA, but there's no API to do it for the
// validator. We work around it here by injecting the `NgControl` in `ngOnInit`, after
// everything has been resolved.
const ngControl = this._injector.get(NgControl, null, {optional: true, self: true});
if (ngControl) {
this.ngControl = ngControl;
this._errorStateTracker.ngControl = ngControl;
}
}
ngDoCheck() {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
}
}
/** Gets whether the input is empty. */
isEmpty(): boolean {
return this._elementRef.nativeElement.value.length === 0;
}
/** Gets the placeholder of the input. */
_getPlaceholder() {
return this._elementRef.nativeElement.placeholder;
}
/** Focuses the input. */
focus(): void {
this._elementRef.nativeElement.focus();
}
/** Gets the value that should be used when mirroring the input's size. */
getMirrorValue(): string {
const element = this._elementRef.nativeElement;
const value = element.value;
return value.length > 0 ? value : element.placeholder;
}
/** Refreshes the error state of the input. */
updateErrorState() {
this._errorStateTracker.updateErrorState();
}
/** Handles `input` events on the input element. */
override _onInput(value: string) {
super._onInput(value);
this._rangeInput._handleChildValueChange();
}
/** Opens the datepicker associated with the input. */
protected _openPopup(): void {
this._rangeInput._openDatepicker();
}
/** Gets the minimum date from the range input. */
_getMinDate() {
return this._rangeInput.min;
}
/** Gets the maximum date from the range input. */
_getMaxDate() {
return this._rangeInput.max;
}
/** Gets the date filter function from the range input. */
protected _getDateFilter() {
return this._rangeInput.dateFilter;
}
protected override _parentDisabled() {
return this._rangeInput._groupDisabled;
}
protected _shouldHandleChangeEvent({source}: DateSelectionModelChange<DateRange<D>>): boolean {
return source !== this._rangeInput._startInput && source !== this._rangeInput._endInput;
}
protected override _assignValueProgrammatically(value: D | null) {
super._assignValueProgrammatically(value);
const opposite = (
this === this._rangeInput._startInput
? this._rangeInput._endInput
: this._rangeInput._startInput
) as MatDateRangeInputPartBase<D> | undefined;
opposite?._validatorOnChange();
}
/** return the ARIA accessible name of the input element */
_getAccessibleName(): string {
return _computeAriaAccessibleName(this._elementRef.nativeElement);
}
}
/** Input for entering the start date in a `mat-date-range-input`. */ | {
"end_byte": 6909,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input-parts.ts"
} |
components/src/material/datepicker/date-range-input-parts.ts_6910_13855 | @Directive({
selector: 'input[matStartDate]',
host: {
'class': 'mat-start-date mat-date-range-input-inner',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(keydown)': '_onKeydown($event)',
'[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
'[attr.aria-owns]': `_rangeInput._ariaOwns
? _rangeInput._ariaOwns()
: (_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null`,
'[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
'[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
'(blur)': '_onBlur()',
'type': 'text',
},
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: MatStartDate, multi: true},
{provide: NG_VALIDATORS, useExisting: MatStartDate, multi: true},
],
// These need to be specified explicitly, because some tooling doesn't
// seem to pick them up from the base class. See #20932.
outputs: ['dateChange', 'dateInput'],
})
export class MatStartDate<D> extends MatDateRangeInputPartBase<D> {
/** Validator that checks that the start date isn't after the end date. */
private _startValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const start = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const end = this._model ? this._model.selection.end : null;
return !start || !end || this._dateAdapter.compareDate(start, end) <= 0
? null
: {'matStartDateInvalid': {'end': end, 'actual': start}};
};
protected _validator = Validators.compose([...super._getValidators(), this._startValidator]);
protected _getValueFromModel(modelValue: DateRange<D>) {
return modelValue.start;
}
protected override _shouldHandleChangeEvent(
change: DateSelectionModelChange<DateRange<D>>,
): boolean {
if (!super._shouldHandleChangeEvent(change)) {
return false;
} else {
return !change.oldValue?.start
? !!change.selection.start
: !change.selection.start ||
!!this._dateAdapter.compareDate(change.oldValue.start, change.selection.start);
}
}
protected _assignValueToModel(value: D | null) {
if (this._model) {
const range = new DateRange(value, this._model.selection.end);
this._model.updateSelection(range, this);
}
}
protected override _formatValue(value: D | null) {
super._formatValue(value);
// Any time the input value is reformatted we need to tell the parent.
this._rangeInput._handleChildValueChange();
}
override _onKeydown(event: KeyboardEvent) {
const endInput = this._rangeInput._endInput;
const element = this._elementRef.nativeElement;
const isLtr = this._dir?.value !== 'rtl';
// If the user hits RIGHT (LTR) when at the end of the input (and no
// selection), move the cursor to the start of the end input.
if (
((event.keyCode === RIGHT_ARROW && isLtr) || (event.keyCode === LEFT_ARROW && !isLtr)) &&
element.selectionStart === element.value.length &&
element.selectionEnd === element.value.length
) {
event.preventDefault();
endInput._elementRef.nativeElement.setSelectionRange(0, 0);
endInput.focus();
} else {
super._onKeydown(event);
}
}
}
/** Input for entering the end date in a `mat-date-range-input`. */
@Directive({
selector: 'input[matEndDate]',
host: {
'class': 'mat-end-date mat-date-range-input-inner',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(keydown)': '_onKeydown($event)',
'[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
'[attr.aria-owns]': `_rangeInput._ariaOwns
? _rangeInput._ariaOwns()
: (_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null`,
'[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
'[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
'(blur)': '_onBlur()',
'type': 'text',
},
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: MatEndDate, multi: true},
{provide: NG_VALIDATORS, useExisting: MatEndDate, multi: true},
],
// These need to be specified explicitly, because some tooling doesn't
// seem to pick them up from the base class. See #20932.
outputs: ['dateChange', 'dateInput'],
})
export class MatEndDate<D> extends MatDateRangeInputPartBase<D> {
/** Validator that checks that the end date isn't before the start date. */
private _endValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const end = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
const start = this._model ? this._model.selection.start : null;
return !end || !start || this._dateAdapter.compareDate(end, start) >= 0
? null
: {'matEndDateInvalid': {'start': start, 'actual': end}};
};
protected _validator = Validators.compose([...super._getValidators(), this._endValidator]);
protected _getValueFromModel(modelValue: DateRange<D>) {
return modelValue.end;
}
protected override _shouldHandleChangeEvent(
change: DateSelectionModelChange<DateRange<D>>,
): boolean {
if (!super._shouldHandleChangeEvent(change)) {
return false;
} else {
return !change.oldValue?.end
? !!change.selection.end
: !change.selection.end ||
!!this._dateAdapter.compareDate(change.oldValue.end, change.selection.end);
}
}
protected _assignValueToModel(value: D | null) {
if (this._model) {
const range = new DateRange(this._model.selection.start, value);
this._model.updateSelection(range, this);
}
}
private _moveCaretToEndOfStartInput() {
const startInput = this._rangeInput._startInput._elementRef.nativeElement;
const value = startInput.value;
if (value.length > 0) {
startInput.setSelectionRange(value.length, value.length);
}
startInput.focus();
}
override _onKeydown(event: KeyboardEvent) {
const element = this._elementRef.nativeElement;
const isLtr = this._dir?.value !== 'rtl';
// If the user is pressing backspace on an empty end input, move focus back to the start.
if (event.keyCode === BACKSPACE && !element.value) {
this._moveCaretToEndOfStartInput();
}
// If the user hits LEFT (LTR) when at the start of the input (and no
// selection), move the cursor to the end of the start input.
else if (
((event.keyCode === LEFT_ARROW && isLtr) || (event.keyCode === RIGHT_ARROW && !isLtr)) &&
element.selectionStart === 0 &&
element.selectionEnd === 0
) {
event.preventDefault();
this._moveCaretToEndOfStartInput();
} else {
super._onKeydown(event);
}
}
} | {
"end_byte": 13855,
"start_byte": 6910,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input-parts.ts"
} |
components/src/material/datepicker/month-view.html_0_1423 | <table class="mat-calendar-table" role="grid">
<thead class="mat-calendar-table-header">
<tr>
@for (day of _weekdays; track day.id) {
<th scope="col">
<span class="cdk-visually-hidden">{{day.long}}</span>
<span aria-hidden="true">{{day.narrow}}</span>
</th>
}
</tr>
<tr aria-hidden="true"><th class="mat-calendar-table-header-divider" colspan="7"></th></tr>
</thead>
<tbody mat-calendar-body
[label]="_monthLabel"
[rows]="_weeks"
[todayValue]="_todayDate!"
[startValue]="_rangeStart!"
[endValue]="_rangeEnd!"
[comparisonStart]="_comparisonRangeStart"
[comparisonEnd]="_comparisonRangeEnd"
[previewStart]="_previewStart"
[previewEnd]="_previewEnd"
[isRange]="_isRange"
[labelMinRequiredCells]="3"
[activeCell]="_dateAdapter.getDate(activeDate) - 1"
[startDateAccessibleName]="startDateAccessibleName"
[endDateAccessibleName]="endDateAccessibleName"
(selectedValueChange)="_dateSelected($event)"
(activeDateChange)="_updateActiveDate($event)"
(previewChange)="_previewChanged($event)"
(dragStarted)="dragStarted.emit($event)"
(dragEnded)="_dragEnded($event)"
(keyup)="_handleCalendarBodyKeyup($event)"
(keydown)="_handleCalendarBodyKeydown($event)">
</tbody>
</table>
| {
"end_byte": 1423,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.html"
} |
components/src/material/datepicker/datepicker.md_0_8196 | The datepicker allows users to enter a date either through text input, or by choosing a date from
the calendar. It is made up of several components, directives and [the date implementation](#choosing-a-date-implementation-and-date-format-settings) that work together.
<!-- example(datepicker-overview) -->
### Connecting a datepicker to an input
A datepicker is composed of a text input and a calendar pop-up, connected via the `matDatepicker`
property on the text input.
There is also an optional datepicker toggle button that gives the user an easy way to open the datepicker pop-up.
<!-- example({"example":"datepicker-overview",
"file":"datepicker-overview-example.html",
"region":"toggle"}) -->
This works exactly the same with an input that is part of an `<mat-form-field>` and the toggle
can easily be used as a prefix or suffix on the Material input:
<!-- example({"example":"datepicker-overview",
"file":"datepicker-overview-example.html"}) -->
If you want to customize the icon that is rendered inside the `mat-datepicker-toggle`, you can do so
by using the `matDatepickerToggleIcon` directive:
<!-- example(datepicker-custom-icon) -->
### Date range selection
If you want your users to select a range of dates, instead of a single date, you can use the
`mat-date-range-input` and `mat-date-range-picker` components. They work in tandem, similarly to the
`mat-datepicker` and the basic datepicker input.
The `mat-date-range-input` component requires two `input` elements for the start and end dates,
respectively:
```html
<mat-date-range-input>
<input matStartDate placeholder="Start date">
<input matEndDate placeholder="End date">
</mat-date-range-input>
```
The `mat-date-range-picker` component acts as the pop-up panel for selecting dates. This works in
the same way as `mat-datepicker`, but allows the user to select multiple times:
```html
<mat-date-range-picker #picker></mat-date-range-picker>
```
Connect the range picker and range input using the `rangePicker` property:
```html
<mat-date-range-input [rangePicker]="picker">
<input matStartDate placeholder="Start date">
<input matEndDate placeholder="End date">
</mat-date-range-input>
<mat-date-range-picker #picker></mat-date-range-picker>
```
<!-- example(date-range-picker-overview) -->
### Date range input forms integration
The `mat-date-range-input` component can be used together with the `FormGroup` directive from
`@angular/forms` to group the start and end values together and to validate them as a group.
<!-- example(date-range-picker-forms) -->
### Setting the calendar starting view
The `startView` property of `<mat-datepicker>` can be used to set the view that will show up when
the calendar first opens. It can be set to `month`, `year`, or `multi-year`; by default it will open
to month view.
The month, year, or range of years that the calendar opens to is determined by first checking if any
date is currently selected, if so it will open to the month or year containing that date. Otherwise
it will open to the month or year containing today's date. This behavior can be overridden by using
the `startAt` property of `<mat-datepicker>`. In this case the calendar will open to the month or
year containing the `startAt` date.
<!-- example(datepicker-start-view) -->
#### Watching the views for changes on selected years and months
When a year or a month is selected in `multi-year` and `year` views respectively, the `yearSelected`
and `monthSelected` outputs emit a normalized date representing the chosen year or month. By
"normalized" we mean that the dates representing years will have their month set to January and
their day set to the 1st. Dates representing months will have their day set to the 1st of the
month. For example, if `<mat-datepicker>` is configured to work with javascript native Date
objects, the `yearSelected` will emit `new Date(2017, 0, 1)` if the user selects 2017 in
`multi-year` view. Similarly, `monthSelected` will emit `new Date(2017, 1, 1)` if the user
selects **February** in `year` view and the current date value of the connected `<input>` was
set to something like `new Date(2017, MM, dd)` when the calendar was opened (the month and day are
irrelevant in this case).
Notice that the emitted value does not affect the current value in the connected `<input>`, which
is only bound to the selection made in the `month` view. So if the end user closes the calendar
after choosing a year in `multi-view` mode (by pressing the `ESC` key, for example), the selected
year, emitted by `yearSelected` output, will not cause any change in the value of the date in the
associated `<input>`.
The following example uses `yearSelected` and `monthSelected` outputs to emulate a month and year
picker (if you're not familiar with the usage of `MomentDateAdapter` and `MAT_DATE_FORMATS`
you can [read more about them](#choosing-a-date-implementation-and-date-format-settings) below in
this document to fully understand the example).
<!-- example(datepicker-views-selection) -->
### Setting the selected date
The type of values that the datepicker expects depends on the type of `DateAdapter` provided in your
application. The `NativeDateAdapter`, for example, works directly with plain JavaScript `Date`
objects. When using the `MomentDateAdapter`, however, the values will all be Moment.js instances.
This use of the adapter pattern allows the datepicker component to work with any arbitrary date
representation with a custom `DateAdapter`.
See [_Choosing a date implementation_](#choosing-a-date-implementation-and-date-format-settings)
for more information.
Depending on the `DateAdapter` being used, the datepicker may automatically deserialize certain date
formats for you as well. For example, both the `NativeDateAdapter` and `MomentDateAdapter` allow
[ISO 8601](https://tools.ietf.org/html/rfc3339) strings to be passed to the datepicker and
automatically converted to the proper object type. This can be convenient when binding data directly
from your backend to the datepicker. However, the datepicker will not accept date strings formatted
in user format such as `"1/2/2017"` as this is ambiguous and will mean different things depending on
the locale of the browser running the code.
As with other types of `<input>`, the datepicker works with `@angular/forms` directives such as
`formGroup`, `formControl`, `ngModel`, etc.
<!-- example(datepicker-value) -->
### Date validation
There are three properties that add date validation to the datepicker input. The first two are the
`min` and `max` properties. In addition to enforcing validation on the input, these properties will
disable all dates on the calendar popup before or after the respective values and prevent the user
from advancing the calendar past the `month` or `year` (depending on current view) containing the
`min` or `max` date.
<!-- example(datepicker-min-max) -->
The second way to add date validation is using the `matDatepickerFilter` property of the datepicker
input. This property accepts a function of `<D> => boolean` (where `<D>` is the date type used by
the datepicker, see
[_Choosing a date implementation_](#choosing-a-date-implementation-and-date-format-settings)).
A result of `true` indicates that the date is valid and a result of `false` indicates that it is
not. Again this will also disable the dates on the calendar that are invalid. However, one important
difference between using `matDatepickerFilter` vs using `min` or `max` is that filtering out all
dates before or after a certain point, will not prevent the user from advancing the calendar past
that point.
<!-- example(datepicker-filter) -->
In this example the user cannot select any date that falls on a Saturday or Sunday, but all of the
dates which fall on other days of the week are selectable.
Each validation property has a different error that can be checked:
- A value that violates the `min` property will have a `matDatepickerMin` error.
- A value that violates the `max` property will have a `matDatepickerMax` error.
- A value that violates the `matDatepickerFilter` property will have a `matDatepickerFilter` error.
| {
"end_byte": 8196,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md"
} |
components/src/material/datepicker/datepicker.md_8196_13080 | ### Input and change events
The input's native `(input)` and `(change)` events will only trigger due to user interaction with
the input element; they will not fire when the user selects a date from the calendar popup.
Therefore, the datepicker input also has support for `(dateInput)` and `(dateChange)` events. These
trigger when the user interacts with either the input or the popup.
The `(dateInput)` event will fire whenever the value changes due to the user typing or selecting a
date from the calendar. The `(dateChange)` event will fire whenever the user finishes typing input
(on `<input>` blur), or when the user chooses a date from the calendar.
<!-- example(datepicker-events) -->
### Disabling parts of the datepicker
As with any standard `<input>`, it is possible to disable the datepicker input by adding the
`disabled` property. By default, the `<mat-datepicker>` and `<mat-datepicker-toggle>` will inherit
their disabled state from the `<input>`, but this can be overridden by setting the `disabled`
property on the datepicker or toggle elements. This can be useful if you want to disable text input
but allow selection via the calendar or vice-versa.
<!-- example(datepicker-disabled) -->
### Confirmation action buttons
By default, clicking on a date in the calendar will select it and close the calendar popup. In some
cases this may not be desirable, because the user doesn't have a quick way of going back if they've
changed their mind. If you want your users to be able to cancel their selection and to have to
explicitly accept the value that they've selected, you can add a `<mat-datepicker-actions>` element
inside `<mat-datepicker>` with a "Cancel" and an "Apply" button marked with the
`matDatepickerCancel` and `matDatepickerApply` attributes respectively. Doing so will cause the
datepicker to only assign the value to the data model if the user presses "Apply", whereas pressing
"Cancel" will close popup without changing the value.
<!-- example({"example":"datepicker-actions",
"file":"datepicker-actions-example.html",
"region":"datepicker-actions"}) -->
The actions element is also supported for `<mat-date-range-picker>` where that it is called
`<mat-date-range-picker-actions>` and the buttons are called `matDateRangePickerCancel` and
`matDateRangePickerApply` respectively.
<!-- example({"example":"datepicker-actions",
"file":"datepicker-actions-example.html",
"region":"date-range-picker-actions"}) -->
<!-- example(datepicker-actions) -->
### Comparison ranges
If your users need to compare the date range that they're currently selecting with another range,
you can provide the comparison range start and end dates to the `mat-date-range-input` using the
`comparisonStart` and `comparisonEnd` bindings. The comparison range will be rendered statically
within the calendar, but it will change colors to indicate which dates overlap with the user's
selected range. The comparison and overlap colors can be customized using the
`datepicker-date-range-colors` mixin.
<!-- example(date-range-picker-comparison) -->
```scss
@use '@angular/material' as mat;
@include mat.datepicker-date-range-colors(hotpink, teal, yellow, purple);
```
### Customizing the date selection logic
The `mat-date-range-picker` supports custom behaviors for range previews and selection. To customize
this, you first create a class that implements `MatDateRangeSelectionStrategy`, and then provide
the class via the `MAT_DATE_RANGE_SELECTION_STRATEGY` injection token. The following example
uses the range selection strategy to create a custom range picker that limits the user to five-day
ranges.
<!-- example(date-range-picker-selection-strategy) -->
### Touch UI mode
The datepicker normally opens as a popup under the input. However this is not ideal for touch
devices that don't have as much screen real estate and need bigger click targets. For this reason
`<mat-datepicker>` has a `touchUi` property that can be set to `true` in order to enable a more
touch friendly UI where the calendar opens in a large dialog.
<!-- example(datepicker-touch) -->
### Manually opening and closing the calendar
The calendar popup can be programmatically controlled using the `open` and `close` methods on the
`<mat-datepicker>`. It also has an `opened` property that reflects the status of the popup.
<!-- example(datepicker-api) -->
### Using `mat-calendar` inline
If you want to allow the user to select a date from a calendar that is inlined on the page rather
than contained in a popup, you can use `<mat-calendar>` directly. The calendar's height is
determined automatically based on the width and the number of dates that need to be shown for a
month. If you want to make the calendar larger or smaller, adjust the width rather than the height.
<!-- example(datepicker-inline-calendar) -->
| {
"end_byte": 13080,
"start_byte": 8196,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md"
} |
components/src/material/datepicker/datepicker.md_13080_20137 | ### Internationalization
Internationalization of the datepicker is configured via four aspects:
1. The date locale.
2. The date implementation that the datepicker accepts.
3. The display and parse formats used by the datepicker.
4. The message strings used in the datepicker's UI.
#### Setting the locale code
By default, the `MAT_DATE_LOCALE` injection token will use the existing `LOCALE_ID` locale code
from `@angular/core`. If you want to override it, you can provide a new value for the
`MAT_DATE_LOCALE` token:
```ts
bootstapApplication(MyApp, {
providers: [{provide: MAT_DATE_LOCALE, useValue: 'en-GB'}],
});
```
It's also possible to set the locale at runtime using the `setLocale` method of the `DateAdapter`.
**Note:** if you're using the `provideDateFnsAdapter`, you have to provide the data object for your
locale to `MAT_DATE_LOCALE` instead of the locale code, in addition to providing a configuration
compatible with `date-fns` to `MAT_DATE_FORMATS`. Locale data for `date-fns` can be imported
from `date-fns/locale`.
<!-- example(datepicker-locale) -->
#### Choosing a date implementation and date format settings
The datepicker was built to be date implementation agnostic. This means that it can be made to work
with a variety of different date implementations. However it also means that developers need to make
sure to provide the appropriate pieces for the datepicker to work with their chosen implementation.
The easiest way to ensure this is to import one of the provided date adapters:
`provideNativeDateAdapter` or `MatNativeDateModule`
<table>
<tbody>
<tr>
<th align="left" scope="row">Date type</th>
<td><code>Date</code></td>
</tr>
<tr>
<th align="left" scope="row">Supported locales</th>
<td>en-US</td>
</tr>
<tr>
<th align="left" scope="row">Dependencies</th>
<td>None</td>
</tr>
<tr>
<th align="left" scope="row">Import from</th>
<td><code>@angular/material/core</code></td>
</tr>
</tbody>
</table>
`provideDateFnsAdapter` or `MatDateFnsModule` (installed via `ng add @angular/material-date-fns-adapter`)
<table>
<tbody>
<tr>
<th align="left" scope="row">Date type</th>
<td><code>Date</code></td>
</tr>
<tr>
<th align="left" scope="row">Supported locales</th>
<td><a href="https://github.com/date-fns/date-fns/tree/master/src/locale/">See project for details</a></td>
</tr>
<tr>
<th align="left" scope="row">Dependencies</th>
<td><a href="https://date-fns.org/">date-fns</a></td>
</tr>
<tr>
<th align="left" scope="row">Import from</th>
<td><code>@angular/material-date-fns-adapter</code></td>
</tr>
</tbody>
</table>
`provideLuxonDateAdapter` or `MatLuxonDateModule` (installed via `ng add @angular/material-luxon-adapter`)
<table>
<tbody>
<tr>
<th align="left" scope="row">Date type</th>
<td><code>DateTime</code></td>
</tr>
<tr>
<th align="left" scope="row">Supported locales</th>
<td><a href="https://moment.github.io/luxon/">See project for details</a></td>
</tr>
<tr>
<th align="left" scope="row">Dependencies</th>
<td><a href="https://moment.github.io/luxon/">Luxon</a></td>
</tr>
<tr>
<th align="left" scope="row">Import from</th>
<td><code>@angular/material-luxon-adapter</code></td>
</tr>
</tbody>
</table>
`provideMomentDateAdapter` or `MatMomentDateModule` (installed via `ng add @angular/material-moment-adapter`)
<table>
<tbody>
<tr>
<th align="left" scope="row">Date type</th>
<td><code>Moment</code></td>
</tr>
<tr>
<th align="left" scope="row">Supported locales</th>
<td><a href="https://github.com/moment/moment/tree/develop/src/locale">See project for details</a></td>
</tr>
<tr>
<th align="left" scope="row">Dependencies</th>
<td><a href="https://momentjs.com/">Moment.js</a></td>
</tr>
<tr>
<th align="left" scope="row">Import from</th>
<td><code>@angular/material-moment-adapter</code></td>
</tr>
</tbody>
</table>
_Please note: `provideNativeDateAdapter` is based off the functionality available in JavaScript's
native [`Date` object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date).
Thus it is not suitable for many locales. One of the biggest shortcomings of the native `Date`
object is the inability to set the parse format. We strongly recommend using an adapter based on
a more robust formatting and parsing library. You can use `provideMomentDateAdapter`
or a custom `DateAdapter` that works with the library of your choice._
These APIs include providers for `DateAdapter` and `MAT_DATE_FORMATS`.
```ts
bootstrapApplication(MyApp, {
providers: [provideNativeDateAdapter()]
});
```
Because `DateAdapter` is a generic class, `MatDatepicker` and `MatDatepickerInput` also need to be
made generic. When working with these classes (for example as a `ViewChild`) you should include the
appropriate generic type that corresponds to the `DateAdapter` implementation you are using. For
example:
```ts
@Component({...})
export class MyComponent {
@ViewChild(MatDatepicker) datepicker: MatDatepicker<Date>;
}
```
<!-- example(datepicker-moment) -->
By default the `MomentDateAdapter` creates dates in your time zone specific locale. You can change
the default behaviour to parse dates as UTC by passing `useUtc: true` into `provideMomentDateAdapter`
or by providing the `MAT_MOMENT_DATE_ADAPTER_OPTIONS` injection token.
```ts
bootstrapApplication(MyApp, {
providers: [provideMomentDateAdapter(undefined, {useUtc: true})]
});
```
By default the `MomentDateAdapter` will parse dates in a
[forgiving way](https://momentjs.com/guides/#/parsing/forgiving-mode/). This may result in dates
being parsed incorrectly. You can change the default behaviour to
[parse dates strictly](https://momentjs.com/guides/#/parsing/strict-mode/) by `strict: true` to
`provideMomentDateAdapter` or by providing the `MAT_MOMENT_DATE_ADAPTER_OPTIONS` injection token.
```ts
bootstrapApplication(MyApp, {
providers: [provideMomentDateAdapter(undefined, {strict: true})]
});
```
It is also possible to create your own `DateAdapter` that works with any date format your app
requires. This is accomplished by subclassing `DateAdapter` and providing your subclass as the
`DateAdapter` implementation. You will also want to make sure that the `MAT_DATE_FORMATS` provided
in your app are formats that can be understood by your date implementation. See
[_Customizing the parse and display formats_](#customizing-the-parse-and-display-formats) for more
information about `MAT_DATE_FORMATS`.
```ts
bootstrapApplication(MyApp, {
providers: [
{provide: DateAdapter, useClass: MyDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS},
]
});
```
If you need to work with native `Date` objects, but need custom behavior (for example custom date
parsing), you can consider subclassing `NativeDateAdapter`.
| {
"end_byte": 20137,
"start_byte": 13080,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md"
} |
components/src/material/datepicker/datepicker.md_20137_28364 | #### Customizing the parse and display formats
The `MAT_DATE_FORMATS` object is a collection of formats that the datepicker uses when parsing
and displaying dates. These formats are passed through to the `DateAdapter` so you will want to make
sure that the format objects you're using are compatible with the `DateAdapter` used in your app.
If you want use one of the `DateAdapters` that ships with Angular Material, but use your own
`MAT_DATE_FORMATS`, you can either pass the formats into the providers function, or provide the
`MAT_DATE_FORMATS` token yourself. For example:
```ts
bootstrapApplication(MyApp, {
providers: [provideNativeDateAdapter(MY_NATIVE_DATE_FORMATS)],
});
```
<!-- example(datepicker-formats) -->
##### Moment.js formats
To use custom formats with the `provideMomentDateAdapter` you can pick from the parse formats
documented [here](https://momentjs.com/docs/#/parsing/string-format/) and the display formats
documented [here](https://momentjs.com/docs/#/displaying/format/).
It is also possible to support multiple parse formats. For example:
```ts
bootstraApplication(MyApp, {
providers: [provideMomentDateAdapter({
parse: {
dateInput: ['l', 'LL'],
},
display: {
dateInput: 'L',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
})]
});
```
#### Customizing the calendar header
The header section of the calendar (the part containing the view switcher and previous and next
buttons) can be replaced with a custom component if desired. This is accomplished using the
`calendarHeaderComponent` property of `<mat-datepicker>`. It takes a component class and constructs
an instance of the component to use as the header.
In order to interact with the calendar in your custom header component, you can inject the parent
`MatCalendar` in the constructor. To make sure your header stays in sync with the calendar,
subscribe to the `stateChanges` observable of the calendar and mark your header component for change
detection.
<!-- example(datepicker-custom-header) -->
#### Localizing labels and messages
The various text strings used by the datepicker are provided through `MatDatepickerIntl`.
Localization of these messages can be done by providing a subclass with translated values in your
app config.
```ts
bootstrapApplication(MyApp, {
providers: [
{provide: MatDatepickerIntl, useClass: MyIntl},
provideNativeDateAdapter(),
],
});
```
#### Highlighting specific dates
If you want to apply one or more CSS classes to some dates in the calendar (e.g. to highlight a
holiday), you can do so with the `dateClass` input. It accepts a function which will be called
with each of the dates in the calendar and will apply any classes that are returned. The return
value can be anything that is accepted by `ngClass`.
<!-- example(datepicker-date-class) -->
### Accessibility
The `MatDatepicker` pop-up uses the `role="dialog"` interaction pattern. This dialog then contains
multiple controls, the most prominent being the calendar itself. This calendar implements the
`role="grid"` interaction pattern.
Always enable [_confirmation action buttons_](#confirmation-action-buttons). This allows assistive
technology users to explicitly confirm their selection before committing a value.
The `MatDatepickerInput` and `MatDatepickerToggle` directives both apply the `aria-haspopup`
attribute to the native input and button elements, respectively.
`MatDatepickerIntl` includes strings that are used for `aria-label` attributes. Always provide
the datepicker text input a meaningful label via `<mat-label>`, `aria-label`, `aria-labelledby` or
`MatDatepickerIntl`.
Always communicate the date format (e.g. 'MM/DD/YYYY'). This can be accomplished using `<mat-hint>`
or by providing an additional label adjacent to the form field.
`MatDatepickerInput` adds <kbd>>Alt</kbd> + <kbd>Down Arrow</kbd> as a keyboard short to open the
datepicker pop-up. However, ChromeOS intercepts this key combination at the OS level such that the
browser only receives a `PageDown` key event. Because of this behavior, you should always include an
additional means of opening the pop-up, such as `MatDatepickerToggle`.
`MatDatepickerToggle` must be included along with `MatDatepicker` for optimal mobile a11y
compatibility. Mobile screen reader users currently do not have a way to trigger the datepicker
dialog without the icon button present.
#### Keyboard interaction
The datepicker supports the following keyboard shortcuts:
| Keyboard Shortcut | Action |
| -------------------------------------- | ------------------------- |
| <kbd>Alt</kbd> + <kbd>Down Arrow</kbd> | Open the calendar pop-up |
| <kbd>Escape</kbd> | Close the calendar pop-up |
In month view:
| Shortcut | Action |
| ------------------------------------- | ---------------------------------------- |
| <kbd>Left Arrow</kbd> | Go to previous day |
| <kbd>Right Arrow</kbd> | Go to next day |
| <kbd>Up Arrow</kbd> | Go to same day in the previous week |
| <kbd>Down Arrow</kbd> | Go to same day in the next week |
| <kbd>Home</kbd> | Go to the first day of the month |
| <kbd>End</kbd> | Go to the last day of the month |
| <kbd>Page up</kbd> | Go to the same day in the previous month |
| <kbd>Alt</kbd> + <kbd>Page up</kbd> | Go to the same day in the previous year |
| <kbd>Page Down</kbd> | Go to the same day in the next month |
| <kbd>Alt</kbd> + <kbd>Page Down</kbd> | Go to the same day in the next year |
| <kbd>Enter</kbd> | Select current date |
In year view:
| Shortcut | Action |
| ------------------------------------- | ----------------------------------------- |
| <kbd>Left Arrow</kbd> | Go to previous month |
| <kbd>Right Arrow</kbd> | Go to next month |
| <kbd>Up Arrow</kbd> | Go up a row (back 4 months) |
| <kbd>Down Arrow</kbd> | Go down a row (forward 4 months) |
| <kbd>Home</kbd> | Go to the first month of the year |
| <kbd>End</kbd> | Go to the last month of the year |
| <kbd>Page Up</kbd> | Go to the same month in the previous year |
| <kbd>Alt</kbd> + <kbd>Page up</kbd> | Go to the same month 10 years back |
| <kbd>Page Down</kbd> | Go to the same month in the next year |
| <kbd>Alt</kbd> + <kbd>Page Down</kbd> | Go to the same month 10 years forward |
| <kbd>Enter</kbd> | Select current month |
In multi-year view:
| Shortcut | Action |
| ------------------------------------- | ----------------------------------------- |
| <kbd>Left Arrow</kbd> | Go to previous year |
| <kbd>Right Arrow</kbd> | Go to next year |
| <kbd>Up Arrow</kbd> | Go up a row (back 4 years) |
| <kbd>Down Arrow</kbd> | Go down a row (forward 4 years) |
| <kbd>Home</kbd> | Go to the first year in the current range |
| <kbd>End</kbd> | Go to the last year in the current range |
| <kbd>Page up</kbd> | Go back 24 years |
| <kbd>Alt</kbd> + <kbd>Page up</kbd> | Go back 240 years |
| <kbd>Page Down</kbd> | Go forward 24 years |
| <kbd>Alt</kbd> + <kbd>Page Down</kbd> | Go forward 240 years |
| <kbd>Enter</kbd> | Select current year |
| {
"end_byte": 28364,
"start_byte": 20137,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md"
} |
components/src/material/datepicker/datepicker.md_28364_29486 | ### Troubleshooting
#### Error: MatDatepicker: No provider found for DateAdapter/MAT_DATE_FORMATS
This error is thrown if you have not provided all of the injectables the datepicker needs to work.
The easiest way to resolve this is to add `provideNativeDateAdapter` or `provideMomentDateAdapter`
to your app config. See
[_Choosing a date implementation_](#choosing-a-date-implementation-and-date-format-settings)) for
more information.
#### Error: A MatDatepicker can only be associated with a single input
This error is thrown if more than one `<input>` tries to claim ownership over the same
`<mat-datepicker>` (via the `matDatepicker` attribute on the input). A datepicker can only be
associated with a single input.
#### Error: Attempted to open an MatDatepicker with no associated input.
This error occurs if your `<mat-datepicker>` is not associated with any `<input>`. To associate an
input with your datepicker, create a template reference for the datepicker and assign it to the
`matDatepicker` attribute on the input:
```html
<input [matDatepicker]="picker">
<mat-datepicker #picker></mat-datepicker>
```
| {
"end_byte": 29486,
"start_byte": 28364,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md"
} |
components/src/material/datepicker/date-range-input.ts_0_2359 | /**
* @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 {CdkMonitorFocus, FocusOrigin} from '@angular/cdk/a11y';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ElementRef,
Input,
OnChanges,
OnDestroy,
SimpleChanges,
ViewEncapsulation,
booleanAttribute,
signal,
inject,
} from '@angular/core';
import {ControlContainer, NgControl, Validators} from '@angular/forms';
import {DateAdapter, ThemePalette} from '@angular/material/core';
import {MAT_FORM_FIELD, MatFormFieldControl} from '@angular/material/form-field';
import {Subject, Subscription, merge} from 'rxjs';
import {
MAT_DATE_RANGE_INPUT_PARENT,
MatDateRangeInputParent,
MatEndDate,
MatStartDate,
} from './date-range-input-parts';
import {MatDateRangePickerInput} from './date-range-picker';
import {DateRange, MatDateSelectionModel} from './date-selection-model';
import {MatDatepickerControl, MatDatepickerPanel} from './datepicker-base';
import {createMissingDateImplError} from './datepicker-errors';
import {DateFilterFn, _MatFormFieldPartial, dateInputsHaveChanged} from './datepicker-input-base';
let nextUniqueId = 0;
@Component({
selector: 'mat-date-range-input',
templateUrl: 'date-range-input.html',
styleUrl: 'date-range-input.css',
exportAs: 'matDateRangeInput',
host: {
'class': 'mat-date-range-input',
'[class.mat-date-range-input-hide-placeholders]': '_shouldHidePlaceholders()',
'[class.mat-date-range-input-required]': 'required',
'[attr.id]': 'id',
'role': 'group',
'[attr.aria-labelledby]': '_getAriaLabelledby()',
'[attr.aria-describedby]': '_ariaDescribedBy',
// Used by the test harness to tie this input to its calendar. We can't depend on
// `aria-owns` for this, because it's only defined while the calendar is open.
'[attr.data-mat-calendar]': 'rangePicker ? rangePicker.id : null',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [
{provide: MatFormFieldControl, useExisting: MatDateRangeInput},
{provide: MAT_DATE_RANGE_INPUT_PARENT, useExisting: MatDateRangeInput},
],
imports: [CdkMonitorFocus],
})
export | {
"end_byte": 2359,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.ts"
} |
components/src/material/datepicker/date-range-input.ts_2360_10119 | class MatDateRangeInput<D>
implements
MatFormFieldControl<DateRange<D>>,
MatDatepickerControl<D>,
MatDateRangeInputParent<D>,
MatDateRangePickerInput<D>,
AfterContentInit,
OnChanges,
OnDestroy
{
private _changeDetectorRef = inject(ChangeDetectorRef);
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _formField = inject<_MatFormFieldPartial>(MAT_FORM_FIELD, {optional: true});
private _closedSubscription = Subscription.EMPTY;
private _openedSubscription = Subscription.EMPTY;
/** Current value of the range input. */
get value() {
return this._model ? this._model.selection : null;
}
/** Unique ID for the group. */
id = `mat-date-range-input-${nextUniqueId++}`;
/** Whether the control is focused. */
focused = false;
/** Whether the control's label should float. */
get shouldLabelFloat(): boolean {
return this.focused || !this.empty;
}
/** Name of the form control. */
controlType = 'mat-date-range-input';
/**
* Implemented as a part of `MatFormFieldControl`.
* Set the placeholder attribute on `matStartDate` and `matEndDate`.
* @docs-private
*/
get placeholder() {
const start = this._startInput?._getPlaceholder() || '';
const end = this._endInput?._getPlaceholder() || '';
return start || end ? `${start} ${this.separator} ${end}` : '';
}
/** The range picker that this input is associated with. */
@Input()
get rangePicker() {
return this._rangePicker;
}
set rangePicker(rangePicker: MatDatepickerPanel<MatDatepickerControl<D>, DateRange<D>, D>) {
if (rangePicker) {
this._model = rangePicker.registerInput(this);
this._rangePicker = rangePicker;
this._closedSubscription.unsubscribe();
this._openedSubscription.unsubscribe();
this._ariaOwns.set(this.rangePicker.opened ? rangePicker.id : null);
this._closedSubscription = rangePicker.closedStream.subscribe(() => {
this._startInput?._onTouched();
this._endInput?._onTouched();
this._ariaOwns.set(null);
});
this._openedSubscription = rangePicker.openedStream.subscribe(() => {
this._ariaOwns.set(rangePicker.id);
});
this._registerModel(this._model!);
}
}
private _rangePicker: MatDatepickerPanel<MatDatepickerControl<D>, DateRange<D>, D>;
/** The id of the panel owned by this input. */
_ariaOwns = signal<string | null>(null);
/** Whether the input is required. */
@Input({transform: booleanAttribute})
get required(): boolean {
return (
this._required ??
(this._isTargetRequired(this) ||
this._isTargetRequired(this._startInput) ||
this._isTargetRequired(this._endInput)) ??
false
);
}
set required(value: boolean) {
this._required = value;
}
private _required: boolean | undefined;
/** Function that can be used to filter out dates within the date range picker. */
@Input()
get dateFilter() {
return this._dateFilter;
}
set dateFilter(value: DateFilterFn<D>) {
const start = this._startInput;
const end = this._endInput;
const wasMatchingStart = start && start._matchesFilter(start.value);
const wasMatchingEnd = end && end._matchesFilter(start.value);
this._dateFilter = value;
if (start && start._matchesFilter(start.value) !== wasMatchingStart) {
start._validatorOnChange();
}
if (end && end._matchesFilter(end.value) !== wasMatchingEnd) {
end._validatorOnChange();
}
}
private _dateFilter: DateFilterFn<D>;
/** The minimum valid date. */
@Input()
get min(): D | null {
return this._min;
}
set min(value: D | null) {
const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
if (!this._dateAdapter.sameDate(validValue, this._min)) {
this._min = validValue;
this._revalidate();
}
}
private _min: D | null;
/** The maximum valid date. */
@Input()
get max(): D | null {
return this._max;
}
set max(value: D | null) {
const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
if (!this._dateAdapter.sameDate(validValue, this._max)) {
this._max = validValue;
this._revalidate();
}
}
private _max: D | null;
/** Whether the input is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._startInput && this._endInput
? this._startInput.disabled && this._endInput.disabled
: this._groupDisabled;
}
set disabled(value: boolean) {
if (value !== this._groupDisabled) {
this._groupDisabled = value;
this.stateChanges.next(undefined);
}
}
_groupDisabled = false;
/** Whether the input is in an error state. */
get errorState(): boolean {
if (this._startInput && this._endInput) {
return this._startInput.errorState || this._endInput.errorState;
}
return false;
}
/** Whether the datepicker input is empty. */
get empty(): boolean {
const startEmpty = this._startInput ? this._startInput.isEmpty() : false;
const endEmpty = this._endInput ? this._endInput.isEmpty() : false;
return startEmpty && endEmpty;
}
/** Value for the `aria-describedby` attribute of the inputs. */
_ariaDescribedBy: string | null = null;
/** Date selection model currently registered with the input. */
private _model: MatDateSelectionModel<DateRange<D>> | undefined;
/** Separator text to be shown between the inputs. */
@Input() separator = '–';
/** Start of the comparison range that should be shown in the calendar. */
@Input() comparisonStart: D | null = null;
/** End of the comparison range that should be shown in the calendar. */
@Input() comparisonEnd: D | null = null;
@ContentChild(MatStartDate) _startInput: MatStartDate<D>;
@ContentChild(MatEndDate) _endInput: MatEndDate<D>;
/**
* Implemented as a part of `MatFormFieldControl`.
* TODO(crisbeto): change type to `AbstractControlDirective` after #18206 lands.
* @docs-private
*/
ngControl: NgControl | null;
/** Emits when the input's state has changed. */
readonly stateChanges = new Subject<void>();
/**
* Disable the automatic labeling to avoid issues like #27241.
* @docs-private
*/
readonly disableAutomaticLabeling = true;
constructor(...args: unknown[]);
constructor() {
if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw createMissingDateImplError('DateAdapter');
}
// The datepicker module can be used both with MDC and non-MDC form fields. We have
// to conditionally add the MDC input class so that the range picker looks correctly.
if (this._formField?._elementRef.nativeElement.classList.contains('mat-mdc-form-field')) {
this._elementRef.nativeElement.classList.add(
'mat-mdc-input-element',
'mat-mdc-form-field-input-control',
'mdc-text-field__input',
);
}
// TODO(crisbeto): remove `as any` after #18206 lands.
this.ngControl = inject(ControlContainer, {optional: true, self: true}) as any;
}
/**
* Implemented as a part of `MatFormFieldControl`.
* @docs-private
*/
setDescribedByIds(ids: string[]): void {
this._ariaDescribedBy = ids.length ? ids.join(' ') : null;
}
/**
* Implemented as a part of `MatFormFieldControl`.
* @docs-private
*/
onContainerClick(): void {
if (!this.focused && !this.disabled) {
if (!this._model || !this._model.selection.start) {
this._startInput.focus();
} else {
this._endInput.focus();
}
}
}
| {
"end_byte": 10119,
"start_byte": 2360,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.ts"
} |
components/src/material/datepicker/date-range-input.ts_10123_14139 | AfterContentInit() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._startInput) {
throw Error('mat-date-range-input must contain a matStartDate input');
}
if (!this._endInput) {
throw Error('mat-date-range-input must contain a matEndDate input');
}
}
if (this._model) {
this._registerModel(this._model);
}
// We don't need to unsubscribe from this, because we
// know that the input streams will be completed on destroy.
merge(this._startInput.stateChanges, this._endInput.stateChanges).subscribe(() => {
this.stateChanges.next(undefined);
});
}
ngOnChanges(changes: SimpleChanges) {
if (dateInputsHaveChanged(changes, this._dateAdapter)) {
this.stateChanges.next(undefined);
}
}
ngOnDestroy() {
this._closedSubscription.unsubscribe();
this._openedSubscription.unsubscribe();
this.stateChanges.complete();
}
/** Gets the date at which the calendar should start. */
getStartValue(): D | null {
return this.value ? this.value.start : null;
}
/** Gets the input's theme palette. */
getThemePalette(): ThemePalette {
return this._formField ? this._formField.color : undefined;
}
/** Gets the element to which the calendar overlay should be attached. */
getConnectedOverlayOrigin(): ElementRef {
return this._formField ? this._formField.getConnectedOverlayOrigin() : this._elementRef;
}
/** Gets the ID of an element that should be used a description for the calendar overlay. */
getOverlayLabelId(): string | null {
return this._formField ? this._formField.getLabelId() : null;
}
/** Gets the value that is used to mirror the state input. */
_getInputMirrorValue(part: 'start' | 'end') {
const input = part === 'start' ? this._startInput : this._endInput;
return input ? input.getMirrorValue() : '';
}
/** Whether the input placeholders should be hidden. */
_shouldHidePlaceholders() {
return this._startInput ? !this._startInput.isEmpty() : false;
}
/** Handles the value in one of the child inputs changing. */
_handleChildValueChange() {
this.stateChanges.next(undefined);
this._changeDetectorRef.markForCheck();
}
/** Opens the date range picker associated with the input. */
_openDatepicker() {
if (this._rangePicker) {
this._rangePicker.open();
}
}
/** Whether the separate text should be hidden. */
_shouldHideSeparator() {
return (
(!this._formField ||
(this._formField.getLabelId() && !this._formField._shouldLabelFloat())) &&
this.empty
);
}
/** Gets the value for the `aria-labelledby` attribute of the inputs. */
_getAriaLabelledby() {
const formField = this._formField;
return formField && formField._hasFloatingLabel() ? formField._labelId : null;
}
_getStartDateAccessibleName(): string {
return this._startInput._getAccessibleName();
}
_getEndDateAccessibleName(): string {
return this._endInput._getAccessibleName();
}
/** Updates the focused state of the range input. */
_updateFocus(origin: FocusOrigin) {
this.focused = origin !== null;
this.stateChanges.next();
}
/** Re-runs the validators on the start/end inputs. */
private _revalidate() {
if (this._startInput) {
this._startInput._validatorOnChange();
}
if (this._endInput) {
this._endInput._validatorOnChange();
}
}
/** Registers the current date selection model with the start/end inputs. */
private _registerModel(model: MatDateSelectionModel<DateRange<D>>) {
if (this._startInput) {
this._startInput._registerModel(model);
}
if (this._endInput) {
this._endInput._registerModel(model);
}
}
/** Checks whether a specific range input directive is required. */
private _isTargetRequired(target: {ngControl: NgControl | null} | null): boolean | undefined {
return target?.ngControl?.control?.hasValidator(Validators.required);
}
}
| {
"end_byte": 14139,
"start_byte": 10123,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.ts"
} |
components/src/material/datepicker/_datepicker-theme.scss_0_7005 | @use 'sass:color';
@use 'sass:map';
@use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/tokens/token-utils';
@use '../core/style/sass-utils';
@use '../core/typography/typography';
@use '../button/icon-button-theme';
// TODO(crisbeto): these variables aren't used anymore and should be removed.
$selected-today-box-shadow-width: 1px;
$selected-fade-amount: 0.6;
$range-fade-amount: 0.2;
$today-fade-amount: 0.2;
$calendar-body-font-size: 13px !default;
$calendar-weekday-table-font-size: 11px !default;
@mixin _calendar-color($theme, $palette-name) {
$palette-color: inspection.get-theme-color($theme, $palette-name);
$range-color: tokens-mat-datepicker.private-get-range-background-color($palette-color);
$range-tokens: tokens-mat-datepicker.get-range-color-tokens($range-color);
$calendar-tokens: tokens-mat-datepicker.private-get-calendar-color-palette-color-tokens(
$theme,
$palette-name
);
@include token-utils.create-token-values(
tokens-mat-datepicker.$prefix,
map.merge($calendar-tokens, $range-tokens)
);
}
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-datepicker.
/// @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-mat-datepicker.$prefix,
tokens-mat-datepicker.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-datepicker.
/// @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 main selection: 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-mat-datepicker.$prefix,
tokens-mat-datepicker.get-color-tokens($theme)
);
}
.mat-datepicker-content {
&.mat-accent {
@include _calendar-color($theme, accent);
}
&.mat-warn {
@include _calendar-color($theme, warn);
}
}
.mat-datepicker-toggle-active {
&.mat-accent {
$accent-tokens: tokens-mat-datepicker.private-get-toggle-color-palette-color-tokens(
$theme,
accent
);
@include token-utils.create-token-values(tokens-mat-datepicker.$prefix, $accent-tokens);
}
&.mat-warn {
$warn-tokens: tokens-mat-datepicker.private-get-toggle-color-palette-color-tokens(
$theme,
warn
);
@include token-utils.create-token-values(tokens-mat-datepicker.$prefix, $warn-tokens);
}
}
}
}
/// Outputs typography theme styles for the mat-datepicker.
/// @param {Map} $theme The theme to generate typography styles for.
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-datepicker.$prefix,
tokens-mat-datepicker.get-typography-tokens($theme)
);
}
}
}
@mixin date-range-colors(
$range-color,
$comparison-color: tokens-mat-datepicker.$private-default-comparison-color,
$overlap-color: tokens-mat-datepicker.$private-default-overlap-color,
$overlap-selected-color:
tokens-mat-datepicker.private-get-default-overlap-selected-color($overlap-color)
) {
$tokens: tokens-mat-datepicker.get-range-color-tokens(
$range-color: $range-color,
$comparison-color: $comparison-color,
$overlap-color: $overlap-color,
$overlap-selected-color: $overlap-selected-color,
);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(tokens-mat-datepicker.$prefix, $tokens);
}
}
/// Outputs density theme styles for the mat-datepicker.
/// @param {Map} $theme The theme to generate density styles for.
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
// TODO(crisbeto): move this into the structural styles
// once the icon button density is switched to tokens.
// Regardless of the user-passed density, we want the calendar
// previous/next buttons to remain at density -2
.mat-calendar-controls {
@include icon-button-theme.density(-2);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-datepicker.$prefix,
tokens: tokens-mat-datepicker.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-datepicker.
/// @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 main selection: 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-datepicker') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mat-datepicker-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-datepicker.$prefix,
$options...
);
@include token-utils.create-token-values(tokens-mat-datepicker.$prefix, $mat-datepicker-tokens);
}
| {
"end_byte": 7005,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/_datepicker-theme.scss"
} |
components/src/material/datepicker/calendar.scss_0_5434 | @use '@angular/cdk';
@use '../core/style/layout-common';
@use '../core/focus-indicators/private';
@use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/tokens/token-utils';
$calendar-padding: 8px !default;
$calendar-header-divider-width: 1px !default;
$calendar-controls-vertical-padding: 5%;
// We use the same padding as the month / year label, but subtract 16px since there is padding
// between the edge of the button and the text. This ensures that the button text lines up with
// the month / year label text.
$calendar-controls-side-margin: calc(33% / 7 - 16px);
$calendar-arrow-size: 5px !default;
$calendar-arrow-disabled-opacity: 0.5 !default;
// Values chosen to approximate https://material.io/icons/#ic_navigate_before and
// https://material.io/icons/#ic_navigate_next as closely as possible.
$calendar-prev-next-icon-border-width: 2px;
$calendar-prev-next-icon-margin: 15.5px;
$calendar-prev-icon-transform: translateX(2px) rotate(-45deg);
$calendar-next-icon-transform: translateX(-2px) rotate(45deg);
$_tokens: tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots();
.mat-calendar {
display: block;
// Prevents layout issues if the line height bleeds in from the body (see #29756).
line-height: normal;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(font-family, calendar-text-font);
@include token-utils.create-token-slot(font-size, calendar-text-size);
}
}
.mat-calendar-header {
padding: $calendar-padding $calendar-padding 0 $calendar-padding;
}
.mat-calendar-content {
padding: 0 $calendar-padding $calendar-padding $calendar-padding;
outline: none;
}
.mat-calendar-controls {
display: flex;
align-items: center;
margin: $calendar-controls-vertical-padding $calendar-controls-side-margin;
}
.mat-calendar-spacer {
flex: 1 1 auto;
}
.mat-calendar-period-button {
min-width: 0;
margin: 0 8px;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(font-size, calendar-period-button-text-size);
@include token-utils.create-token-slot(font-weight, calendar-period-button-text-weight);
@include token-utils.create-token-slot(--mdc-text-button-label-text-color,
calendar-period-button-text-color);
}
}
.mat-calendar-arrow {
display: inline-block;
width: $calendar-arrow-size * 2;
height: $calendar-arrow-size;
margin: 0 0 0 $calendar-arrow-size;
vertical-align: middle;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(fill, calendar-period-button-icon-color);
}
&.mat-calendar-invert {
transform: rotate(180deg);
}
[dir='rtl'] & {
margin: 0 $calendar-arrow-size 0 0;
}
@include cdk.high-contrast {
// Setting the fill to `currentColor` doesn't work on Chromium browsers.
fill: CanvasText;
}
}
.mat-calendar-previous-button,
.mat-calendar-next-button {
position: relative;
@include token-utils.use-tokens($_tokens...) {
// Needs need a bit more specificity to avoid being overwritten by the .mat-icon-button.
.mat-datepicker-content &:not(.mat-mdc-button-disabled) {
@include token-utils.create-token-slot(color, calendar-navigation-button-icon-color);
}
}
&::after {
@include layout-common.fill;
content: '';
margin: $calendar-prev-next-icon-margin;
border: 0 solid currentColor;
border-top-width: $calendar-prev-next-icon-border-width;
}
[dir='rtl'] & {
transform: rotate(180deg);
}
}
.mat-calendar-previous-button::after {
border-left-width: $calendar-prev-next-icon-border-width;
transform: $calendar-prev-icon-transform;
}
.mat-calendar-next-button::after {
border-right-width: $calendar-prev-next-icon-border-width;
transform: $calendar-next-icon-transform;
}
.mat-calendar-table {
border-spacing: 0;
border-collapse: collapse;
width: 100%;
}
.mat-calendar-table-header th {
text-align: center;
padding: 0 0 $calendar-padding 0;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, calendar-header-text-color);
@include token-utils.create-token-slot(font-size, calendar-header-text-size);
@include token-utils.create-token-slot(font-weight, calendar-header-text-weight);
}
}
.mat-calendar-table-header-divider {
position: relative;
height: $calendar-header-divider-width;
// We use an absolutely positioned pseudo-element as the divider line for the table header so we
// can extend it all the way to the edge of the calendar.
&::after {
content: '';
position: absolute;
top: 0;
left: -$calendar-padding;
right: -$calendar-padding;
height: $calendar-header-divider-width;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(background, calendar-header-divider-color);
}
}
}
// For the calendar element, default inset/offset values are necessary to ensure that
// the focus indicator is sufficiently contrastive and renders appropriately.
.mat-calendar-body-cell-content::before {
$border-width: var(--mat-focus-indicator-border-width, #{private.$default-border-width});
$offset: calc(#{$border-width} + 3px);
margin: calc(#{$offset} * -1);
}
// For calendar cells, render the focus indicator when the parent cell is
// focused.
.mat-calendar-body-cell:focus .mat-focus-indicator::before {
content: '';
}
| {
"end_byte": 5434,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.scss"
} |
components/src/material/datepicker/calendar-body.spec.ts_0_5584 | import {
dispatchFakeEvent,
dispatchMouseEvent,
dispatchTouchEvent,
} from '@angular/cdk/testing/private';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatCalendarBody, MatCalendarCell, MatCalendarUserEvent} from './calendar-body';
describe('MatCalendarBody', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatCalendarBody, StandardCalendarBody, RangeCalendarBody],
});
}));
describe('standard calendar body', () => {
let fixture: ComponentFixture<StandardCalendarBody>;
let testComponent: StandardCalendarBody;
let calendarBodyNativeElement: Element;
let rowEls: Element[];
let labelEls: Element[];
let cellEls: Element[];
function refreshElementLists() {
rowEls = Array.from(calendarBodyNativeElement.querySelectorAll('tr'));
labelEls = Array.from(calendarBodyNativeElement.querySelectorAll('.mat-calendar-body-label'));
cellEls = Array.from(calendarBodyNativeElement.querySelectorAll('.mat-calendar-body-cell'));
}
beforeEach(() => {
fixture = TestBed.createComponent(StandardCalendarBody);
fixture.detectChanges();
const calendarBodyDebugElement = fixture.debugElement.query(By.directive(MatCalendarBody))!;
calendarBodyNativeElement = calendarBodyDebugElement.nativeElement;
testComponent = fixture.componentInstance;
refreshElementLists();
});
it('creates body', () => {
expect(rowEls.length).toBe(3);
expect(labelEls.length).toBe(1);
expect(cellEls.length).toBe(14);
});
it('highlights today', () => {
const todayCells = calendarBodyNativeElement.querySelectorAll('.mat-calendar-body-today')!;
expect(todayCells.length).toBe(1);
const todayCell = todayCells[0];
expect(todayCell).not.toBeNull();
expect(todayCell.textContent!.trim()).toBe('3');
});
it('sets aria-current="date" on today', () => {
const todayCells = calendarBodyNativeElement.querySelectorAll(
'[aria-current="date"] .mat-calendar-body-today',
)!;
expect(todayCells.length).toBe(1);
const todayCell = todayCells[0];
expect(todayCell).not.toBeNull();
expect(todayCell.textContent!.trim()).toBe('3');
});
it('does not highlight today if today is not within the scope', () => {
testComponent.todayValue = 100000;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const todayCell = calendarBodyNativeElement.querySelector('.mat-calendar-body-today')!;
expect(todayCell).toBeNull();
});
it('does not set aria-current="date" on any cell if today is not ' + 'the scope', () => {
testComponent.todayValue = 100000;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const todayCell = calendarBodyNativeElement.querySelector(
'[aria-current="date"] .mat-calendar-body-today',
)!;
expect(todayCell).toBeNull();
});
it('highlights selected', () => {
const selectedCell = calendarBodyNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedCell).not.toBeNull();
expect(selectedCell.innerHTML.trim()).toBe('4');
});
it('should set aria-pressed correctly', () => {
const pressedCells = cellEls.filter(c => c.getAttribute('aria-pressed') === 'true');
const depressedCells = cellEls.filter(c => c.getAttribute('aria-pressed') === 'false');
expect(pressedCells.length).withContext('Expected one cell to be marked as pressed.').toBe(1);
expect(depressedCells.length)
.withContext('Expected remaining cells to be marked as not pressed.')
.toBe(cellEls.length - 1);
});
it('places label in first row if space is available', () => {
testComponent.rows[0] = testComponent.rows[0].slice(3);
testComponent.rows = testComponent.rows.slice();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
refreshElementLists();
expect(rowEls.length).toBe(2);
expect(labelEls.length).toBe(1);
expect(cellEls.length).toBe(11);
expect(rowEls[0].firstElementChild!.classList)
.withContext('first cell should be the label')
.toContain('mat-calendar-body-label');
expect(labelEls[0].getAttribute('colspan')).toBe('3');
});
it('cell should be selected on click', () => {
const todayElement = calendarBodyNativeElement.querySelector(
'.mat-calendar-body-today',
) as HTMLElement;
todayElement.click();
fixture.detectChanges();
expect(todayElement.classList)
.withContext('today should be selected')
.toContain('mat-calendar-body-selected');
});
it('should mark active date', () => {
expect((cellEls[10] as HTMLElement).innerText.trim()).toBe('11');
expect(cellEls[10].classList).toContain('mat-calendar-body-active');
});
it('should set a class on even dates', () => {
expect((cellEls[0] as HTMLElement).innerText.trim()).toBe('1');
expect((cellEls[1] as HTMLElement).innerText.trim()).toBe('2');
expect(cellEls[0].classList).not.toContain('even');
expect(cellEls[1].classList).toContain('even');
});
it('should have a focus indicator', () => {
expect(cellEls.every(element => !!element.querySelector('.mat-focus-indicator'))).toBe(true);
});
});
describe('range calendar body', | {
"end_byte": 5584,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.spec.ts"
} |
components/src/material/datepicker/calendar-body.spec.ts_5585_14901 | () => {
const startClass = 'mat-calendar-body-range-start';
const inRangeClass = 'mat-calendar-body-in-range';
const endClass = 'mat-calendar-body-range-end';
const comparisonStartClass = 'mat-calendar-body-comparison-start';
const inComparisonClass = 'mat-calendar-body-in-comparison-range';
const comparisonEndClass = 'mat-calendar-body-comparison-end';
const bridgeStart = 'mat-calendar-body-comparison-bridge-start';
const bridgeEnd = 'mat-calendar-body-comparison-bridge-end';
const previewStartClass = 'mat-calendar-body-preview-start';
const inPreviewClass = 'mat-calendar-body-in-preview';
const previewEndClass = 'mat-calendar-body-preview-end';
let fixture: ComponentFixture<RangeCalendarBody>;
let testComponent: RangeCalendarBody;
let cells: HTMLElement[];
beforeEach(() => {
fixture = TestBed.createComponent(RangeCalendarBody);
fixture.detectChanges();
testComponent = fixture.componentInstance;
cells = Array.from(fixture.nativeElement.querySelectorAll('.mat-calendar-body-cell'));
});
it('should render a range', () => {
testComponent.startValue = 1;
testComponent.endValue = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).toContain(startClass);
expect(cells[1].classList).toContain(inRangeClass);
expect(cells[2].classList).toContain(inRangeClass);
expect(cells[3].classList).toContain(inRangeClass);
expect(cells[4].classList).toContain(endClass);
});
it('should render a comparison range', () => {
testComponent.comparisonStart = 1;
testComponent.comparisonEnd = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).toContain(comparisonStartClass);
expect(cells[1].classList).toContain(inComparisonClass);
expect(cells[2].classList).toContain(inComparisonClass);
expect(cells[3].classList).toContain(inComparisonClass);
expect(cells[4].classList).toContain(comparisonEndClass);
});
it('should be able to render two completely overlapping ranges', () => {
testComponent.startValue = testComponent.comparisonStart = 1;
testComponent.endValue = testComponent.comparisonEnd = 5;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).toContain(startClass);
expect(cells[0].classList).toContain(comparisonStartClass);
expect(cells[1].classList).toContain(inRangeClass);
expect(cells[1].classList).toContain(inComparisonClass);
expect(cells[2].classList).toContain(inRangeClass);
expect(cells[2].classList).toContain(inComparisonClass);
expect(cells[3].classList).toContain(inRangeClass);
expect(cells[3].classList).toContain(inComparisonClass);
expect(cells[4].classList).toContain(endClass);
expect(cells[4].classList).toContain(comparisonEndClass);
});
it(
'should mark a cell as a start bridge if it is the end of the main range ' +
'and the start of the comparison',
() => {
testComponent.startValue = 1;
testComponent.endValue = 5;
testComponent.comparisonStart = 5;
testComponent.comparisonEnd = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[4].classList).toContain(bridgeStart);
},
);
it('should not mark a cell as a start bridge if there is no end range value', () => {
testComponent.startValue = 1;
testComponent.endValue = null;
testComponent.comparisonStart = 5;
testComponent.comparisonEnd = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(bridgeStart))).toBe(false);
});
it(
'should mark a cell as an end bridge if it is the start of the main range ' +
'and the end of the comparison',
() => {
testComponent.comparisonStart = 1;
testComponent.comparisonEnd = 5;
testComponent.startValue = 5;
testComponent.endValue = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[4].classList).toContain(bridgeEnd);
},
);
it('should not mark a cell as an end bridge if there is no end range value', () => {
testComponent.comparisonStart = 1;
testComponent.comparisonEnd = 5;
testComponent.startValue = 5;
testComponent.endValue = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(bridgeEnd))).toBe(false);
});
it('should be able to show a main range inside a comparison range', () => {
testComponent.comparisonStart = 1;
testComponent.comparisonEnd = 5;
testComponent.startValue = 2;
testComponent.endValue = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).toContain(comparisonStartClass);
expect(cells[1].classList).toContain(inComparisonClass);
expect(cells[1].classList).toContain(startClass);
expect(cells[2].classList).toContain(inComparisonClass);
expect(cells[2].classList).toContain(inRangeClass);
expect(cells[3].classList).toContain(inComparisonClass);
expect(cells[3].classList).toContain(endClass);
expect(cells[4].classList).toContain(comparisonEndClass);
});
it('should be able to show a comparison range inside a main range', () => {
testComponent.startValue = 1;
testComponent.endValue = 5;
testComponent.comparisonStart = 2;
testComponent.comparisonEnd = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).toContain(startClass);
expect(cells[1].classList).toContain(inRangeClass);
expect(cells[1].classList).toContain(comparisonStartClass);
expect(cells[2].classList).toContain(inRangeClass);
expect(cells[2].classList).toContain(inComparisonClass);
expect(cells[3].classList).toContain(inRangeClass);
expect(cells[3].classList).toContain(comparisonEndClass);
expect(cells[4].classList).toContain(endClass);
});
it('should be able to show a range that is larger than the calendar', () => {
testComponent.startValue = -10;
testComponent.endValue = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.every(cell => cell.classList.contains(inRangeClass))).toBe(true);
expect(cells.some(cell => cell.classList.contains(startClass))).toBe(false);
expect(cells.some(cell => cell.classList.contains(endClass))).toBe(false);
});
it('should be able to show a comparison range that is larger than the calendar', () => {
testComponent.comparisonStart = -10;
testComponent.comparisonEnd = 100;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.every(cell => cell.classList.contains(inComparisonClass))).toBe(true);
expect(cells.some(cell => cell.classList.contains(comparisonStartClass))).toBe(false);
expect(cells.some(cell => cell.classList.contains(comparisonEndClass))).toBe(false);
});
it('should be able to show a range that starts before the beginning of the calendar', () => {
testComponent.startValue = -10;
testComponent.endValue = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(startClass))).toBe(false);
expect(cells[0].classList).toContain(inRangeClass);
expect(cells[1].classList).toContain(endClass);
});
it('should be able to show a comparison range that starts before the beginning of the calendar', () => {
testComponent.comparisonStart = -10;
testComponent.comparisonEnd = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(comparisonStartClass))).toBe(false);
expect(cells[0].classList).toContain(inComparisonClass);
expect(cells[1].classList).toContain(comparisonEndClass);
});
it('should be able to show a range that ends after the end of the calendar', () => {
testComponent.startValue = 27;
testComponent.endValue = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(endClass))).toBe(false);
expect(cells[26].classList).toContain(startClass);
expect(cells[27].classList).toContain(inRangeClass);
});
it('should be able to show a comparison range that ends after the end of the calendar', () => {
testComponent.comparisonStart = 27;
testComponent.comparisonEnd = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(comparisonEndClass))).toBe(false);
expect(cells[26].classList).toContain(comparisonStartClass);
expect(cells[27].classList).toContain(inComparisonClass);
}); | {
"end_byte": 14901,
"start_byte": 5585,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.spec.ts"
} |
components/src/material/datepicker/calendar-body.spec.ts_14907_23745 | it('should be able to show a range that ends after the end of the calendar', () => {
testComponent.startValue = 27;
testComponent.endValue = 50;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(endClass))).toBe(false);
expect(cells[26].classList).toContain(startClass);
expect(cells[27].classList).toContain(inRangeClass);
});
it('should not to mark a date as both the start and end', () => {
testComponent.startValue = 1;
testComponent.endValue = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).not.toContain(startClass);
expect(cells[0].classList).not.toContain(inRangeClass);
expect(cells[0].classList).not.toContain(endClass);
});
it('should not mark a date as both the comparison start and end', () => {
testComponent.comparisonStart = 1;
testComponent.comparisonEnd = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).not.toContain(comparisonStartClass);
expect(cells[0].classList).not.toContain(inComparisonClass);
expect(cells[0].classList).not.toContain(comparisonEndClass);
});
it('should not mark a date as the range end if it comes before the start', () => {
testComponent.startValue = 2;
testComponent.endValue = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).not.toContain(endClass);
expect(cells[0].classList).not.toContain(inRangeClass);
expect(cells[1].classList).not.toContain(startClass);
});
it('should not mark a date as the comparison range end if it comes before the start', () => {
testComponent.comparisonStart = 2;
testComponent.comparisonEnd = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells[0].classList).not.toContain(comparisonEndClass);
expect(cells[0].classList).not.toContain(inComparisonClass);
expect(cells[1].classList).not.toContain(comparisonStartClass);
});
it('should not show a range if there is no start', () => {
testComponent.startValue = null;
testComponent.endValue = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(inRangeClass))).toBe(false);
expect(cells.some(cell => cell.classList.contains(endClass))).toBe(false);
});
it('should not show a comparison range if there is no start', () => {
testComponent.comparisonStart = null;
testComponent.comparisonEnd = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(inComparisonClass))).toBe(false);
expect(cells.some(cell => cell.classList.contains(comparisonEndClass))).toBe(false);
});
it('should not show a comparison range if there is no end', () => {
testComponent.comparisonStart = 10;
testComponent.comparisonEnd = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(inComparisonClass))).toBe(false);
expect(cells.some(cell => cell.classList.contains(comparisonEndClass))).toBe(false);
});
it('should preview the selected range after the user clicks on a start and hovers away', () => {
cells[2].click();
fixture.detectChanges();
dispatchMouseEvent(cells[5], 'mouseenter');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
// Go a few cells ahead.
dispatchMouseEvent(cells[7], 'mouseenter');
fixture.detectChanges();
expect(cells[5].classList).not.toContain(previewEndClass);
expect(cells[5].classList).toContain(inPreviewClass);
expect(cells[6].classList).toContain(inPreviewClass);
expect(cells[7].classList).toContain(previewEndClass);
// Go back a few cells.
dispatchMouseEvent(cells[4], 'mouseenter');
fixture.detectChanges();
expect(cells[5].classList).not.toContain(inPreviewClass);
expect(cells[6].classList).not.toContain(inPreviewClass);
expect(cells[7].classList).not.toContain(previewEndClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(previewEndClass);
});
it('should preview the selected range after the user selects a start and moves focus away', () => {
cells[2].click();
fixture.detectChanges();
dispatchFakeEvent(cells[5], 'focus');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
// Go a few cells ahead.
dispatchFakeEvent(cells[7], 'focus');
fixture.detectChanges();
expect(cells[5].classList).not.toContain(previewEndClass);
expect(cells[5].classList).toContain(inPreviewClass);
expect(cells[6].classList).toContain(inPreviewClass);
expect(cells[7].classList).toContain(previewEndClass);
// Go back a few cells.
dispatchFakeEvent(cells[4], 'focus');
fixture.detectChanges();
expect(cells[5].classList).not.toContain(inPreviewClass);
expect(cells[6].classList).not.toContain(inPreviewClass);
expect(cells[7].classList).not.toContain(previewEndClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(previewEndClass);
});
it('should not be able to extend the range before the start', () => {
cells[5].click();
fixture.detectChanges();
dispatchMouseEvent(cells[2], 'mouseenter');
fixture.detectChanges();
expect(cells[5].classList).not.toContain(startClass);
expect(cells[5].classList).not.toContain(previewStartClass);
expect(cells.some(cell => cell.classList.contains(inPreviewClass))).toBe(false);
});
it(
'should be able to show a range, starting before the beginning of the calendar, ' +
'while hovering',
() => {
fixture.componentInstance.startValue = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cells[2], 'mouseenter');
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(previewStartClass))).toBe(false);
expect(cells[0].classList).toContain(inPreviewClass);
expect(cells[1].classList).toContain(inPreviewClass);
expect(cells[2].classList).toContain(previewEndClass);
},
);
it(
'should be able to show a range, starting before the beginning of the calendar, ' +
'while moving focus',
() => {
fixture.componentInstance.startValue = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cells[2], 'focus');
fixture.detectChanges();
expect(cells.some(cell => cell.classList.contains(previewStartClass))).toBe(false);
expect(cells[0].classList).toContain(inPreviewClass);
expect(cells[1].classList).toContain(inPreviewClass);
expect(cells[2].classList).toContain(previewEndClass);
},
);
it('should remove the preview if the user moves their pointer away', () => {
cells[2].click();
fixture.detectChanges();
dispatchMouseEvent(cells[4], 'mouseenter');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(previewEndClass);
// Move the pointer away.
dispatchMouseEvent(cells[4], 'mouseleave');
fixture.detectChanges();
expect(cells[2].classList).not.toContain(previewStartClass);
expect(cells[3].classList).not.toContain(inPreviewClass);
expect(cells[4].classList).not.toContain(previewEndClass);
// Move the pointer back in to a different cell.
dispatchMouseEvent(cells[5], 'mouseenter');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
}); | {
"end_byte": 23745,
"start_byte": 14907,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.spec.ts"
} |
components/src/material/datepicker/calendar-body.spec.ts_23751_30749 | it('should remove the preview if the user moves their focus away', () => {
cells[2].click();
fixture.detectChanges();
dispatchFakeEvent(cells[4], 'focus');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(previewEndClass);
// Move the pointer away.
dispatchFakeEvent(cells[4], 'blur');
fixture.detectChanges();
expect(cells[2].classList).not.toContain(previewStartClass);
expect(cells[3].classList).not.toContain(inPreviewClass);
expect(cells[4].classList).not.toContain(previewEndClass);
// Move the pointer back in to a different cell.
dispatchFakeEvent(cells[5], 'focus');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
});
it('should mark a cell as being identical to the comparison range', () => {
testComponent.comparisonStart = testComponent.comparisonEnd = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const comparisonIdenticalCells: NodeListOf<HTMLElement> =
fixture.nativeElement.querySelectorAll('.mat-calendar-body-comparison-identical');
expect(comparisonIdenticalCells.length).toBe(1);
expect(cells[2].contains(comparisonIdenticalCells[0])).toBe(true);
expect(
cells.some(cell => {
const classList = cell.classList;
return (
classList.contains(startClass) ||
classList.contains(inRangeClass) ||
classList.contains(endClass) ||
classList.contains(comparisonStartClass) ||
classList.contains(inComparisonClass) ||
classList.contains(comparisonEndClass)
);
}),
).toBe(false);
});
describe('drag and drop ranges', () => {
beforeEach(() => {
// Pre-select a range to drag.
fixture.componentInstance.startValue = 4;
fixture.componentInstance.endValue = 6;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('triggers and previews a drag (mouse)', () => {
dispatchMouseEvent(cells[3], 'mousedown');
fixture.detectChanges();
expect(fixture.componentInstance.drag).not.toBe(null);
// Expand to earlier.
dispatchMouseEvent(cells[2], 'mouseenter');
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
// End drag.
dispatchMouseEvent(cells[2], 'mouseup');
expect(fixture.componentInstance.drag).toBe(null);
});
it('triggers and previews a drag (touch)', () => {
dispatchTouchEvent(cells[3], 'touchstart');
fixture.detectChanges();
expect(fixture.componentInstance.drag).not.toBe(null);
// Expand to earlier.
const rect = cells[2].getBoundingClientRect();
dispatchTouchEvent(cells[2], 'touchmove', rect.left, rect.top, rect.left, rect.top);
fixture.detectChanges();
expect(cells[2].classList).toContain(previewStartClass);
expect(cells[3].classList).toContain(inPreviewClass);
expect(cells[4].classList).toContain(inPreviewClass);
expect(cells[5].classList).toContain(previewEndClass);
// End drag.
dispatchTouchEvent(cells[2], 'touchend', rect.left, rect.top, rect.left, rect.top);
expect(fixture.componentInstance.drag).toBe(null);
});
});
});
});
@Component({
template: `
<table mat-calendar-body
[label]="label"
[rows]="rows"
[todayValue]="todayValue"
[startValue]="selectedValue"
[endValue]="selectedValue"
[labelMinRequiredCells]="labelMinRequiredCells"
[numCols]="numCols"
[activeCell]="10"
(selectedValueChange)="onSelect($event)">
</table>`,
standalone: true,
imports: [MatCalendarBody],
})
class StandardCalendarBody {
label = 'Jan 2017';
rows = createCalendarCells(2);
todayValue = 3;
selectedValue = 4;
labelMinRequiredCells = 3;
numCols = 7;
onSelect(event: MatCalendarUserEvent<number>) {
this.selectedValue = event.value;
}
}
@Component({
template: `
<table mat-calendar-body
[isRange]="true"
[rows]="rows"
[startValue]="startValue"
[endValue]="endValue"
[comparisonStart]="comparisonStart"
[comparisonEnd]="comparisonEnd"
[previewStart]="previewStart"
[previewEnd]="previewEnd"
(selectedValueChange)="onSelect($event)"
(previewChange)="previewChanged($event)"
(dragStarted)="dragStarted($event)"
(dragEnded)="dragEnded($event)"
>
</table>`,
standalone: true,
imports: [MatCalendarBody],
})
class RangeCalendarBody {
rows = createCalendarCells(4);
startValue: number | null;
endValue: number | null;
comparisonStart: number | null;
comparisonEnd: number | null;
previewStart: number | null;
previewEnd: number | null;
drag: MatCalendarUserEvent<unknown> | null = null;
onSelect(event: MatCalendarUserEvent<number>) {
const value = event.value;
if (!this.startValue) {
this.startValue = value;
} else if (!this.endValue) {
this.endValue = value;
} else {
this.startValue = value;
this.endValue = null;
}
}
previewChanged(event: MatCalendarUserEvent<MatCalendarCell<Date> | null>) {
this.previewStart = this.startValue;
this.previewEnd = event.value?.compareValue || null;
if (this.drag) {
// For sake of testing, hardcode a preview for drags.
this.previewStart = this.startValue! - 1;
this.previewEnd = this.endValue;
}
}
dragStarted(event: MatCalendarUserEvent<unknown>) {
this.drag = event;
}
dragEnded(event: MatCalendarUserEvent<unknown>) {
this.drag = null;
}
}
/**
* Creates a 2d array of days, split into weeks.
* @param weeks Number of weeks that should be generated.
*/
function createCalendarCells(weeks: number): MatCalendarCell[][] {
const rows: number[][] = [];
let dayCounter = 1;
for (let i = 0; i < weeks; i++) {
const row = [];
while (row.length < 7) {
row.push(dayCounter++);
}
rows.push(row);
}
return rows.map(row =>
row.map(cell => {
return new MatCalendarCell(
cell,
`${cell}`,
`${cell}-label`,
true,
cell % 2 === 0 ? 'even' : undefined,
cell,
cell,
);
}),
);
} | {
"end_byte": 30749,
"start_byte": 23751,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.spec.ts"
} |
components/src/material/datepicker/year-view.spec.ts_0_4033 | import {Direction, Directionality} from '@angular/cdk/bidi';
import {
DOWN_ARROW,
END,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {dispatchFakeEvent, dispatchKeyboardEvent} from '@angular/cdk/testing/private';
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {MatNativeDateModule} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {AUG, DEC, FEB, JAN, JUL, JUN, MAR, MAY, NOV, OCT, SEP} from '../testing';
import {MatCalendarBody} from './calendar-body';
import {MatYearView} from './year-view';
describe('MatYearView', () => {
let dir: {value: Direction};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatNativeDateModule,
MatCalendarBody,
MatYearView,
// Test components.
StandardYearView,
YearViewWithDateFilter,
YearViewWithDateClass,
],
providers: [{provide: Directionality, useFactory: () => (dir = {value: 'ltr'})}],
});
}));
describe('standard year view', () => {
let fixture: ComponentFixture<StandardYearView>;
let testComponent: StandardYearView;
let yearViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(StandardYearView);
fixture.detectChanges();
let yearViewDebugElement = fixture.debugElement.query(By.directive(MatYearView))!;
yearViewNativeElement = yearViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('has correct year label', () => {
let labelEl = yearViewNativeElement.querySelector('.mat-calendar-body-label')!;
expect(labelEl.innerHTML.trim()).toBe('2017');
});
it('has 12 months', () => {
let cellEls = yearViewNativeElement.querySelectorAll('.mat-calendar-body-cell')!;
expect(cellEls.length).toBe(12);
});
it('shows selected month if in same year', () => {
let selectedEl = yearViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('MAR');
});
it('does not show selected month if in different year', () => {
testComponent.selected = new Date(2016, MAR, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let selectedEl = yearViewNativeElement.querySelector('.mat-calendar-body-selected');
expect(selectedEl).toBeNull();
});
it('fires selected change event on cell clicked', () => {
let cellEls = yearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
(cellEls[cellEls.length - 1] as HTMLElement).click();
fixture.detectChanges();
let selectedEl = yearViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('DEC');
});
it('should emit the selected month on cell clicked', () => {
let cellEls = yearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
(cellEls[cellEls.length - 1] as HTMLElement).click();
fixture.detectChanges();
const normalizedMonth: Date = fixture.componentInstance.selectedMonth;
expect(normalizedMonth.getMonth()).toEqual(11);
});
it('should mark active date', () => {
let cellEls = yearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cellEls[0] as HTMLElement).innerText.trim()).toBe('JAN');
expect(cellEls[0].classList).toContain('mat-calendar-body-active');
});
it('should allow selection of month with less days than current active date', () => {
testComponent.date = new Date(2017, JUL, 31);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.yearView._monthSelected({value: JUN, event: null!});
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JUN, 30));
}); | {
"end_byte": 4033,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.spec.ts"
} |
components/src/material/datepicker/year-view.spec.ts_4039_13561 | describe('a11y', () => {
it('should set the correct role on the internal table node', () => {
const table = yearViewNativeElement.querySelector('table')!;
expect(table.getAttribute('role')).toBe('grid');
});
describe('calendar body', () => {
let calendarBodyEl: HTMLElement;
let calendarInstance: StandardYearView;
beforeEach(() => {
calendarInstance = fixture.componentInstance;
calendarBodyEl = fixture.debugElement.nativeElement.querySelector(
'.mat-calendar-body',
) as HTMLElement;
expect(calendarBodyEl).not.toBeNull();
dir.value = 'ltr';
fixture.componentInstance.date = new Date(2017, JAN, 5);
fixture.changeDetectorRef.markForCheck();
dispatchFakeEvent(calendarBodyEl, 'focus');
fixture.detectChanges();
});
it('should decrement month on left arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, NOV, 5));
});
it('should increment month on left arrow press in rtl', () => {
dir.value = 'rtl';
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, FEB, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAR, 5));
});
it('should increment month on right arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, FEB, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAR, 5));
});
it('should decrement month on right arrow press in rtl', () => {
dir.value = 'rtl';
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, NOV, 5));
});
it('should go up a row on up arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, SEP, 5));
calendarInstance.date = new Date(2017, JUL, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAR, 1));
calendarInstance.date = new Date(2017, DEC, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, AUG, 10));
});
it('should go down a row on down arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAY, 5));
calendarInstance.date = new Date(2017, JUN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, OCT, 1));
calendarInstance.date = new Date(2017, SEP, 30);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2018, JAN, 30));
});
it('should go to first month of the year on home press', () => {
calendarInstance.date = new Date(2017, SEP, 30);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 30));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 30));
});
it('should go to last month of the year on end press', () => {
calendarInstance.date = new Date(2017, OCT, 31);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, DEC, 31));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, DEC, 31));
});
it('should go back one year on page up press', () => {
calendarInstance.date = new Date(2016, FEB, 29);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2015, FEB, 28));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2014, FEB, 28));
});
it('should go forward one year on page down press', () => {
calendarInstance.date = new Date(2016, FEB, 29);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, FEB, 28));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2018, FEB, 28));
});
it('should go to date that is focused', () => {
const juneCell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="1"][data-mat-col="1"] button',
) as HTMLElement;
dispatchFakeEvent(juneCell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JUN, 5));
});
it('should not call `.focus()` when the active date is focused', () => {
const janCell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="0"][data-mat-col="0"] button',
) as HTMLElement;
const focusSpy = (janCell.focus = jasmine.createSpy('cellFocused'));
dispatchFakeEvent(janCell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 5));
expect(focusSpy).not.toHaveBeenCalled();
});
});
});
});
describe('year view with date filter', () => {
it('should disable months with no enabled days', () => {
const fixture = TestBed.createComponent(YearViewWithDateFilter);
fixture.detectChanges();
const cells = fixture.nativeElement.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).not.toContain('mat-calendar-body-disabled');
expect(cells[1].classList).toContain('mat-calendar-body-disabled');
});
it('should not call the date filter function if the date is before the min date', () => {
const fixture = TestBed.createComponent(YearViewWithDateFilter);
const activeDate = fixture.componentInstance.activeDate;
const spy = spyOn(fixture.componentInstance, 'dateFilter').and.callThrough();
fixture.componentInstance.minDate = new Date(
activeDate.getFullYear() + 1,
activeDate.getMonth(),
activeDate.getDate(),
);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).not.toHaveBeenCalled();
});
it('should not call the date filter function if the date is after the max date', () => {
const fixture = TestBed.createComponent(YearViewWithDateFilter);
const activeDate = fixture.componentInstance.activeDate;
const spy = spyOn(fixture.componentInstance, 'dateFilter').and.callThrough();
fixture.componentInstance.maxDate = new Date(
activeDate.getFullYear() - 1,
activeDate.getMonth(),
activeDate.getDate(),
);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).not.toHaveBeenCalled();
});
}); | {
"end_byte": 13561,
"start_byte": 4039,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.spec.ts"
} |
components/src/material/datepicker/year-view.spec.ts_13565_15823 | describe('year view with custom date classes', () => {
let fixture: ComponentFixture<YearViewWithDateClass>;
let yearViewNativeElement: Element;
let dateClassSpy: jasmine.Spy;
beforeEach(() => {
fixture = TestBed.createComponent(YearViewWithDateClass);
dateClassSpy = spyOn(fixture.componentInstance, 'dateClass').and.callThrough();
fixture.detectChanges();
let yearViewDebugElement = fixture.debugElement.query(By.directive(MatYearView))!;
yearViewNativeElement = yearViewDebugElement.nativeElement;
});
it('should be able to add a custom class to some month cells', () => {
let cells = yearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).toContain('even');
expect(cells[1].classList).not.toContain('even');
});
it('should call dateClass with the correct view name', () => {
expect(dateClassSpy).toHaveBeenCalledWith(jasmine.any(Date), 'year');
});
});
});
@Component({
template: `
<mat-year-view [(activeDate)]="date" [(selected)]="selected"
(monthSelected)="selectedMonth=$event"></mat-year-view>`,
standalone: true,
imports: [MatYearView],
})
class StandardYearView {
date = new Date(2017, JAN, 5);
selected = new Date(2017, MAR, 10);
selectedMonth: Date;
@ViewChild(MatYearView) yearView: MatYearView<Date>;
}
@Component({
template: `
<mat-year-view
[activeDate]="activeDate"
[dateFilter]="dateFilter"
[minDate]="minDate"
[maxDate]="maxDate"></mat-year-view>`,
standalone: true,
imports: [MatYearView],
})
class YearViewWithDateFilter {
activeDate = new Date(2017, JAN, 1);
minDate: Date | null = null;
maxDate: Date | null = null;
dateFilter(date: Date) {
if (date.getMonth() == JAN) {
return date.getDate() == 10;
}
if (date.getMonth() == FEB) {
return false;
}
return true;
}
}
@Component({
template: `<mat-year-view [activeDate]="activeDate" [dateClass]="dateClass"></mat-year-view>`,
standalone: true,
imports: [MatYearView],
})
class YearViewWithDateClass {
activeDate = new Date(2017, JAN, 1);
dateClass(date: Date) {
return date.getMonth() % 2 == 0 ? 'even' : undefined;
}
} | {
"end_byte": 15823,
"start_byte": 13565,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.spec.ts"
} |
components/src/material/datepicker/date-range-input.scss_0_5250 | @use 'sass:math';
@use '@angular/cdk';
@use '../core/style/variables';
@use '../core/style/vendor-prefixes';
@use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/tokens/token-utils';
$date-range-input-separator-spacing: 4px;
$date-range-input-part-max-width: calc(50% - #{$date-range-input-separator-spacing});
$_tokens: tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots();
@mixin _placeholder-transition($property) {
transition: #{$property} variables.$swift-ease-out-duration
math.div(variables.$swift-ease-out-duration, 3)
variables.$swift-ease-out-timing-function;
}
// Host of the date range input.
.mat-date-range-input {
display: block;
width: 100%;
}
// Inner container that wraps around all the content.
.mat-date-range-input-container {
display: flex;
align-items: center;
}
// Text shown between the two inputs.
.mat-date-range-input-separator {
@include _placeholder-transition(opacity);
margin: 0 $date-range-input-separator-spacing;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, range-input-separator-color);
.mat-form-field-disabled & {
@include token-utils.create-token-slot(color, range-input-disabled-state-separator-color);
}
}
._mat-animation-noopable & {
transition: none;
}
}
.mat-date-range-input-separator-hidden {
// Disable text selection, because the user can click
// through the main label when the input is disabled.
@include vendor-prefixes.user-select(none);
// Use opacity to hide the text, because `color: transparent` will be shown in high contrast mode.
opacity: 0;
transition: none;
}
// Wrapper around the inner inputs. Used to facilitate the auto-resizing input.
.mat-date-range-input-wrapper {
position: relative;
overflow: hidden;
max-width: $date-range-input-part-max-width;
}
.mat-date-range-input-end-wrapper {
// Allow the end input to fill the rest of the available space.
flex-grow: 1;
}
// Underlying input inside the range input.
.mat-date-range-input-inner {
position: absolute;
top: 0;
left: 0;
// Reset the input so it's just a transparent rectangle.
font: inherit;
background: transparent;
color: currentColor;
border: none;
outline: none;
padding: 0;
margin: 0;
vertical-align: bottom;
text-align: inherit;
-webkit-appearance: none;
width: 100%;
// Does nothing on Chrome, but necessary for the text
// to align in some cases on Safari and Firefox.
height: 100%;
// Undo the red box-shadow glow added by Firefox on invalid inputs.
// See https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid
&:-moz-ui-invalid {
box-shadow: none;
}
@include vendor-prefixes.input-placeholder {
@include _placeholder-transition(color);
}
@include token-utils.use-tokens($_tokens...) {
&[disabled] {
@include token-utils.create-token-slot(color, range-input-disabled-state-text-color);
}
}
.mat-form-field-hide-placeholder &,
.mat-date-range-input-hide-placeholders & {
@include vendor-prefixes.input-placeholder {
// Disable text selection, because the user can click
// through the main label when the input is disabled.
@include vendor-prefixes.user-select(none);
// Needs to be !important, because the placeholder will end up inheriting the
// input color in IE, if the consumer overrides it with a higher specificity.
color: transparent !important;
-webkit-text-fill-color: transparent;
transition: none;
@include cdk.high-contrast {
// In high contrast mode the browser will render the
// placeholder despite the `color: transparent` above.
opacity: 0;
}
}
}
._mat-animation-noopable & {
@include vendor-prefixes.input-placeholder {
transition: none;
}
}
}
// We want the start input to be flush against the separator, no matter how much text it has, but
// the problem is that inputs have a fixed width. We work around the issue by implementing an
// auto-resizing input that stretches based on its text, up to a point. It works by having
// a relatively-positioned wrapper (`.mat-date-range-input-wrapper` below) and an absolutely-
// positioned `input`, as well as a `span` inside the wrapper which mirrors the input's value and
// placeholder. As the user is typing, the value gets mirrored in the span which causes the wrapper
// to stretch and the input with it.
.mat-date-range-input-mirror {
// Disable user selection so users don't accidentally copy the text via ctrl + A.
@include vendor-prefixes.user-select(none);
// Hide the element so it doesn't get read out by screen
// readers and it doesn't show up behind the input.
visibility: hidden;
// Text inside inputs never wraps so the one in the span shouldn't either.
white-space: nowrap;
display: inline-block;
// Prevent the container from collapsing. Make it more
// than 1px so the input caret doesn't get clipped.
min-width: 2px;
}
.mat-mdc-form-field-type-mat-date-range-input .mat-mdc-form-field-infix {
// Bump the default width slightly since it's somewhat cramped with two inputs and a separator.
width: 200px;
}
| {
"end_byte": 5250,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.scss"
} |
components/src/material/datepicker/datepicker-actions.spec.ts_0_10190 | import {Component, ElementRef, Type, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatNativeDateModule} from '@angular/material/core';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatDatepicker} from './datepicker';
import {MatDatepickerModule} from './datepicker-module';
describe('MatDatepickerActions', () => {
function createComponent<T>(component: Type<T>): ComponentFixture<T> {
TestBed.configureTestingModule({
declarations: [component],
imports: [
FormsModule,
MatDatepickerModule,
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
MatNativeDateModule,
],
});
return TestBed.createComponent(component);
}
it('should render the actions inside calendar panel in popup mode', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
flush();
const actions = document.querySelector('.mat-datepicker-content .mat-datepicker-actions');
expect(actions).toBeTruthy();
expect(actions?.querySelector('.cancel')).toBeTruthy();
expect(actions?.querySelector('.apply')).toBeTruthy();
}));
it('should render the actions inside calendar panel in touch UI mode', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.componentInstance.touchUi = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
flush();
const actions = document.querySelector('.mat-datepicker-content .mat-datepicker-actions');
expect(actions).toBeTruthy();
expect(actions?.querySelector('.cancel')).toBeTruthy();
expect(actions?.querySelector('.apply')).toBeTruthy();
}));
it('should not assign the value or close the datepicker when a value is selected', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
const {control, datepicker, onDateChange, input} = fixture.componentInstance;
datepicker.open();
fixture.detectChanges();
tick();
const content = document.querySelector('.mat-datepicker-content')!;
const cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeFalsy();
cells[10].click();
fixture.detectChanges();
flush();
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeTruthy();
}));
it('should close without changing the value when clicking on the cancel button', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
const {control, datepicker, onDateChange, input} = fixture.componentInstance;
datepicker.open();
fixture.detectChanges();
tick();
flush();
const content = document.querySelector('.mat-datepicker-content')!;
const cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeFalsy();
cells[10].click();
fixture.detectChanges();
tick();
flush();
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeTruthy();
(content.querySelector('.cancel') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(datepicker.opened).toBe(false);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
}));
it('should close while keeping the previous control value when clicking on cancel', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
const {control, datepicker, onDateChange} = fixture.componentInstance;
const value = new Date(2021, 0, 20);
control.setValue(value);
fixture.detectChanges();
datepicker.open();
fixture.detectChanges();
tick();
flush();
const content = document.querySelector('.mat-datepicker-content')!;
const cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(datepicker.opened).toBe(true);
expect(control.value).toBe(value);
expect(onDateChange).not.toHaveBeenCalled();
cells[10].click();
fixture.detectChanges();
tick();
flush();
expect(datepicker.opened).toBe(true);
expect(control.value).toBe(value);
expect(onDateChange).not.toHaveBeenCalled();
(content.querySelector('.cancel') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(datepicker.opened).toBe(false);
expect(control.value).toBe(value);
expect(onDateChange).not.toHaveBeenCalled();
}));
it('should close and accept the value when clicking on the apply button', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
const {control, datepicker, onDateChange, input} = fixture.componentInstance;
datepicker.open();
fixture.detectChanges();
tick();
flush();
const content = document.querySelector('.mat-datepicker-content')!;
const cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeFalsy();
cells[10].click();
fixture.detectChanges();
tick();
flush();
expect(datepicker.opened).toBe(true);
expect(input.nativeElement.value).toBeFalsy();
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
expect(content.querySelector('.mat-calendar-body-selected')).toBeTruthy();
(content.querySelector('.apply') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(datepicker.opened).toBe(false);
expect(input.nativeElement.value).toBeTruthy();
expect(control.value).toBeTruthy();
expect(onDateChange).toHaveBeenCalledTimes(1);
}));
it('should revert to the default behavior if the actions are removed', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.detectChanges();
const {control, datepicker, onDateChange} = fixture.componentInstance;
datepicker.open();
fixture.detectChanges();
tick();
flush();
let content = document.querySelector('.mat-datepicker-content')!;
let actions = content.querySelector('.mat-datepicker-actions')!;
let cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(actions).toBeTruthy();
expect(datepicker.opened).toBe(true);
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
cells[10].click();
fixture.detectChanges();
tick();
flush();
expect(datepicker.opened).toBe(true);
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
(actions.querySelector('.cancel') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(datepicker.opened).toBe(false);
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
fixture.componentInstance.renderActions = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
datepicker.open();
fixture.detectChanges();
content = document.querySelector('.mat-datepicker-content')!;
actions = content.querySelector('.mat-datepicker-actions')!;
cells = content.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
expect(actions).toBeFalsy();
expect(datepicker.opened).toBe(true);
expect(control.value).toBeFalsy();
expect(onDateChange).not.toHaveBeenCalled();
cells[10].click();
fixture.detectChanges();
tick();
flush();
expect(datepicker.opened).toBe(false);
expect(control.value).toBeTruthy();
expect(onDateChange).toHaveBeenCalledTimes(1);
}));
it('should be able to toggle the actions while the datepicker is open', fakeAsync(() => {
const fixture = createComponent(DatepickerWithActions);
fixture.componentInstance.renderActions = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
flush();
const content = document.querySelector('.mat-datepicker-content')!;
expect(content.querySelector('.mat-datepicker-actions')).toBeFalsy();
fixture.componentInstance.renderActions = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(content.querySelector('.mat-datepicker-actions')).toBeTruthy();
fixture.componentInstance.renderActions = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(content.querySelector('.mat-datepicker-actions')).toBeFalsy();
}));
}); | {
"end_byte": 10190,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-actions.spec.ts"
} |
components/src/material/datepicker/datepicker-actions.spec.ts_10192_11216 | @Component({
template: `
<mat-form-field>
<mat-label>Pick a date</mat-label>
<input
#input
matInput
[matDatepicker]="picker"
[formControl]="control"
(dateChange)="onDateChange()">
<mat-datepicker #picker [touchUi]="touchUi" [startAt]="startAt">
@if (renderActions) {
<mat-datepicker-actions>
<button mat-button class="cancel" matDatepickerCancel>Cancel</button>
<button mat-raised-button class="apply" matDatepickerApply>Apply</button>
</mat-datepicker-actions>
}
</mat-datepicker>
</mat-form-field>
`,
standalone: false,
})
class DatepickerWithActions {
@ViewChild(MatDatepicker) datepicker: MatDatepicker<Date>;
@ViewChild('input', {read: ElementRef}) input: ElementRef<HTMLInputElement>;
control = new FormControl<Date | null>(null);
onDateChange = jasmine.createSpy('dateChange spy');
touchUi = false;
startAt = new Date(2021, 0, 15);
renderActions = true;
} | {
"end_byte": 11216,
"start_byte": 10192,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-actions.spec.ts"
} |
components/src/material/datepicker/date-range-picker.ts_0_2178 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core';
import {MatDatepickerBase, MatDatepickerContent, MatDatepickerControl} from './datepicker-base';
import {MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER, DateRange} from './date-selection-model';
import {MAT_CALENDAR_RANGE_STRATEGY_PROVIDER} from './date-range-selection-strategy';
/**
* Input that can be associated with a date range picker.
* @docs-private
*/
export interface MatDateRangePickerInput<D> extends MatDatepickerControl<D> {
_getEndDateAccessibleName(): string | null;
_getStartDateAccessibleName(): string | null;
comparisonStart: D | null;
comparisonEnd: D | null;
}
// TODO(mmalerba): We use a component instead of a directive here so the user can use implicit
// template reference variables (e.g. #d vs #d="matDateRangePicker"). We can change this to a
// directive if angular adds support for `exportAs: '$implicit'` on directives.
/** Component responsible for managing the date range picker popup/dialog. */
@Component({
selector: 'mat-date-range-picker',
template: '',
exportAs: 'matDateRangePicker',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [
MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER,
MAT_CALENDAR_RANGE_STRATEGY_PROVIDER,
{provide: MatDatepickerBase, useExisting: MatDateRangePicker},
],
})
export class MatDateRangePicker<D> extends MatDatepickerBase<
MatDateRangePickerInput<D>,
DateRange<D>,
D
> {
protected override _forwardContentValues(instance: MatDatepickerContent<DateRange<D>, D>) {
super._forwardContentValues(instance);
const input = this.datepickerInput;
if (input) {
instance.comparisonStart = input.comparisonStart;
instance.comparisonEnd = input.comparisonEnd;
instance.startDateAccessibleName = input._getStartDateAccessibleName();
instance.endDateAccessibleName = input._getEndDateAccessibleName();
}
}
}
| {
"end_byte": 2178,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-picker.ts"
} |
components/src/material/datepicker/_datepicker-legacy-compat.scss_0_1871 | @use '../button/button-theme';
@use '../button/icon-button-theme';
@mixin legacy-button-compat-theme($theme) {
.mat-datepicker-content {
@include button-theme.theme($theme);
@include icon-button-theme.theme($theme);
}
}
@mixin legacy-button-compat() {
.mat-datepicker-toggle .mat-mdc-button-base {
width: 40px;
height: 40px;
padding: 8px 0;
}
.mat-datepicker-actions {
$spacing: 8px;
.mat-button-base + .mat-button-base {
margin-left: $spacing;
[dir='rtl'] & {
margin-left: 0;
margin-right: $spacing;
}
}
}
}
@mixin legacy-form-field-compat() {
.mat-form-field {
.mat-form-field-prefix,
.mat-form-field-suffix {
.mat-datepicker-toggle .mat-mdc-button-base {
width: 40px;
height: 40px;
padding: 8px 0;
}
}
.mat-datepicker-toggle .mat-mdc-icon-button .mat-icon {
font-size: 1em;
display: inline-block;
margin: -2px 0 1px;
}
}
.mat-form-field-type-mat-date-range-input .mat-form-field-infix {
// Bump the default width slightly since it's somewhat cramped with two inputs and a separator.
width: 200px;
}
.mat-form-field-appearance-legacy {
.mat-form-field-prefix,
.mat-form-field-suffix {
.mat-datepicker-toggle .mat-mdc-icon-button {
font-size: inherit;
width: 1.5em;
height: 1.5em;
padding: 0;
}
.mat-datepicker-toggle-default-icon {
width: 1em;
}
.mat-datepicker-toggle .mat-mdc-icon-button .mat-icon {
line-height: 1.5em;
margin: 0;
}
}
}
.mat-form-field {
.mat-datepicker-toggle .mat-mdc-button-base {
vertical-align: middle;
}
&:not(.mat-form-field-appearance-legacy) .mat-datepicker-toggle .mat-mdc-button-base {
vertical-align: baseline;
}
}
}
| {
"end_byte": 1871,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/_datepicker-legacy-compat.scss"
} |
components/src/material/datepicker/date-range-input.html_0_762 | <div
class="mat-date-range-input-container"
cdkMonitorSubtreeFocus
(cdkFocusChange)="_updateFocus($event)">
<div class="mat-date-range-input-wrapper">
<ng-content select="input[matStartDate]"></ng-content>
<span
class="mat-date-range-input-mirror"
aria-hidden="true">{{_getInputMirrorValue('start')}}</span>
</div>
<span
class="mat-date-range-input-separator"
[class.mat-date-range-input-separator-hidden]="_shouldHideSeparator()">{{separator}}</span>
<div class="mat-date-range-input-wrapper mat-date-range-input-end-wrapper">
<ng-content select="input[matEndDate]"></ng-content>
<span
class="mat-date-range-input-mirror"
aria-hidden="true">{{_getInputMirrorValue('end')}}</span>
</div>
</div>
| {
"end_byte": 762,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.html"
} |
components/src/material/datepicker/month-view.ts_0_1434 | /**
* @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 {
DOWN_ARROW,
END,
ENTER,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
UP_ARROW,
SPACE,
ESCAPE,
hasModifierKey,
} from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
Output,
ViewEncapsulation,
ViewChild,
OnDestroy,
SimpleChanges,
OnChanges,
inject,
} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {Directionality} from '@angular/cdk/bidi';
import {
MatCalendarBody,
MatCalendarCell,
MatCalendarUserEvent,
MatCalendarCellClassFunction,
} from './calendar-body';
import {createMissingDateImplError} from './datepicker-errors';
import {Subscription} from 'rxjs';
import {startWith} from 'rxjs/operators';
import {DateRange} from './date-selection-model';
import {
MatDateRangeSelectionStrategy,
MAT_DATE_RANGE_SELECTION_STRATEGY,
} from './date-range-selection-strategy';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
const DAYS_PER_WEEK = 7;
let uniqueIdCounter = 0;
/**
* An internal component used to display a single month in the datepicker.
* @docs-private
*/ | {
"end_byte": 1434,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.ts"
} |
components/src/material/datepicker/month-view.ts_1435_9587 | @Component({
selector: 'mat-month-view',
templateUrl: 'month-view.html',
exportAs: 'matMonthView',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatCalendarBody],
})
export class MatMonthView<D> implements AfterContentInit, OnChanges, OnDestroy {
readonly _changeDetectorRef = inject(ChangeDetectorRef);
private _dateFormats = inject<MatDateFormats>(MAT_DATE_FORMATS, {optional: true})!;
_dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dir = inject(Directionality, {optional: true});
private _rangeStrategy = inject<MatDateRangeSelectionStrategy<D>>(
MAT_DATE_RANGE_SELECTION_STRATEGY,
{optional: true},
);
private _rerenderSubscription = Subscription.EMPTY;
/** Flag used to filter out space/enter keyup events that originated outside of the view. */
private _selectionKeyPressed: boolean;
/**
* The date to display in this month view (everything other than the month and year is ignored).
*/
@Input()
get activeDate(): D {
return this._activeDate;
}
set activeDate(value: D) {
const oldActiveDate = this._activeDate;
const validDate =
this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)) ||
this._dateAdapter.today();
this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
if (!this._hasSameMonthAndYear(oldActiveDate, this._activeDate)) {
this._init();
}
}
private _activeDate: D;
/** The currently selected date. */
@Input()
get selected(): DateRange<D> | D | null {
return this._selected;
}
set selected(value: DateRange<D> | D | null) {
if (value instanceof DateRange) {
this._selected = value;
} else {
this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
this._setRanges(this._selected);
}
private _selected: DateRange<D> | D | null;
/** The minimum selectable date. */
@Input()
get minDate(): D | null {
return this._minDate;
}
set minDate(value: D | null) {
this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _minDate: D | null;
/** The maximum selectable date. */
@Input()
get maxDate(): D | null {
return this._maxDate;
}
set maxDate(value: D | null) {
this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _maxDate: D | null;
/** Function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Function that can be used to add custom CSS classes to dates. */
@Input() dateClass: MatCalendarCellClassFunction<D>;
/** Start of the comparison range. */
@Input() comparisonStart: D | null;
/** End of the comparison range. */
@Input() comparisonEnd: D | null;
/** ARIA Accessible name of the `<input matStartDate/>` */
@Input() startDateAccessibleName: string | null;
/** ARIA Accessible name of the `<input matEndDate/>` */
@Input() endDateAccessibleName: string | null;
/** Origin of active drag, or null when dragging is not active. */
@Input() activeDrag: MatCalendarUserEvent<D> | null = null;
/** Emits when a new date is selected. */
@Output() readonly selectedChange: EventEmitter<D | null> = new EventEmitter<D | null>();
/** Emits when any date is selected. */
@Output() readonly _userSelection: EventEmitter<MatCalendarUserEvent<D | null>> =
new EventEmitter<MatCalendarUserEvent<D | null>>();
/** Emits when the user initiates a date range drag via mouse or touch. */
@Output() readonly dragStarted = new EventEmitter<MatCalendarUserEvent<D>>();
/**
* Emits when the user completes or cancels a date range drag.
* Emits null when the drag was canceled or the newly selected date range if completed.
*/
@Output() readonly dragEnded = new EventEmitter<MatCalendarUserEvent<DateRange<D> | null>>();
/** Emits when any date is activated. */
@Output() readonly activeDateChange: EventEmitter<D> = new EventEmitter<D>();
/** The body of calendar table */
@ViewChild(MatCalendarBody) _matCalendarBody: MatCalendarBody;
/** The label for this month (e.g. "January 2017"). */
_monthLabel: string;
/** Grid of calendar cells representing the dates of the month. */
_weeks: MatCalendarCell[][];
/** The number of blank cells in the first row before the 1st of the month. */
_firstWeekOffset: number;
/** Start value of the currently-shown date range. */
_rangeStart: number | null;
/** End value of the currently-shown date range. */
_rangeEnd: number | null;
/** Start value of the currently-shown comparison date range. */
_comparisonRangeStart: number | null;
/** End value of the currently-shown comparison date range. */
_comparisonRangeEnd: number | null;
/** Start of the preview range. */
_previewStart: number | null;
/** End of the preview range. */
_previewEnd: number | null;
/** Whether the user is currently selecting a range of dates. */
_isRange: boolean;
/** The date of the month that today falls on. Null if today is in another month. */
_todayDate: number | null;
/** The names of the weekdays. */
_weekdays: {long: string; narrow: string; id: number}[];
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MAT_DATE_FORMATS');
}
}
this._activeDate = this._dateAdapter.today();
}
ngAfterContentInit() {
this._rerenderSubscription = this._dateAdapter.localeChanges
.pipe(startWith(null))
.subscribe(() => this._init());
}
ngOnChanges(changes: SimpleChanges) {
const comparisonChange = changes['comparisonStart'] || changes['comparisonEnd'];
if (comparisonChange && !comparisonChange.firstChange) {
this._setRanges(this.selected);
}
if (changes['activeDrag'] && !this.activeDrag) {
this._clearPreview();
}
}
ngOnDestroy() {
this._rerenderSubscription.unsubscribe();
}
/** Handles when a new date is selected. */
_dateSelected(event: MatCalendarUserEvent<number>) {
const date = event.value;
const selectedDate = this._getDateFromDayOfMonth(date);
let rangeStartDate: number | null;
let rangeEndDate: number | null;
if (this._selected instanceof DateRange) {
rangeStartDate = this._getDateInCurrentMonth(this._selected.start);
rangeEndDate = this._getDateInCurrentMonth(this._selected.end);
} else {
rangeStartDate = rangeEndDate = this._getDateInCurrentMonth(this._selected);
}
if (rangeStartDate !== date || rangeEndDate !== date) {
this.selectedChange.emit(selectedDate);
}
this._userSelection.emit({value: selectedDate, event: event.event});
this._clearPreview();
this._changeDetectorRef.markForCheck();
}
/**
* Takes the index of a calendar body cell wrapped in an event as argument. For the date that
* corresponds to the given cell, set `activeDate` to that date and fire `activeDateChange` with
* that date.
*
* This function is used to match each component's model of the active date with the calendar
* body cell that was focused. It updates its value of `activeDate` synchronously and updates the
* parent's value asynchronously via the `activeDateChange` event. The child component receives an
* updated value asynchronously via the `activeCell` Input.
*/
_updateActiveDate(event: MatCalendarUserEvent<number>) {
const month = event.value;
const oldActiveDate = this._activeDate;
this.activeDate = this._getDateFromDayOfMonth(month);
if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this._activeDate);
}
}
/** Handles keydown events on the calendar body when calendar is in month view. */ | {
"end_byte": 9587,
"start_byte": 1435,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.ts"
} |
components/src/material/datepicker/month-view.ts_9590_18048 | _handleCalendarBodyKeydown(event: KeyboardEvent): void {
// TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent
// disabled ones from being selected. This may not be ideal, we should look into whether
// navigation should skip over disabled dates, and if so, how to implement that efficiently.
const oldActiveDate = this._activeDate;
const isRtl = this._isRtl();
switch (event.keyCode) {
case LEFT_ARROW:
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? 1 : -1);
break;
case RIGHT_ARROW:
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? -1 : 1);
break;
case UP_ARROW:
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, -7);
break;
case DOWN_ARROW:
this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 7);
break;
case HOME:
this.activeDate = this._dateAdapter.addCalendarDays(
this._activeDate,
1 - this._dateAdapter.getDate(this._activeDate),
);
break;
case END:
this.activeDate = this._dateAdapter.addCalendarDays(
this._activeDate,
this._dateAdapter.getNumDaysInMonth(this._activeDate) -
this._dateAdapter.getDate(this._activeDate),
);
break;
case PAGE_UP:
this.activeDate = event.altKey
? this._dateAdapter.addCalendarYears(this._activeDate, -1)
: this._dateAdapter.addCalendarMonths(this._activeDate, -1);
break;
case PAGE_DOWN:
this.activeDate = event.altKey
? this._dateAdapter.addCalendarYears(this._activeDate, 1)
: this._dateAdapter.addCalendarMonths(this._activeDate, 1);
break;
case ENTER:
case SPACE:
this._selectionKeyPressed = true;
if (this._canSelect(this._activeDate)) {
// Prevent unexpected default actions such as form submission.
// Note that we only prevent the default action here while the selection happens in
// `keyup` below. We can't do the selection here, because it can cause the calendar to
// reopen if focus is restored immediately. We also can't call `preventDefault` on `keyup`
// because it's too late (see #23305).
event.preventDefault();
}
return;
case ESCAPE:
// Abort the current range selection if the user presses escape mid-selection.
if (this._previewEnd != null && !hasModifierKey(event)) {
this._clearPreview();
// If a drag is in progress, cancel the drag without changing the
// current selection.
if (this.activeDrag) {
this.dragEnded.emit({value: null, event});
} else {
this.selectedChange.emit(null);
this._userSelection.emit({value: null, event});
}
event.preventDefault();
event.stopPropagation(); // Prevents the overlay from closing.
}
return;
default:
// Don't prevent default or focus active cell on keys that we don't explicitly handle.
return;
}
if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this.activeDate);
this._focusActiveCellAfterViewChecked();
}
// Prevent unexpected default actions such as form submission.
event.preventDefault();
}
/** Handles keyup events on the calendar body when calendar is in month view. */
_handleCalendarBodyKeyup(event: KeyboardEvent): void {
if (event.keyCode === SPACE || event.keyCode === ENTER) {
if (this._selectionKeyPressed && this._canSelect(this._activeDate)) {
this._dateSelected({value: this._dateAdapter.getDate(this._activeDate), event});
}
this._selectionKeyPressed = false;
}
}
/** Initializes this month view. */
_init() {
this._setRanges(this.selected);
this._todayDate = this._getCellCompareValue(this._dateAdapter.today());
this._monthLabel = this._dateFormats.display.monthLabel
? this._dateAdapter.format(this.activeDate, this._dateFormats.display.monthLabel)
: this._dateAdapter
.getMonthNames('short')
[this._dateAdapter.getMonth(this.activeDate)].toLocaleUpperCase();
let firstOfMonth = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
this._dateAdapter.getMonth(this.activeDate),
1,
);
this._firstWeekOffset =
(DAYS_PER_WEEK +
this._dateAdapter.getDayOfWeek(firstOfMonth) -
this._dateAdapter.getFirstDayOfWeek()) %
DAYS_PER_WEEK;
this._initWeekdays();
this._createWeekCells();
this._changeDetectorRef.markForCheck();
}
/** Focuses the active cell after the microtask queue is empty. */
_focusActiveCell(movePreview?: boolean) {
this._matCalendarBody._focusActiveCell(movePreview);
}
/** Focuses the active cell after change detection has run and the microtask queue is empty. */
_focusActiveCellAfterViewChecked() {
this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
}
/** Called when the user has activated a new cell and the preview needs to be updated. */
_previewChanged({event, value: cell}: MatCalendarUserEvent<MatCalendarCell<D> | null>) {
if (this._rangeStrategy) {
// We can assume that this will be a range, because preview
// events aren't fired for single date selections.
const value = cell ? cell.rawValue! : null;
const previewRange = this._rangeStrategy.createPreview(
value,
this.selected as DateRange<D>,
event,
);
this._previewStart = this._getCellCompareValue(previewRange.start);
this._previewEnd = this._getCellCompareValue(previewRange.end);
if (this.activeDrag && value) {
const dragRange = this._rangeStrategy.createDrag?.(
this.activeDrag.value,
this.selected as DateRange<D>,
value,
event,
);
if (dragRange) {
this._previewStart = this._getCellCompareValue(dragRange.start);
this._previewEnd = this._getCellCompareValue(dragRange.end);
}
}
// Note that here we need to use `detectChanges`, rather than `markForCheck`, because
// the way `_focusActiveCell` is set up at the moment makes it fire at the wrong time
// when navigating one month back using the keyboard which will cause this handler
// to throw a "changed after checked" error when updating the preview state.
this._changeDetectorRef.detectChanges();
}
}
/**
* Called when the user has ended a drag. If the drag/drop was successful,
* computes and emits the new range selection.
*/
protected _dragEnded(event: MatCalendarUserEvent<D | null>) {
if (!this.activeDrag) return;
if (event.value) {
// Propagate drag effect
const dragDropResult = this._rangeStrategy?.createDrag?.(
this.activeDrag.value,
this.selected as DateRange<D>,
event.value,
event.event,
);
this.dragEnded.emit({value: dragDropResult ?? null, event: event.event});
} else {
this.dragEnded.emit({value: null, event: event.event});
}
}
/**
* Takes a day of the month and returns a new date in the same month and year as the currently
* active date. The returned date will have the same day of the month as the argument date.
*/
private _getDateFromDayOfMonth(dayOfMonth: number): D {
return this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
this._dateAdapter.getMonth(this.activeDate),
dayOfMonth,
);
}
/** Initializes the weekdays. */
private _initWeekdays() {
const firstDayOfWeek = this._dateAdapter.getFirstDayOfWeek();
const narrowWeekdays = this._dateAdapter.getDayOfWeekNames('narrow');
const longWeekdays = this._dateAdapter.getDayOfWeekNames('long');
// Rotate the labels for days of the week based on the configured first day of the week.
let weekdays = longWeekdays.map((long, i) => {
return {long, narrow: narrowWeekdays[i], id: uniqueIdCounter++};
});
this._weekdays = weekdays.slice(firstDayOfWeek).concat(weekdays.slice(0, firstDayOfWeek));
}
/** Creates MatCalendarCells for the dates in this month. */ | {
"end_byte": 18048,
"start_byte": 9590,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.ts"
} |
components/src/material/datepicker/month-view.ts_18051_21749 | private _createWeekCells() {
const daysInMonth = this._dateAdapter.getNumDaysInMonth(this.activeDate);
const dateNames = this._dateAdapter.getDateNames();
this._weeks = [[]];
for (let i = 0, cell = this._firstWeekOffset; i < daysInMonth; i++, cell++) {
if (cell == DAYS_PER_WEEK) {
this._weeks.push([]);
cell = 0;
}
const date = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
this._dateAdapter.getMonth(this.activeDate),
i + 1,
);
const enabled = this._shouldEnableDate(date);
const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.dateA11yLabel);
const cellClasses = this.dateClass ? this.dateClass(date, 'month') : undefined;
this._weeks[this._weeks.length - 1].push(
new MatCalendarCell<D>(
i + 1,
dateNames[i],
ariaLabel,
enabled,
cellClasses,
this._getCellCompareValue(date)!,
date,
),
);
}
}
/** Date filter for the month */
private _shouldEnableDate(date: D): boolean {
return (
!!date &&
(!this.minDate || this._dateAdapter.compareDate(date, this.minDate) >= 0) &&
(!this.maxDate || this._dateAdapter.compareDate(date, this.maxDate) <= 0) &&
(!this.dateFilter || this.dateFilter(date))
);
}
/**
* Gets the date in this month that the given Date falls on.
* Returns null if the given Date is in another month.
*/
private _getDateInCurrentMonth(date: D | null): number | null {
return date && this._hasSameMonthAndYear(date, this.activeDate)
? this._dateAdapter.getDate(date)
: null;
}
/** Checks whether the 2 dates are non-null and fall within the same month of the same year. */
private _hasSameMonthAndYear(d1: D | null, d2: D | null): boolean {
return !!(
d1 &&
d2 &&
this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&
this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2)
);
}
/** Gets the value that will be used to one cell to another. */
private _getCellCompareValue(date: D | null): number | null {
if (date) {
// We use the time since the Unix epoch to compare dates in this view, rather than the
// cell values, because we need to support ranges that span across multiple months/years.
const year = this._dateAdapter.getYear(date);
const month = this._dateAdapter.getMonth(date);
const day = this._dateAdapter.getDate(date);
return new Date(year, month, day).getTime();
}
return null;
}
/** Determines whether the user has the RTL layout direction. */
private _isRtl() {
return this._dir && this._dir.value === 'rtl';
}
/** Sets the current range based on a model value. */
private _setRanges(selectedValue: DateRange<D> | D | null) {
if (selectedValue instanceof DateRange) {
this._rangeStart = this._getCellCompareValue(selectedValue.start);
this._rangeEnd = this._getCellCompareValue(selectedValue.end);
this._isRange = true;
} else {
this._rangeStart = this._rangeEnd = this._getCellCompareValue(selectedValue);
this._isRange = false;
}
this._comparisonRangeStart = this._getCellCompareValue(this.comparisonStart);
this._comparisonRangeEnd = this._getCellCompareValue(this.comparisonEnd);
}
/** Gets whether a date can be selected in the month view. */
private _canSelect(date: D) {
return !this.dateFilter || this.dateFilter(date);
}
/** Clears out preview state. */
private _clearPreview() {
this._previewStart = this._previewEnd = null;
}
} | {
"end_byte": 21749,
"start_byte": 18051,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.ts"
} |
components/src/material/datepicker/calendar.html_0_1698 | <ng-template [cdkPortalOutlet]="_calendarHeaderPortal"></ng-template>
<div class="mat-calendar-content" cdkMonitorSubtreeFocus tabindex="-1">
@switch (currentView) {
@case ('month') {
<mat-month-view
[(activeDate)]="activeDate"
[selected]="selected"
[dateFilter]="dateFilter"
[maxDate]="maxDate"
[minDate]="minDate"
[dateClass]="dateClass"
[comparisonStart]="comparisonStart"
[comparisonEnd]="comparisonEnd"
[startDateAccessibleName]="startDateAccessibleName"
[endDateAccessibleName]="endDateAccessibleName"
(_userSelection)="_dateSelected($event)"
(dragStarted)="_dragStarted($event)"
(dragEnded)="_dragEnded($event)"
[activeDrag]="_activeDrag"></mat-month-view>
}
@case ('year') {
<mat-year-view
[(activeDate)]="activeDate"
[selected]="selected"
[dateFilter]="dateFilter"
[maxDate]="maxDate"
[minDate]="minDate"
[dateClass]="dateClass"
(monthSelected)="_monthSelectedInYearView($event)"
(selectedChange)="_goToDateInView($event, 'month')"></mat-year-view>
}
@case ('multi-year') {
<mat-multi-year-view
[(activeDate)]="activeDate"
[selected]="selected"
[dateFilter]="dateFilter"
[maxDate]="maxDate"
[minDate]="minDate"
[dateClass]="dateClass"
(yearSelected)="_yearSelectedInMultiYearView($event)"
(selectedChange)="_goToDateInView($event, 'year')"></mat-multi-year-view>
}
}
</div>
| {
"end_byte": 1698,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.html"
} |
components/src/material/datepicker/datepicker-animations.ts_0_1737 | /**
* @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,
keyframes,
AnimationTriggerMetadata,
} from '@angular/animations';
/**
* Animations used by the Material datepicker.
* @docs-private
*/
export const matDatepickerAnimations: {
readonly transformPanel: AnimationTriggerMetadata;
readonly fadeInCalendar: AnimationTriggerMetadata;
} = {
/** Transforms the height of the datepicker's calendar. */
transformPanel: trigger('transformPanel', [
transition(
'void => enter-dropdown',
animate(
'120ms cubic-bezier(0, 0, 0.2, 1)',
keyframes([
style({opacity: 0, transform: 'scale(1, 0.8)'}),
style({opacity: 1, transform: 'scale(1, 1)'}),
]),
),
),
transition(
'void => enter-dialog',
animate(
'150ms cubic-bezier(0, 0, 0.2, 1)',
keyframes([
style({opacity: 0, transform: 'scale(0.7)'}),
style({transform: 'none', opacity: 1}),
]),
),
),
transition('* => void', animate('100ms linear', style({opacity: 0}))),
]),
/** Fades in the content of the calendar. */
fadeInCalendar: trigger('fadeInCalendar', [
state('void', style({opacity: 0})),
state('enter', style({opacity: 1})),
// TODO(crisbeto): this animation should be removed since it isn't quite on spec, but we
// need to keep it until #12440 gets in, otherwise the exit animation will look glitchy.
transition('void => *', animate('120ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)')),
]),
};
| {
"end_byte": 1737,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-animations.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.