_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/datepicker/date-selection-model.ts_0_7131 | /**
* @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 {FactoryProvider, Injectable, Optional, SkipSelf, OnDestroy} from '@angular/core';
import {DateAdapter} from '@angular/material/core';
import {Observable, Subject} from 'rxjs';
/** A class representing a range of dates. */
export class DateRange<D> {
/**
* Ensures that objects with a `start` and `end` property can't be assigned to a variable that
* expects a `DateRange`
*/
// tslint:disable-next-line:no-unused-variable
private _disableStructuralEquivalency: never;
constructor(
/** The start date of the range. */
readonly start: D | null,
/** The end date of the range. */
readonly end: D | null,
) {}
}
/**
* Conditionally picks the date type, if a DateRange is passed in.
* @docs-private
*/
export type ExtractDateTypeFromSelection<T> = T extends DateRange<infer D> ? D : NonNullable<T>;
/**
* Event emitted by the date selection model when its selection changes.
* @docs-private
*/
export interface DateSelectionModelChange<S> {
/** New value for the selection. */
selection: S;
/** Object that triggered the change. */
source: unknown;
/** Previous value */
oldValue?: S;
}
/**
* A selection model containing a date selection.
* @docs-private
*/
@Injectable()
export abstract class MatDateSelectionModel<S, D = ExtractDateTypeFromSelection<S>>
implements OnDestroy
{
private readonly _selectionChanged = new Subject<DateSelectionModelChange<S>>();
/** Emits when the selection has changed. */
selectionChanged: Observable<DateSelectionModelChange<S>> = this._selectionChanged;
protected constructor(
/** The current selection. */
readonly selection: S,
protected _adapter: DateAdapter<D>,
) {
this.selection = selection;
}
/**
* Updates the current selection in the model.
* @param value New selection that should be assigned.
* @param source Object that triggered the selection change.
*/
updateSelection(value: S, source: unknown) {
const oldValue = (this as {selection: S}).selection;
(this as {selection: S}).selection = value;
this._selectionChanged.next({selection: value, source, oldValue});
}
ngOnDestroy() {
this._selectionChanged.complete();
}
protected _isValidDateInstance(date: D): boolean {
return this._adapter.isDateInstance(date) && this._adapter.isValid(date);
}
/** Adds a date to the current selection. */
abstract add(date: D | null): void;
/** Checks whether the current selection is valid. */
abstract isValid(): boolean;
/** Checks whether the current selection is complete. */
abstract isComplete(): boolean;
/** Clones the selection model. */
abstract clone(): MatDateSelectionModel<S, D>;
}
/**
* A selection model that contains a single date.
* @docs-private
*/
@Injectable()
export class MatSingleDateSelectionModel<D> extends MatDateSelectionModel<D | null, D> {
constructor(adapter: DateAdapter<D>) {
super(null, adapter);
}
/**
* Adds a date to the current selection. In the case of a single date selection, the added date
* simply overwrites the previous selection
*/
add(date: D | null) {
super.updateSelection(date, this);
}
/** Checks whether the current selection is valid. */
isValid(): boolean {
return this.selection != null && this._isValidDateInstance(this.selection);
}
/**
* Checks whether the current selection is complete. In the case of a single date selection, this
* is true if the current selection is not null.
*/
isComplete() {
return this.selection != null;
}
/** Clones the selection model. */
clone() {
const clone = new MatSingleDateSelectionModel<D>(this._adapter);
clone.updateSelection(this.selection, this);
return clone;
}
}
/**
* A selection model that contains a date range.
* @docs-private
*/
@Injectable()
export class MatRangeDateSelectionModel<D> extends MatDateSelectionModel<DateRange<D>, D> {
constructor(adapter: DateAdapter<D>) {
super(new DateRange<D>(null, null), adapter);
}
/**
* Adds a date to the current selection. In the case of a date range selection, the added date
* fills in the next `null` value in the range. If both the start and the end already have a date,
* the selection is reset so that the given date is the new `start` and the `end` is null.
*/
add(date: D | null): void {
let {start, end} = this.selection;
if (start == null) {
start = date;
} else if (end == null) {
end = date;
} else {
start = date;
end = null;
}
super.updateSelection(new DateRange<D>(start, end), this);
}
/** Checks whether the current selection is valid. */
isValid(): boolean {
const {start, end} = this.selection;
// Empty ranges are valid.
if (start == null && end == null) {
return true;
}
// Complete ranges are only valid if both dates are valid and the start is before the end.
if (start != null && end != null) {
return (
this._isValidDateInstance(start) &&
this._isValidDateInstance(end) &&
this._adapter.compareDate(start, end) <= 0
);
}
// Partial ranges are valid if the start/end is valid.
return (
(start == null || this._isValidDateInstance(start)) &&
(end == null || this._isValidDateInstance(end))
);
}
/**
* Checks whether the current selection is complete. In the case of a date range selection, this
* is true if the current selection has a non-null `start` and `end`.
*/
isComplete(): boolean {
return this.selection.start != null && this.selection.end != null;
}
/** Clones the selection model. */
clone() {
const clone = new MatRangeDateSelectionModel<D>(this._adapter);
clone.updateSelection(this.selection, this);
return clone;
}
}
/** @docs-private */
export function MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY(
parent: MatSingleDateSelectionModel<unknown>,
adapter: DateAdapter<unknown>,
) {
return parent || new MatSingleDateSelectionModel(adapter);
}
/**
* Used to provide a single selection model to a component.
* @docs-private
*/
export const MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER: FactoryProvider = {
provide: MatDateSelectionModel,
deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter],
useFactory: MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY,
};
/** @docs-private */
export function MAT_RANGE_DATE_SELECTION_MODEL_FACTORY(
parent: MatSingleDateSelectionModel<unknown>,
adapter: DateAdapter<unknown>,
) {
return parent || new MatRangeDateSelectionModel(adapter);
}
/**
* Used to provide a range selection model to a component.
* @docs-private
*/
export const MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER: FactoryProvider = {
provide: MatDateSelectionModel,
deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter],
useFactory: MAT_RANGE_DATE_SELECTION_MODEL_FACTORY,
};
| {
"end_byte": 7131,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-selection-model.ts"
} |
components/src/material/datepicker/date-range-selection-strategy.spec.ts_0_3876 | import {TestBed} from '@angular/core/testing';
import {MatNativeDateModule} from '@angular/material/core';
import {JAN, FEB, MAR} from '../testing';
import {
MAT_DATE_RANGE_SELECTION_STRATEGY,
DefaultMatCalendarRangeStrategy,
} from './date-range-selection-strategy';
import {DateRange} from './date-selection-model';
describe('DefaultMatCalendarRangeStrategy', () => {
let strategy: DefaultMatCalendarRangeStrategy<Date>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatNativeDateModule],
providers: [
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: DefaultMatCalendarRangeStrategy},
],
});
strategy = TestBed.inject(
MAT_DATE_RANGE_SELECTION_STRATEGY,
) as DefaultMatCalendarRangeStrategy<Date>;
});
describe('createDrag', () => {
const initialRange = new DateRange(new Date(2017, FEB, 10), new Date(2017, FEB, 13));
it('drags the range start', () => {
const rangeStart = new Date(2017, FEB, 10);
// Grow range.
expect(strategy.createDrag(rangeStart, initialRange, new Date(2017, FEB, 9))).toEqual(
new DateRange(new Date(2017, FEB, 9), new Date(2017, FEB, 13)),
);
expect(strategy.createDrag(rangeStart, initialRange, new Date(2016, JAN, 9))).toEqual(
new DateRange(new Date(2016, JAN, 9), new Date(2017, FEB, 13)),
);
// Shrink range.
expect(strategy.createDrag(rangeStart, initialRange, new Date(2017, FEB, 11))).toEqual(
new DateRange(new Date(2017, FEB, 11), new Date(2017, FEB, 13)),
);
// Move range after end.
expect(strategy.createDrag(rangeStart, initialRange, new Date(2017, FEB, 14))).toEqual(
new DateRange(new Date(2017, FEB, 14), new Date(2017, FEB, 17)),
);
expect(strategy.createDrag(rangeStart, initialRange, new Date(2018, MAR, 14))).toEqual(
new DateRange(new Date(2018, MAR, 14), new Date(2018, MAR, 17)),
);
});
it('drags the range end', () => {
const rangeEnd = new Date(2017, FEB, 13);
// Grow range.
expect(strategy.createDrag(rangeEnd, initialRange, new Date(2017, FEB, 14))).toEqual(
new DateRange(new Date(2017, FEB, 10), new Date(2017, FEB, 14)),
);
expect(strategy.createDrag(rangeEnd, initialRange, new Date(2018, MAR, 14))).toEqual(
new DateRange(new Date(2017, FEB, 10), new Date(2018, MAR, 14)),
);
// Shrink range.
expect(strategy.createDrag(rangeEnd, initialRange, new Date(2017, FEB, 12))).toEqual(
new DateRange(new Date(2017, FEB, 10), new Date(2017, FEB, 12)),
);
// Move range before start.
expect(strategy.createDrag(rangeEnd, initialRange, new Date(2017, FEB, 9))).toEqual(
new DateRange(new Date(2017, FEB, 6), new Date(2017, FEB, 9)),
);
expect(strategy.createDrag(rangeEnd, initialRange, new Date(2016, JAN, 9))).toEqual(
new DateRange(new Date(2016, JAN, 6), new Date(2016, JAN, 9)),
);
});
it('drags the range middle', () => {
const rangeMiddle = new Date(2017, FEB, 11);
// Move range earlier.
expect(strategy.createDrag(rangeMiddle, initialRange, new Date(2017, FEB, 7))).toEqual(
new DateRange(new Date(2017, FEB, 6), new Date(2017, FEB, 9)),
);
expect(strategy.createDrag(rangeMiddle, initialRange, new Date(2016, JAN, 7))).toEqual(
new DateRange(new Date(2016, JAN, 6), new Date(2016, JAN, 9)),
);
// Move range later.
expect(strategy.createDrag(rangeMiddle, initialRange, new Date(2017, FEB, 15))).toEqual(
new DateRange(new Date(2017, FEB, 14), new Date(2017, FEB, 17)),
);
expect(strategy.createDrag(rangeMiddle, initialRange, new Date(2018, MAR, 15))).toEqual(
new DateRange(new Date(2018, MAR, 14), new Date(2018, MAR, 17)),
);
});
});
});
| {
"end_byte": 3876,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-selection-strategy.spec.ts"
} |
components/src/material/datepicker/month-view.spec.ts_0_8168 | import {Direction, Directionality} from '@angular/cdk/bidi';
import {
DOWN_ARROW,
END,
ENTER,
ESCAPE,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
SPACE,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {
createKeyboardEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
} from '@angular/cdk/testing/private';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {MAT_DATE_FORMATS, MatNativeDateModule} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {DEC, FEB, JAN, MAR, NOV} from '../testing';
import {MatCalendarBody, MatCalendarUserEvent} from './calendar-body';
import {
DefaultMatCalendarRangeStrategy,
MAT_DATE_RANGE_SELECTION_STRATEGY,
} from './date-range-selection-strategy';
import {DateRange} from './date-selection-model';
import {MatMonthView} from './month-view';
describe('MatMonthView', () => {
describe('standard providers', () => {
let dir: {value: Direction};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatNativeDateModule,
MatCalendarBody,
MatMonthView,
// Test components.
StandardMonthView,
MonthViewWithDateFilter,
MonthViewWithDateClass,
],
providers: [
{provide: Directionality, useFactory: () => (dir = {value: 'ltr'})},
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: DefaultMatCalendarRangeStrategy},
],
});
}));
describe('standard month view', () => {
let fixture: ComponentFixture<StandardMonthView>;
let testComponent: StandardMonthView;
let monthViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(StandardMonthView);
fixture.detectChanges();
let monthViewDebugElement = fixture.debugElement.query(By.directive(MatMonthView))!;
monthViewNativeElement = monthViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('has correct month label', () => {
let labelEl = monthViewNativeElement.querySelector('.mat-calendar-body-label')!;
expect(labelEl.innerHTML.trim()).toBe('JAN');
});
it('has 31 days', () => {
let cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell')!;
expect(cellEls.length).toBe(31);
});
it('shows selected date if in same month', () => {
let selectedEl = monthViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('10');
});
it('does not show selected date if in different month', () => {
testComponent.selected = new Date(2017, MAR, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let selectedEl = monthViewNativeElement.querySelector('.mat-calendar-body-selected');
expect(selectedEl).toBeNull();
});
it('fires selected change event on cell clicked', () => {
let cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
(cellEls[cellEls.length - 1] as HTMLElement).click();
fixture.detectChanges();
let selectedEl = monthViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('31');
});
it('should mark active date', () => {
let cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cellEls[4] as HTMLElement).innerText.trim()).toBe('5');
expect(cellEls[4].classList).toContain('mat-calendar-body-active');
});
describe('drag and drop with default range strategy', () => {
const initialRange = new DateRange(new Date(2017, JAN, 10), new Date(2017, JAN, 13));
beforeEach(() => {
testComponent.selected = initialRange;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
function getDaysMatching(selector: string) {
return Array.from(monthViewNativeElement.querySelectorAll(selector)).map(elem =>
Number(elem.textContent!.trim()),
);
}
it('drags the range start', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cellEls[9], 'mousedown');
fixture.detectChanges();
// Grow range.
dispatchMouseEvent(cellEls[8], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([9, 10, 11, 12, 13]);
// Shrink range.
dispatchMouseEvent(cellEls[10], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([11, 12, 13]);
// Move range past end.
dispatchMouseEvent(cellEls[13], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([14, 15, 16, 17]);
// End drag.
dispatchMouseEvent(cellEls[13], 'mouseup');
fixture.detectChanges();
expect(testComponent.selected).toEqual(
new DateRange(new Date(2017, JAN, 14), new Date(2017, JAN, 17)),
);
});
it('drags the range end', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cellEls[12], 'mousedown');
fixture.detectChanges();
// Grow range.
dispatchMouseEvent(cellEls[13], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([10, 11, 12, 13, 14]);
// Shrink range.
dispatchMouseEvent(cellEls[11], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([10, 11, 12]);
// Move range before start.
dispatchMouseEvent(cellEls[8], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([6, 7, 8, 9]);
// End drag.
dispatchMouseEvent(cellEls[8], 'mouseup');
fixture.detectChanges();
expect(testComponent.selected).toEqual(
new DateRange(new Date(2017, JAN, 6), new Date(2017, JAN, 9)),
);
});
it('drags the range middle', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cellEls[11], 'mousedown');
fixture.detectChanges();
// Move range down.
dispatchMouseEvent(cellEls[10], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([9, 10, 11, 12]);
// Move range up.
dispatchMouseEvent(cellEls[12], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([11, 12, 13, 14]);
// End drag.
dispatchMouseEvent(cellEls[12], 'mouseup');
fixture.detectChanges();
expect(testComponent.selected).toEqual(
new DateRange(new Date(2017, JAN, 11), new Date(2017, JAN, 14)),
);
});
it('does nothing when dragging outside range', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cellEls[8], 'mousedown');
fixture.detectChanges();
dispatchMouseEvent(cellEls[7], 'mouseenter');
fixture.detectChanges();
expect(getDaysMatching('.mat-calendar-body-in-preview')).toEqual([]);
dispatchMouseEvent(cellEls[7], 'mouseup');
fixture.detectChanges();
expect(testComponent.selected).toEqual(initialRange);
});
}); | {
"end_byte": 8168,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.spec.ts"
} |
components/src/material/datepicker/month-view.spec.ts_8176_17912 | describe('a11y', () => {
it('should set the correct role on the internal table node', () => {
const table = monthViewNativeElement.querySelector('table')!;
expect(table.getAttribute('role')).toBe('grid');
});
it('should set the correct scope on the table headers', () => {
const nonDividerHeaders = monthViewNativeElement.querySelectorAll(
'.mat-calendar-table-header th:not(.mat-calendar-table-header-divider)',
);
const dividerHeader = monthViewNativeElement.querySelector(
'.mat-calendar-table-header-divider',
)!;
expect(
Array.from(nonDividerHeaders).every(header => {
return header.getAttribute('scope') === 'col';
}),
).toBe(true);
expect(dividerHeader.hasAttribute('scope')).toBe(false);
});
describe('calendar body', () => {
let calendarBodyEl: HTMLElement;
let calendarInstance: StandardMonthView;
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 date on left arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 4));
calendarInstance.date = new Date(2017, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 31));
});
it('should increment date on left arrow press in rtl', () => {
dir.value = 'rtl';
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 6));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 7));
});
it('should increment date on right arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 6));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 7));
});
it('should decrement date on right arrow press in rtl', () => {
dir.value = 'rtl';
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 4));
calendarInstance.date = new Date(2017, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 31));
});
it('should go up a row on up arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 29));
calendarInstance.date = new Date(2017, JAN, 7);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 31));
});
it('should go down a row on down arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 12));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 19));
});
it('should go to beginning of the month on home press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 1));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 1));
});
it('should go to end of the month on end press', () => {
calendarInstance.date = new Date(2017, JAN, 10);
fixture.changeDetectorRef.markForCheck();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 31));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 31));
});
it('should go back one month on page up press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, DEC, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, NOV, 5));
});
it('should go forward one month on page down press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, FEB, 5));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAR, 5));
});
it('should select active date on enter', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JAN, 10));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', ENTER);
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keyup', ENTER);
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JAN, 4));
});
it('should select active date on space', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JAN, 10));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', SPACE);
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keyup', SPACE);
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JAN, 4));
});
it('should cancel the current range selection when pressing escape', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
testComponent.selected = new DateRange(new Date(2017, JAN, 10), null);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cellEls[15], 'mouseenter');
fixture.detectChanges();
// Note that here we only care that _some_ kind of range is rendered. There are
// plenty of tests in the calendar body which assert that everything is correct.
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-start').length,
).toBeGreaterThan(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-in-preview').length,
).toBeGreaterThan(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-end').length,
).toBeGreaterThan(0);
const event = createKeyboardEvent('keydown', ESCAPE, 'Escape');
spyOn(event, 'stopPropagation');
dispatchEvent(calendarBodyEl, event);
fixture.detectChanges();
// Expect the range range to have been cleared.
expect(
monthViewNativeElement.querySelectorAll(
[
'.mat-calendar-body-preview-start',
'.mat-calendar-body-in-preview',
'.mat-calendar-body-preview-end',
].join(','),
).length,
).toBe(0);
expect(event.stopPropagation).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
expect(testComponent.selected).toBeFalsy();
}); | {
"end_byte": 17912,
"start_byte": 8176,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.spec.ts"
} |
components/src/material/datepicker/month-view.spec.ts_17924_28620 | it(
'should not cancel the current range selection when pressing escape with a ' +
'modifier key',
() => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
testComponent.selected = new DateRange(new Date(2017, JAN, 10), null);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cellEls[15], 'mouseenter');
fixture.detectChanges();
const rangeStarts = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-preview-start',
).length;
const rangeMids = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-in-preview',
).length;
const rangeEnds = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-preview-end',
).length;
// Note that here we only care that _some_ kind of range is rendered. There are
// plenty of tests in the calendar body which assert that everything is correct.
expect(rangeStarts).toBeGreaterThan(0);
expect(rangeMids).toBeGreaterThan(0);
expect(rangeEnds).toBeGreaterThan(0);
const event = createKeyboardEvent('keydown', ESCAPE, 'Escape', {alt: true});
spyOn(event, 'stopPropagation');
dispatchEvent(calendarBodyEl, event);
fixture.detectChanges();
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-start').length,
).toBe(rangeStarts);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-in-preview').length,
).toBe(rangeMids);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-end').length,
).toBe(rangeEnds);
expect(event.stopPropagation).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
expect(testComponent.selected).toBeTruthy();
},
);
it('cancels the active drag but not the selection on escape during an active drag', () => {
const cellEls = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
const selectedRange = new DateRange(new Date(2017, JAN, 10), new Date(2017, JAN, 17));
testComponent.selected = selectedRange;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cellEls[11], 'mousedown');
fixture.detectChanges();
dispatchMouseEvent(cellEls[4], 'mouseenter');
fixture.detectChanges();
const rangeStarts = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-preview-start',
).length;
const rangeMids = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-in-preview',
).length;
const rangeEnds = monthViewNativeElement.querySelectorAll(
'.mat-calendar-body-preview-end',
).length;
// Note that here we only care that _some_ kind of range is rendered. There are
// plenty of tests in the calendar body which assert that everything is correct.
expect(rangeStarts).toBeGreaterThan(0);
expect(rangeMids).toBeGreaterThan(0);
expect(rangeEnds).toBeGreaterThan(0);
const event = createKeyboardEvent('keydown', ESCAPE, 'Escape');
spyOn(event, 'stopPropagation');
dispatchEvent(calendarBodyEl, event);
fixture.detectChanges();
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-start').length,
).toBe(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-in-preview').length,
).toBe(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-end').length,
).toBe(0);
expect(event.stopPropagation).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
expect(testComponent.selected).toEqual(selectedRange);
});
it('should clear the preview range when the user is done selecting', () => {
const cellEls =
monthViewNativeElement.querySelectorAll<HTMLElement>('.mat-calendar-body-cell');
testComponent.selected = new DateRange(new Date(2017, JAN, 10), null);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchMouseEvent(cellEls[15], 'mouseenter');
fixture.detectChanges();
// Note that here we only care that _some_ kind of range is rendered. There are
// plenty of tests in the calendar body which assert that everything is correct.
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-start').length,
).toBeGreaterThan(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-in-preview').length,
).toBeGreaterThan(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-end').length,
).toBeGreaterThan(0);
cellEls[15].click();
fixture.detectChanges();
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-start').length,
).toBe(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-in-preview').length,
).toBe(0);
expect(
monthViewNativeElement.querySelectorAll('.mat-calendar-body-preview-end').length,
).toBe(0);
});
it('should not clear the range when pressing escape while there is no preview', () => {
const getRangeElements = () =>
monthViewNativeElement.querySelectorAll(
[
'.mat-calendar-body-range-start',
'.mat-calendar-body-in-range',
'.mat-calendar-body-range-end',
].join(','),
);
testComponent.selected = new DateRange(
new Date(2017, JAN, 10),
new Date(2017, JAN, 15),
);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getRangeElements().length)
.withContext('Expected range to be present on init.')
.toBeGreaterThan(0);
dispatchKeyboardEvent(calendarBodyEl, 'keydown', ESCAPE);
fixture.detectChanges();
expect(getRangeElements().length)
.withContext('Expected range to be present after pressing the escape key.')
.toBeGreaterThan(0);
});
it(
'should not fire the selected change event when clicking on an already-selected ' +
'date while selecting a single date',
() => {
testComponent.selected = new Date(2017, JAN, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.selectedChangeSpy).not.toHaveBeenCalled();
const selectedCell = monthViewNativeElement.querySelector(
'.mat-calendar-body-selected',
) as HTMLElement;
selectedCell.click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedChangeSpy).not.toHaveBeenCalled();
},
);
it(
'should fire the selected change event when clicking on an already-selected ' +
'date while selecting a range',
() => {
const selectedDate = new Date(2017, JAN, 10);
testComponent.selected = new DateRange(selectedDate, null);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.selectedChangeSpy).not.toHaveBeenCalled();
const selectedCell = monthViewNativeElement.querySelector(
'.mat-calendar-body-selected',
) as HTMLElement;
selectedCell.click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedChangeSpy).toHaveBeenCalledWith(
selectedDate,
);
},
);
it(
'should fire the _userSelection event with the correct value when clicking ' +
'on a selected date',
() => {
const date = new Date(2017, JAN, 10);
testComponent.selected = date;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.userSelectionSpy).not.toHaveBeenCalled();
const selectedCell = monthViewNativeElement.querySelector(
'.mat-calendar-body-selected',
) as HTMLElement;
selectedCell.click();
fixture.detectChanges();
expect(fixture.componentInstance.userSelectionSpy).toHaveBeenCalledWith(
jasmine.objectContaining({value: date}),
);
},
);
it('should go to month that is focused', () => {
const jan11Cell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="1"][data-mat-col="3"] button',
) as HTMLElement;
dispatchFakeEvent(jan11Cell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 11));
});
it('should not call `.focus()` when the active date is focused', () => {
const jan5Cell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="0"][data-mat-col="4"] button',
) as HTMLElement;
const focusSpy = (jan5Cell.focus = jasmine.createSpy('cellFocused'));
dispatchFakeEvent(jan5Cell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 5));
expect(focusSpy).not.toHaveBeenCalled();
});
});
});
}); | {
"end_byte": 28620,
"start_byte": 17924,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.spec.ts"
} |
components/src/material/datepicker/month-view.spec.ts_28626_34859 | describe('month view with date filter', () => {
it('should disable filtered dates', () => {
const fixture = TestBed.createComponent(MonthViewWithDateFilter);
fixture.detectChanges();
let cells = fixture.nativeElement.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).toContain('mat-calendar-body-disabled');
expect(cells[1].classList).not.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(MonthViewWithDateFilter);
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(MonthViewWithDateFilter);
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();
});
});
describe('month view with custom date classes', () => {
let fixture: ComponentFixture<MonthViewWithDateClass>;
let monthViewNativeElement: Element;
let dateClassSpy: jasmine.Spy;
beforeEach(() => {
fixture = TestBed.createComponent(MonthViewWithDateClass);
dateClassSpy = spyOn(fixture.componentInstance, 'dateClass').and.callThrough();
fixture.detectChanges();
let monthViewDebugElement = fixture.debugElement.query(By.directive(MatMonthView))!;
monthViewNativeElement = monthViewDebugElement.nativeElement;
});
it('should be able to add a custom class to some dates', () => {
let cells = monthViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).not.toContain('even');
expect(cells[1].classList).toContain('even');
});
it('should call dateClass with the correct view name', () => {
expect(dateClassSpy).toHaveBeenCalledWith(jasmine.any(Date), 'month');
});
});
});
describe('month view with custom date formats', () => {
let fixture: ComponentFixture<StandardMonthView>;
let monthViewNativeElement: Element;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatNativeDateModule,
MatCalendarBody,
MatMonthView,
// Test components.
StandardMonthView,
MonthViewWithDateFilter,
MonthViewWithDateClass,
],
providers: [
{provide: Directionality, useFactory: () => ({value: 'ltr'})},
{provide: MAT_DATE_RANGE_SELECTION_STRATEGY, useClass: DefaultMatCalendarRangeStrategy},
{
provide: MAT_DATE_FORMATS,
useValue: {
parse: {
dateInput: null,
},
display: {
dateInput: {year: 'numeric', month: 'numeric', day: 'numeric'},
monthLabel: {year: 'numeric', month: 'short'},
monthYearLabel: {year: 'numeric', month: 'short'},
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
},
},
},
],
});
fixture = TestBed.createComponent(StandardMonthView);
fixture.detectChanges();
let monthViewDebugElement = fixture.debugElement.query(By.directive(MatMonthView))!;
monthViewNativeElement = monthViewDebugElement.nativeElement;
}));
it('has correct month label', () => {
let labelEl = monthViewNativeElement.querySelector('.mat-calendar-body-label')!;
expect(labelEl.innerHTML.trim()).toBe('Jan 2017');
});
});
});
@Component({
template: `
<mat-month-view
[(activeDate)]="date"
[(selected)]="selected"
(selectedChange)="selectedChangeSpy($event)"
(_userSelection)="userSelectionSpy($event)"
(dragStarted)="dragStarted($event)"
(dragEnded)="dragEnded($event)"
[activeDrag]="activeDrag"></mat-month-view>
`,
standalone: true,
imports: [MatMonthView],
})
class StandardMonthView {
date = new Date(2017, JAN, 5);
selected: Date | DateRange<Date> = new Date(2017, JAN, 10);
selectedChangeSpy = jasmine.createSpy('selectedChange');
userSelectionSpy = jasmine.createSpy('userSelection');
activeDrag: MatCalendarUserEvent<Date> | null = null;
dragStarted(event: MatCalendarUserEvent<Date>) {
this.activeDrag = event;
}
dragEnded(event: MatCalendarUserEvent<DateRange<Date> | null>) {
if (!this.activeDrag) return;
if (event.value) {
this.selected = event.value;
}
this.activeDrag = null;
}
}
@Component({
template: `
<mat-month-view
[activeDate]="activeDate"
[dateFilter]="dateFilter"
[minDate]="minDate"
[maxDate]="maxDate"></mat-month-view>`,
standalone: true,
imports: [MatMonthView],
})
class MonthViewWithDateFilter {
activeDate = new Date(2017, JAN, 1);
minDate: Date | null = null;
maxDate: Date | null = null;
dateFilter(date: Date) {
return date.getDate() % 2 == 0;
}
}
@Component({
template: `<mat-month-view [activeDate]="activeDate" [dateClass]="dateClass"></mat-month-view>`,
standalone: true,
imports: [MatMonthView],
})
class MonthViewWithDateClass {
activeDate = new Date(2017, JAN, 1);
dateClass(date: Date) {
return date.getDate() % 2 == 0 ? 'even' : undefined;
}
} | {
"end_byte": 34859,
"start_byte": 28626,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/month-view.spec.ts"
} |
components/src/material/datepicker/datepicker-content.html_0_1694 | <div
cdkTrapFocus
role="dialog"
[attr.aria-modal]="true"
[attr.aria-labelledby]="_dialogLabelId ?? undefined"
class="mat-datepicker-content-container"
[class.mat-datepicker-content-container-with-custom-header]="datepicker.calendarHeaderComponent"
[class.mat-datepicker-content-container-with-actions]="_actionsPortal">
<mat-calendar
[id]="datepicker.id"
[class]="datepicker.panelClass"
[startAt]="datepicker.startAt"
[startView]="datepicker.startView"
[minDate]="datepicker._getMinDate()"
[maxDate]="datepicker._getMaxDate()"
[dateFilter]="datepicker._getDateFilter()"
[headerComponent]="datepicker.calendarHeaderComponent"
[selected]="_getSelected()"
[dateClass]="datepicker.dateClass"
[comparisonStart]="comparisonStart"
[comparisonEnd]="comparisonEnd"
[@fadeInCalendar]="'enter'"
[startDateAccessibleName]="startDateAccessibleName"
[endDateAccessibleName]="endDateAccessibleName"
(yearSelected)="datepicker._selectYear($event)"
(monthSelected)="datepicker._selectMonth($event)"
(viewChanged)="datepicker._viewChanged($event)"
(_userSelection)="_handleUserSelection($event)"
(_userDragDrop)="_handleUserDragDrop($event)"></mat-calendar>
<ng-template [cdkPortalOutlet]="_actionsPortal"></ng-template>
<!-- Invisible close button for screen reader users. -->
<button
type="button"
mat-raised-button
[color]="color || 'primary'"
class="mat-datepicker-close-button"
[class.cdk-visually-hidden]="!_closeButtonFocused"
(focus)="_closeButtonFocused = true"
(blur)="_closeButtonFocused = false"
(click)="datepicker.close()">{{ _closeButtonText }}</button>
</div>
| {
"end_byte": 1694,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-content.html"
} |
components/src/material/datepicker/multi-year-view.spec.ts_0_684 | 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 {JAN, MAR} from '../testing';
import {MatCalendarBody} from './calendar-body';
import {MatMultiYearView, yearsPerPage, yearsPerRow} from './multi-year-view'; | {
"end_byte": 684,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.spec.ts"
} |
components/src/material/datepicker/multi-year-view.spec.ts_686_9374 | describe('MatMultiYearView', () => {
let dir: {value: Direction};
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatNativeDateModule,
MatCalendarBody,
MatMultiYearView,
// Test components.
StandardMultiYearView,
MultiYearViewWithDateFilter,
MultiYearViewWithMinMaxDate,
MultiYearViewWithDateClass,
],
providers: [{provide: Directionality, useFactory: () => (dir = {value: 'ltr'})}],
});
}));
describe('standard multi-year view', () => {
let fixture: ComponentFixture<StandardMultiYearView>;
let testComponent: StandardMultiYearView;
let multiYearViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(StandardMultiYearView);
fixture.detectChanges();
let multiYearViewDebugElement = fixture.debugElement.query(By.directive(MatMultiYearView))!;
multiYearViewNativeElement = multiYearViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('has correct number of years', () => {
let cellEls = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell')!;
expect(cellEls.length).toBe(yearsPerPage);
});
it('shows selected year if in same range', () => {
let selectedEl = multiYearViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('2020');
});
it('does not show selected year if in different range', () => {
testComponent.selected = new Date(2040, JAN, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let selectedEl = multiYearViewNativeElement.querySelector('.mat-calendar-body-selected');
expect(selectedEl).toBeNull();
});
it('fires selected change event on cell clicked', () => {
let cellEls = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
(cellEls[cellEls.length - 1] as HTMLElement).click();
fixture.detectChanges();
let selectedEl = multiYearViewNativeElement.querySelector('.mat-calendar-body-selected')!;
expect(selectedEl.innerHTML.trim()).toBe('2039');
});
it('should emit the selected year on cell clicked', () => {
let cellEls = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
(cellEls[1] as HTMLElement).click();
fixture.detectChanges();
const normalizedYear: Date = fixture.componentInstance.selectedYear;
expect(normalizedYear.getFullYear()).toEqual(2017);
});
it('should mark active date', () => {
let cellEls = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cellEls[1] as HTMLElement).innerText.trim()).toBe('2017');
expect(cellEls[1].classList).toContain('mat-calendar-body-active');
});
describe('a11y', () => {
it('should set the correct role on the internal table node', () => {
const table = multiYearViewNativeElement.querySelector('table')!;
expect(table.getAttribute('role')).toBe('grid');
});
describe('calendar body', () => {
let calendarBodyEl: HTMLElement;
let calendarInstance: StandardMultiYearView;
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, 3);
fixture.changeDetectorRef.markForCheck();
dispatchFakeEvent(calendarBodyEl, 'focus');
fixture.detectChanges();
});
it('should decrement year on left arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2015, JAN, 3));
});
it('should increment year on right arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2018, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2019, JAN, 3));
});
it('should go up a row on up arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 - yearsPerRow, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 - yearsPerRow * 2, JAN, 3));
});
it('should go down a row on down arrow press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 + yearsPerRow, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 + yearsPerRow * 2, JAN, 3));
});
it('should go to first year in current range on home press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', HOME);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2016, JAN, 3));
});
it('should go to last year in current range on end press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2039, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', END);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2039, JAN, 3));
});
it('should go to same index in previous year range page up press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 - yearsPerPage, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 - yearsPerPage * 2, JAN, 3));
});
it('should go to same index in next year range on page down press', () => {
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 + yearsPerPage, JAN, 3));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017 + yearsPerPage * 2, JAN, 3));
});
it('should go to the year that is focused', () => {
fixture.componentInstance.date = new Date(2017, MAR, 5);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, MAR, 5));
const year2022Cell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="1"][data-mat-col="2"] button',
) as HTMLElement;
dispatchFakeEvent(year2022Cell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2022, MAR, 5));
});
it('should not call `.focus()` when the active date is focused', () => {
const year2017Cell = fixture.debugElement.nativeElement.querySelector(
'[data-mat-row="0"][data-mat-col="1"] button',
) as HTMLElement;
const focusSpy = (year2017Cell.focus = jasmine.createSpy('cellFocused'));
dispatchFakeEvent(year2017Cell, 'focus');
fixture.detectChanges();
expect(calendarInstance.date).toEqual(new Date(2017, JAN, 3));
expect(focusSpy).not.toHaveBeenCalled();
});
});
});
}); | {
"end_byte": 9374,
"start_byte": 686,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.spec.ts"
} |
components/src/material/datepicker/multi-year-view.spec.ts_9378_17166 | describe('multi year view with date filter', () => {
it('should disable years with no enabled days', () => {
const fixture = TestBed.createComponent(MultiYearViewWithDateFilter);
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(MultiYearViewWithDateFilter);
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(MultiYearViewWithDateFilter);
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();
});
});
describe('multi year view with minDate only', () => {
let fixture: ComponentFixture<MultiYearViewWithMinMaxDate>;
let testComponent: MultiYearViewWithMinMaxDate;
let multiYearViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(MultiYearViewWithMinMaxDate);
const multiYearViewDebugElement = fixture.debugElement.query(By.directive(MatMultiYearView))!;
multiYearViewNativeElement = multiYearViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('should begin first page with minDate', () => {
testComponent.minDate = new Date(2014, JAN, 1);
testComponent.maxDate = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const cells = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cells[0] as HTMLElement).innerText.trim()).toBe('2014');
});
});
describe('multi year view with maxDate only', () => {
let fixture: ComponentFixture<MultiYearViewWithMinMaxDate>;
let testComponent: MultiYearViewWithMinMaxDate;
let multiYearViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(MultiYearViewWithMinMaxDate);
const multiYearViewDebugElement = fixture.debugElement.query(By.directive(MatMultiYearView))!;
multiYearViewNativeElement = multiYearViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('should end last page with maxDate', () => {
testComponent.minDate = null;
testComponent.maxDate = new Date(2020, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const cells = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cells[cells.length - 1] as HTMLElement).innerText.trim()).toBe('2020');
});
});
describe('multi year view with minDate and maxDate', () => {
let fixture: ComponentFixture<MultiYearViewWithMinMaxDate>;
let testComponent: MultiYearViewWithMinMaxDate;
let multiYearViewNativeElement: Element;
beforeEach(() => {
fixture = TestBed.createComponent(MultiYearViewWithMinMaxDate);
const multiYearViewDebugElement = fixture.debugElement.query(By.directive(MatMultiYearView))!;
multiYearViewNativeElement = multiYearViewDebugElement.nativeElement;
testComponent = fixture.componentInstance;
});
it('should end last page with maxDate', () => {
testComponent.minDate = new Date(2006, JAN, 1);
testComponent.maxDate = new Date(2020, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const cells = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect((cells[cells.length - 1] as HTMLElement).innerText.trim()).toBe('2020');
});
it('should disable dates before minDate', () => {
testComponent.minDate = new Date(2006, JAN, 1);
testComponent.maxDate = new Date(2020, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const cells = multiYearViewNativeElement.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).toContain('mat-calendar-body-disabled');
expect(cells[8].classList).toContain('mat-calendar-body-disabled');
expect(cells[9].classList).not.toContain('mat-calendar-body-disabled');
});
});
describe('multi-year view with custom date classes', () => {
let fixture: ComponentFixture<MultiYearViewWithDateClass>;
let multiYearViewNativeElement: Element;
let dateClassSpy: jasmine.Spy;
beforeEach(() => {
fixture = TestBed.createComponent(MultiYearViewWithDateClass);
dateClassSpy = spyOn(fixture.componentInstance, 'dateClass').and.callThrough();
fixture.detectChanges();
let multiYearViewDebugElement = fixture.debugElement.query(By.directive(MatMultiYearView))!;
multiYearViewNativeElement = multiYearViewDebugElement.nativeElement;
});
it('should be able to add a custom class to some dates', () => {
let cells = multiYearViewNativeElement.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), 'multi-year');
});
});
});
@Component({
template: `
<mat-multi-year-view [(activeDate)]="date" [(selected)]="selected"
(yearSelected)="selectedYear=$event"></mat-multi-year-view>`,
standalone: true,
imports: [MatMultiYearView],
})
class StandardMultiYearView {
date = new Date(2017, JAN, 1);
selected = new Date(2020, JAN, 1);
selectedYear: Date;
@ViewChild(MatMultiYearView) multiYearView: MatMultiYearView<Date>;
}
@Component({
template: `
<mat-multi-year-view
[(activeDate)]="activeDate"
[dateFilter]="dateFilter"
[minDate]="minDate"
[maxDate]="maxDate"></mat-multi-year-view>
`,
standalone: true,
imports: [MatMultiYearView],
})
class MultiYearViewWithDateFilter {
activeDate = new Date(2017, JAN, 1);
minDate: Date | null = null;
maxDate: Date | null = null;
dateFilter(date: Date) {
return date.getFullYear() !== 2017;
}
}
@Component({
template: `
<mat-multi-year-view [(activeDate)]="activeDate" [minDate]="minDate" [maxDate]="maxDate">
</mat-multi-year-view>
`,
standalone: true,
imports: [MatMultiYearView],
})
class MultiYearViewWithMinMaxDate {
activeDate = new Date(2019, JAN, 1);
minDate: Date | null;
maxDate: Date | null;
}
@Component({
template: `
<mat-multi-year-view [activeDate]="activeDate" [dateClass]="dateClass"></mat-multi-year-view>
`,
standalone: true,
imports: [MatMultiYearView],
})
class MultiYearViewWithDateClass {
activeDate = new Date(2017, JAN, 1);
dateClass(date: Date) {
return date.getFullYear() % 2 == 0 ? 'even' : undefined;
}
} | {
"end_byte": 17166,
"start_byte": 9378,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.spec.ts"
} |
components/src/material/datepicker/calendar-body.scss_0_8511 | @use 'sass:math';
@use '@angular/cdk';
@use '../core/style/button-common';
@use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/tokens/token-utils';
$calendar-body-label-padding-start: 5% !default;
// We don't want the label to jump around when we switch between month and year views, so we use
// the same amount of padding regardless of the number of columns. We align the header label with
// the one third mark of the first cell, this was chosen somewhat arbitrarily to make it look
// roughly like the mock. Half way is too far since the cell text is center aligned.
$calendar-body-label-side-padding: math.div(33%, 7) !default;
$calendar-body-cell-min-size: 32px !default;
$calendar-body-cell-content-margin: 5% !default;
$calendar-body-cell-content-border-width: 1px !default;
$calendar-body-cell-radius: 999px !default;
$calendar-body-preview-cell-border: dashed 1px;
$calendar-body-min-size: 7 * $calendar-body-cell-min-size !default;
$calendar-body-cell-content-size: 100% - $calendar-body-cell-content-margin * 2 !default;
$calendar-range-end-body-cell-size:
$calendar-body-cell-content-size + $calendar-body-cell-content-margin !default;
$_tokens: (tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots());
// Styles for a highlighted calendar cell (e.g. hovered or focused).
@mixin _highlighted-cell($token-name) {
& > .mat-calendar-body-cell-content {
@include _unselected-cell {
@include token-utils.create-token-slot(background-color, $token-name);
}
}
}
// Utility mixin to target cells that aren't selected. Used to make selector easier to follow.
@mixin _unselected-cell {
&:not(.mat-calendar-body-selected):not(.mat-calendar-body-comparison-identical) {
@content;
}
}
.mat-calendar-body {
min-width: $calendar-body-min-size;
}
.mat-calendar-body-today {
@include _unselected-cell {
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(border-color,
calendar-date-today-outline-color);
}
}
}
.mat-calendar-body-label {
height: 0;
line-height: 0;
text-align: start;
padding-left: $calendar-body-label-side-padding;
padding-right: $calendar-body-label-side-padding;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(font-size, calendar-body-label-text-size);
@include token-utils.create-token-slot(font-weight, calendar-body-label-text-weight);
@include token-utils.create-token-slot(color, calendar-body-label-text-color);
}
}
// Label that is not rendered and removed from the accessibility tree.
.mat-calendar-body-hidden-label {
display: none;
}
.mat-calendar-body-cell-container {
position: relative;
height: 0;
line-height: 0;
}
.mat-calendar-body-cell {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: none;
text-align: center;
outline: none;
font-family: inherit;
margin: 0;
// Needs to be repeated here in order to override the user agent styles.
@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);
}
@include button-common.reset();
}
// We use ::before to apply a background to the body cell, because we need to apply a border
// radius to the start/end which means that part of the element will be cut off, making hovering
// through all the cells look glitchy. We can't do it on the cell itself, because it's the one
// that has the event listener and it can't be on the cell content, because it always has a
// border radius. Note that this and the selectors below can be much simpler if we were to use
// two separate elements for the main and comparison ranges, like we're doing for the preview
// range. We don't follow the simpler approach, because the range colors usually have some
// kind of opacity, which means that they'll start mixing when they're layered on top of each
// other, making the calendar look messy.
.mat-calendar-body-cell::before,
.mat-calendar-body-cell::after,
.mat-calendar-body-cell-preview {
content: '';
position: absolute;
top: $calendar-body-cell-content-margin;
left: 0;
z-index: 0;
box-sizing: border-box;
display: block;
// We want the range background to be slightly shorter than the cell so
// that there's a gap when the range goes across multiple rows.
height: $calendar-body-cell-content-size;
width: 100%;
}
.mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,
.mat-calendar-body-range-start::after,
.mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,
.mat-calendar-body-comparison-start::after,
.mat-calendar-body-preview-start .mat-calendar-body-cell-preview {
// Since the range background isn't a perfect circle, we need to size
// and offset the start so that it aligns with the main circle.
left: $calendar-body-cell-content-margin;
width: $calendar-range-end-body-cell-size;
border-top-left-radius: $calendar-body-cell-radius;
border-bottom-left-radius: $calendar-body-cell-radius;
[dir='rtl'] & {
left: 0;
border-radius: 0;
border-top-right-radius: $calendar-body-cell-radius;
border-bottom-right-radius: $calendar-body-cell-radius;
}
}
@mixin _range-right-radius {
// Since the range background isn't a perfect circle, we need to
// resize the end so that it aligns with the main circle.
width: $calendar-range-end-body-cell-size;
border-top-right-radius: $calendar-body-cell-radius;
border-bottom-right-radius: $calendar-body-cell-radius;
}
.mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,
.mat-calendar-body-range-end::after,
.mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,
.mat-calendar-body-comparison-end::after,
.mat-calendar-body-preview-end .mat-calendar-body-cell-preview {
@include _range-right-radius;
[dir='rtl'] & {
left: $calendar-body-cell-content-margin;
border-radius: 0;
border-top-left-radius: $calendar-body-cell-radius;
border-bottom-left-radius: $calendar-body-cell-radius;
}
}
// Styles necessary to make RTL work.
[dir='rtl'] {
.mat-calendar-body-comparison-bridge-start.mat-calendar-body-range-end::after,
.mat-calendar-body-comparison-bridge-end.mat-calendar-body-range-start::after {
@include _range-right-radius;
}
}
// Prevents the extra overlap range indication from showing up when it's not supposed to.
.mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,
.mat-calendar-body-comparison-end.mat-calendar-body-range-start::after {
// Note that the RTL selector here is redundant, but we need to keep it in order to
// raise the specificity since it can be overridden by some of the styles from above.
&, [dir='rtl'] & {
width: $calendar-body-cell-content-size;
}
}
.mat-calendar-body-in-preview {
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, calendar-date-preview-state-outline-color);
}
.mat-calendar-body-cell-preview {
border-top: $calendar-body-preview-cell-border;
border-bottom: $calendar-body-preview-cell-border;
}
}
.mat-calendar-body-preview-start .mat-calendar-body-cell-preview {
border-left: $calendar-body-preview-cell-border;
[dir='rtl'] & {
border-left: 0;
border-right: $calendar-body-preview-cell-border;
}
}
.mat-calendar-body-preview-end .mat-calendar-body-cell-preview {
border-right: $calendar-body-preview-cell-border;
[dir='rtl'] & {
border-right: 0;
border-left: $calendar-body-preview-cell-border;
}
}
.mat-calendar-body-disabled {
cursor: default;
@include token-utils.use-tokens($_tokens...) {
& > .mat-calendar-body-cell-content {
@include _unselected-cell {
@include token-utils.create-token-slot(color, calendar-date-disabled-state-text-color);
}
}
& > .mat-calendar-body-today {
@include _unselected-cell {
@include token-utils.create-token-slot(border-color,
calendar-date-today-disabled-state-outline-color);
}
}
}
// Fade out the disabled cells so that they can be distinguished from the enabled ones. Note that
// ideally we'd use `color: GreyText` here which is what the browser uses for disabled buttons,
// but we can't because Firefox doesn't recognize it.
@include cdk | {
"end_byte": 8511,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.scss"
} |
components/src/material/datepicker/calendar-body.scss_8511_14207 | .high-contrast {
opacity: 0.5;
}
}
.mat-calendar-body-cell-content {
top: $calendar-body-cell-content-margin;
left: $calendar-body-cell-content-margin;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
width: $calendar-body-cell-content-size;
height: $calendar-body-cell-content-size;
// Prevents text being off-center on Android.
line-height: 1;
border-width: $calendar-body-cell-content-border-width;
border-style: solid;
// Choosing a value clearly larger than the height ensures we get the correct capsule shape.
border-radius: $calendar-body-cell-radius;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, calendar-date-text-color);
@include token-utils.create-token-slot(border-color,
calendar-date-outline-color);
}
// Increase specificity because focus indicator styles are part of the `mat-core` mixin and can
// potentially overwrite the absolute position of the container.
&.mat-focus-indicator {
position: absolute;
}
@include cdk.high-contrast {
border: none;
}
}
.mat-calendar-body-active {
@include token-utils.use-tokens($_tokens...) {
.cdk-keyboard-focused &, .cdk-program-focused & {
@include _highlighted-cell(calendar-date-focus-state-background-color);
}
}
}
@media (hover: hover) {
.mat-calendar-body-cell:not(.mat-calendar-body-disabled):hover {
@include token-utils.use-tokens($_tokens...) {
@include _highlighted-cell(calendar-date-hover-state-background-color);
}
}
}
.mat-calendar-body-selected {
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(background-color,
calendar-date-selected-state-background-color);
@include token-utils.create-token-slot(color, calendar-date-selected-state-text-color);
.mat-calendar-body-disabled > & {
@include token-utils.create-token-slot(background-color,
calendar-date-selected-disabled-state-background-color);
}
&.mat-calendar-body-today {
$shadow: token-utils.get-token-variable(calendar-date-today-selected-state-outline-color);
box-shadow: inset 0 0 0 1px #{$shadow};
}
}
}
@include token-utils.use-tokens($_tokens...) {
$range-color:
token-utils.get-token-variable(calendar-date-in-range-state-background-color);
$comparison-color:
token-utils.get-token-variable(calendar-date-in-comparison-range-state-background-color);
.mat-calendar-body-in-range::before {
@include token-utils.create-token-slot(background,
calendar-date-in-range-state-background-color);
}
.mat-calendar-body-comparison-identical,
.mat-calendar-body-in-comparison-range::before {
@include token-utils.create-token-slot(background,
calendar-date-in-comparison-range-state-background-color);
}
.mat-calendar-body-comparison-identical,
.mat-calendar-body-in-comparison-range::before {
@include token-utils.create-token-slot(background,
calendar-date-in-comparison-range-state-background-color);
}
.mat-calendar-body-comparison-bridge-start::before,
[dir='rtl'] .mat-calendar-body-comparison-bridge-end::before {
background: linear-gradient(to right, $range-color 50%, $comparison-color 50%);
}
.mat-calendar-body-comparison-bridge-end::before,
[dir='rtl'] .mat-calendar-body-comparison-bridge-start::before {
background: linear-gradient(to left, $range-color 50%, $comparison-color 50%);
}
.mat-calendar-body-in-range > .mat-calendar-body-comparison-identical,
.mat-calendar-body-in-comparison-range.mat-calendar-body-in-range::after {
@include token-utils.create-token-slot(background,
calendar-date-in-overlap-range-state-background-color);
}
.mat-calendar-body-comparison-identical.mat-calendar-body-selected,
.mat-calendar-body-in-comparison-range > .mat-calendar-body-selected {
@include token-utils.create-token-slot(background,
calendar-date-in-overlap-range-selected-state-background-color);
}
}
@include cdk.high-contrast {
$main-range-border: solid 1px;
$comparison-range-border: dashed 1px;
.mat-datepicker-popup:not(:empty),
.mat-calendar-body-cell:not(.mat-calendar-body-in-range) .mat-calendar-body-selected {
outline: solid 1px;
}
.mat-calendar-body-today {
outline: dotted 1px;
}
// These backgrounds need to be removed, because they'll block the date ranges.
.mat-calendar-body-cell::before,
.mat-calendar-body-cell::after,
.mat-calendar-body-selected {
background: none;
}
.mat-calendar-body-in-range::before,
.mat-calendar-body-comparison-bridge-start::before,
.mat-calendar-body-comparison-bridge-end::before {
border-top: $main-range-border;
border-bottom: $main-range-border;
}
.mat-calendar-body-range-start::before {
border-left: $main-range-border;
[dir='rtl'] & {
border-left: 0;
border-right: $main-range-border;
}
}
.mat-calendar-body-range-end::before {
border-right: $main-range-border;
[dir='rtl'] & {
border-right: 0;
border-left: $main-range-border;
}
}
.mat-calendar-body-in-comparison-range::before {
border-top: $comparison-range-border;
border-bottom: $comparison-range-border;
}
.mat-calendar-body-comparison-start::before {
border-left: $comparison-range-border;
[dir='rtl'] & {
border-left: 0;
border-right: $comparison-range-border;
}
}
.mat-calendar-body-comparison-end::before {
border-right: $comparison-range-border;
[dir='rtl'] & {
border-right: 0;
border-left: $comparison-range-border;
}
}
} | {
"end_byte": 14207,
"start_byte": 8511,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.scss"
} |
components/src/material/datepicker/aria-accessible-name.spec.ts_0_5935 | import {_computeAriaAccessibleName} from './aria-accessible-name';
describe('_computeAriaAccessibleName', () => {
let rootElement: HTMLSpanElement;
beforeEach(() => {
rootElement = document.createElement('span');
document.body.appendChild(rootElement);
});
afterEach(() => {
rootElement.remove();
});
it('uses aria-labelledby over aria-label', () => {
rootElement.innerHTML = `
<label id='test-label'>Aria Labelledby</label>
<input id='test-el' aria-labelledby='test-label' aria-label='Aria Label'/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Labelledby');
});
it('uses aria-label over for/id', () => {
rootElement.innerHTML = `
<label for='test-el'>For</label>
<input id='test-el' aria-label='Aria Label'/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Label');
});
it('uses a label with for/id over a title attribute', () => {
rootElement.innerHTML = `
<label for='test-el'>For</label>
<input id='test-el' title='Title'/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('For');
});
it('returns title when argument has a specified title', () => {
rootElement.innerHTML = `<input id="test-el" title='Title'/>`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Title');
});
// match browser behavior of giving placeholder attribute preference over title attribute
it('uses placeholder over title', () => {
rootElement.innerHTML = `<input id="test-el" title='Title' placeholder='Placeholder'/>`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Placeholder');
});
it('uses aria-label over title and placeholder', () => {
rootElement.innerHTML = `<input id="test-el" title='Title' placeholder='Placeholder'
aria-label="Aria Label"/>`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Aria Label');
});
it('includes both textnode and element children of label with for/id', () => {
rootElement.innerHTML = `
<label for="test-el">
Hello
<span>
Wo
<span><span>r</span></span>
<span> ld </span>
</span>
!
</label>
<input id='test-el'/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Hello Wo r ld !');
});
it('return computed name of hidden label which has for/id', () => {
rootElement.innerHTML = `
<label for="test-el" aria-hidden="true" style="display: none;">For</label>
<input id='test-el'/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('For');
});
it('returns computed names of existing elements when 2 of 3 targets of aria-labelledby exist', () => {
rootElement.innerHTML = `
<label id="label-1-of-2" aria-hidden="true" style="display: none;">Label1</label>
<label id="label-2-of-2" aria-hidden="true" style="display: none;">Label2</label>
<input id="test-el" aria-labelledby="label-1-of-2 label-2-of-2 non-existant-label"/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label1 Label2');
});
it('returns repeated label when there are duplicate ids in aria-labelledby', () => {
rootElement.innerHTML = `
<label id="label-1-of-1" aria-hidden="true" style="display: none;">Label1</label>
<input id="test-el" aria-labelledby="label-1-of-1 label-1-of-1"/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label1 Label1');
});
it('returns empty string when passed `<input id="test-el"/>`', () => {
rootElement.innerHTML = `<input id="test-el"/>`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('');
});
it('ignores the aria-labelledby of an aria-labelledby', () => {
rootElement.innerHTML = `
<label id="label" aria-labelledby="transitive-label">Label</label>
<label id="transitive-label" aria-labelled-by="transitive-label">Transitive Label</div>
<input id="test-el" aria-labelledby="label"/>
`;
const input = rootElement.querySelector('#test-el')!;
const label = rootElement.querySelector('#label')!;
expect(_computeAriaAccessibleName(label as any)).toBe('Transitive Label');
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('Label');
});
it('ignores the aria-labelledby on a label with for/id', () => {
rootElement.innerHTML = `
<label for="transitive2-label" aria-labelledby="transitive2-div"></label>
<div id="transitive2-div">Div</div>
<input id="test-el" aria-labelled-by="transitive2-label"/>
`;
const input = rootElement.querySelector('#test-el')!;
expect(_computeAriaAccessibleName(input as HTMLInputElement)).toBe('');
});
it('returns empty string when argument input is aria-labelledby itself', () => {
rootElement.innerHTML = `
<input id="test-el" aria-labelled-by="test-el"/>
`;
const input = rootElement.querySelector('#test-el')!;
const computedName = _computeAriaAccessibleName(input as HTMLInputElement);
expect(typeof computedName)
.withContext('should return value of type string')
.toBe('string');
});
});
| {
"end_byte": 5935,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/aria-accessible-name.spec.ts"
} |
components/src/material/datepicker/public-api.ts_0_1473 | /**
* @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 './datepicker-module';
export * from './calendar';
export * from './calendar-body';
export * from './datepicker';
export {
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDateRangeSelectionStrategy,
DefaultMatCalendarRangeStrategy,
} from './date-range-selection-strategy';
export * from './datepicker-animations';
export {
MAT_DATEPICKER_SCROLL_STRATEGY,
MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY,
MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER,
MatDatepickerContent,
DatepickerDropdownPositionX,
DatepickerDropdownPositionY,
MatDatepickerControl,
MatDatepickerPanel,
} from './datepicker-base';
export {MatDatepickerInputEvent, DateFilterFn} from './datepicker-input-base';
export {
MAT_DATEPICKER_VALUE_ACCESSOR,
MAT_DATEPICKER_VALIDATORS,
MatDatepickerInput,
} from './datepicker-input';
export * from './datepicker-intl';
export * from './datepicker-toggle';
export * from './month-view';
export * from './year-view';
export * from './date-range-input';
export {MatDateRangePicker} from './date-range-picker';
export * from './date-selection-model';
export {MatStartDate, MatEndDate} from './date-range-input-parts';
export {MatMultiYearView, yearsPerPage, yearsPerRow} from './multi-year-view';
export * from './datepicker-actions';
| {
"end_byte": 1473,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/public-api.ts"
} |
components/src/material/datepicker/datepicker.ts_0_1189 | /**
* @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, MatDatepickerControl} from './datepicker-base';
import {MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER} from './date-selection-model';
// 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="matDatepicker"). We can change this to a directive
// if angular adds support for `exportAs: '$implicit'` on directives.
/** Component responsible for managing the datepicker popup/dialog. */
@Component({
selector: 'mat-datepicker',
template: '',
exportAs: 'matDatepicker',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [
MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER,
{provide: MatDatepickerBase, useExisting: MatDatepicker},
],
})
export class MatDatepicker<D> extends MatDatepickerBase<MatDatepickerControl<D>, D | null, D> {}
| {
"end_byte": 1189,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.ts"
} |
components/src/material/datepicker/datepicker-intl.ts_0_2623 | /**
* @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 {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
/** Datepicker data that requires internationalization. */
@Injectable({providedIn: 'root'})
export class MatDatepickerIntl {
/**
* Stream that emits whenever the labels here are changed. Use this to notify
* components if the labels have changed after initialization.
*/
readonly changes: Subject<void> = new Subject<void>();
/** A label for the calendar popup (used by screen readers). */
calendarLabel = 'Calendar';
/** A label for the button used to open the calendar popup (used by screen readers). */
openCalendarLabel = 'Open calendar';
/** Label for the button used to close the calendar popup. */
closeCalendarLabel = 'Close calendar';
/** A label for the previous month button (used by screen readers). */
prevMonthLabel = 'Previous month';
/** A label for the next month button (used by screen readers). */
nextMonthLabel = 'Next month';
/** A label for the previous year button (used by screen readers). */
prevYearLabel = 'Previous year';
/** A label for the next year button (used by screen readers). */
nextYearLabel = 'Next year';
/** A label for the previous multi-year button (used by screen readers). */
prevMultiYearLabel = 'Previous 24 years';
/** A label for the next multi-year button (used by screen readers). */
nextMultiYearLabel = 'Next 24 years';
/** A label for the 'switch to month view' button (used by screen readers). */
switchToMonthViewLabel = 'Choose date';
/** A label for the 'switch to year view' button (used by screen readers). */
switchToMultiYearViewLabel = 'Choose month and year';
/**
* A label for the first date of a range of dates (used by screen readers).
* @deprecated Provide your own internationalization string.
* @breaking-change 17.0.0
*/
startDateLabel = 'Start date';
/**
* A label for the last date of a range of dates (used by screen readers).
* @deprecated Provide your own internationalization string.
* @breaking-change 17.0.0
*/
endDateLabel = 'End date';
/** Formats a range of years (used for visuals). */
formatYearRange(start: string, end: string): string {
return `${start} \u2013 ${end}`;
}
/** Formats a label for a range of years (used by screen readers). */
formatYearRangeLabel(start: string, end: string): string {
return `${start} to ${end}`;
}
}
| {
"end_byte": 2623,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-intl.ts"
} |
components/src/material/datepicker/calendar.spec.ts_0_1181 | import {Directionality} from '@angular/cdk/bidi';
import {ENTER, RIGHT_ARROW, SPACE} from '@angular/cdk/keycodes';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
} from '@angular/cdk/testing/private';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, inject, waitForAsync} from '@angular/core/testing';
import {DateAdapter, MatNativeDateModule} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {DEC, FEB, JAN, JUL, NOV} from '../testing';
import {MatCalendar} from './calendar';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatDatepickerModule} from './datepicker-module';
describe('MatCalendar', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatNativeDateModule, MatDatepickerModule],
providers: [MatDatepickerIntl, {provide: Directionality, useFactory: () => ({value: 'ltr'})}],
declarations: [
// Test components.
StandardCalendar,
CalendarWithMinMax,
CalendarWithDateFilter,
CalendarWithSelectableMinDate,
],
});
}));
describe('standard calendar', () => | {
"end_byte": 1181,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.spec.ts"
} |
components/src/material/datepicker/calendar.spec.ts_1182_11599 | {
let fixture: ComponentFixture<StandardCalendar>;
let testComponent: StandardCalendar;
let calendarElement: HTMLElement;
let periodButton: HTMLElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(StandardCalendar);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector('.mat-calendar-period-button') as HTMLElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it(`should update today's date`, inject([DateAdapter], (adapter: DateAdapter<Date>) => {
let fakeToday = new Date(2018, 0, 1);
spyOn(adapter, 'today').and.callFake(() => fakeToday);
calendarInstance.activeDate = fakeToday;
calendarInstance.updateTodaysDate();
fixture.detectChanges();
let todayCell = calendarElement.querySelector('.mat-calendar-body-today')!;
expect(todayCell).not.toBeNull();
expect(todayCell.innerHTML.trim()).toBe('1');
fakeToday = new Date(2018, 0, 10);
calendarInstance.updateTodaysDate();
fixture.detectChanges();
todayCell = calendarElement.querySelector('.mat-calendar-body-today')!;
expect(todayCell).not.toBeNull();
expect(todayCell.innerHTML.trim()).toBe('10');
}));
it('should be in month view with specified month active', () => {
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
});
it('should select date in month view', () => {
let monthCells = calendarElement.querySelectorAll('.mat-calendar-body-cell');
(monthCells[monthCells.length - 1] as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
expect(testComponent.selected).toEqual(new Date(2017, JAN, 31));
});
it('should emit the selected month on cell clicked in year view', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
const normalizedMonth: Date = fixture.componentInstance.selectedMonth;
expect(normalizedMonth.getMonth()).toEqual(0);
});
it('should emit the selected year on cell clicked in multiyear view', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
const normalizedYear: Date = fixture.componentInstance.selectedYear;
expect(normalizedYear.getFullYear()).toEqual(2017);
});
it('should re-render when the i18n labels have changed', inject(
[MatDatepickerIntl],
(intl: MatDatepickerIntl) => {
const button = fixture.debugElement.nativeElement.querySelector(
'.mat-calendar-period-button',
);
intl.switchToMultiYearViewLabel = 'Go to multi-year view?';
intl.changes.next();
fixture.detectChanges();
expect(button.getAttribute('aria-label')).toBe('Go to multi-year view?');
},
));
it('should set all buttons to be `type="button"`', () => {
const invalidButtons = calendarElement.querySelectorAll('button:not([type="button"])');
expect(invalidButtons.length).toBe(0);
});
it('should complete the stateChanges stream', () => {
const spy = jasmine.createSpy('complete spy');
const subscription = calendarInstance.stateChanges.subscribe({complete: spy});
fixture.destroy();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
describe('a11y', () => {
describe('calendar body', () => {
let calendarBodyEl: HTMLElement;
beforeEach(() => {
calendarBodyEl = calendarElement.querySelector('.mat-calendar-content') as HTMLElement;
expect(calendarBodyEl).not.toBeNull();
dispatchFakeEvent(calendarBodyEl, 'focus');
fixture.detectChanges();
});
it('should initially set start date active', () => {
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
});
it('should make the calendar body focusable', () => {
expect(calendarBodyEl.getAttribute('tabindex')).toBe('-1');
});
it('should not move focus to the active cell on init', waitForAsync(async () => {
const activeCell = calendarBodyEl.querySelector(
'.mat-calendar-body-active',
)! as HTMLElement;
spyOn(activeCell, 'focus').and.callThrough();
fixture.detectChanges();
await new Promise(resolve => setTimeout(resolve));
expect(activeCell.focus).not.toHaveBeenCalled();
}));
it('should move focus to the active cell when the view changes', waitForAsync(async () => {
calendarInstance.currentView = 'multi-year';
fixture.detectChanges();
const activeCell = calendarBodyEl.querySelector(
'.mat-calendar-body-active',
)! as HTMLElement;
spyOn(activeCell, 'focus').and.callThrough();
await new Promise(resolve => setTimeout(resolve));
expect(activeCell.focus).toHaveBeenCalled();
}));
describe('year view', () => {
beforeEach(() => {
dispatchMouseEvent(periodButton, 'click');
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
(calendarBodyEl.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
});
it('should return to month view on enter', () => {
const tableBodyEl = calendarBodyEl.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keyup', ENTER);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2017, FEB, 28));
expect(testComponent.selected).toBeUndefined();
});
it('should return to month view on space', () => {
const tableBodyEl = calendarBodyEl.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keydown', SPACE);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keyup', SPACE);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2017, FEB, 28));
expect(testComponent.selected).toBeUndefined();
});
});
describe('multi-year view', () => {
beforeEach(() => {
dispatchMouseEvent(periodButton, 'click');
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
});
it('should go to year view on enter', () => {
const tableBodyEl = calendarBodyEl.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keyup', ENTER);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 31));
expect(testComponent.selected).toBeUndefined();
});
it('should go to year view on space', () => {
const tableBodyEl = calendarBodyEl.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keydown', SPACE);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keyup', SPACE);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 31));
expect(testComponent.selected).toBeUndefined();
});
});
});
});
it('should re-render the month view when the locale changes', inject(
[DateAdapter],
(adapter: DateAdapter<Date>) => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, '_init').and.callThrough();
adapter.setLocale('bg-BG');
fixture.detectChanges();
expect(calendarInstance.monthView._init).toHaveBeenCalled();
},
));
it('should re-render the year view when the locale changes', inject(
[DateAdapter],
(adapter: DateAdapter<Date>) => {
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, '_init').and.callThrough();
adapter.setLocale('bg-BG');
fixture.detectChanges();
expect(calendarInstance.yearView._init).toHaveBeenCalled();
},
)); | {
"end_byte": 11599,
"start_byte": 1182,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.spec.ts"
} |
components/src/material/datepicker/calendar.spec.ts_11605_20874 | it('should re-render the multi-year view when the locale changes', inject(
[DateAdapter],
(adapter: DateAdapter<Date>) => {
periodButton.click();
fixture.detectChanges();
spyOn(calendarInstance.multiYearView, '_init').and.callThrough();
adapter.setLocale('bg-BG');
fixture.detectChanges();
expect(calendarInstance.multiYearView._init).toHaveBeenCalled();
},
));
});
describe('calendar with min and max date', () => {
let fixture: ComponentFixture<CalendarWithMinMax>;
let testComponent: CalendarWithMinMax;
let calendarElement: HTMLElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithMinMax);
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should clamp startAt value below min date', () => {
testComponent.startAt = new Date(2000, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2016, JAN, 1));
});
it('should clamp startAt value above max date', () => {
testComponent.startAt = new Date(2020, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 1));
});
it('should not go back past min date', () => {
testComponent.startAt = new Date(2016, FEB, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let prevButton = calendarElement.querySelector(
'.mat-calendar-previous-button',
) as HTMLButtonElement;
expect(prevButton.disabled).withContext('previous button should not be disabled').toBe(false);
expect(calendarInstance.activeDate).toEqual(new Date(2016, FEB, 1));
prevButton.click();
fixture.detectChanges();
expect(prevButton.disabled).withContext('previous button should be disabled').toBe(true);
expect(calendarInstance.activeDate).toEqual(new Date(2016, JAN, 1));
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2016, JAN, 1));
});
it('should not go forward past max date', () => {
testComponent.startAt = new Date(2017, DEC, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let nextButton = calendarElement.querySelector(
'.mat-calendar-next-button',
) as HTMLButtonElement;
expect(nextButton.disabled).withContext('next button should not be disabled').toBe(false);
expect(calendarInstance.activeDate).toEqual(new Date(2017, DEC, 1));
nextButton.click();
fixture.detectChanges();
expect(nextButton.disabled).withContext('next button should be disabled').toBe(true);
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 1));
nextButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 1));
});
it('should re-render the month view when the minDate changes', () => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, '_init').and.callThrough();
testComponent.minDate = new Date(2017, NOV, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.monthView._init).toHaveBeenCalled();
});
it('should not re-render the month view when the minDate changes to the same day at a different time', () => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, '_init').and.callThrough();
testComponent.minDate = new Date(2016, JAN, 1, 0, 0, 0, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.monthView._init).not.toHaveBeenCalled();
});
it('should re-render the month view when the maxDate changes', () => {
fixture.detectChanges();
spyOn(calendarInstance.monthView, '_init').and.callThrough();
testComponent.maxDate = new Date(2017, DEC, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.monthView._init).toHaveBeenCalled();
});
it('should re-render the year view when the minDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, '_init').and.callThrough();
testComponent.minDate = new Date(2017, NOV, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.yearView._init).toHaveBeenCalled();
});
it('should re-render the year view when the maxDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, '_init').and.callThrough();
testComponent.maxDate = new Date(2017, DEC, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.yearView._init).toHaveBeenCalled();
});
it('should not re-render the year view when the maxDate changes to the same day at a different time', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
periodButton.click();
fixture.detectChanges();
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
spyOn(calendarInstance.yearView, '_init').and.callThrough();
testComponent.maxDate = new Date(2018, JAN, 1, 0, 0, 1, 0);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.yearView._init).not.toHaveBeenCalled();
});
it('should re-render the multi-year view when the minDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
periodButton.click();
fixture.detectChanges();
spyOn(calendarInstance.multiYearView, '_init').and.callThrough();
testComponent.minDate = new Date(2017, NOV, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.multiYearView._init).toHaveBeenCalled();
});
it('should re-render the multi-year view when the maxDate changes', () => {
fixture.detectChanges();
const periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
periodButton.click();
fixture.detectChanges();
spyOn(calendarInstance.multiYearView, '_init').and.callThrough();
testComponent.maxDate = new Date(2017, DEC, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(calendarInstance.multiYearView._init).toHaveBeenCalled();
});
it('should update the minDate in the child view if it changed after an interaction', () => {
fixture.destroy();
const dynamicFixture = TestBed.createComponent(CalendarWithSelectableMinDate);
dynamicFixture.detectChanges();
const calendarDebugElement = dynamicFixture.debugElement.query(By.directive(MatCalendar))!;
const disabledClass = 'mat-calendar-body-disabled';
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
let cells = Array.from(calendarElement.querySelectorAll('.mat-calendar-body-cell'));
expect(cells.slice(0, 9).every(c => c.classList.contains(disabledClass)))
.withContext('Expected dates up to the 10th to be disabled.')
.toBe(true);
expect(cells.slice(9).every(c => c.classList.contains(disabledClass)))
.withContext('Expected dates after the 10th to be enabled.')
.toBe(false);
(cells[14] as HTMLElement).click();
dynamicFixture.detectChanges();
cells = Array.from(calendarElement.querySelectorAll('.mat-calendar-body-cell'));
expect(cells.slice(0, 14).every(c => c.classList.contains(disabledClass)))
.withContext('Expected dates up to the 14th to be disabled.')
.toBe(true);
expect(cells.slice(14).every(c => c.classList.contains(disabledClass)))
.withContext('Expected dates after the 14th to be enabled.')
.toBe(false);
});
}); | {
"end_byte": 20874,
"start_byte": 11605,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.spec.ts"
} |
components/src/material/datepicker/calendar.spec.ts_20878_25077 | describe('calendar with date filter', () => {
let fixture: ComponentFixture<CalendarWithDateFilter>;
let testComponent: CalendarWithDateFilter;
let calendarElement: HTMLElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithDateFilter);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should disable and prevent selection of filtered dates', () => {
let cells = calendarElement.querySelectorAll('.mat-calendar-body-cell');
(cells[0] as HTMLElement).click();
fixture.detectChanges();
expect(testComponent.selected).toBeFalsy();
(cells[1] as HTMLElement).click();
fixture.detectChanges();
expect(testComponent.selected).toEqual(new Date(2017, JAN, 2));
});
describe('a11y', () => {
let tableBodyEl: HTMLElement;
beforeEach(() => {
tableBodyEl = calendarElement.querySelector('.mat-calendar-body') as HTMLElement;
expect(tableBodyEl).not.toBeNull();
dispatchFakeEvent(tableBodyEl, 'focus');
fixture.detectChanges();
});
it('should not allow selection of disabled date in month view', () => {
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 1));
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
expect(testComponent.selected).toBeUndefined();
});
it('should allow entering month view at disabled month', () => {
let periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLElement;
dispatchMouseEvent(periodButton, 'click');
fixture.detectChanges();
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
calendarInstance.activeDate = new Date(2017, NOV, 1);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
tableBodyEl = calendarElement.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(tableBodyEl, 'keydown', ENTER);
fixture.detectChanges();
dispatchKeyboardEvent(tableBodyEl, 'keyup', ENTER);
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
expect(testComponent.selected).toBeUndefined();
});
});
});
});
@Component({
template: `
<mat-calendar
[startAt]="startDate"
[(selected)]="selected"
(yearSelected)="selectedYear=$event"
(monthSelected)="selectedMonth=$event">
</mat-calendar>`,
standalone: false,
})
class StandardCalendar {
selected: Date;
selectedYear: Date;
selectedMonth: Date;
startDate = new Date(2017, JAN, 31);
}
@Component({
template: `
<mat-calendar [startAt]="startAt" [minDate]="minDate" [maxDate]="maxDate"></mat-calendar>
`,
standalone: false,
})
class CalendarWithMinMax {
startAt: Date;
minDate = new Date(2016, JAN, 1);
maxDate = new Date(2018, JAN, 1);
}
@Component({
template: `
<mat-calendar [startAt]="startDate" [(selected)]="selected" [dateFilter]="dateFilter">
</mat-calendar>
`,
standalone: false,
})
class CalendarWithDateFilter {
selected: Date;
startDate = new Date(2017, JAN, 1);
dateFilter(date: Date) {
return !(date.getDate() % 2) && date.getMonth() !== NOV;
}
}
@Component({
template: `
<mat-calendar
[startAt]="startAt"
(selectedChange)="select($event)"
[selected]="selected"
[minDate]="selected">
</mat-calendar>
`,
standalone: false,
})
class CalendarWithSelectableMinDate {
startAt = new Date(2018, JUL, 0);
selected: Date;
minDate: Date;
constructor() {
this.select(new Date(2018, JUL, 10));
}
select(value: Date) {
this.minDate = this.selected = value;
}
} | {
"end_byte": 25077,
"start_byte": 20878,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.spec.ts"
} |
components/src/material/datepicker/calendar-body.html_0_4506 | <!--
If there's not enough space in the first row, create a separate label row. We mark this row as
aria-hidden because we don't want it to be read out as one of the weeks in the month.
-->
@if (_firstRowOffset < labelMinRequiredCells) {
<tr aria-hidden="true">
<td class="mat-calendar-body-label"
[attr.colspan]="numCols"
[style.paddingTop]="_cellPadding"
[style.paddingBottom]="_cellPadding">
{{label}}
</td>
</tr>
}
<!-- Create the first row separately so we can include a special spacer cell. -->
@for (row of rows; track _trackRow(row); let rowIndex = $index) {
<tr role="row">
<!--
This cell is purely decorative, but we can't put `aria-hidden` or `role="presentation"` on it,
because it throws off the week days for the rest of the row on NVDA. The aspect ratio of the
table cells is maintained by setting the top and bottom padding as a percentage of the width
(a variant of the trick described here: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp).
-->
@if (rowIndex === 0 && _firstRowOffset) {
<td
class="mat-calendar-body-label"
[attr.colspan]="_firstRowOffset"
[style.paddingTop]="_cellPadding"
[style.paddingBottom]="_cellPadding">
{{_firstRowOffset >= labelMinRequiredCells ? label : ''}}
</td>
}
<!--
Each gridcell in the calendar contains a button, which signals to assistive technology that the
cell is interactable, as well as the selection state via `aria-pressed`. See #23476 for
background.
-->
@for (item of row; track item.id; let colIndex = $index) {
<td
role="gridcell"
class="mat-calendar-body-cell-container"
[style.width]="_cellWidth"
[style.paddingTop]="_cellPadding"
[style.paddingBottom]="_cellPadding"
[attr.data-mat-row]="rowIndex"
[attr.data-mat-col]="colIndex"
>
<button
type="button"
class="mat-calendar-body-cell"
[ngClass]="item.cssClasses"
[tabindex]="_isActiveCell(rowIndex, colIndex) ? 0 : -1"
[class.mat-calendar-body-disabled]="!item.enabled"
[class.mat-calendar-body-active]="_isActiveCell(rowIndex, colIndex)"
[class.mat-calendar-body-range-start]="_isRangeStart(item.compareValue)"
[class.mat-calendar-body-range-end]="_isRangeEnd(item.compareValue)"
[class.mat-calendar-body-in-range]="_isInRange(item.compareValue)"
[class.mat-calendar-body-comparison-bridge-start]="_isComparisonBridgeStart(item.compareValue, rowIndex, colIndex)"
[class.mat-calendar-body-comparison-bridge-end]="_isComparisonBridgeEnd(item.compareValue, rowIndex, colIndex)"
[class.mat-calendar-body-comparison-start]="_isComparisonStart(item.compareValue)"
[class.mat-calendar-body-comparison-end]="_isComparisonEnd(item.compareValue)"
[class.mat-calendar-body-in-comparison-range]="_isInComparisonRange(item.compareValue)"
[class.mat-calendar-body-preview-start]="_isPreviewStart(item.compareValue)"
[class.mat-calendar-body-preview-end]="_isPreviewEnd(item.compareValue)"
[class.mat-calendar-body-in-preview]="_isInPreview(item.compareValue)"
[attr.aria-label]="item.ariaLabel"
[attr.aria-disabled]="!item.enabled || null"
[attr.aria-pressed]="_isSelected(item.compareValue)"
[attr.aria-current]="todayValue === item.compareValue ? 'date' : null"
[attr.aria-describedby]="_getDescribedby(item.compareValue)"
(click)="_cellClicked(item, $event)"
(focus)="_emitActiveDateChange(item, $event)">
<span class="mat-calendar-body-cell-content mat-focus-indicator"
[class.mat-calendar-body-selected]="_isSelected(item.compareValue)"
[class.mat-calendar-body-comparison-identical]="_isComparisonIdentical(item.compareValue)"
[class.mat-calendar-body-today]="todayValue === item.compareValue">
{{item.displayValue}}
</span>
<span class="mat-calendar-body-cell-preview" aria-hidden="true"></span>
</button>
</td>
}
</tr>
}
<span [id]="_startDateLabelId" class="mat-calendar-body-hidden-label">
{{startDateAccessibleName}}
</span>
<span [id]="_endDateLabelId" class="mat-calendar-body-hidden-label">
{{endDateAccessibleName}}
</span>
| {
"end_byte": 4506,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.html"
} |
components/src/material/datepicker/datepicker-module.ts_0_2518 | /**
* @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 {A11yModule} from '@angular/cdk/a11y';
import {OverlayModule} from '@angular/cdk/overlay';
import {PortalModule} from '@angular/cdk/portal';
import {NgModule} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {CdkScrollableModule} from '@angular/cdk/scrolling';
import {MatCommonModule} from '@angular/material/core';
import {MatCalendar, MatCalendarHeader} from './calendar';
import {MatCalendarBody} from './calendar-body';
import {MatDatepicker} from './datepicker';
import {
MatDatepickerContent,
MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER,
} from './datepicker-base';
import {MatDatepickerInput} from './datepicker-input';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatDatepickerToggle, MatDatepickerToggleIcon} from './datepicker-toggle';
import {MatMonthView} from './month-view';
import {MatMultiYearView} from './multi-year-view';
import {MatYearView} from './year-view';
import {MatDateRangeInput} from './date-range-input';
import {MatStartDate, MatEndDate} from './date-range-input-parts';
import {MatDateRangePicker} from './date-range-picker';
import {MatDatepickerActions, MatDatepickerApply, MatDatepickerCancel} from './datepicker-actions';
@NgModule({
imports: [
MatButtonModule,
OverlayModule,
A11yModule,
PortalModule,
MatCommonModule,
MatCalendar,
MatCalendarBody,
MatDatepicker,
MatDatepickerContent,
MatDatepickerInput,
MatDatepickerToggle,
MatDatepickerToggleIcon,
MatMonthView,
MatYearView,
MatMultiYearView,
MatCalendarHeader,
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatDateRangePicker,
MatDatepickerActions,
MatDatepickerCancel,
MatDatepickerApply,
],
exports: [
CdkScrollableModule,
MatCalendar,
MatCalendarBody,
MatDatepicker,
MatDatepickerContent,
MatDatepickerInput,
MatDatepickerToggle,
MatDatepickerToggleIcon,
MatMonthView,
MatYearView,
MatMultiYearView,
MatCalendarHeader,
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatDateRangePicker,
MatDatepickerActions,
MatDatepickerCancel,
MatDatepickerApply,
],
providers: [MatDatepickerIntl, MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER],
})
export class MatDatepickerModule {}
| {
"end_byte": 2518,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-module.ts"
} |
components/src/material/datepicker/datepicker-content.scss_0_4178 | @use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/tokens/token-utils';
$calendar-padding: 8px;
$non-touch-calendar-cell-size: 40px;
$non-touch-calendar-width:
$non-touch-calendar-cell-size * 7 + $calendar-padding * 2;
// Based on the natural height of the calendar in a month with 6 rows of dates
// (largest the calendar will get).
$non-touch-calendar-height: 354px;
// Ideally the calendar would have a constant aspect ratio, no matter its size, and we would base
// these measurements off the aspect ratio. Unfortunately, the aspect ratio does change a little as
// the calendar grows, since some of the elements have pixel-based sizes. These numbers have been
// chosen to minimize extra whitespace at larger sizes, while still ensuring we won't need
// scrollbars at smaller sizes.
$touch-landscape-width: 64vh;
$touch-landscape-height: 80vh;
$touch-portrait-width: 80vw;
$touch-portrait-height: 100vw;
$touch-portrait-height-with-actions: 115vw;
$touch-min-width: 250px;
$touch-min-height: 312px;
$touch-max-width: 750px;
$touch-max-height: 788px;
.mat-datepicker-content {
display: block;
border-radius: 4px;
@include token-utils.use-tokens(
tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots()) {
@include token-utils.create-token-slot(background-color, calendar-container-background-color);
@include token-utils.create-token-slot(color, calendar-container-text-color);
@include token-utils.create-token-slot(box-shadow, calendar-container-elevation-shadow);
@include token-utils.create-token-slot(border-radius, calendar-container-shape);
}
.mat-calendar {
width: $non-touch-calendar-width;
height: $non-touch-calendar-height;
}
// Override mat-calendar's height when custom header is provided
// Height should be auto, when the custom header is provided.
// This will prevent the content from overflowing.
.mat-datepicker-content-container-with-custom-header .mat-calendar {
height: auto;
}
// Note that this selector doesn't technically have to be nested, but we want the slightly
// higher specificity, or it can be overridden based on the CSS insertion order (see #21043).
.mat-datepicker-close-button {
position: absolute;
top: 100%;
left: 0;
margin-top: 8px;
// Hide the button while the overlay is animating, because it's rendered
// outside of it and it seems to cause scrollbars in some cases (see #21493).
.ng-animating & {
display: none;
}
}
}
.mat-datepicker-content-container {
display: flex;
flex-direction: column;
// Ensures that `mat-datepicker-actions` is pushed to the bottom of the popup.
justify-content: space-between;
}
.mat-datepicker-content-touch {
display: block;
max-height: 80vh;
@include token-utils.use-tokens(
tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots()) {
@include token-utils.create-token-slot(box-shadow, calendar-container-touch-elevation-shadow);
@include token-utils.create-token-slot(border-radius, calendar-container-touch-shape);
}
// Allows for the screen reader close button to be seen in touch UI mode.
position: relative;
// Prevents the content from jumping around on Windows while the animation is running.
overflow: visible;
.mat-datepicker-content-container {
min-height: $touch-min-height;
max-height: $touch-max-height;
min-width: $touch-min-width;
max-width: $touch-max-width;
}
.mat-calendar {
width: 100%;
height: auto;
}
}
@media all and (orientation: landscape) {
.mat-datepicker-content-touch .mat-datepicker-content-container {
width: $touch-landscape-width;
height: $touch-landscape-height;
}
}
@media all and (orientation: portrait) {
.mat-datepicker-content-touch .mat-datepicker-content-container {
width: $touch-portrait-width;
height: $touch-portrait-height;
}
// The content needs to be a bit taller when actions have
// been projected so that it doesn't have to scroll.
.mat-datepicker-content-touch .mat-datepicker-content-container-with-actions {
height: $touch-portrait-height-with-actions;
}
}
| {
"end_byte": 4178,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-content.scss"
} |
components/src/material/datepicker/datepicker-errors.ts_0_580 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/** @docs-private */
export function createMissingDateImplError(provider: string) {
return Error(
`MatDatepicker: No provider found for ${provider}. You must add one of the following ` +
`to your app config: provideNativeDateAdapter, provideDateFnsAdapter, ` +
`provideLuxonDateAdapter, provideMomentDateAdapter, or provide a custom implementation.`,
);
}
| {
"end_byte": 580,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-errors.ts"
} |
components/src/material/datepicker/calendar.ts_0_8390 | /**
* @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 {CdkPortalOutlet, ComponentPortal, ComponentType, Portal} from '@angular/cdk/portal';
import {
AfterContentInit,
AfterViewChecked,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
SimpleChange,
SimpleChanges,
ViewChild,
ViewEncapsulation,
inject,
} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {Subject, Subscription} from 'rxjs';
import {MatCalendarUserEvent, MatCalendarCellClassFunction} from './calendar-body';
import {createMissingDateImplError} from './datepicker-errors';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatMonthView} from './month-view';
import {
getActiveOffset,
isSameMultiYearView,
MatMultiYearView,
yearsPerPage,
} from './multi-year-view';
import {MatYearView} from './year-view';
import {MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER, DateRange} from './date-selection-model';
import {MatIconButton, MatButton} from '@angular/material/button';
import {CdkMonitorFocus} from '@angular/cdk/a11y';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
let calendarHeaderId = 1;
/**
* Possible views for the calendar.
* @docs-private
*/
export type MatCalendarView = 'month' | 'year' | 'multi-year';
/** Default header for MatCalendar */
@Component({
selector: 'mat-calendar-header',
templateUrl: 'calendar-header.html',
exportAs: 'matCalendarHeader',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatButton, MatIconButton],
})
export class MatCalendarHeader<D> {
private _intl = inject(MatDatepickerIntl);
calendar = inject<MatCalendar<D>>(MatCalendar);
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dateFormats = inject<MatDateFormats>(MAT_DATE_FORMATS, {optional: true})!;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
const changeDetectorRef = inject(ChangeDetectorRef);
this.calendar.stateChanges.subscribe(() => changeDetectorRef.markForCheck());
}
/** The display text for the current calendar view. */
get periodButtonText(): string {
if (this.calendar.currentView == 'month') {
return this._dateAdapter
.format(this.calendar.activeDate, this._dateFormats.display.monthYearLabel)
.toLocaleUpperCase();
}
if (this.calendar.currentView == 'year') {
return this._dateAdapter.getYearName(this.calendar.activeDate);
}
return this._intl.formatYearRange(...this._formatMinAndMaxYearLabels());
}
/** The aria description for the current calendar view. */
get periodButtonDescription(): string {
if (this.calendar.currentView == 'month') {
return this._dateAdapter
.format(this.calendar.activeDate, this._dateFormats.display.monthYearLabel)
.toLocaleUpperCase();
}
if (this.calendar.currentView == 'year') {
return this._dateAdapter.getYearName(this.calendar.activeDate);
}
// Format a label for the window of years displayed in the multi-year calendar view. Use
// `formatYearRangeLabel` because it is TTS friendly.
return this._intl.formatYearRangeLabel(...this._formatMinAndMaxYearLabels());
}
/** The `aria-label` for changing the calendar view. */
get periodButtonLabel(): string {
return this.calendar.currentView == 'month'
? this._intl.switchToMultiYearViewLabel
: this._intl.switchToMonthViewLabel;
}
/** The label for the previous button. */
get prevButtonLabel(): string {
return {
'month': this._intl.prevMonthLabel,
'year': this._intl.prevYearLabel,
'multi-year': this._intl.prevMultiYearLabel,
}[this.calendar.currentView];
}
/** The label for the next button. */
get nextButtonLabel(): string {
return {
'month': this._intl.nextMonthLabel,
'year': this._intl.nextYearLabel,
'multi-year': this._intl.nextMultiYearLabel,
}[this.calendar.currentView];
}
/** Handles user clicks on the period label. */
currentPeriodClicked(): void {
this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';
}
/** Handles user clicks on the previous button. */
previousClicked(): void {
this.calendar.activeDate =
this.calendar.currentView == 'month'
? this._dateAdapter.addCalendarMonths(this.calendar.activeDate, -1)
: this._dateAdapter.addCalendarYears(
this.calendar.activeDate,
this.calendar.currentView == 'year' ? -1 : -yearsPerPage,
);
}
/** Handles user clicks on the next button. */
nextClicked(): void {
this.calendar.activeDate =
this.calendar.currentView == 'month'
? this._dateAdapter.addCalendarMonths(this.calendar.activeDate, 1)
: this._dateAdapter.addCalendarYears(
this.calendar.activeDate,
this.calendar.currentView == 'year' ? 1 : yearsPerPage,
);
}
/** Whether the previous period button is enabled. */
previousEnabled(): boolean {
if (!this.calendar.minDate) {
return true;
}
return (
!this.calendar.minDate || !this._isSameView(this.calendar.activeDate, this.calendar.minDate)
);
}
/** Whether the next period button is enabled. */
nextEnabled(): boolean {
return (
!this.calendar.maxDate || !this._isSameView(this.calendar.activeDate, this.calendar.maxDate)
);
}
/** Whether the two dates represent the same view in the current view mode (month or year). */
private _isSameView(date1: D, date2: D): boolean {
if (this.calendar.currentView == 'month') {
return (
this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2) &&
this._dateAdapter.getMonth(date1) == this._dateAdapter.getMonth(date2)
);
}
if (this.calendar.currentView == 'year') {
return this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2);
}
// Otherwise we are in 'multi-year' view.
return isSameMultiYearView(
this._dateAdapter,
date1,
date2,
this.calendar.minDate,
this.calendar.maxDate,
);
}
/**
* Format two individual labels for the minimum year and maximum year available in the multi-year
* calendar view. Returns an array of two strings where the first string is the formatted label
* for the minimum year, and the second string is the formatted label for the maximum year.
*/
private _formatMinAndMaxYearLabels(): [minYearLabel: string, maxYearLabel: string] {
// The offset from the active year to the "slot" for the starting year is the
// *actual* first rendered year in the multi-year view, and the last year is
// just yearsPerPage - 1 away.
const activeYear = this._dateAdapter.getYear(this.calendar.activeDate);
const minYearOfPage =
activeYear -
getActiveOffset(
this._dateAdapter,
this.calendar.activeDate,
this.calendar.minDate,
this.calendar.maxDate,
);
const maxYearOfPage = minYearOfPage + yearsPerPage - 1;
const minYearLabel = this._dateAdapter.getYearName(
this._dateAdapter.createDate(minYearOfPage, 0, 1),
);
const maxYearLabel = this._dateAdapter.getYearName(
this._dateAdapter.createDate(maxYearOfPage, 0, 1),
);
return [minYearLabel, maxYearLabel];
}
private _id = `mat-calendar-header-${calendarHeaderId++}`;
_periodButtonLabelId = `${this._id}-period-label`;
}
/** A calendar that is used as part of the datepicker. */
@Component({
selector: 'mat-calendar',
templateUrl: 'calendar.html',
styleUrl: 'calendar.css',
host: {
'class': 'mat-calendar',
},
exportAs: 'matCalendar',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER],
imports: [CdkPortalOutlet, CdkMonitorFocus, MatMonthView, MatYearView, MatMultiYearView],
})
export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDestroy, OnChanges | {
"end_byte": 8390,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.ts"
} |
components/src/material/datepicker/calendar.ts_8391_16565 | {
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dateFormats = inject<MatDateFormats>(MAT_DATE_FORMATS, {optional: true});
private _changeDetectorRef = inject(ChangeDetectorRef);
/** An input indicating the type of the header component, if set. */
@Input() headerComponent: ComponentType<any>;
/** A portal containing the header component type for this calendar. */
_calendarHeaderPortal: Portal<any>;
private _intlChanges: Subscription;
/**
* Used for scheduling that focus should be moved to the active cell on the next tick.
* We need to schedule it, rather than do it immediately, because we have to wait
* for Angular to re-evaluate the view children.
*/
private _moveFocusOnNextTick = false;
/** A date representing the period (month or year) to start the calendar in. */
@Input()
get startAt(): D | null {
return this._startAt;
}
set startAt(value: D | null) {
this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _startAt: D | null;
/** Whether the calendar should be started in month or year view. */
@Input() startView: MatCalendarView = 'month';
/** 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));
}
}
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;
/** Emits when the currently selected date changes. */
@Output() readonly selectedChange: EventEmitter<D | null> = new EventEmitter<D | null>();
/**
* Emits the year chosen in multiyear view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits the month chosen in year view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits when the current view changes.
*/
@Output() readonly viewChanged: EventEmitter<MatCalendarView> = new EventEmitter<MatCalendarView>(
true,
);
/** Emits when any date is selected. */
@Output() readonly _userSelection: EventEmitter<MatCalendarUserEvent<D | null>> =
new EventEmitter<MatCalendarUserEvent<D | null>>();
/** Emits a new date range value when the user completes a drag drop operation. */
@Output() readonly _userDragDrop = new EventEmitter<MatCalendarUserEvent<DateRange<D>>>();
/** Reference to the current month view component. */
@ViewChild(MatMonthView) monthView: MatMonthView<D>;
/** Reference to the current year view component. */
@ViewChild(MatYearView) yearView: MatYearView<D>;
/** Reference to the current multi-year view component. */
@ViewChild(MatMultiYearView) multiYearView: MatMultiYearView<D>;
/**
* The current active date. This determines which time period is shown and which date is
* highlighted when using keyboard navigation.
*/
get activeDate(): D {
return this._clampedActiveDate;
}
set activeDate(value: D) {
this._clampedActiveDate = this._dateAdapter.clampDate(value, this.minDate, this.maxDate);
this.stateChanges.next();
this._changeDetectorRef.markForCheck();
}
private _clampedActiveDate: D;
/** Whether the calendar is in month view. */
get currentView(): MatCalendarView {
return this._currentView;
}
set currentView(value: MatCalendarView) {
const viewChangedResult = this._currentView !== value ? value : null;
this._currentView = value;
this._moveFocusOnNextTick = true;
this._changeDetectorRef.markForCheck();
if (viewChangedResult) {
this.viewChanged.emit(viewChangedResult);
}
}
private _currentView: MatCalendarView;
/** Origin of active drag, or null when dragging is not active. */
protected _activeDrag: MatCalendarUserEvent<D> | null = null;
/**
* Emits whenever there is a state change that the header may need to respond to.
*/
readonly stateChanges = new Subject<void>();
constructor(...args: unknown[]);
constructor() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MAT_DATE_FORMATS');
}
}
this._intlChanges = inject(MatDatepickerIntl).changes.subscribe(() => {
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
});
}
ngAfterContentInit() {
this._calendarHeaderPortal = new ComponentPortal(this.headerComponent || MatCalendarHeader);
this.activeDate = this.startAt || this._dateAdapter.today();
// Assign to the private property since we don't want to move focus on init.
this._currentView = this.startView;
}
ngAfterViewChecked() {
if (this._moveFocusOnNextTick) {
this._moveFocusOnNextTick = false;
this.focusActiveCell();
}
}
ngOnDestroy() {
this._intlChanges.unsubscribe();
this.stateChanges.complete();
}
ngOnChanges(changes: SimpleChanges) {
// Ignore date changes that are at a different time on the same day. This fixes issues where
// the calendar re-renders when there is no meaningful change to [minDate] or [maxDate]
// (#24435).
const minDateChange: SimpleChange | undefined =
changes['minDate'] &&
!this._dateAdapter.sameDate(changes['minDate'].previousValue, changes['minDate'].currentValue)
? changes['minDate']
: undefined;
const maxDateChange: SimpleChange | undefined =
changes['maxDate'] &&
!this._dateAdapter.sameDate(changes['maxDate'].previousValue, changes['maxDate'].currentValue)
? changes['maxDate']
: undefined;
const changeRequiringRerender = minDateChange || maxDateChange || changes['dateFilter'];
if (changeRequiringRerender && !changeRequiringRerender.firstChange) {
const view = this._getCurrentViewComponent();
if (view) {
// Schedule focus to be moved to the active date since re-rendering
// can blur the active cell. See #29265.
this._moveFocusOnNextTick = true;
// We need to `detectChanges` manually here, because the `minDate`, `maxDate` etc. are
// passed down to the view via data bindings which won't be up-to-date when we call `_init`.
this._changeDetectorRef.detectChanges();
view._init();
}
}
this.stateChanges.next();
}
/** Focuses the active date. */
focusActiveCell() {
this._getCurrentViewComponent()._focusActiveCell(false);
}
/** Updates today's date after an update of the active date */
updateTodaysDate() {
this._getCurrentViewComponent()._init();
}
/** Handles date selection in the month view. */ | {
"end_byte": 16565,
"start_byte": 8391,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.ts"
} |
components/src/material/datepicker/calendar.ts_16568_18434 | _dateSelected(event: MatCalendarUserEvent<D | null>): void {
const date = event.value;
if (
this.selected instanceof DateRange ||
(date && !this._dateAdapter.sameDate(date, this.selected))
) {
this.selectedChange.emit(date);
}
this._userSelection.emit(event);
}
/** Handles year selection in the multiyear view. */
_yearSelectedInMultiYearView(normalizedYear: D) {
this.yearSelected.emit(normalizedYear);
}
/** Handles month selection in the year view. */
_monthSelectedInYearView(normalizedMonth: D) {
this.monthSelected.emit(normalizedMonth);
}
/** Handles year/month selection in the multi-year/year views. */
_goToDateInView(date: D, view: 'month' | 'year' | 'multi-year'): void {
this.activeDate = date;
this.currentView = view;
}
/** Called when the user starts dragging to change a date range. */
_dragStarted(event: MatCalendarUserEvent<D>) {
this._activeDrag = event;
}
/**
* Called when a drag completes. It may end in cancelation or in the selection
* of a new range.
*/
_dragEnded(event: MatCalendarUserEvent<DateRange<D> | null>) {
if (!this._activeDrag) return;
if (event.value) {
this._userDragDrop.emit(event as MatCalendarUserEvent<DateRange<D>>);
}
this._activeDrag = null;
}
/** Returns the component instance that corresponds to the current calendar view. */
private _getCurrentViewComponent(): MatMonthView<D> | MatYearView<D> | MatMultiYearView<D> {
// The return type is explicitly written as a union to ensure that the Closure compiler does
// not optimize calls to _init(). Without the explicit return type, TypeScript narrows it to
// only the first component type. See https://github.com/angular/components/issues/22996.
return this.monthView || this.yearView || this.multiYearView;
}
} | {
"end_byte": 18434,
"start_byte": 16568,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar.ts"
} |
components/src/material/datepicker/multi-year-view.ts_0_7403 | /**
* @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,
} from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
Output,
ViewChild,
ViewEncapsulation,
OnDestroy,
inject,
} from '@angular/core';
import {DateAdapter} 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';
export const yearsPerPage = 24;
export const yearsPerRow = 4;
/**
* An internal component used to display a year selector in the datepicker.
* @docs-private
*/
@Component({
selector: 'mat-multi-year-view',
templateUrl: 'multi-year-view.html',
exportAs: 'matMultiYearView',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatCalendarBody],
})
export class MatMultiYearView<D> implements AfterContentInit, OnDestroy {
private _changeDetectorRef = inject(ChangeDetectorRef);
_dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dir = inject(Directionality, {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 multi-year view (everything other than the year is ignored). */
@Input()
get activeDate(): D {
return this._activeDate;
}
set activeDate(value: D) {
let 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 (
!isSameMultiYearView(
this._dateAdapter,
oldActiveDate,
this._activeDate,
this.minDate,
this.maxDate,
)
) {
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._setSelectedYear(value);
}
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;
/** A function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Function that can be used to add custom CSS classes to date cells. */
@Input() dateClass: MatCalendarCellClassFunction<D>;
/** Emits when a new year is selected. */
@Output() readonly selectedChange: EventEmitter<D> = new EventEmitter<D>();
/** Emits the selected year. This doesn't imply a change on the selected date */
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/** Emits when any date is activated. */
@Output() readonly activeDateChange: EventEmitter<D> = new EventEmitter<D>();
/** The body of calendar table */
@ViewChild(MatCalendarBody) _matCalendarBody: MatCalendarBody;
/** Grid of calendar cells representing the currently displayed years. */
_years: MatCalendarCell[][];
/** The year that today falls on. */
_todayYear: number;
/** The year of the selected date. Null if the selected date is null. */
_selectedYear: number | null;
constructor(...args: unknown[]);
constructor() {
if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw createMissingDateImplError('DateAdapter');
}
this._activeDate = this._dateAdapter.today();
}
ngAfterContentInit() {
this._rerenderSubscription = this._dateAdapter.localeChanges
.pipe(startWith(null))
.subscribe(() => this._init());
}
ngOnDestroy() {
this._rerenderSubscription.unsubscribe();
}
/** Initializes this multi-year view. */
_init() {
this._todayYear = this._dateAdapter.getYear(this._dateAdapter.today());
// We want a range years such that we maximize the number of
// enabled dates visible at once. This prevents issues where the minimum year
// is the last item of a page OR the maximum year is the first item of a page.
// The offset from the active year to the "slot" for the starting year is the
// *actual* first rendered year in the multi-year view.
const activeYear = this._dateAdapter.getYear(this._activeDate);
const minYearOfPage =
activeYear - getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate);
this._years = [];
for (let i = 0, row: number[] = []; i < yearsPerPage; i++) {
row.push(minYearOfPage + i);
if (row.length == yearsPerRow) {
this._years.push(row.map(year => this._createCellForYear(year)));
row = [];
}
}
this._changeDetectorRef.markForCheck();
}
/** Handles when a new year is selected. */
_yearSelected(event: MatCalendarUserEvent<number>) {
const year = event.value;
const selectedYear = this._dateAdapter.createDate(year, 0, 1);
const selectedDate = this._getDateFromYear(year);
this.yearSelected.emit(selectedYear);
this.selectedChange.emit(selectedDate);
}
/**
* 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 year = event.value;
const oldActiveDate = this._activeDate;
this.activeDate = this._getDateFromYear(year);
if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this.activeDate);
}
}
/** Handles keydown events on the calendar body when calendar is in multi-year view. */ | {
"end_byte": 7403,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.ts"
} |
components/src/material/datepicker/multi-year-view.ts_7406_14850 | _handleCalendarBodyKeydown(event: KeyboardEvent): void {
const oldActiveDate = this._activeDate;
const isRtl = this._isRtl();
switch (event.keyCode) {
case LEFT_ARROW:
this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, isRtl ? 1 : -1);
break;
case RIGHT_ARROW:
this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, isRtl ? -1 : 1);
break;
case UP_ARROW:
this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, -yearsPerRow);
break;
case DOWN_ARROW:
this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, yearsPerRow);
break;
case HOME:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
-getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate),
);
break;
case END:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
yearsPerPage -
getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate) -
1,
);
break;
case PAGE_UP:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
event.altKey ? -yearsPerPage * 10 : -yearsPerPage,
);
break;
case PAGE_DOWN:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
event.altKey ? yearsPerPage * 10 : yearsPerPage,
);
break;
case ENTER:
case SPACE:
// 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).
this._selectionKeyPressed = true;
break;
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 multi-year view. */
_handleCalendarBodyKeyup(event: KeyboardEvent): void {
if (event.keyCode === SPACE || event.keyCode === ENTER) {
if (this._selectionKeyPressed) {
this._yearSelected({value: this._dateAdapter.getYear(this._activeDate), event});
}
this._selectionKeyPressed = false;
}
}
_getActiveCell(): number {
return getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate);
}
/** Focuses the active cell after the microtask queue is empty. */
_focusActiveCell() {
this._matCalendarBody._focusActiveCell();
}
/** Focuses the active cell after change detection has run and the microtask queue is empty. */
_focusActiveCellAfterViewChecked() {
this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
}
/**
* Takes a year and returns a new date on the same day and month as the currently active date
* The returned date will have the same year as the argument date.
*/
private _getDateFromYear(year: number) {
const activeMonth = this._dateAdapter.getMonth(this.activeDate);
const daysInMonth = this._dateAdapter.getNumDaysInMonth(
this._dateAdapter.createDate(year, activeMonth, 1),
);
const normalizedDate = this._dateAdapter.createDate(
year,
activeMonth,
Math.min(this._dateAdapter.getDate(this.activeDate), daysInMonth),
);
return normalizedDate;
}
/** Creates an MatCalendarCell for the given year. */
private _createCellForYear(year: number) {
const date = this._dateAdapter.createDate(year, 0, 1);
const yearName = this._dateAdapter.getYearName(date);
const cellClasses = this.dateClass ? this.dateClass(date, 'multi-year') : undefined;
return new MatCalendarCell(year, yearName, yearName, this._shouldEnableYear(year), cellClasses);
}
/** Whether the given year is enabled. */
private _shouldEnableYear(year: number) {
// disable if the year is greater than maxDate lower than minDate
if (
year === undefined ||
year === null ||
(this.maxDate && year > this._dateAdapter.getYear(this.maxDate)) ||
(this.minDate && year < this._dateAdapter.getYear(this.minDate))
) {
return false;
}
// enable if it reaches here and there's no filter defined
if (!this.dateFilter) {
return true;
}
const firstOfYear = this._dateAdapter.createDate(year, 0, 1);
// If any date in the year is enabled count the year as enabled.
for (
let date = firstOfYear;
this._dateAdapter.getYear(date) == year;
date = this._dateAdapter.addCalendarDays(date, 1)
) {
if (this.dateFilter(date)) {
return true;
}
}
return false;
}
/** Determines whether the user has the RTL layout direction. */
private _isRtl() {
return this._dir && this._dir.value === 'rtl';
}
/** Sets the currently-highlighted year based on a model value. */
private _setSelectedYear(value: DateRange<D> | D | null) {
this._selectedYear = null;
if (value instanceof DateRange) {
const displayValue = value.start || value.end;
if (displayValue) {
this._selectedYear = this._dateAdapter.getYear(displayValue);
}
} else if (value) {
this._selectedYear = this._dateAdapter.getYear(value);
}
}
}
export function isSameMultiYearView<D>(
dateAdapter: DateAdapter<D>,
date1: D,
date2: D,
minDate: D | null,
maxDate: D | null,
): boolean {
const year1 = dateAdapter.getYear(date1);
const year2 = dateAdapter.getYear(date2);
const startingYear = getStartingYear(dateAdapter, minDate, maxDate);
return (
Math.floor((year1 - startingYear) / yearsPerPage) ===
Math.floor((year2 - startingYear) / yearsPerPage)
);
}
/**
* When the multi-year view is first opened, the active year will be in view.
* So we compute how many years are between the active year and the *slot* where our
* "startingYear" will render when paged into view.
*/
export function getActiveOffset<D>(
dateAdapter: DateAdapter<D>,
activeDate: D,
minDate: D | null,
maxDate: D | null,
): number {
const activeYear = dateAdapter.getYear(activeDate);
return euclideanModulo(activeYear - getStartingYear(dateAdapter, minDate, maxDate), yearsPerPage);
}
/**
* We pick a "starting" year such that either the maximum year would be at the end
* or the minimum year would be at the beginning of a page.
*/
function getStartingYear<D>(
dateAdapter: DateAdapter<D>,
minDate: D | null,
maxDate: D | null,
): number {
let startingYear = 0;
if (maxDate) {
const maxYear = dateAdapter.getYear(maxDate);
startingYear = maxYear - yearsPerPage + 1;
} else if (minDate) {
startingYear = dateAdapter.getYear(minDate);
}
return startingYear;
}
/** Gets remainder that is non-negative, even if first number is negative */
function euclideanModulo(a: number, b: number): number {
return ((a % b) + b) % b;
} | {
"end_byte": 14850,
"start_byte": 7406,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.ts"
} |
components/src/material/datepicker/calendar-header.spec.ts_0_9452 | import {Directionality} from '@angular/cdk/bidi';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {MatNativeDateModule, DateAdapter} from '@angular/material/core';
import {DEC, FEB, JAN} from '../testing';
import {By} from '@angular/platform-browser';
import {MatCalendar} from './calendar';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatDatepickerModule} from './datepicker-module';
import {yearsPerPage} from './multi-year-view';
describe('MatCalendarHeader', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatNativeDateModule,
MatDatepickerModule,
// Test components.
StandardCalendar,
CalendarWithMinMaxDate,
],
providers: [MatDatepickerIntl, {provide: Directionality, useFactory: () => ({value: 'ltr'})}],
});
}));
describe('standard calendar', () => {
let fixture: ComponentFixture<StandardCalendar>;
let testComponent: StandardCalendar;
let calendarElement: HTMLElement;
let periodButton: HTMLElement;
let prevButton: HTMLElement;
let nextButton: HTMLElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(StandardCalendar);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector('.mat-calendar-period-button') as HTMLElement;
prevButton = calendarElement.querySelector('.mat-calendar-previous-button') as HTMLElement;
nextButton = calendarElement.querySelector('.mat-calendar-next-button') as HTMLElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should be in month view with specified month active', () => {
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
});
it('should toggle view when period clicked', () => {
expect(calendarInstance.currentView).toBe('month');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
});
it("should emit viewChanged when view changed from 'month' to 'multi-year'", () => {
expect(calendarInstance.currentView).toBe('month');
spyOn(calendarInstance.viewChanged, 'emit');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.viewChanged.emit).toHaveBeenCalledWith('multi-year');
});
it("should emit viewChanged when view changed from 'multi-year' to 'month'", () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
spyOn(calendarInstance.viewChanged, 'emit');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.viewChanged.emit).toHaveBeenCalledWith('month');
});
it("should emit viewChanged when view changed from 'multi-year' to 'year'", () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
spyOn(calendarInstance.viewChanged, 'emit');
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.viewChanged.emit).toHaveBeenCalledWith('year');
});
it('should go to next and previous month', () => {
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
nextButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2017, FEB, 28));
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 28));
});
it('should go to previous and next year', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
(calendarElement.querySelector('.mat-calendar-body-active') as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
nextButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2018, JAN, 31));
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
});
it('should go to previous and next multi-year range', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
nextButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2017 + yearsPerPage, JAN, 31));
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
});
it('should go back to month view after selecting year and month', () => {
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(calendarInstance.activeDate).toEqual(new Date(2017, JAN, 31));
let yearCells = calendarElement.querySelectorAll('.mat-calendar-body-cell');
(yearCells[0] as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('year');
expect(calendarInstance.activeDate).toEqual(new Date(2016, JAN, 31));
let monthCells = calendarElement.querySelectorAll('.mat-calendar-body-cell');
(monthCells[monthCells.length - 1] as HTMLElement).click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('month');
expect(calendarInstance.activeDate).toEqual(new Date(2016, DEC, 31));
expect(testComponent.selected).withContext('no date should be selected yet').toBeFalsy();
});
it('should format the year in the period button using the date adapter', () => {
const adapter = fixture.debugElement.injector.get(DateAdapter);
spyOn(adapter, 'getYearName').and.returnValue('FAKE_YEAR');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(periodButton.textContent).toContain('FAKE_YEAR');
});
it('should label and describe period button for assistive technology', () => {
expect(calendarInstance.currentView).toBe('month');
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(periodButton.hasAttribute('aria-label')).toBe(true);
expect(periodButton.getAttribute('aria-label')).toMatch(/^[a-z0-9\s]+$/i);
expect(periodButton.hasAttribute('aria-describedby')).toBe(true);
expect(periodButton.getAttribute('aria-describedby')).toMatch(/mat-calendar-header-[0-9]+/i);
});
});
describe('calendar with minDate only', () => {
let fixture: ComponentFixture<CalendarWithMinMaxDate>;
let testComponent: CalendarWithMinMaxDate;
let calendarElement: HTMLElement;
let periodButton: HTMLButtonElement;
let prevButton: HTMLButtonElement;
let nextButton: HTMLButtonElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithMinMaxDate);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLButtonElement;
prevButton = calendarElement.querySelector(
'.mat-calendar-previous-button',
) as HTMLButtonElement;
nextButton = calendarElement.querySelector('.mat-calendar-next-button') as HTMLButtonElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should start the first page with minDate', () => {
testComponent.minDate = new Date(2010, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(periodButton.innerText.trim()).toEqual('2010 \u2013 2033');
});
it('should disable the page before the one showing minDate', () => {
testComponent.minDate = new Date(2010, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(prevButton.disabled).toBe(true);
});
it('should enable the page after the one showing minDate', () => {
testComponent.minDate = new Date(2010, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(nextButton.disabled).toBe(false);
});
}); | {
"end_byte": 9452,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-header.spec.ts"
} |
components/src/material/datepicker/calendar-header.spec.ts_9456_14593 | describe('calendar with maxDate only', () => {
let fixture: ComponentFixture<CalendarWithMinMaxDate>;
let testComponent: CalendarWithMinMaxDate;
let calendarElement: HTMLElement;
let periodButton: HTMLButtonElement;
let prevButton: HTMLButtonElement;
let nextButton: HTMLButtonElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithMinMaxDate);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLButtonElement;
prevButton = calendarElement.querySelector(
'.mat-calendar-previous-button',
) as HTMLButtonElement;
nextButton = calendarElement.querySelector('.mat-calendar-next-button') as HTMLButtonElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should end the last page with maxDate', () => {
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(periodButton.innerText.trim()).toEqual('1997 \u2013 2020');
});
it('should disable the page after the one showing maxDate', () => {
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(nextButton.disabled).toBe(true);
});
it('should enable the page before the one showing maxDate', () => {
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(prevButton.disabled).toBe(false);
});
});
describe('calendar with minDate and maxDate', () => {
let fixture: ComponentFixture<CalendarWithMinMaxDate>;
let testComponent: CalendarWithMinMaxDate;
let calendarElement: HTMLElement;
let periodButton: HTMLButtonElement;
let prevButton: HTMLButtonElement;
let nextButton: HTMLButtonElement;
let calendarInstance: MatCalendar<Date>;
beforeEach(() => {
fixture = TestBed.createComponent(CalendarWithMinMaxDate);
fixture.detectChanges();
let calendarDebugElement = fixture.debugElement.query(By.directive(MatCalendar))!;
calendarElement = calendarDebugElement.nativeElement;
periodButton = calendarElement.querySelector(
'.mat-calendar-period-button',
) as HTMLButtonElement;
prevButton = calendarElement.querySelector(
'.mat-calendar-previous-button',
) as HTMLButtonElement;
nextButton = calendarElement.querySelector('.mat-calendar-next-button') as HTMLButtonElement;
calendarInstance = calendarDebugElement.componentInstance;
testComponent = fixture.componentInstance;
});
it('should end the last page with maxDate', () => {
testComponent.minDate = new Date(1993, JAN, 1);
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(periodButton.innerText.trim()).toEqual('1997 \u2013 2020');
});
it('should disable the page after the one showing maxDate', () => {
testComponent.minDate = new Date(1993, JAN, 1);
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
expect(nextButton.disabled).toBe(true);
});
it('should disable the page before the one showing minDate', () => {
testComponent.minDate = new Date(1993, JAN, 1);
testComponent.maxDate = new Date(2020, JAN, 1);
periodButton.click();
fixture.detectChanges();
expect(calendarInstance.currentView).toBe('multi-year');
prevButton.click();
fixture.detectChanges();
expect(calendarInstance.activeDate).toEqual(new Date(2018 - yearsPerPage, JAN, 1));
expect(prevButton.disabled).toBe(true);
});
});
});
@Component({
template: `
<mat-calendar
[startAt]="startDate"
[(selected)]="selected"
(yearSelected)="selectedYear=$event"
(monthSelected)="selectedMonth=$event">
</mat-calendar>`,
standalone: true,
imports: [MatNativeDateModule, MatDatepickerModule],
})
class StandardCalendar {
selected: Date;
selectedYear: Date;
selectedMonth: Date;
startDate = new Date(2017, JAN, 31);
}
@Component({
template: `
<mat-calendar
[startAt]="startAt"
[minDate]="minDate"
[maxDate]="maxDate">
</mat-calendar>
`,
standalone: true,
imports: [MatNativeDateModule, MatDatepickerModule],
})
class CalendarWithMinMaxDate {
startAt = new Date(2018, JAN, 1);
minDate: Date | null;
maxDate: Date | null;
} | {
"end_byte": 14593,
"start_byte": 9456,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-header.spec.ts"
} |
components/src/material/datepicker/datepicker-input-base.ts_0_2420 | /**
* @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, hasModifierKey, ModifierKey} from '@angular/cdk/keycodes';
import {
Directive,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
AfterViewInit,
OnChanges,
SimpleChanges,
booleanAttribute,
inject,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
ValidationErrors,
Validator,
ValidatorFn,
} from '@angular/forms';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats, ThemePalette} from '@angular/material/core';
import {Subscription, Subject} from 'rxjs';
import {createMissingDateImplError} from './datepicker-errors';
import {
ExtractDateTypeFromSelection,
MatDateSelectionModel,
DateSelectionModelChange,
} from './date-selection-model';
/**
* An event used for datepicker input and change events. We don't always have access to a native
* input or change event because the event may have been triggered by the user clicking on the
* calendar popup. For consistency, we always use MatDatepickerInputEvent instead.
*/
export class MatDatepickerInputEvent<D, S = unknown> {
/** The new value for the target datepicker input. */
value: D | null;
constructor(
/** Reference to the datepicker input component that emitted the event. */
public target: MatDatepickerInputBase<S, D>,
/** Reference to the native input element associated with the datepicker input. */
public targetElement: HTMLElement,
) {
this.value = this.target.value;
}
}
/**
* Function that can be used to filter out dates from a calendar.
* Datepicker can sometimes receive a null value as input for the date argument.
* This doesn't represent a "null date" but rather signifies that no date has been selected yet in the calendar.
*/
export type DateFilterFn<D> = (date: D | null) => boolean;
/**
* Partial representation of `MatFormField` that is used for backwards-compatibility
* between the legacy and non-legacy variants.
*/
export interface _MatFormFieldPartial {
getConnectedOverlayOrigin(): ElementRef;
getLabelId(): string | null;
color: ThemePalette;
_elementRef: ElementRef;
_shouldLabelFloat(): boolean;
_hasFloatingLabel(): boolean;
_labelId: string;
}
/** Base class for datepicker inputs. */ | {
"end_byte": 2420,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-input-base.ts"
} |
components/src/material/datepicker/datepicker-input-base.ts_2421_10777 | @Directive()
export abstract class MatDatepickerInputBase<S, D = ExtractDateTypeFromSelection<S>>
implements ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy, Validator
{
protected _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
_dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dateFormats = inject<MatDateFormats>(MAT_DATE_FORMATS, {optional: true})!;
/** Whether the component has been initialized. */
private _isInitialized: boolean;
/** The value of the input. */
@Input()
get value(): D | null {
return this._model ? this._getValueFromModel(this._model.selection) : this._pendingValue;
}
set value(value: any) {
this._assignValueProgrammatically(value);
}
protected _model: MatDateSelectionModel<S, D> | undefined;
/** Whether the datepicker-input is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return !!this._disabled || this._parentDisabled();
}
set disabled(value: boolean) {
const newValue = value;
const element = this._elementRef.nativeElement;
if (this._disabled !== newValue) {
this._disabled = newValue;
this.stateChanges.next(undefined);
}
// We need to null check the `blur` method, because it's undefined during SSR.
// In Ivy static bindings are invoked earlier, before the element is attached to the DOM.
// This can cause an error to be thrown in some browsers (IE/Edge) which assert that the
// element has been inserted.
if (newValue && this._isInitialized && element.blur) {
// Normally, native input elements automatically blur if they turn disabled. This behavior
// is problematic, because it would mean that it triggers another change detection cycle,
// which then causes a changed after checked error if the input element was focused before.
element.blur();
}
}
private _disabled: boolean;
/** Emits when a `change` event is fired on this `<input>`. */
@Output() readonly dateChange: EventEmitter<MatDatepickerInputEvent<D, S>> = new EventEmitter<
MatDatepickerInputEvent<D, S>
>();
/** Emits when an `input` event is fired on this `<input>`. */
@Output() readonly dateInput: EventEmitter<MatDatepickerInputEvent<D, S>> = new EventEmitter<
MatDatepickerInputEvent<D, S>
>();
/** Emits when the internal state has changed */
readonly stateChanges = new Subject<void>();
_onTouched = () => {};
_validatorOnChange = () => {};
private _cvaOnChange: (value: any) => void = () => {};
private _valueChangesSubscription = Subscription.EMPTY;
private _localeSubscription = Subscription.EMPTY;
/**
* Since the value is kept on the model which is assigned in an Input,
* we might get a value before we have a model. This property keeps track
* of the value until we have somewhere to assign it.
*/
private _pendingValue: D | null;
/** The form control validator for whether the input parses. */
private _parseValidator: ValidatorFn = (): ValidationErrors | null => {
return this._lastValueValid
? null
: {'matDatepickerParse': {'text': this._elementRef.nativeElement.value}};
};
/** The form control validator for the date filter. */
private _filterValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
return !controlValue || this._matchesFilter(controlValue)
? null
: {'matDatepickerFilter': true};
};
/** The form control validator for the min date. */
private _minValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const min = this._getMinDate();
return !min || !controlValue || this._dateAdapter.compareDate(min, controlValue) <= 0
? null
: {'matDatepickerMin': {'min': min, 'actual': controlValue}};
};
/** The form control validator for the max date. */
private _maxValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value),
);
const max = this._getMaxDate();
return !max || !controlValue || this._dateAdapter.compareDate(max, controlValue) >= 0
? null
: {'matDatepickerMax': {'max': max, 'actual': controlValue}};
};
/** Gets the base validator functions. */
protected _getValidators(): ValidatorFn[] {
return [this._parseValidator, this._minValidator, this._maxValidator, this._filterValidator];
}
/** Gets the minimum date for the input. Used for validation. */
abstract _getMinDate(): D | null;
/** Gets the maximum date for the input. Used for validation. */
abstract _getMaxDate(): D | null;
/** Gets the date filter function. Used for validation. */
protected abstract _getDateFilter(): DateFilterFn<D> | undefined;
/** Registers a date selection model with the input. */
_registerModel(model: MatDateSelectionModel<S, D>): void {
this._model = model;
this._valueChangesSubscription.unsubscribe();
if (this._pendingValue) {
this._assignValue(this._pendingValue);
}
this._valueChangesSubscription = this._model.selectionChanged.subscribe(event => {
if (this._shouldHandleChangeEvent(event)) {
const value = this._getValueFromModel(event.selection);
this._lastValueValid = this._isValidValue(value);
this._cvaOnChange(value);
this._onTouched();
this._formatValue(value);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
});
}
/** Opens the popup associated with the input. */
protected abstract _openPopup(): void;
/** Assigns a value to the input's model. */
protected abstract _assignValueToModel(model: D | null): void;
/** Converts a value from the model into a native value for the input. */
protected abstract _getValueFromModel(modelValue: S): D | null;
/** Combined form control validator for this input. */
protected abstract _validator: ValidatorFn | null;
/** Predicate that determines whether the input should handle a particular change event. */
protected abstract _shouldHandleChangeEvent(event: DateSelectionModelChange<S>): boolean;
/** Whether the last value set on the input was valid. */
protected _lastValueValid = false;
constructor(...args: unknown[]);
constructor() {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MAT_DATE_FORMATS');
}
}
// Update the displayed date when the locale changes.
this._localeSubscription = this._dateAdapter.localeChanges.subscribe(() => {
this._assignValueProgrammatically(this.value);
});
}
ngAfterViewInit() {
this._isInitialized = true;
}
ngOnChanges(changes: SimpleChanges) {
if (dateInputsHaveChanged(changes, this._dateAdapter)) {
this.stateChanges.next(undefined);
}
}
ngOnDestroy() {
this._valueChangesSubscription.unsubscribe();
this._localeSubscription.unsubscribe();
this.stateChanges.complete();
}
/** @docs-private */
registerOnValidatorChange(fn: () => void): void {
this._validatorOnChange = fn;
}
/** @docs-private */
validate(c: AbstractControl): ValidationErrors | null {
return this._validator ? this._validator(c) : null;
}
// Implemented as part of ControlValueAccessor.
writeValue(value: D): void {
this._assignValueProgrammatically(value);
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void): void {
this._cvaOnChange = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
} | {
"end_byte": 10777,
"start_byte": 2421,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-input-base.ts"
} |
components/src/material/datepicker/datepicker-input-base.ts_10781_14694 | _onKeydown(event: KeyboardEvent) {
const ctrlShiftMetaModifiers: ModifierKey[] = ['ctrlKey', 'shiftKey', 'metaKey'];
const isAltDownArrow =
hasModifierKey(event, 'altKey') &&
event.keyCode === DOWN_ARROW &&
ctrlShiftMetaModifiers.every((modifier: ModifierKey) => !hasModifierKey(event, modifier));
if (isAltDownArrow && !this._elementRef.nativeElement.readOnly) {
this._openPopup();
event.preventDefault();
}
}
_onInput(value: string) {
const lastValueWasValid = this._lastValueValid;
let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
this._lastValueValid = this._isValidValue(date);
date = this._dateAdapter.getValidDateOrNull(date);
const hasChanged = !this._dateAdapter.sameDate(date, this.value);
// We need to fire the CVA change event for all
// nulls, otherwise the validators won't run.
if (!date || hasChanged) {
this._cvaOnChange(date);
} else {
// Call the CVA change handler for invalid values
// since this is what marks the control as dirty.
if (value && !this.value) {
this._cvaOnChange(date);
}
if (lastValueWasValid !== this._lastValueValid) {
this._validatorOnChange();
}
}
if (hasChanged) {
this._assignValue(date);
this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
}
_onChange() {
this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
}
/** Handles blur events on the input. */
_onBlur() {
// Reformat the input only if we have a valid value.
if (this.value) {
this._formatValue(this.value);
}
this._onTouched();
}
/** Formats a value and sets it on the input element. */
protected _formatValue(value: D | null) {
this._elementRef.nativeElement.value =
value != null ? this._dateAdapter.format(value, this._dateFormats.display.dateInput) : '';
}
/** Assigns a value to the model. */
private _assignValue(value: D | null) {
// We may get some incoming values before the model was
// assigned. Save the value so that we can assign it later.
if (this._model) {
this._assignValueToModel(value);
this._pendingValue = null;
} else {
this._pendingValue = value;
}
}
/** Whether a value is considered valid. */
private _isValidValue(value: D | null): boolean {
return !value || this._dateAdapter.isValid(value);
}
/**
* Checks whether a parent control is disabled. This is in place so that it can be overridden
* by inputs extending this one which can be placed inside of a group that can be disabled.
*/
protected _parentDisabled() {
return false;
}
/** Programmatically assigns a value to the input. */
protected _assignValueProgrammatically(value: D | null) {
value = this._dateAdapter.deserialize(value);
this._lastValueValid = this._isValidValue(value);
value = this._dateAdapter.getValidDateOrNull(value);
this._assignValue(value);
this._formatValue(value);
}
/** Gets whether a value matches the current date filter. */
_matchesFilter(value: D | null): boolean {
const filter = this._getDateFilter();
return !filter || filter(value);
}
}
/**
* Checks whether the `SimpleChanges` object from an `ngOnChanges`
* callback has any changes, accounting for date objects.
*/
export function dateInputsHaveChanged(
changes: SimpleChanges,
adapter: DateAdapter<unknown>,
): boolean {
const keys = Object.keys(changes);
for (let key of keys) {
const {previousValue, currentValue} = changes[key];
if (adapter.isDateInstance(previousValue) && adapter.isDateInstance(currentValue)) {
if (!adapter.sameDate(previousValue, currentValue)) {
return true;
}
} else {
return true;
}
}
return false;
} | {
"end_byte": 14694,
"start_byte": 10781,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-input-base.ts"
} |
components/src/material/datepicker/calendar-body.ts_0_2705 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Platform, normalizePassiveListenerOptions} from '@angular/cdk/platform';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
Output,
ViewEncapsulation,
NgZone,
OnChanges,
SimpleChanges,
OnDestroy,
AfterViewChecked,
inject,
afterNextRender,
Injector,
} from '@angular/core';
import {NgClass} from '@angular/common';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {_StructuralStylesLoader} from '@angular/material/core';
/** Extra CSS classes that can be associated with a calendar cell. */
export type MatCalendarCellCssClasses = string | string[] | Set<string> | {[key: string]: any};
/** Function that can generate the extra classes that should be added to a calendar cell. */
export type MatCalendarCellClassFunction<D> = (
date: D,
view: 'month' | 'year' | 'multi-year',
) => MatCalendarCellCssClasses;
let uniqueIdCounter = 0;
/**
* An internal class that represents the data corresponding to a single calendar cell.
* @docs-private
*/
export class MatCalendarCell<D = any> {
readonly id = uniqueIdCounter++;
constructor(
public value: number,
public displayValue: string,
public ariaLabel: string,
public enabled: boolean,
public cssClasses: MatCalendarCellCssClasses = {},
public compareValue = value,
public rawValue?: D,
) {}
}
/** Event emitted when a date inside the calendar is triggered as a result of a user action. */
export interface MatCalendarUserEvent<D> {
value: D;
event: Event;
}
let calendarBodyId = 1;
/** Event options that can be used to bind an active, capturing event. */
const activeCapturingEventOptions = normalizePassiveListenerOptions({
passive: false,
capture: true,
});
/** Event options that can be used to bind a passive, capturing event. */
const passiveCapturingEventOptions = normalizePassiveListenerOptions({
passive: true,
capture: true,
});
/** Event options that can be used to bind a passive, non-capturing event. */
const passiveEventOptions = normalizePassiveListenerOptions({passive: true});
/**
* An internal component used to display calendar data in a table.
* @docs-private
*/
@Component({
selector: '[mat-calendar-body]',
templateUrl: 'calendar-body.html',
styleUrl: 'calendar-body.css',
host: {
'class': 'mat-calendar-body',
},
exportAs: 'matCalendarBody',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgClass],
})
export | {
"end_byte": 2705,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.ts"
} |
components/src/material/datepicker/calendar-body.ts_2706_11209 | class MatCalendarBody<D = any> implements OnChanges, OnDestroy, AfterViewChecked {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _ngZone = inject(NgZone);
private _platform = inject(Platform);
/**
* Used to skip the next focus event when rendering the preview range.
* We need a flag like this, because some browsers fire focus events asynchronously.
*/
private _skipNextFocus: boolean;
/**
* Used to focus the active cell after change detection has run.
*/
private _focusActiveCellAfterViewChecked = false;
/** The label for the table. (e.g. "Jan 2017"). */
@Input() label: string;
/** The cells to display in the table. */
@Input() rows: MatCalendarCell[][];
/** The value in the table that corresponds to today. */
@Input() todayValue: number;
/** Start value of the selected date range. */
@Input() startValue: number;
/** End value of the selected date range. */
@Input() endValue: number;
/** The minimum number of free cells needed to fit the label in the first row. */
@Input() labelMinRequiredCells: number;
/** The number of columns in the table. */
@Input() numCols: number = 7;
/** The cell number of the active cell in the table. */
@Input() activeCell: number = 0;
ngAfterViewChecked() {
if (this._focusActiveCellAfterViewChecked) {
this._focusActiveCell();
this._focusActiveCellAfterViewChecked = false;
}
}
/** Whether a range is being selected. */
@Input() isRange: boolean = false;
/**
* The aspect ratio (width / height) to use for the cells in the table. This aspect ratio will be
* maintained even as the table resizes.
*/
@Input() cellAspectRatio: number = 1;
/** Start of the comparison range. */
@Input() comparisonStart: number | null;
/** End of the comparison range. */
@Input() comparisonEnd: number | null;
/** Start of the preview range. */
@Input() previewStart: number | null = null;
/** End of the preview range. */
@Input() previewEnd: number | null = null;
/** ARIA Accessible name of the `<input matStartDate/>` */
@Input() startDateAccessibleName: string | null;
/** ARIA Accessible name of the `<input matEndDate/>` */
@Input() endDateAccessibleName: string | null;
/** Emits when a new value is selected. */
@Output() readonly selectedValueChange = new EventEmitter<MatCalendarUserEvent<number>>();
/** Emits when the preview has changed as a result of a user action. */
@Output() readonly previewChange = new EventEmitter<
MatCalendarUserEvent<MatCalendarCell | null>
>();
@Output() readonly activeDateChange = new EventEmitter<MatCalendarUserEvent<number>>();
/** Emits the date at the possible start of a drag event. */
@Output() readonly dragStarted = new EventEmitter<MatCalendarUserEvent<D>>();
/** Emits the date at the conclusion of a drag, or null if mouse was not released on a date. */
@Output() readonly dragEnded = new EventEmitter<MatCalendarUserEvent<D | null>>();
/** The number of blank cells to put at the beginning for the first row. */
_firstRowOffset: number;
/** Padding for the individual date cells. */
_cellPadding: string;
/** Width of an individual cell. */
_cellWidth: string;
private _didDragSinceMouseDown = false;
private _injector = inject(Injector);
/**
* Tracking function for rows based on their identity. Ideally we would use some sort of
* key on the row, but that would require a breaking change for the `rows` input. We don't
* use the built-in identity tracking, because it logs warnings.
*/
_trackRow = (row: MatCalendarCell[]) => row;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
this._ngZone.runOutsideAngular(() => {
const element = this._elementRef.nativeElement;
// `touchmove` is active since we need to call `preventDefault`.
element.addEventListener('touchmove', this._touchmoveHandler, activeCapturingEventOptions);
element.addEventListener('mouseenter', this._enterHandler, passiveCapturingEventOptions);
element.addEventListener('focus', this._enterHandler, passiveCapturingEventOptions);
element.addEventListener('mouseleave', this._leaveHandler, passiveCapturingEventOptions);
element.addEventListener('blur', this._leaveHandler, passiveCapturingEventOptions);
element.addEventListener('mousedown', this._mousedownHandler, passiveEventOptions);
element.addEventListener('touchstart', this._mousedownHandler, passiveEventOptions);
if (this._platform.isBrowser) {
window.addEventListener('mouseup', this._mouseupHandler);
window.addEventListener('touchend', this._touchendHandler);
}
});
}
/** Called when a cell is clicked. */
_cellClicked(cell: MatCalendarCell, event: MouseEvent): void {
// Ignore "clicks" that are actually canceled drags (eg the user dragged
// off and then went back to this cell to undo).
if (this._didDragSinceMouseDown) {
return;
}
if (cell.enabled) {
this.selectedValueChange.emit({value: cell.value, event});
}
}
_emitActiveDateChange(cell: MatCalendarCell, event: FocusEvent): void {
if (cell.enabled) {
this.activeDateChange.emit({value: cell.value, event});
}
}
/** Returns whether a cell should be marked as selected. */
_isSelected(value: number) {
return this.startValue === value || this.endValue === value;
}
ngOnChanges(changes: SimpleChanges) {
const columnChanges = changes['numCols'];
const {rows, numCols} = this;
if (changes['rows'] || columnChanges) {
this._firstRowOffset = rows && rows.length && rows[0].length ? numCols - rows[0].length : 0;
}
if (changes['cellAspectRatio'] || columnChanges || !this._cellPadding) {
this._cellPadding = `${(50 * this.cellAspectRatio) / numCols}%`;
}
if (columnChanges || !this._cellWidth) {
this._cellWidth = `${100 / numCols}%`;
}
}
ngOnDestroy() {
const element = this._elementRef.nativeElement;
element.removeEventListener('touchmove', this._touchmoveHandler, activeCapturingEventOptions);
element.removeEventListener('mouseenter', this._enterHandler, passiveCapturingEventOptions);
element.removeEventListener('focus', this._enterHandler, passiveCapturingEventOptions);
element.removeEventListener('mouseleave', this._leaveHandler, passiveCapturingEventOptions);
element.removeEventListener('blur', this._leaveHandler, passiveCapturingEventOptions);
element.removeEventListener('mousedown', this._mousedownHandler, passiveEventOptions);
element.removeEventListener('touchstart', this._mousedownHandler, passiveEventOptions);
if (this._platform.isBrowser) {
window.removeEventListener('mouseup', this._mouseupHandler);
window.removeEventListener('touchend', this._touchendHandler);
}
}
/** Returns whether a cell is active. */
_isActiveCell(rowIndex: number, colIndex: number): boolean {
let cellNumber = rowIndex * this.numCols + colIndex;
// Account for the fact that the first row may not have as many cells.
if (rowIndex) {
cellNumber -= this._firstRowOffset;
}
return cellNumber == this.activeCell;
}
/**
* Focuses the active cell after the microtask queue is empty.
*
* Adding a 0ms setTimeout seems to fix Voiceover losing focus when pressing PageUp/PageDown
* (issue #24330).
*
* Determined a 0ms by gradually increasing duration from 0 and testing two use cases with screen
* reader enabled:
*
* 1. Pressing PageUp/PageDown repeatedly with pausing between each key press.
* 2. Pressing and holding the PageDown key with repeated keys enabled.
*
* Test 1 worked roughly 95-99% of the time with 0ms and got a little bit better as the duration
* increased. Test 2 got slightly better until the duration was long enough to interfere with
* repeated keys. If the repeated key speed was faster than the timeout duration, then pressing
* and holding pagedown caused the entire page to scroll.
*
* Since repeated key speed can verify across machines, determined that any duration could
* potentially interfere with repeated keys. 0ms would be best because it almost entirely
* eliminates the focus being lost in Voiceover (#24330) without causing unintended side effects.
* Adding delay also complicates writing tests.
*/ | {
"end_byte": 11209,
"start_byte": 2706,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.ts"
} |
components/src/material/datepicker/calendar-body.ts_11212_19064 | _focusActiveCell(movePreview = true) {
afterNextRender(
() => {
setTimeout(() => {
const activeCell: HTMLElement | null = this._elementRef.nativeElement.querySelector(
'.mat-calendar-body-active',
);
if (activeCell) {
if (!movePreview) {
this._skipNextFocus = true;
}
activeCell.focus();
}
});
},
{injector: this._injector},
);
}
/** Focuses the active cell after change detection has run and the microtask queue is empty. */
_scheduleFocusActiveCellAfterViewChecked() {
this._focusActiveCellAfterViewChecked = true;
}
/** Gets whether a value is the start of the main range. */
_isRangeStart(value: number) {
return isStart(value, this.startValue, this.endValue);
}
/** Gets whether a value is the end of the main range. */
_isRangeEnd(value: number) {
return isEnd(value, this.startValue, this.endValue);
}
/** Gets whether a value is within the currently-selected range. */
_isInRange(value: number): boolean {
return isInRange(value, this.startValue, this.endValue, this.isRange);
}
/** Gets whether a value is the start of the comparison range. */
_isComparisonStart(value: number) {
return isStart(value, this.comparisonStart, this.comparisonEnd);
}
/** Whether the cell is a start bridge cell between the main and comparison ranges. */
_isComparisonBridgeStart(value: number, rowIndex: number, colIndex: number) {
if (!this._isComparisonStart(value) || this._isRangeStart(value) || !this._isInRange(value)) {
return false;
}
let previousCell: MatCalendarCell | undefined = this.rows[rowIndex][colIndex - 1];
if (!previousCell) {
const previousRow = this.rows[rowIndex - 1];
previousCell = previousRow && previousRow[previousRow.length - 1];
}
return previousCell && !this._isRangeEnd(previousCell.compareValue);
}
/** Whether the cell is an end bridge cell between the main and comparison ranges. */
_isComparisonBridgeEnd(value: number, rowIndex: number, colIndex: number) {
if (!this._isComparisonEnd(value) || this._isRangeEnd(value) || !this._isInRange(value)) {
return false;
}
let nextCell: MatCalendarCell | undefined = this.rows[rowIndex][colIndex + 1];
if (!nextCell) {
const nextRow = this.rows[rowIndex + 1];
nextCell = nextRow && nextRow[0];
}
return nextCell && !this._isRangeStart(nextCell.compareValue);
}
/** Gets whether a value is the end of the comparison range. */
_isComparisonEnd(value: number) {
return isEnd(value, this.comparisonStart, this.comparisonEnd);
}
/** Gets whether a value is within the current comparison range. */
_isInComparisonRange(value: number) {
return isInRange(value, this.comparisonStart, this.comparisonEnd, this.isRange);
}
/**
* Gets whether a value is the same as the start and end of the comparison range.
* For context, the functions that we use to determine whether something is the start/end of
* a range don't allow for the start and end to be on the same day, because we'd have to use
* much more specific CSS selectors to style them correctly in all scenarios. This is fine for
* the regular range, because when it happens, the selected styles take over and still show where
* the range would've been, however we don't have these selected styles for a comparison range.
* This function is used to apply a class that serves the same purpose as the one for selected
* dates, but it only applies in the context of a comparison range.
*/
_isComparisonIdentical(value: number) {
// Note that we don't need to null check the start/end
// here, because the `value` will always be defined.
return this.comparisonStart === this.comparisonEnd && value === this.comparisonStart;
}
/** Gets whether a value is the start of the preview range. */
_isPreviewStart(value: number) {
return isStart(value, this.previewStart, this.previewEnd);
}
/** Gets whether a value is the end of the preview range. */
_isPreviewEnd(value: number) {
return isEnd(value, this.previewStart, this.previewEnd);
}
/** Gets whether a value is inside the preview range. */
_isInPreview(value: number) {
return isInRange(value, this.previewStart, this.previewEnd, this.isRange);
}
/** Gets ids of aria descriptions for the start and end of a date range. */
_getDescribedby(value: number): string | null {
if (!this.isRange) {
return null;
}
if (this.startValue === value && this.endValue === value) {
return `${this._startDateLabelId} ${this._endDateLabelId}`;
} else if (this.startValue === value) {
return this._startDateLabelId;
} else if (this.endValue === value) {
return this._endDateLabelId;
}
return null;
}
/**
* Event handler for when the user enters an element
* inside the calendar body (e.g. by hovering in or focus).
*/
private _enterHandler = (event: Event) => {
if (this._skipNextFocus && event.type === 'focus') {
this._skipNextFocus = false;
return;
}
// We only need to hit the zone when we're selecting a range.
if (event.target && this.isRange) {
const cell = this._getCellFromElement(event.target as HTMLElement);
if (cell) {
this._ngZone.run(() => this.previewChange.emit({value: cell.enabled ? cell : null, event}));
}
}
};
private _touchmoveHandler = (event: TouchEvent) => {
if (!this.isRange) return;
const target = getActualTouchTarget(event);
const cell = target ? this._getCellFromElement(target as HTMLElement) : null;
if (target !== event.target) {
this._didDragSinceMouseDown = true;
}
// If the initial target of the touch is a date cell, prevent default so
// that the move is not handled as a scroll.
if (getCellElement(event.target as HTMLElement)) {
event.preventDefault();
}
this._ngZone.run(() => this.previewChange.emit({value: cell?.enabled ? cell : null, event}));
};
/**
* Event handler for when the user's pointer leaves an element
* inside the calendar body (e.g. by hovering out or blurring).
*/
private _leaveHandler = (event: Event) => {
// We only need to hit the zone when we're selecting a range.
if (this.previewEnd !== null && this.isRange) {
if (event.type !== 'blur') {
this._didDragSinceMouseDown = true;
}
// Only reset the preview end value when leaving cells. This looks better, because
// we have a gap between the cells and the rows and we don't want to remove the
// range just for it to show up again when the user moves a few pixels to the side.
if (
event.target &&
this._getCellFromElement(event.target as HTMLElement) &&
!(
(event as MouseEvent).relatedTarget &&
this._getCellFromElement((event as MouseEvent).relatedTarget as HTMLElement)
)
) {
this._ngZone.run(() => this.previewChange.emit({value: null, event}));
}
}
};
/**
* Triggered on mousedown or touchstart on a date cell.
* Respsonsible for starting a drag sequence.
*/
private _mousedownHandler = (event: Event) => {
if (!this.isRange) return;
this._didDragSinceMouseDown = false;
// Begin a drag if a cell within the current range was targeted.
const cell = event.target && this._getCellFromElement(event.target as HTMLElement);
if (!cell || !this._isInRange(cell.compareValue)) {
return;
}
this._ngZone.run(() => {
this.dragStarted.emit({
value: cell.rawValue,
event,
});
});
};
/** Triggered on mouseup anywhere. Respsonsible for ending a drag sequence. */ | {
"end_byte": 19064,
"start_byte": 11212,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.ts"
} |
components/src/material/datepicker/calendar-body.ts_19067_22513 | private _mouseupHandler = (event: Event) => {
if (!this.isRange) return;
const cellElement = getCellElement(event.target as HTMLElement);
if (!cellElement) {
// Mouseup happened outside of datepicker. Cancel drag.
this._ngZone.run(() => {
this.dragEnded.emit({value: null, event});
});
return;
}
if (cellElement.closest('.mat-calendar-body') !== this._elementRef.nativeElement) {
// Mouseup happened inside a different month instance.
// Allow it to handle the event.
return;
}
this._ngZone.run(() => {
const cell = this._getCellFromElement(cellElement);
this.dragEnded.emit({value: cell?.rawValue ?? null, event});
});
};
/** Triggered on touchend anywhere. Respsonsible for ending a drag sequence. */
private _touchendHandler = (event: TouchEvent) => {
const target = getActualTouchTarget(event);
if (target) {
this._mouseupHandler({target} as unknown as Event);
}
};
/** Finds the MatCalendarCell that corresponds to a DOM node. */
private _getCellFromElement(element: HTMLElement): MatCalendarCell | null {
const cell = getCellElement(element);
if (cell) {
const row = cell.getAttribute('data-mat-row');
const col = cell.getAttribute('data-mat-col');
if (row && col) {
return this.rows[parseInt(row)][parseInt(col)];
}
}
return null;
}
private _id = `mat-calendar-body-${calendarBodyId++}`;
_startDateLabelId = `${this._id}-start-date`;
_endDateLabelId = `${this._id}-end-date`;
}
/** Checks whether a node is a table cell element. */
function isTableCell(node: Node | undefined | null): node is HTMLTableCellElement {
return node?.nodeName === 'TD';
}
/**
* Gets the date table cell element that is or contains the specified element.
* Or returns null if element is not part of a date cell.
*/
function getCellElement(element: HTMLElement): HTMLElement | null {
let cell: HTMLElement | undefined;
if (isTableCell(element)) {
cell = element;
} else if (isTableCell(element.parentNode)) {
cell = element.parentNode as HTMLElement;
} else if (isTableCell(element.parentNode?.parentNode)) {
cell = element.parentNode!.parentNode as HTMLElement;
}
return cell?.getAttribute('data-mat-row') != null ? cell : null;
}
/** Checks whether a value is the start of a range. */
function isStart(value: number, start: number | null, end: number | null): boolean {
return end !== null && start !== end && value < end && value === start;
}
/** Checks whether a value is the end of a range. */
function isEnd(value: number, start: number | null, end: number | null): boolean {
return start !== null && start !== end && value >= start && value === end;
}
/** Checks whether a value is inside of a range. */
function isInRange(
value: number,
start: number | null,
end: number | null,
rangeEnabled: boolean,
): boolean {
return (
rangeEnabled &&
start !== null &&
end !== null &&
start !== end &&
value >= start &&
value <= end
);
}
/**
* Extracts the element that actually corresponds to a touch event's location
* (rather than the element that initiated the sequence of touch events).
*/
function getActualTouchTarget(event: TouchEvent): Element | null {
const touchLocation = event.changedTouches[0];
return document.elementFromPoint(touchLocation.clientX, touchLocation.clientY);
} | {
"end_byte": 22513,
"start_byte": 19067,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-body.ts"
} |
components/src/material/datepicker/README.md_0_101 | Please see the official documentation at https://material.angular.io/components/component/datepicker
| {
"end_byte": 101,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/README.md"
} |
components/src/material/datepicker/datepicker-base.ts_0_3683 | /**
* @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 {AnimationEvent} from '@angular/animations';
import {CdkTrapFocus} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {coerceStringArray} from '@angular/cdk/coercion';
import {
DOWN_ARROW,
ESCAPE,
hasModifierKey,
LEFT_ARROW,
ModifierKey,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {
FlexibleConnectedPositionStrategy,
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
} from '@angular/cdk/overlay';
import {_getFocusedElementPierceShadowDom} from '@angular/cdk/platform';
import {CdkPortalOutlet, ComponentPortal, ComponentType, TemplatePortal} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {
afterNextRender,
AfterViewInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
Directive,
ElementRef,
EventEmitter,
inject,
InjectionToken,
Injector,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
} from '@angular/core';
import {MatButton} from '@angular/material/button';
import {DateAdapter, ThemePalette} from '@angular/material/core';
import {merge, Observable, Subject, Subscription} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {MatCalendar, MatCalendarView} from './calendar';
import {MatCalendarCellClassFunction, MatCalendarUserEvent} from './calendar-body';
import {
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDateRangeSelectionStrategy,
} from './date-range-selection-strategy';
import {
DateRange,
ExtractDateTypeFromSelection,
MatDateSelectionModel,
} from './date-selection-model';
import {matDatepickerAnimations} from './datepicker-animations';
import {createMissingDateImplError} from './datepicker-errors';
import {DateFilterFn} from './datepicker-input-base';
import {MatDatepickerIntl} from './datepicker-intl';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
/** Used to generate a unique ID for each datepicker instance. */
let datepickerUid = 0;
/** Injection token that determines the scroll handling while the calendar is open. */
export const MAT_DATEPICKER_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mat-datepicker-scroll-strategy',
{
providedIn: 'root',
factory: () => {
const overlay = inject(Overlay);
return () => overlay.scrollStrategies.reposition();
},
},
);
/** @docs-private */
export function MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** Possible positions for the datepicker dropdown along the X axis. */
export type DatepickerDropdownPositionX = 'start' | 'end';
/** Possible positions for the datepicker dropdown along the Y axis. */
export type DatepickerDropdownPositionY = 'above' | 'below';
/** @docs-private */
export const MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MAT_DATEPICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY,
};
/**
* Component used as the content for the datepicker overlay. We use this instead of using
* MatCalendar directly as the content so we can control the initial focus. This also gives us a
* place to put additional features of the overlay that are not part of the calendar itself in the
* future. (e.g. confirmation buttons).
* @docs-private
*/ | {
"end_byte": 3683,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-base.ts"
} |
components/src/material/datepicker/datepicker-base.ts_3684_11838 | @Component({
selector: 'mat-datepicker-content',
templateUrl: 'datepicker-content.html',
styleUrl: 'datepicker-content.css',
host: {
'class': 'mat-datepicker-content',
'[class]': 'color ? "mat-" + color : ""',
'[@transformPanel]': '_animationState',
'(@transformPanel.start)': '_handleAnimationEvent($event)',
'(@transformPanel.done)': '_handleAnimationEvent($event)',
'[class.mat-datepicker-content-touch]': 'datepicker.touchUi',
},
animations: [matDatepickerAnimations.transformPanel, matDatepickerAnimations.fadeInCalendar],
exportAs: 'matDatepickerContent',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [CdkTrapFocus, MatCalendar, CdkPortalOutlet, MatButton],
})
export class MatDatepickerContent<S, D = ExtractDateTypeFromSelection<S>>
implements OnInit, AfterViewInit, OnDestroy
{
protected _elementRef = inject(ElementRef);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _globalModel = inject<MatDateSelectionModel<S, D>>(MatDateSelectionModel);
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter)!;
private _rangeSelectionStrategy = inject<MatDateRangeSelectionStrategy<D>>(
MAT_DATE_RANGE_SELECTION_STRATEGY,
{optional: true},
);
private _subscriptions = new Subscription();
private _model: MatDateSelectionModel<S, D>;
/** Reference to the internal calendar component. */
@ViewChild(MatCalendar) _calendar: MatCalendar<D>;
/**
* Theme color of the internal calendar. This API is supported in M2 themes
* only, it has no effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*/
@Input() color: ThemePalette;
/** Reference to the datepicker that created the overlay. */
datepicker: MatDatepickerBase<any, S, D>;
/** Start of the comparison range. */
comparisonStart: D | null;
/** End of the comparison range. */
comparisonEnd: D | null;
/** ARIA Accessible name of the `<input matStartDate/>` */
startDateAccessibleName: string | null;
/** ARIA Accessible name of the `<input matEndDate/>` */
endDateAccessibleName: string | null;
/** Whether the datepicker is above or below the input. */
_isAbove: boolean;
/** Current state of the animation. */
_animationState: 'enter-dropdown' | 'enter-dialog' | 'void';
/** Emits when an animation has finished. */
readonly _animationDone = new Subject<void>();
/** Whether there is an in-progress animation. */
_isAnimating = false;
/** Text for the close button. */
_closeButtonText: string;
/** Whether the close button currently has focus. */
_closeButtonFocused: boolean;
/** Portal with projected action buttons. */
_actionsPortal: TemplatePortal | null = null;
/** Id of the label for the `role="dialog"` element. */
_dialogLabelId: string | null;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
const intl = inject(MatDatepickerIntl);
this._closeButtonText = intl.closeCalendarLabel;
}
ngOnInit() {
this._animationState = this.datepicker.touchUi ? 'enter-dialog' : 'enter-dropdown';
}
ngAfterViewInit() {
this._subscriptions.add(
this.datepicker.stateChanges.subscribe(() => {
this._changeDetectorRef.markForCheck();
}),
);
this._calendar.focusActiveCell();
}
ngOnDestroy() {
this._subscriptions.unsubscribe();
this._animationDone.complete();
}
_handleUserSelection(event: MatCalendarUserEvent<D | null>) {
const selection = this._model.selection;
const value = event.value;
const isRange = selection instanceof DateRange;
// If we're selecting a range and we have a selection strategy, always pass the value through
// there. Otherwise don't assign null values to the model, unless we're selecting a range.
// A null value when picking a range means that the user cancelled the selection (e.g. by
// pressing escape), whereas when selecting a single value it means that the value didn't
// change. This isn't very intuitive, but it's here for backwards-compatibility.
if (isRange && this._rangeSelectionStrategy) {
const newSelection = this._rangeSelectionStrategy.selectionFinished(
value,
selection as unknown as DateRange<D>,
event.event,
);
this._model.updateSelection(newSelection as unknown as S, this);
} else if (
value &&
(isRange || !this._dateAdapter.sameDate(value, selection as unknown as D))
) {
this._model.add(value);
}
// Delegate closing the overlay to the actions.
if ((!this._model || this._model.isComplete()) && !this._actionsPortal) {
this.datepicker.close();
}
}
_handleUserDragDrop(event: MatCalendarUserEvent<DateRange<D>>) {
this._model.updateSelection(event.value as unknown as S, this);
}
_startExitAnimation() {
this._animationState = 'void';
this._changeDetectorRef.markForCheck();
}
_handleAnimationEvent(event: AnimationEvent) {
this._isAnimating = event.phaseName === 'start';
if (!this._isAnimating) {
this._animationDone.next();
}
}
_getSelected() {
return this._model.selection as unknown as D | DateRange<D> | null;
}
/** Applies the current pending selection to the global model. */
_applyPendingSelection() {
if (this._model !== this._globalModel) {
this._globalModel.updateSelection(this._model.selection, this);
}
}
/**
* Assigns a new portal containing the datepicker actions.
* @param portal Portal with the actions to be assigned.
* @param forceRerender Whether a re-render of the portal should be triggered. This isn't
* necessary if the portal is assigned during initialization, but it may be required if it's
* added at a later point.
*/
_assignActions(portal: TemplatePortal<any> | null, forceRerender: boolean) {
// If we have actions, clone the model so that we have the ability to cancel the selection,
// otherwise update the global model directly. Note that we want to assign this as soon as
// possible, but `_actionsPortal` isn't available in the constructor so we do it in `ngOnInit`.
this._model = portal ? this._globalModel.clone() : this._globalModel;
this._actionsPortal = portal;
if (forceRerender) {
this._changeDetectorRef.detectChanges();
}
}
}
/** Form control that can be associated with a datepicker. */
export interface MatDatepickerControl<D> {
getStartValue(): D | null;
getThemePalette(): ThemePalette;
min: D | null;
max: D | null;
disabled: boolean;
dateFilter: DateFilterFn<D>;
getConnectedOverlayOrigin(): ElementRef;
getOverlayLabelId(): string | null;
stateChanges: Observable<void>;
}
/** A datepicker that can be attached to a {@link MatDatepickerControl}. */
export interface MatDatepickerPanel<
C extends MatDatepickerControl<D>,
S,
D = ExtractDateTypeFromSelection<S>,
> {
/** Stream that emits whenever the date picker is closed. */
closedStream: EventEmitter<void>;
/**
* Color palette to use on the datepicker's calendar. 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;
/** The input element the datepicker is associated with. */
datepickerInput: C;
/** Whether the datepicker pop-up should be disabled. */
disabled: boolean;
/** The id for the datepicker's calendar. */
id: string;
/** Whether the datepicker is open. */
opened: boolean;
/** Stream that emits whenever the date picker is opened. */
openedStream: EventEmitter<void>;
/** Emits when the datepicker's state changes. */
stateChanges: Subject<void>;
/** Opens the datepicker. */
open(): void;
/** Register an input with the datepicker. */
registerInput(input: C): MatDateSelectionModel<S, D>;
}
/** Base class for a datepicker. */ | {
"end_byte": 11838,
"start_byte": 3684,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-base.ts"
} |
components/src/material/datepicker/datepicker-base.ts_11839_20228 | @Directive()
export abstract class MatDatepickerBase<
C extends MatDatepickerControl<D>,
S,
D = ExtractDateTypeFromSelection<S>,
>
implements MatDatepickerPanel<C, S, D>, OnDestroy, OnChanges
{
private _overlay = inject(Overlay);
private _viewContainerRef = inject(ViewContainerRef);
private _dateAdapter = inject<DateAdapter<D>>(DateAdapter, {optional: true})!;
private _dir = inject(Directionality, {optional: true});
private _model = inject<MatDateSelectionModel<S, D>>(MatDateSelectionModel);
private _scrollStrategy = inject(MAT_DATEPICKER_SCROLL_STRATEGY);
private _inputStateChanges = Subscription.EMPTY;
private _document = inject(DOCUMENT);
/** An input indicating the type of the custom header component for the calendar, if set. */
@Input() calendarHeaderComponent: ComponentType<any>;
/** The date to open the calendar to initially. */
@Input()
get startAt(): D | null {
// If an explicit startAt is set we start there, otherwise we start at whatever the currently
// selected value is.
return this._startAt || (this.datepickerInput ? this.datepickerInput.getStartValue() : null);
}
set startAt(value: D | null) {
this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _startAt: D | null;
/** The view that the calendar should start in. */
@Input() startView: 'month' | 'year' | 'multi-year' = 'month';
/**
* Theme color of the datepicker's calendar. 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(): ThemePalette {
return (
this._color || (this.datepickerInput ? this.datepickerInput.getThemePalette() : undefined)
);
}
set color(value: ThemePalette) {
this._color = value;
}
_color: ThemePalette;
/**
* Whether the calendar UI is in touch mode. In touch mode the calendar opens in a dialog rather
* than a dropdown and elements have more padding to allow for bigger touch targets.
*/
@Input({transform: booleanAttribute})
touchUi: boolean = false;
/** Whether the datepicker pop-up should be disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled === undefined && this.datepickerInput
? this.datepickerInput.disabled
: !!this._disabled;
}
set disabled(value: boolean) {
if (value !== this._disabled) {
this._disabled = value;
this.stateChanges.next(undefined);
}
}
private _disabled: boolean;
/** Preferred position of the datepicker in the X axis. */
@Input()
xPosition: DatepickerDropdownPositionX = 'start';
/** Preferred position of the datepicker in the Y axis. */
@Input()
yPosition: DatepickerDropdownPositionY = 'below';
/**
* Whether to restore focus to the previously-focused element when the calendar is closed.
* Note that automatic focus restoration is an accessibility feature and it is recommended that
* you provide your own equivalent, if you decide to turn it off.
*/
@Input({transform: booleanAttribute})
restoreFocus: boolean = true;
/**
* Emits selected year in multiyear view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits selected month in year view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits when the current view changes.
*/
@Output() readonly viewChanged: EventEmitter<MatCalendarView> = new EventEmitter<MatCalendarView>(
true,
);
/** Function that can be used to add custom CSS classes to dates. */
@Input() dateClass: MatCalendarCellClassFunction<D>;
/** Emits when the datepicker has been opened. */
@Output('opened') readonly openedStream = new EventEmitter<void>();
/** Emits when the datepicker has been closed. */
@Output('closed') readonly closedStream = new EventEmitter<void>();
/** Classes to be passed to the date picker panel. */
@Input()
get panelClass(): string | string[] {
return this._panelClass;
}
set panelClass(value: string | string[]) {
this._panelClass = coerceStringArray(value);
}
private _panelClass: string[];
/** Whether the calendar is open. */
@Input({transform: booleanAttribute})
get opened(): boolean {
return this._opened;
}
set opened(value: boolean) {
if (value) {
this.open();
} else {
this.close();
}
}
private _opened = false;
/** The id for the datepicker calendar. */
id: string = `mat-datepicker-${datepickerUid++}`;
/** The minimum selectable date. */
_getMinDate(): D | null {
return this.datepickerInput && this.datepickerInput.min;
}
/** The maximum selectable date. */
_getMaxDate(): D | null {
return this.datepickerInput && this.datepickerInput.max;
}
_getDateFilter(): DateFilterFn<D> {
return this.datepickerInput && this.datepickerInput.dateFilter;
}
/** A reference to the overlay into which we've rendered the calendar. */
private _overlayRef: OverlayRef | null;
/** Reference to the component instance rendered in the overlay. */
private _componentRef: ComponentRef<MatDatepickerContent<S, D>> | null;
/** The element that was focused before the datepicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
/** Unique class that will be added to the backdrop so that the test harnesses can look it up. */
private _backdropHarnessClass = `${this.id}-backdrop`;
/** Currently-registered actions portal. */
private _actionsPortal: TemplatePortal | null;
/** The input element this datepicker is associated with. */
datepickerInput: C;
/** Emits when the datepicker's state changes. */
readonly stateChanges = new Subject<void>();
private _injector = inject(Injector);
private readonly _changeDetectorRef = inject(ChangeDetectorRef);
constructor(...args: unknown[]);
constructor() {
if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw createMissingDateImplError('DateAdapter');
}
this._model.selectionChanged.subscribe(() => {
this._changeDetectorRef.markForCheck();
});
}
ngOnChanges(changes: SimpleChanges) {
const positionChange = changes['xPosition'] || changes['yPosition'];
if (positionChange && !positionChange.firstChange && this._overlayRef) {
const positionStrategy = this._overlayRef.getConfig().positionStrategy;
if (positionStrategy instanceof FlexibleConnectedPositionStrategy) {
this._setConnectedPositions(positionStrategy);
if (this.opened) {
this._overlayRef.updatePosition();
}
}
}
this.stateChanges.next(undefined);
}
ngOnDestroy() {
this._destroyOverlay();
this.close();
this._inputStateChanges.unsubscribe();
this.stateChanges.complete();
}
/** Selects the given date */
select(date: D): void {
this._model.add(date);
}
/** Emits the selected year in multiyear view */
_selectYear(normalizedYear: D): void {
this.yearSelected.emit(normalizedYear);
}
/** Emits selected month in year view */
_selectMonth(normalizedMonth: D): void {
this.monthSelected.emit(normalizedMonth);
}
/** Emits changed view */
_viewChanged(view: MatCalendarView): void {
this.viewChanged.emit(view);
}
/**
* Register an input with this datepicker.
* @param input The datepicker input to register with this datepicker.
* @returns Selection model that the input should hook itself up to.
*/
registerInput(input: C): MatDateSelectionModel<S, D> {
if (this.datepickerInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('A MatDatepicker can only be associated with a single input.');
}
this._inputStateChanges.unsubscribe();
this.datepickerInput = input;
this._inputStateChanges = input.stateChanges.subscribe(() => this.stateChanges.next(undefined));
return this._model;
}
/**
* Registers a portal containing action buttons with the datepicker.
* @param portal Portal to be registered.
*/ | {
"end_byte": 20228,
"start_byte": 11839,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-base.ts"
} |
components/src/material/datepicker/datepicker-base.ts_20231_28910 | registerActions(portal: TemplatePortal): void {
if (this._actionsPortal && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('A MatDatepicker can only be associated with a single actions row.');
}
this._actionsPortal = portal;
this._componentRef?.instance._assignActions(portal, true);
}
/**
* Removes a portal containing action buttons from the datepicker.
* @param portal Portal to be removed.
*/
removeActions(portal: TemplatePortal): void {
if (portal === this._actionsPortal) {
this._actionsPortal = null;
this._componentRef?.instance._assignActions(null, true);
}
}
/** Open the calendar. */
open(): void {
// Skip reopening if there's an in-progress animation to avoid overlapping
// sequences which can cause "changed after checked" errors. See #25837.
if (this._opened || this.disabled || this._componentRef?.instance._isAnimating) {
return;
}
if (!this.datepickerInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Attempted to open an MatDatepicker with no associated input.');
}
this._focusedElementBeforeOpen = _getFocusedElementPierceShadowDom();
this._openOverlay();
this._opened = true;
this.openedStream.emit();
}
/** Close the calendar. */
close(): void {
// Skip reopening if there's an in-progress animation to avoid overlapping
// sequences which can cause "changed after checked" errors. See #25837.
if (!this._opened || this._componentRef?.instance._isAnimating) {
return;
}
const canRestoreFocus =
this.restoreFocus &&
this._focusedElementBeforeOpen &&
typeof this._focusedElementBeforeOpen.focus === 'function';
const completeClose = () => {
// The `_opened` could've been reset already if
// we got two events in quick succession.
if (this._opened) {
this._opened = false;
this.closedStream.emit();
}
};
if (this._componentRef) {
const {instance, location} = this._componentRef;
instance._startExitAnimation();
instance._animationDone.pipe(take(1)).subscribe(() => {
const activeElement = this._document.activeElement;
// Since we restore focus after the exit animation, we have to check that
// the user didn't move focus themselves inside the `close` handler.
if (
canRestoreFocus &&
(!activeElement ||
activeElement === this._document.activeElement ||
location.nativeElement.contains(activeElement))
) {
this._focusedElementBeforeOpen!.focus();
}
this._focusedElementBeforeOpen = null;
this._destroyOverlay();
});
}
if (canRestoreFocus) {
// Because IE moves focus asynchronously, we can't count on it being restored before we've
// marked the datepicker as closed. If the event fires out of sequence and the element that
// we're refocusing opens the datepicker on focus, the user could be stuck with not being
// able to close the calendar at all. We work around it by making the logic, that marks
// the datepicker as closed, async as well.
setTimeout(completeClose);
} else {
completeClose();
}
}
/** Applies the current pending selection on the overlay to the model. */
_applyPendingSelection() {
this._componentRef?.instance?._applyPendingSelection();
}
/** Forwards relevant values from the datepicker to the datepicker content inside the overlay. */
protected _forwardContentValues(instance: MatDatepickerContent<S, D>) {
instance.datepicker = this;
instance.color = this.color;
instance._dialogLabelId = this.datepickerInput.getOverlayLabelId();
instance._assignActions(this._actionsPortal, false);
}
/** Opens the overlay with the calendar. */
private _openOverlay(): void {
this._destroyOverlay();
const isDialog = this.touchUi;
const portal = new ComponentPortal<MatDatepickerContent<S, D>>(
MatDatepickerContent,
this._viewContainerRef,
);
const overlayRef = (this._overlayRef = this._overlay.create(
new OverlayConfig({
positionStrategy: isDialog ? this._getDialogStrategy() : this._getDropdownStrategy(),
hasBackdrop: true,
backdropClass: [
isDialog ? 'cdk-overlay-dark-backdrop' : 'mat-overlay-transparent-backdrop',
this._backdropHarnessClass,
],
direction: this._dir || 'ltr',
scrollStrategy: isDialog ? this._overlay.scrollStrategies.block() : this._scrollStrategy(),
panelClass: `mat-datepicker-${isDialog ? 'dialog' : 'popup'}`,
}),
));
this._getCloseStream(overlayRef).subscribe(event => {
if (event) {
event.preventDefault();
}
this.close();
});
// The `preventDefault` call happens inside the calendar as well, however focus moves into
// it inside a timeout which can give browsers a chance to fire off a keyboard event in-between
// that can scroll the page (see #24969). Always block default actions of arrow keys for the
// entire overlay so the page doesn't get scrolled by accident.
overlayRef.keydownEvents().subscribe(event => {
const keyCode = event.keyCode;
if (
keyCode === UP_ARROW ||
keyCode === DOWN_ARROW ||
keyCode === LEFT_ARROW ||
keyCode === RIGHT_ARROW ||
keyCode === PAGE_UP ||
keyCode === PAGE_DOWN
) {
event.preventDefault();
}
});
this._componentRef = overlayRef.attach(portal);
this._forwardContentValues(this._componentRef.instance);
// Update the position once the calendar has rendered. Only relevant in dropdown mode.
if (!isDialog) {
afterNextRender(
() => {
overlayRef.updatePosition();
},
{injector: this._injector},
);
}
}
/** Destroys the current overlay. */
private _destroyOverlay() {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = this._componentRef = null;
}
}
/** Gets a position strategy that will open the calendar as a dropdown. */
private _getDialogStrategy() {
return this._overlay.position().global().centerHorizontally().centerVertically();
}
/** Gets a position strategy that will open the calendar as a dropdown. */
private _getDropdownStrategy() {
const strategy = this._overlay
.position()
.flexibleConnectedTo(this.datepickerInput.getConnectedOverlayOrigin())
.withTransformOriginOn('.mat-datepicker-content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition();
return this._setConnectedPositions(strategy);
}
/** Sets the positions of the datepicker in dropdown mode based on the current configuration. */
private _setConnectedPositions(strategy: FlexibleConnectedPositionStrategy) {
const primaryX = this.xPosition === 'end' ? 'end' : 'start';
const secondaryX = primaryX === 'start' ? 'end' : 'start';
const primaryY = this.yPosition === 'above' ? 'bottom' : 'top';
const secondaryY = primaryY === 'top' ? 'bottom' : 'top';
return strategy.withPositions([
{
originX: primaryX,
originY: secondaryY,
overlayX: primaryX,
overlayY: primaryY,
},
{
originX: primaryX,
originY: primaryY,
overlayX: primaryX,
overlayY: secondaryY,
},
{
originX: secondaryX,
originY: secondaryY,
overlayX: secondaryX,
overlayY: primaryY,
},
{
originX: secondaryX,
originY: primaryY,
overlayX: secondaryX,
overlayY: secondaryY,
},
]);
}
/** Gets an observable that will emit when the overlay is supposed to be closed. */
private _getCloseStream(overlayRef: OverlayRef) {
const ctrlShiftMetaModifiers: ModifierKey[] = ['ctrlKey', 'shiftKey', 'metaKey'];
return merge(
overlayRef.backdropClick(),
overlayRef.detachments(),
overlayRef.keydownEvents().pipe(
filter(event => {
// Closing on alt + up is only valid when there's an input associated with the datepicker.
return (
(event.keyCode === ESCAPE && !hasModifierKey(event)) ||
(this.datepickerInput &&
hasModifierKey(event, 'altKey') &&
event.keyCode === UP_ARROW &&
ctrlShiftMetaModifiers.every(
(modifier: ModifierKey) => !hasModifierKey(event, modifier),
))
);
}),
),
);
}
} | {
"end_byte": 28910,
"start_byte": 20231,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-base.ts"
} |
components/src/material/datepicker/datepicker-actions.ts_0_2723 | /**
* @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 {
AfterViewInit,
ChangeDetectionStrategy,
Component,
Directive,
OnDestroy,
TemplateRef,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
inject,
} from '@angular/core';
import {TemplatePortal} from '@angular/cdk/portal';
import {MatDatepickerBase, MatDatepickerControl} from './datepicker-base';
/** Button that will close the datepicker and assign the current selection to the data model. */
@Directive({
selector: '[matDatepickerApply], [matDateRangePickerApply]',
host: {'(click)': '_applySelection()'},
})
export class MatDatepickerApply {
private _datepicker =
inject<MatDatepickerBase<MatDatepickerControl<any>, unknown>>(MatDatepickerBase);
constructor(...args: unknown[]);
constructor() {}
_applySelection() {
this._datepicker._applyPendingSelection();
this._datepicker.close();
}
}
/** Button that will close the datepicker and discard the current selection. */
@Directive({
selector: '[matDatepickerCancel], [matDateRangePickerCancel]',
host: {'(click)': '_datepicker.close()'},
})
export class MatDatepickerCancel {
_datepicker = inject<MatDatepickerBase<MatDatepickerControl<any>, unknown>>(MatDatepickerBase);
constructor(...args: unknown[]);
constructor() {}
}
/**
* Container that can be used to project a row of action buttons
* to the bottom of a datepicker or date range picker.
*/
@Component({
selector: 'mat-datepicker-actions, mat-date-range-picker-actions',
styleUrl: 'datepicker-actions.css',
template: `
<ng-template>
<div class="mat-datepicker-actions">
<ng-content></ng-content>
</div>
</ng-template>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatDatepickerActions implements AfterViewInit, OnDestroy {
private _datepicker =
inject<MatDatepickerBase<MatDatepickerControl<any>, unknown>>(MatDatepickerBase);
private _viewContainerRef = inject(ViewContainerRef);
@ViewChild(TemplateRef) _template: TemplateRef<unknown>;
private _portal: TemplatePortal;
constructor(...args: unknown[]);
constructor() {}
ngAfterViewInit() {
this._portal = new TemplatePortal(this._template, this._viewContainerRef);
this._datepicker.registerActions(this._portal);
}
ngOnDestroy() {
this._datepicker.removeActions(this._portal);
// Needs to be null checked since we initialize it in `ngAfterViewInit`.
if (this._portal && this._portal.isAttached) {
this._portal?.detach();
}
}
}
| {
"end_byte": 2723,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-actions.ts"
} |
components/src/material/datepicker/calendar-header.html_0_1464 | <div class="mat-calendar-header">
<div class="mat-calendar-controls">
<!-- [Firefox Issue: https://bugzilla.mozilla.org/show_bug.cgi?id=1880533]
Relocated label next to related button and made visually hidden via cdk-visually-hidden
to enable label to appear in a11y tree for SR when using Firefox -->
<span [id]="_periodButtonLabelId" class="cdk-visually-hidden" aria-live="polite">{{periodButtonDescription}}</span>
<button mat-button type="button" class="mat-calendar-period-button"
(click)="currentPeriodClicked()" [attr.aria-label]="periodButtonLabel"
[attr.aria-describedby]="_periodButtonLabelId">
<span aria-hidden="true">{{periodButtonText}}</span>
<svg class="mat-calendar-arrow" [class.mat-calendar-invert]="calendar.currentView !== 'month'"
viewBox="0 0 10 5" focusable="false" aria-hidden="true">
<polygon points="0,0 5,5 10,0"/>
</svg>
</button>
<div class="mat-calendar-spacer"></div>
<ng-content></ng-content>
<button mat-icon-button type="button" class="mat-calendar-previous-button"
[disabled]="!previousEnabled()" (click)="previousClicked()"
[attr.aria-label]="prevButtonLabel">
</button>
<button mat-icon-button type="button" class="mat-calendar-next-button"
[disabled]="!nextEnabled()" (click)="nextClicked()"
[attr.aria-label]="nextButtonLabel">
</button>
</div>
</div>
| {
"end_byte": 1464,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/calendar-header.html"
} |
components/src/material/datepicker/datepicker-actions.scss_0_314 | .mat-datepicker-actions {
$spacing: 8px;
display: flex;
justify-content: flex-end;
align-items: center;
padding: 0 $spacing $spacing $spacing;
.mat-mdc-button-base + .mat-mdc-button-base {
margin-left: $spacing;
[dir='rtl'] & {
margin-left: 0;
margin-right: $spacing;
}
}
}
| {
"end_byte": 314,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-actions.scss"
} |
components/src/material/datepicker/aria-accessible-name.ts_0_7056 | /**
* @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
*/
// This file contains the `_computeAriaAccessibleName` function, which computes what the *expected*
// ARIA accessible name would be for a given element. Implements a subset of ARIA specification
// [Accessible Name and Description Computation 1.2](https://www.w3.org/TR/accname-1.2/).
//
// Specification accname-1.2 can be summarized by returning the result of the first method
// available.
//
// 1. `aria-labelledby` attribute
// ```
// <!-- example using aria-labelledby-->
// <label id='label-id'>Start Date</label>
// <input aria-labelledby='label-id'/>
// ```
// 2. `aria-label` attribute (e.g. `<input aria-label="Departure"/>`)
// 3. Label with `for`/`id`
// ```
// <!-- example using for/id -->
// <label for="current-node">Label</label>
// <input id="current-node"/>
// ```
// 4. `placeholder` attribute (e.g. `<input placeholder="06/03/1990"/>`)
// 5. `title` attribute (e.g. `<input title="Check-In"/>`)
// 6. text content
// ```
// <!-- example using text content -->
// <label for="current-node"><span>Departure</span> Date</label>
// <input id="current-node"/>
// ```
/**
* Computes the *expected* ARIA accessible name for argument element based on [accname-1.2
* specification](https://www.w3.org/TR/accname-1.2/). Implements a subset of accname-1.2,
* and should only be used for the Datepicker's specific use case.
*
* Intended use:
* This is not a general use implementation. Only implements the parts of accname-1.2 that are
* required for the Datepicker's specific use case. This function is not intended for any other
* use.
*
* Limitations:
* - Only covers the needs of `matStartDate` and `matEndDate`. Does not support other use cases.
* - See NOTES's in implementation for specific details on what parts of the accname-1.2
* specification are not implemented.
*
* @param element {HTMLInputElement} native <input/> element of `matStartDate` or
* `matEndDate` component. Corresponds to the 'Root Element' from accname-1.2
*
* @return expected ARIA accessible name of argument <input/>
*/
export function _computeAriaAccessibleName(
element: HTMLInputElement | HTMLTextAreaElement,
): string {
return _computeAriaAccessibleNameInternal(element, true);
}
/**
* Determine if argument node is an Element based on `nodeType` property. This function is safe to
* use with server-side rendering.
*/
function ssrSafeIsElement(node: Node): node is Element {
return node.nodeType === Node.ELEMENT_NODE;
}
/**
* Determine if argument node is an HTMLInputElement based on `nodeName` property. This funciton is
* safe to use with server-side rendering.
*/
function ssrSafeIsHTMLInputElement(node: Node): node is HTMLInputElement {
return node.nodeName === 'INPUT';
}
/**
* Determine if argument node is an HTMLTextAreaElement based on `nodeName` property. This
* funciton is safe to use with server-side rendering.
*/
function ssrSafeIsHTMLTextAreaElement(node: Node): node is HTMLTextAreaElement {
return node.nodeName === 'TEXTAREA';
}
/**
* Calculate the expected ARIA accessible name for given DOM Node. Given DOM Node may be either the
* "Root node" passed to `_computeAriaAccessibleName` or "Current node" as result of recursion.
*
* @return the accessible name of argument DOM Node
*
* @param currentNode node to determine accessible name of
* @param isDirectlyReferenced true if `currentNode` is the root node to calculate ARIA accessible
* name of. False if it is a result of recursion.
*/
function _computeAriaAccessibleNameInternal(
currentNode: Node,
isDirectlyReferenced: boolean,
): string {
// NOTE: this differs from accname-1.2 specification.
// - Does not implement Step 1. of accname-1.2: '''If `currentNode`'s role prohibits naming,
// return the empty string ("")'''.
// - Does not implement Step 2.A. of accname-1.2: '''if current node is hidden and not directly
// referenced by aria-labelledby... return the empty string.'''
// acc-name-1.2 Step 2.B.: aria-labelledby
if (ssrSafeIsElement(currentNode) && isDirectlyReferenced) {
const labelledbyIds: string[] =
currentNode.getAttribute?.('aria-labelledby')?.split(/\s+/g) || [];
const validIdRefs: HTMLElement[] = labelledbyIds.reduce((validIds, id) => {
const elem = document.getElementById(id);
if (elem) {
validIds.push(elem);
}
return validIds;
}, [] as HTMLElement[]);
if (validIdRefs.length) {
return validIdRefs
.map(idRef => {
return _computeAriaAccessibleNameInternal(idRef, false);
})
.join(' ');
}
}
// acc-name-1.2 Step 2.C.: aria-label
if (ssrSafeIsElement(currentNode)) {
const ariaLabel = currentNode.getAttribute('aria-label')?.trim();
if (ariaLabel) {
return ariaLabel;
}
}
// acc-name-1.2 Step 2.D. attribute or element that defines a text alternative
//
// NOTE: this differs from accname-1.2 specification.
// Only implements Step 2.D. for `<label>`,`<input/>`, and `<textarea/>` element. Does not
// implement other elements that have an attribute or element that defines a text alternative.
if (ssrSafeIsHTMLInputElement(currentNode) || ssrSafeIsHTMLTextAreaElement(currentNode)) {
// use label with a `for` attribute referencing the current node
if (currentNode.labels?.length) {
return Array.from(currentNode.labels)
.map(x => _computeAriaAccessibleNameInternal(x, false))
.join(' ');
}
// use placeholder if available
const placeholder = currentNode.getAttribute('placeholder')?.trim();
if (placeholder) {
return placeholder;
}
// use title if available
const title = currentNode.getAttribute('title')?.trim();
if (title) {
return title;
}
}
// NOTE: this differs from accname-1.2 specification.
// - does not implement acc-name-1.2 Step 2.E.: '''if the current node is a control embedded
// within the label... then include the embedded control as part of the text alternative in
// the following manner...'''. Step 2E applies to embedded controls such as textbox, listbox,
// range, etc.
// - does not implement acc-name-1.2 step 2.F.: check that '''role allows name from content''',
// which applies to `currentNode` and its children.
// - does not implement acc-name-1.2 Step 2.F.ii.: '''Check for CSS generated textual content'''
// (e.g. :before and :after).
// - does not implement acc-name-1.2 Step 2.I.: '''if the current node has a Tooltip attribute,
// return its value'''
// Return text content with whitespace collapsed into a single space character. Accomplish
// acc-name-1.2 steps 2F, 2G, and 2H.
return (currentNode.textContent || '').replace(/\s+/g, ' ').trim();
}
| {
"end_byte": 7056,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/aria-accessible-name.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_0_2375 | import {Directionality} from '@angular/cdk/bidi';
import {
DOWN_ARROW,
ENTER,
ESCAPE,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {Overlay} from '@angular/cdk/overlay';
import {_supportsShadowDom} from '@angular/cdk/platform';
import {ScrollDispatcher} from '@angular/cdk/scrolling';
import {
createKeyboardEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
dispatchMouseEvent,
typeInElement,
} from '@angular/cdk/testing/private';
import {Component, Directive, Provider, Type, ViewChild, ViewEncapsulation} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, inject, tick} from '@angular/core/testing';
import {
FormControl,
FormsModule,
NG_VALIDATORS,
NgModel,
ReactiveFormsModule,
Validator,
} from '@angular/forms';
import {MAT_DATE_LOCALE, MatNativeDateModule, NativeDateModule} from '@angular/material/core';
import {MatFormField, MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {DEC, JAN, JUL, JUN, SEP} from '../testing';
import {MatDatepicker} from './datepicker';
import {DatepickerDropdownPositionX, DatepickerDropdownPositionY} from './datepicker-base';
import {MatDatepickerInput} from './datepicker-input';
import {MatDatepickerToggle} from './datepicker-toggle';
import {
MAT_DATEPICKER_SCROLL_STRATEGY,
MatDateSelectionModel,
MatDatepickerIntl,
MatDatepickerModule,
} from './index';
describe('MatDatepicker', () => {
const SUPPORTS_INTL = typeof Intl != 'undefined';
// Creates a test component fixture.
function createComponent<T>(
component: Type<T>,
imports: Type<any>[] = [],
providers: Provider[] = [],
declarations: Type<any>[] = [],
): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [
FormsModule,
MatDatepickerModule,
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
...imports,
],
providers,
declarations: [component, ...declarations],
});
return TestBed.createComponent(component);
}
describe('with MatNativeDateModule', | {
"end_byte": 2375,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_2376_13248 | () => {
describe('standard datepicker', () => {
let fixture: ComponentFixture<StandardDatepicker>;
let testComponent: StandardDatepicker;
let model: MatDateSelectionModel<Date | null, Date>;
beforeEach(fakeAsync(() => {
fixture = createComponent(StandardDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get(MatDateSelectionModel);
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should initialize with correct value shown in input', () => {
if (SUPPORTS_INTL) {
expect(fixture.nativeElement.querySelector('input').value).toBe('1/1/2020');
}
});
it('open non-touch should open popup', fakeAsync(() => {
expect(document.querySelector('.cdk-overlay-pane.mat-datepicker-popup')).toBeNull();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.cdk-overlay-pane.mat-datepicker-popup')).not.toBeNull();
}));
it('touch should open dialog', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
}));
it('should not be able to open more than one dialog', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(document.querySelectorAll('.mat-datepicker-dialog').length).toBe(0);
testComponent.datepicker.open();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
dispatchKeyboardEvent(document.querySelector('.mat-calendar-body')!, 'keydown', ENTER);
fixture.detectChanges();
tick(100);
testComponent.datepicker.open();
tick(500);
fixture.detectChanges();
flush();
expect(document.querySelectorAll('.mat-datepicker-dialog').length).toBe(1);
}));
it('should open datepicker if opened input is set to true', fakeAsync(() => {
testComponent.opened = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.mat-datepicker-content')).not.toBeNull();
testComponent.opened = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(document.querySelector('.mat-datepicker-content')).toBeNull();
}));
it('open in disabled mode should not open the calendar', fakeAsync(() => {
testComponent.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(document.querySelector('.cdk-overlay-pane')).toBeNull();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
testComponent.datepicker.open();
tick();
fixture.detectChanges();
flush();
expect(document.querySelector('.cdk-overlay-pane')).toBeNull();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
}));
it('disabled datepicker input should open the calendar if datepicker is enabled', fakeAsync(() => {
testComponent.datepicker.disabled = false;
testComponent.datepickerInput.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(document.querySelector('.cdk-overlay-pane')).toBeNull();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.cdk-overlay-pane')).not.toBeNull();
}));
it('close should close popup', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const popup = document.querySelector('.cdk-overlay-pane')!;
expect(popup).not.toBeNull();
expect(popup.getBoundingClientRect().height).toBeGreaterThan(0);
testComponent.datepicker.close();
fixture.detectChanges();
flush();
expect(popup.getBoundingClientRect().height).toBe(0);
}));
it('should close the popup when pressing ESCAPE', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to be open.')
.toBe(true);
const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
fixture.detectChanges();
flush();
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to be closed.')
.toBe(false);
expect(event.defaultPrevented).toBe(true);
}));
it('should not close the popup when pressing ESCAPE with a modifier key', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to be open.')
.toBe(true);
const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE, undefined, {
alt: true,
});
fixture.detectChanges();
flush();
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to stay open.')
.toBe(true);
expect(event.defaultPrevented).toBe(false);
}));
it('should set the proper role on the popup', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const popup = document.querySelector('.mat-datepicker-content-container')!;
expect(popup).toBeTruthy();
expect(popup.getAttribute('role')).toBe('dialog');
}));
it(
'should set aria-labelledby to the one from the input, if not placed inside ' +
'a mat-form-field',
fakeAsync(() => {
expect(fixture.nativeElement.querySelector('mat-form-field')).toBeFalsy();
const input: HTMLInputElement = fixture.nativeElement.querySelector('input');
input.setAttribute('aria-labelledby', 'test-label');
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const popup = document.querySelector(
'.cdk-overlay-pane .mat-datepicker-content-container',
)!;
expect(popup).toBeTruthy();
expect(popup.getAttribute('aria-labelledby')).toBe('test-label');
}),
);
it('close should close dialog', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
testComponent.datepicker.close();
fixture.detectChanges();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
}));
it('setting selected via click should update input and close calendar', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 1));
let cells = document.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cells[1], 'click');
fixture.detectChanges();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 2));
}));
it('setting selected via enter press should update input and close calendar', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 1));
let calendarBodyEl = document.querySelector('.mat-calendar-body') as HTMLElement;
dispatchKeyboardEvent(calendarBodyEl, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
tick();
flush();
dispatchKeyboardEvent(calendarBodyEl, 'keydown', ENTER);
fixture.detectChanges();
dispatchKeyboardEvent(calendarBodyEl, 'keyup', ENTER);
fixture.detectChanges();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 2));
}));
it(
'clicking the currently selected date should close the calendar ' +
'without firing selectedChanged',
fakeAsync(() => {
const spy = jasmine.createSpy('selectionChanged spy');
const selectedSubscription = model.selectionChanged.subscribe(spy);
for (let changeCount = 1; changeCount < 3; changeCount++) {
const currentDay = changeCount;
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(document.querySelector('mat-datepicker-content')).not.toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, currentDay));
let cells = document.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cells[1], 'click');
fixture.detectChanges();
flush();
}
expect(spy).toHaveBeenCalledTimes(1);
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 2));
selectedSubscription.unsubscribe();
}),
); | {
"end_byte": 13248,
"start_byte": 2376,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_13256_23682 | it(
'pressing enter on the currently selected date should close the calendar without ' +
'firing selectedChanged',
fakeAsync(() => {
const spy = jasmine.createSpy('selectionChanged spy');
const selectedSubscription = model.selectionChanged.subscribe(spy);
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
let calendarBodyEl = document.querySelector('.mat-calendar-body') as HTMLElement;
expect(calendarBodyEl).not.toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 1));
dispatchKeyboardEvent(calendarBodyEl, 'keydown', ENTER);
fixture.detectChanges();
flush();
fixture.whenStable().then(() => {
expect(spy).not.toHaveBeenCalled();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
expect(testComponent.datepickerInput.value).toEqual(new Date(2020, JAN, 1));
selectedSubscription.unsubscribe();
});
}),
);
it('startAt should fallback to input value', () => {
expect(testComponent.datepicker.startAt).toEqual(new Date(2020, JAN, 1));
});
it('should attach popup to native input', () => {
let attachToRef = testComponent.datepickerInput.getConnectedOverlayOrigin();
expect(attachToRef.nativeElement.tagName.toLowerCase())
.withContext('popup should be attached to native input')
.toBe('input');
});
it('input should aria-owns calendar after opened in non-touch mode', fakeAsync(() => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.getAttribute('aria-owns')).toBeNull();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
let ownedElementId = inputEl.getAttribute('aria-owns');
expect(ownedElementId).not.toBeNull();
let ownedElement = document.getElementById(ownedElementId);
expect(ownedElement).not.toBeNull();
expect((ownedElement as Element).tagName.toLowerCase()).toBe('mat-calendar');
}));
it('input should aria-owns calendar after opened in touch mode', fakeAsync(() => {
testComponent.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.getAttribute('aria-owns')).toBeNull();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
let ownedElementId = inputEl.getAttribute('aria-owns');
expect(ownedElementId).not.toBeNull();
let ownedElement = document.getElementById(ownedElementId);
expect(ownedElement).not.toBeNull();
expect((ownedElement as Element).tagName.toLowerCase()).toBe('mat-calendar');
}));
it('should not throw when given wrong data type', () => {
testComponent.date = '1/1/2017' as any;
fixture.changeDetectorRef.markForCheck();
expect(() => fixture.detectChanges()).not.toThrow();
});
it('should clear out the backdrop subscriptions on close', fakeAsync(() => {
for (let i = 0; i < 3; i++) {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
testComponent.datepicker.close();
fixture.detectChanges();
tick();
}
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const spy = jasmine.createSpy('close event spy');
const subscription = testComponent.datepicker.closedStream.subscribe(spy);
const backdrop = document.querySelector('.cdk-overlay-backdrop')! as HTMLElement;
backdrop.click();
fixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledTimes(1);
expect(testComponent.datepicker.opened).toBe(false);
subscription.unsubscribe();
}));
it('should reset the datepicker when it is closed externally', fakeAsync(() => {
TestBed.resetTestingModule();
const scrolledSubject = new Subject();
// Stub out a `CloseScrollStrategy` so we can trigger a detachment via the `OverlayRef`.
fixture = createComponent(
StandardDatepicker,
[MatNativeDateModule],
[
{
provide: ScrollDispatcher,
useValue: {scrolled: () => scrolledSubject},
},
{
provide: MAT_DATEPICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close(),
},
],
);
fixture.detectChanges();
testComponent = fixture.componentInstance;
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(testComponent.datepicker.opened).toBe(true);
scrolledSubject.next();
flush();
fixture.detectChanges();
expect(testComponent.datepicker.opened).toBe(false);
}));
it('should close the datepicker using ALT + UP_ARROW', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(testComponent.datepicker.opened).toBe(true);
const event = createKeyboardEvent('keydown', UP_ARROW, undefined, {alt: true});
dispatchEvent(document.body, event);
fixture.detectChanges();
flush();
expect(testComponent.datepicker.opened).toBe(false);
}));
it('should not close the datepicker when using CTRL + SHIFT + ALT + UP_ARROW', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(testComponent.datepicker.opened).toBe(true);
const event = createKeyboardEvent('keydown', UP_ARROW, undefined, {
alt: true,
shift: true,
control: true,
});
dispatchEvent(document.body, event);
fixture.detectChanges();
flush();
expect(testComponent.datepicker.opened).toBe(true);
}));
it('should open the datepicker using ALT + DOWN_ARROW', fakeAsync(() => {
expect(testComponent.datepicker.opened).toBe(false);
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {alt: true});
dispatchEvent(fixture.nativeElement.querySelector('input'), event);
fixture.detectChanges();
tick();
flush();
expect(testComponent.datepicker.opened).toBe(true);
expect(event.defaultPrevented).toBe(true);
}));
it('should not open for ALT + DOWN_ARROW on readonly input', fakeAsync(() => {
const input = fixture.nativeElement.querySelector('input');
expect(testComponent.datepicker.opened).toBe(false);
input.setAttribute('readonly', 'true');
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {alt: true});
dispatchEvent(input, event);
fixture.detectChanges();
flush();
expect(testComponent.datepicker.opened).toBe(false);
expect(event.defaultPrevented).toBe(false);
}));
it('should not open the datepicker using SHIFT + CTRL + ALT + DOWN_ARROW', fakeAsync(() => {
expect(testComponent.datepicker.opened).toBe(false);
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {
alt: true,
shift: true,
control: true,
});
dispatchEvent(fixture.nativeElement.querySelector('input'), event);
fixture.detectChanges();
tick();
flush();
expect(testComponent.datepicker.opened).toBe(false);
expect(event.defaultPrevented).toBe(false);
}));
it('should show the invisible close button on focus', fakeAsync(() => {
testComponent.opened = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
flush();
const button = document.querySelector('.mat-datepicker-close-button') as HTMLButtonElement;
expect(button.classList).toContain('cdk-visually-hidden');
dispatchFakeEvent(button, 'focus');
fixture.detectChanges();
expect(button.classList).not.toContain('cdk-visually-hidden');
dispatchFakeEvent(button, 'blur');
fixture.detectChanges();
expect(button.classList).toContain('cdk-visually-hidden');
}));
it('should close the overlay when clicking on the invisible close button', fakeAsync(() => {
testComponent.opened = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
flush();
const button = document.querySelector('.mat-datepicker-close-button') as HTMLButtonElement;
expect(document.querySelector('.mat-datepicker-content')).not.toBeNull();
button.click();
fixture.detectChanges();
flush();
expect(document.querySelector('.mat-datepicker-content')).toBeNull();
}));
it('should prevent the default action of navigation keys before the focus timeout has elapsed', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
// Do the assertions before flushing the delays since we want
// to check specifically what happens before they have fired.
[UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, PAGE_UP, PAGE_DOWN].forEach(keyCode => {
const event = dispatchKeyboardEvent(document.body, 'keydown', keyCode);
fixture.detectChanges();
expect(event.defaultPrevented)
.withContext(`Expected default action to be prevented for key code ${keyCode}`)
.toBe(true);
});
tick();
flush();
}));
});
describe('datepicker with too many inputs', () => {
it('should throw when multiple inputs registered', fakeAsync(() => {
const fixture = createComponent(MultiInputDatepicker, [MatNativeDateModule]);
expect(() => fixture.detectChanges()).toThrow();
}));
}); | {
"end_byte": 23682,
"start_byte": 13256,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_23688_30333 | describe('datepicker that is assigned to input at a later point', () => {
it('should not throw on ALT + DOWN_ARROW for input without datepicker', fakeAsync(() => {
const fixture = createComponent(DelayedDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
expect(() => {
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {alt: true});
dispatchEvent(fixture.nativeElement.querySelector('input'), event);
fixture.detectChanges();
flush();
}).not.toThrow();
}));
it('should handle value changes when a datepicker is assigned after init', fakeAsync(() => {
const fixture = createComponent(DelayedDatepicker, [MatNativeDateModule]);
const testComponent: DelayedDatepicker = fixture.componentInstance;
const toSelect = new Date(2017, JAN, 1);
fixture.detectChanges();
const model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get(MatDateSelectionModel);
expect(testComponent.datepickerInput.value).toBeNull();
expect(model.selection).toBeNull();
testComponent.assignedDatepicker = testComponent.datepicker;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.assignedDatepicker.select(toSelect);
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(testComponent.datepickerInput.value).toEqual(toSelect);
expect(model.selection).toEqual(toSelect);
}));
});
describe('datepicker with no inputs', () => {
let fixture: ComponentFixture<NoInputDatepicker>;
let testComponent: NoInputDatepicker;
beforeEach(fakeAsync(() => {
fixture = createComponent(NoInputDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('should not throw when accessing disabled property', () => {
expect(() => testComponent.datepicker.disabled).not.toThrow();
});
it('should throw when opened with no registered inputs', fakeAsync(() => {
expect(() => testComponent.datepicker.open()).toThrow();
}));
});
describe('datepicker with startAt', () => {
let fixture: ComponentFixture<DatepickerWithStartAt>;
let testComponent: DatepickerWithStartAt;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithStartAt, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('explicit startAt should override input value', () => {
expect(testComponent.datepicker.startAt).toEqual(new Date(2010, JAN, 1));
});
});
describe('datepicker with startView set to year', () => {
let fixture: ComponentFixture<DatepickerWithStartViewYear>;
let testComponent: DatepickerWithStartViewYear;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithStartViewYear, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should start at the specified view', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const firstCalendarCell = document.querySelector('.mat-calendar-body-cell')!;
// When the calendar is in year view, the first cell should be for a month rather than
// for a date.
// When the calendar is in year view, the first cell should be for a month rather than
// for a date.
expect(firstCalendarCell.textContent!.trim())
.withContext('Expected the calendar to be in year-view')
.toBe('JAN');
}));
it('should fire yearSelected when user selects calendar year in year view', fakeAsync(() => {
spyOn(testComponent, 'onYearSelection');
expect(testComponent.onYearSelection).not.toHaveBeenCalled();
testComponent.datepicker.open();
tick();
fixture.detectChanges();
flush();
const cells = document.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cells[0], 'click');
fixture.detectChanges();
tick();
flush();
expect(testComponent.onYearSelection).toHaveBeenCalled();
}));
});
describe('datepicker with startView set to multiyear', () => {
let fixture: ComponentFixture<DatepickerWithStartViewMultiYear>;
let testComponent: DatepickerWithStartViewMultiYear;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithStartViewMultiYear, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
spyOn(testComponent, 'onMultiYearSelection');
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should start at the specified view', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const firstCalendarCell = document.querySelector('.mat-calendar-body-cell')!;
// When the calendar is in year view, the first cell should be for a month rather than
// for a date.
// When the calendar is in year view, the first cell should be for a month rather than
// for a date.
expect(firstCalendarCell.textContent!.trim())
.withContext('Expected the calendar to be in multi-year-view')
.toBe('2016');
}));
it('should fire yearSelected when user selects calendar year in multiyear view', fakeAsync(() => {
expect(testComponent.onMultiYearSelection).not.toHaveBeenCalled();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const cells = document.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cells[0], 'click');
fixture.detectChanges();
tick();
flush();
expect(testComponent.onMultiYearSelection).toHaveBeenCalled();
}));
}); | {
"end_byte": 30333,
"start_byte": 23688,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_30339_36510 | describe('datepicker with ngModel', () => {
let fixture: ComponentFixture<DatepickerWithNgModel>;
let testComponent: DatepickerWithNgModel;
let model: MatDateSelectionModel<Date | null, Date>;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithNgModel, [MatNativeDateModule]);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
testComponent = fixture.componentInstance;
model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get(MatDateSelectionModel);
});
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('should update datepicker when model changes', fakeAsync(() => {
expect(testComponent.datepickerInput.value).toBeNull();
expect(model.selection).toBeNull();
let selected = new Date(2017, JAN, 1);
testComponent.selected = selected;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(testComponent.datepickerInput.value).toEqual(selected);
expect(model.selection).toEqual(selected);
}));
it('should update model when date is selected', fakeAsync(() => {
expect(testComponent.selected).toBeNull();
expect(testComponent.datepickerInput.value).toBeNull();
let selected = new Date(2017, JAN, 1);
testComponent.datepicker.select(selected);
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(testComponent.selected).toEqual(selected);
expect(testComponent.datepickerInput.value).toEqual(selected);
}));
it('should mark input dirty after input event', () => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-pristine');
inputEl.value = '2001-01-01';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-dirty');
});
it('should mark input dirty after date selected', fakeAsync(() => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-pristine');
testComponent.datepicker.select(new Date(2017, JAN, 1));
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-dirty');
}));
it('should mark input dirty after invalid value is typed in', () => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-pristine');
inputEl.value = 'hello there';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-dirty');
});
it('should not mark dirty after model change', fakeAsync(() => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-pristine');
testComponent.selected = new Date(2017, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-pristine');
}));
it('should mark input touched on blur', () => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-untouched');
dispatchFakeEvent(inputEl, 'focus');
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-untouched');
dispatchFakeEvent(inputEl, 'blur');
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-touched');
});
it('should mark input as touched when the datepicker is closed', fakeAsync(() => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-untouched');
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
flush();
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-untouched');
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-touched');
}));
it('should reformat the input value on blur', () => {
if (SUPPORTS_INTL) {
// Skip this test if the internationalization API is not supported in the current
// browser. Browsers like Safari 9 do not support the "Intl" API.
return;
}
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
inputEl.value = '2001-01-01';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
dispatchFakeEvent(inputEl, 'blur');
fixture.detectChanges();
expect(inputEl.value).toBe('1/1/2001');
});
it('should not reformat invalid dates on blur', () => {
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
inputEl.value = 'very-valid-date';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
dispatchFakeEvent(inputEl, 'blur');
fixture.detectChanges();
expect(inputEl.value).toBe('very-valid-date');
});
it('should mark input touched on calendar selection', fakeAsync(() => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.classList).toContain('ng-untouched');
testComponent.datepicker.select(new Date(2017, JAN, 1));
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(inputEl.classList).toContain('ng-touched');
}));
}); | {
"end_byte": 36510,
"start_byte": 30339,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_36516_40604 | describe('datepicker with formControl', () => {
let fixture: ComponentFixture<DatepickerWithFormControl>;
let testComponent: DatepickerWithFormControl;
let model: MatDateSelectionModel<Date | null, Date>;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithFormControl, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get(MatDateSelectionModel);
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('should update datepicker when formControl changes', () => {
expect(testComponent.datepickerInput.value).toBeNull();
expect(model.selection).toBeNull();
let selected = new Date(2017, JAN, 1);
testComponent.formControl.setValue(selected);
fixture.detectChanges();
expect(testComponent.datepickerInput.value).toEqual(selected);
expect(model.selection).toEqual(selected);
});
it('should update formControl when date is selected', () => {
expect(testComponent.formControl.value).toBeNull();
expect(testComponent.datepickerInput.value).toBeNull();
let selected = new Date(2017, JAN, 1);
testComponent.datepicker.select(selected);
fixture.detectChanges();
expect(testComponent.formControl.value).toEqual(selected);
expect(testComponent.datepickerInput.value).toEqual(selected);
});
it('should disable input when form control disabled', () => {
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.disabled).toBe(false);
testComponent.formControl.disable();
fixture.detectChanges();
expect(inputEl.disabled).toBe(true);
});
it('should disable toggle when form control disabled', () => {
expect(testComponent.datepickerToggle.disabled).toBe(false);
testComponent.formControl.disable();
fixture.detectChanges();
expect(testComponent.datepickerToggle.disabled).toBe(true);
});
it(
'should not dispatch FormControl change event for invalid values on input when set ' +
'to update on blur',
fakeAsync(() => {
const formControl = new FormControl({value: null} as unknown as Date, {updateOn: 'blur'});
const spy = jasmine.createSpy('change spy');
const subscription = formControl.valueChanges.subscribe(spy);
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
const setValue = (value: string) => {
inputEl.value = value;
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
flush();
fixture.detectChanges();
};
fixture.componentInstance.formControl = formControl;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).not.toHaveBeenCalled();
setValue('10/10/2010');
expect(spy).not.toHaveBeenCalled();
setValue('10/10/');
expect(spy).not.toHaveBeenCalled();
setValue('10/10');
expect(spy).not.toHaveBeenCalled();
dispatchFakeEvent(inputEl, 'blur');
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
}),
);
it('should set the matDatepickerParse error when an invalid value is typed for the first time', () => {
const formControl = fixture.componentInstance.formControl;
expect(formControl.hasError('matDatepickerParse')).toBe(false);
typeInElement(fixture.nativeElement.querySelector('input'), 'Today');
fixture.detectChanges();
expect(formControl.hasError('matDatepickerParse')).toBe(true);
});
}); | {
"end_byte": 40604,
"start_byte": 36516,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_40610_50941 | describe('datepicker with mat-datepicker-toggle', () => {
let fixture: ComponentFixture<DatepickerWithToggle>;
let testComponent: DatepickerWithToggle;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithToggle, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should set `aria-haspopup` on the toggle button', () => {
const button = fixture.debugElement.query(By.css('button'))!;
expect(button).toBeTruthy();
expect(button.nativeElement.getAttribute('aria-haspopup')).toBe('dialog');
});
it('should set a default `aria-label` on the toggle button', () => {
const button = fixture.debugElement.query(By.css('button'))!;
expect(button).toBeTruthy();
expect(button.nativeElement.getAttribute('aria-label')).toBe('Open calendar');
});
it('should be able to change the button `aria-label`', () => {
fixture.componentInstance.ariaLabel = 'Toggle the datepicker';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'))!;
expect(button).toBeTruthy();
expect(button.nativeElement.getAttribute('aria-label')).toBe('Toggle the datepicker');
});
it('should open calendar when toggle clicked', () => {
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
let toggle = fixture.debugElement.query(By.css('button'))!;
dispatchMouseEvent(toggle.nativeElement, 'click');
fixture.detectChanges();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
});
it('should not open calendar when toggle clicked if datepicker is disabled', () => {
testComponent.datepicker.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
expect(toggle.hasAttribute('disabled')).toBe(true);
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
dispatchMouseEvent(toggle, 'click');
fixture.detectChanges();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
});
it('should not open calendar when toggle clicked if input is disabled', () => {
expect(testComponent.datepicker.disabled).toBe(false);
testComponent.input.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
expect(toggle.hasAttribute('disabled')).toBe(true);
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
dispatchMouseEvent(toggle, 'click');
fixture.detectChanges();
expect(document.querySelector('.mat-datepicker-dialog')).toBeNull();
});
it('should set the `button` type on the trigger to prevent form submissions', () => {
let toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
expect(toggle.getAttribute('type')).toBe('button');
});
it('should remove the underlying SVG icon from the tab order', () => {
const icon = fixture.debugElement.nativeElement.querySelector('svg');
expect(icon.getAttribute('focusable')).toBe('false');
});
it('should restore focus to the toggle after the calendar is closed', fakeAsync(() => {
let toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
fixture.componentInstance.touchUI = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
toggle.focus();
expect(document.activeElement).withContext('Expected toggle to be focused.').toBe(toggle);
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
let pane = document.querySelector('.cdk-overlay-pane')!;
expect(pane).withContext('Expected calendar to be open.').toBeTruthy();
expect(pane.contains(document.activeElement))
.withContext('Expected focus to be inside the calendar.')
.toBe(true);
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
expect(document.activeElement)
.withContext('Expected focus to be restored to toggle.')
.toBe(toggle);
}));
it('should restore focus when placed inside a shadow root', fakeAsync(() => {
if (!_supportsShadowDom()) {
return;
}
fixture.destroy();
TestBed.resetTestingModule();
fixture = createComponent(DatepickerWithToggleInShadowDom, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
const toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
fixture.componentInstance.touchUI = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
toggle.focus();
spyOn(toggle, 'focus').and.callThrough();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
// We have to assert by looking at the `focus` method, because
// `document.activeElement` will return the shadow root.
expect(toggle.focus).toHaveBeenCalled();
}));
it('should allow for focus restoration to be disabled', fakeAsync(() => {
let toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
fixture.componentInstance.touchUI = false;
fixture.componentInstance.restoreFocus = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
toggle.focus();
expect(document.activeElement).withContext('Expected toggle to be focused.').toBe(toggle);
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
let pane = document.querySelector('.cdk-overlay-pane')!;
expect(pane).withContext('Expected calendar to be open.').toBeTruthy();
expect(pane.contains(document.activeElement))
.withContext('Expected focus to be inside the calendar.')
.toBe(true);
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
expect(document.activeElement)
.not.withContext('Expected focus not to be restored to toggle.')
.toBe(toggle);
}));
it('should not override focus if it was moved inside the closed event in touchUI mode', fakeAsync(() => {
const focusTarget = document.createElement('button');
const datepicker = fixture.componentInstance.datepicker;
const subscription = datepicker.closedStream.subscribe(() => focusTarget.focus());
const input = fixture.nativeElement.querySelector('input');
focusTarget.setAttribute('tabindex', '0');
document.body.appendChild(focusTarget);
// Important: we're testing the touchUI behavior on particular.
fixture.componentInstance.touchUI = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Focus the input before opening so that the datepicker restores focus to it on close.
input.focus();
expect(document.activeElement)
.withContext('Expected input to be focused on init.')
.toBe(input);
datepicker.open();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(document.activeElement).not.toBe(
input,
'Expected input not to be focused while dialog is open.',
);
datepicker.close();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(document.activeElement)
.withContext('Expected alternate focus target to be focused after closing.')
.toBe(focusTarget);
focusTarget.remove();
subscription.unsubscribe();
}));
it('should re-render when the i18n labels change', inject(
[MatDatepickerIntl],
(intl: MatDatepickerIntl) => {
const toggle = fixture.debugElement.query(By.css('button'))!.nativeElement;
intl.openCalendarLabel = 'Open the calendar, perhaps?';
intl.changes.next();
fixture.detectChanges();
expect(toggle.getAttribute('aria-label')).toBe('Open the calendar, perhaps?');
},
));
it('should toggle the active state of the datepicker toggle', fakeAsync(() => {
const toggle = fixture.debugElement.query(By.css('mat-datepicker-toggle'))!.nativeElement;
expect(toggle.classList).not.toContain('mat-datepicker-toggle-active');
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(toggle.classList).toContain('mat-datepicker-toggle-active');
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(toggle.classList).not.toContain('mat-datepicker-toggle-active');
}));
});
describe('datepicker with custom mat-datepicker-toggle icon', () => {
it('should be able to override the mat-datepicker-toggle icon', fakeAsync(() => {
const fixture = createComponent(DatepickerWithCustomIcon, [MatNativeDateModule]);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.mat-datepicker-toggle .custom-icon'))
.withContext('Expected custom icon to be rendered.')
.toBeTruthy();
expect(fixture.nativeElement.querySelector('.mat-datepicker-toggle mat-icon'))
.withContext('Expected default icon to be removed.')
.toBeFalsy();
}));
}); | {
"end_byte": 50941,
"start_byte": 40610,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_50947_60556 | describe('datepicker with tabindex on mat-datepicker-toggle', () => {
it('should forward the tabindex to the underlying button', () => {
const fixture = createComponent(DatepickerWithTabindexOnToggle, [MatNativeDateModule]);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('.mat-datepicker-toggle button');
expect(button.getAttribute('tabindex')).toBe('7');
});
it('should remove the tabindex from the mat-datepicker-toggle host', () => {
const fixture = createComponent(DatepickerWithTabindexOnToggle, [MatNativeDateModule]);
fixture.detectChanges();
const host = fixture.nativeElement.querySelector('.mat-datepicker-toggle');
expect(host.hasAttribute('tabindex')).toBe(false);
});
});
describe('datepicker inside mat-form-field', () => {
let fixture: ComponentFixture<FormFieldDatepicker>;
let testComponent: FormFieldDatepicker;
beforeEach(fakeAsync(() => {
fixture = createComponent(FormFieldDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should float the placeholder when an invalid value is entered', () => {
testComponent.datepickerInput.value = 'totally-not-a-date' as any;
fixture.changeDetectorRef.markForCheck();
fixture.debugElement.nativeElement.querySelector('input').value = 'totally-not-a-date';
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('label').classList).toContain(
'mdc-floating-label--float-above',
);
});
it('should pass the form field theme color to the overlay', fakeAsync(() => {
testComponent.formField.color = 'primary';
fixture.changeDetectorRef.markForCheck();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
let contentEl = document.querySelector('.mat-datepicker-content')!;
expect(contentEl.classList).toContain('mat-primary');
testComponent.datepicker.close();
fixture.detectChanges();
flush();
testComponent.formField.color = 'warn';
fixture.changeDetectorRef.markForCheck();
testComponent.datepicker.open();
contentEl = document.querySelector('.mat-datepicker-content')!;
fixture.detectChanges();
tick();
flush();
expect(contentEl.classList).toContain('mat-warn');
expect(contentEl.classList).not.toContain('mat-primary');
}));
it('should prefer the datepicker color over the form field one', fakeAsync(() => {
testComponent.datepicker.color = 'accent';
testComponent.formField.color = 'warn';
fixture.changeDetectorRef.markForCheck();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const contentEl = document.querySelector('.mat-datepicker-content')!;
expect(contentEl.classList).toContain('mat-accent');
expect(contentEl.classList).not.toContain('mat-warn');
}));
it('should set aria-labelledby of the overlay to the form field label', fakeAsync(() => {
const label: HTMLElement = fixture.nativeElement.querySelector('label');
expect(label).toBeTruthy();
expect(label.getAttribute('id')).toBeTruthy();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
const popup = document.querySelector(
'.cdk-overlay-pane .mat-datepicker-content-container',
)!;
expect(popup).toBeTruthy();
expect(popup.getAttribute('aria-labelledby')).toBe(label.getAttribute('id'));
}));
});
describe('datepicker with min and max dates and validation', () => {
let fixture: ComponentFixture<DatepickerWithMinAndMaxValidation>;
let testComponent: DatepickerWithMinAndMaxValidation;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithMinAndMaxValidation, [MatNativeDateModule]);
fixture.detectChanges();
flush();
testComponent = fixture.componentInstance;
}));
function revalidate() {
fixture.detectChanges();
flush();
fixture.detectChanges();
}
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should use min and max dates specified by the input', () => {
expect(testComponent.datepicker._getMinDate()).toEqual(new Date(2010, JAN, 1));
expect(testComponent.datepicker._getMaxDate()).toEqual(new Date(2020, JAN, 1));
});
it('should mark invalid when value is before min', fakeAsync(() => {
testComponent.date = new Date(2009, DEC, 31);
fixture.changeDetectorRef.markForCheck();
revalidate();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).toContain(
'ng-invalid',
);
}));
it('should mark invalid when value is after max', fakeAsync(() => {
testComponent.date = new Date(2020, JAN, 2);
fixture.changeDetectorRef.markForCheck();
revalidate();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).toContain(
'ng-invalid',
);
}));
it('should not mark invalid when value equals min', fakeAsync(() => {
testComponent.date = testComponent.datepicker._getMinDate();
fixture.changeDetectorRef.markForCheck();
revalidate();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).not.toContain(
'ng-invalid',
);
}));
it('should not mark invalid when value equals max', fakeAsync(() => {
testComponent.date = testComponent.datepicker._getMaxDate();
fixture.changeDetectorRef.markForCheck();
revalidate();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).not.toContain(
'ng-invalid',
);
}));
it('should not mark invalid when value is between min and max', fakeAsync(() => {
testComponent.date = new Date(2010, JAN, 2);
fixture.changeDetectorRef.markForCheck();
revalidate();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).not.toContain(
'ng-invalid',
);
}));
it('should update validity when switching between null and invalid', fakeAsync(() => {
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
inputEl.value = '';
dispatchFakeEvent(inputEl, 'input');
revalidate();
expect(testComponent.model.valid).toBe(true);
inputEl.value = 'abcdefg';
dispatchFakeEvent(inputEl, 'input');
revalidate();
expect(testComponent.model.valid).toBe(false);
inputEl.value = '';
dispatchFakeEvent(inputEl, 'input');
revalidate();
expect(testComponent.model.valid).toBe(true);
}));
it('should update validity when a value is assigned', fakeAsync(() => {
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
inputEl.value = '';
dispatchFakeEvent(inputEl, 'input');
revalidate();
expect(testComponent.model.valid).toBe(true);
inputEl.value = 'abcdefg';
dispatchFakeEvent(inputEl, 'input');
revalidate();
expect(testComponent.model.valid).toBe(false);
const validDate = new Date(2010, JAN, 2);
// Assigning through the selection model simulates the user doing it via the calendar.
const model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get<MatDateSelectionModel<Date>>(MatDateSelectionModel);
model.updateSelection(validDate, null);
revalidate();
expect(testComponent.model.valid).toBe(true);
expect(testComponent.date).toBe(validDate);
}));
it('should update the calendar when the min/max dates change', fakeAsync(() => {
const getDisabledCells = () => {
return document.querySelectorAll('.mat-calendar-body-disabled').length;
};
testComponent.date = new Date(2020, JAN, 5);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.minDate = new Date(2020, JAN, 3);
testComponent.maxDate = new Date(2020, JAN, 7);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
let disabledCellCount = getDisabledCells();
expect(disabledCellCount).not.toBe(0);
testComponent.minDate = new Date(2020, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(getDisabledCells()).not.toBe(disabledCellCount);
disabledCellCount = getDisabledCells();
testComponent.maxDate = new Date(2020, JAN, 10);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(getDisabledCells()).not.toBe(disabledCellCount);
}));
}); | {
"end_byte": 60556,
"start_byte": 50947,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_60562_70623 | describe('datepicker with filter and validation', () => {
let fixture: ComponentFixture<DatepickerWithFilterAndValidation>;
let testComponent: DatepickerWithFilterAndValidation;
beforeEach(() => {
fixture = createComponent(DatepickerWithFilterAndValidation, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
});
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should mark input invalid', fakeAsync(() => {
testComponent.date = new Date(2017, JAN, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).toContain(
'ng-invalid',
);
testComponent.date = new Date(2017, JAN, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('input'))!.nativeElement.classList).not.toContain(
'ng-invalid',
);
}));
it('should disable filtered calendar cells', fakeAsync(() => {
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
let cells = document.querySelectorAll('.mat-calendar-body-cell');
expect(cells[0].classList).toContain('mat-calendar-body-disabled');
expect(cells[1].classList).not.toContain('mat-calendar-body-disabled');
}));
it('should revalidate when a new function is assigned', fakeAsync(() => {
const classList = fixture.debugElement.query(By.css('input'))!.nativeElement.classList;
testComponent.date = new Date(2017, JAN, 1);
testComponent.filter = () => true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(classList).not.toContain('ng-invalid');
testComponent.filter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(classList).toContain('ng-invalid');
}));
it('should not dispatch the change event if a new function with the same result is assigned', fakeAsync(() => {
const spy = jasmine.createSpy('change spy');
const subscription = fixture.componentInstance.model.valueChanges?.subscribe(spy);
testComponent.filter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
testComponent.filter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription?.unsubscribe();
}));
});
describe('datepicker with change and input events', () => {
let fixture: ComponentFixture<DatepickerWithChangeAndInputEvents>;
let testComponent: DatepickerWithChangeAndInputEvents;
let inputEl: HTMLInputElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithChangeAndInputEvents, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
spyOn(testComponent, 'onChange');
spyOn(testComponent, 'onInput');
spyOn(testComponent, 'onDateChange');
spyOn(testComponent, 'onDateInput');
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('should fire input and dateInput events when user types input', () => {
expect(testComponent.onChange).not.toHaveBeenCalled();
expect(testComponent.onDateChange).not.toHaveBeenCalled();
expect(testComponent.onInput).not.toHaveBeenCalled();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
inputEl.value = '2001-01-01';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(testComponent.onChange).not.toHaveBeenCalled();
expect(testComponent.onDateChange).not.toHaveBeenCalled();
expect(testComponent.onInput).toHaveBeenCalled();
expect(testComponent.onDateInput).toHaveBeenCalled();
});
it('should fire change and dateChange events when user commits typed input', () => {
expect(testComponent.onChange).not.toHaveBeenCalled();
expect(testComponent.onDateChange).not.toHaveBeenCalled();
expect(testComponent.onInput).not.toHaveBeenCalled();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
dispatchFakeEvent(inputEl, 'change');
fixture.detectChanges();
expect(testComponent.onChange).toHaveBeenCalled();
expect(testComponent.onDateChange).toHaveBeenCalled();
expect(testComponent.onInput).not.toHaveBeenCalled();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
});
it('should fire dateChange and dateInput events when user selects calendar date', fakeAsync(() => {
expect(testComponent.onChange).not.toHaveBeenCalled();
expect(testComponent.onDateChange).not.toHaveBeenCalled();
expect(testComponent.onInput).not.toHaveBeenCalled();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(document.querySelector('.mat-datepicker-dialog')).not.toBeNull();
const cells = document.querySelectorAll('.mat-calendar-body-cell');
dispatchMouseEvent(cells[0], 'click');
fixture.detectChanges();
flush();
expect(testComponent.onChange).not.toHaveBeenCalled();
expect(testComponent.onDateChange).toHaveBeenCalled();
expect(testComponent.onInput).not.toHaveBeenCalled();
expect(testComponent.onDateInput).toHaveBeenCalled();
}));
it('should not fire the dateInput event if the value has not changed', () => {
expect(testComponent.onDateInput).not.toHaveBeenCalled();
inputEl.value = '12/12/2012';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(testComponent.onDateInput).toHaveBeenCalledTimes(1);
});
it('should have updated the native input value when the dateChange event is emitted', () => {
let valueDuringChangeEvent = '';
(testComponent.onDateChange as jasmine.Spy).and.callFake(() => {
valueDuringChangeEvent = inputEl.value;
});
const model = fixture.debugElement
.query(By.directive(MatDatepicker))
.injector.get<MatDateSelectionModel<Date>>(MatDateSelectionModel);
model.updateSelection(new Date(2020, 0, 1), null);
fixture.detectChanges();
expect(valueDuringChangeEvent).toBe('1/1/2020');
});
it('should not fire dateInput when typing an invalid value', () => {
expect(testComponent.onDateInput).not.toHaveBeenCalled();
inputEl.value = 'a';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
inputEl.value = 'b';
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(testComponent.onDateInput).not.toHaveBeenCalled();
});
});
describe('with ISO 8601 strings as input', () => {
let fixture: ComponentFixture<DatepickerWithISOStrings>;
let testComponent: DatepickerWithISOStrings;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithISOStrings, [MatNativeDateModule]);
flush();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
}));
it('should coerce ISO strings', fakeAsync(() => {
expect(() => fixture.detectChanges()).not.toThrow();
flush();
fixture.detectChanges();
expect(testComponent.datepicker.startAt).toEqual(new Date(2017, JUL, 1));
expect(testComponent.datepickerInput.value).toEqual(new Date(2017, JUN, 1));
expect(testComponent.datepickerInput.min).toEqual(new Date(2017, JAN, 1));
expect(testComponent.datepickerInput.max).toEqual(new Date(2017, DEC, 31));
}));
});
describe('with events', () => {
let fixture: ComponentFixture<DatepickerWithEvents>;
let testComponent: DatepickerWithEvents;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerWithEvents, [MatNativeDateModule]);
fixture.detectChanges();
flush();
testComponent = fixture.componentInstance;
}));
it('should dispatch an event when a datepicker is opened', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
expect(testComponent.openedSpy).toHaveBeenCalled();
}));
it('should dispatch an event when a datepicker is closed', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
testComponent.datepicker.close();
flush();
fixture.detectChanges();
expect(testComponent.closedSpy).toHaveBeenCalled();
}));
}); | {
"end_byte": 70623,
"start_byte": 60562,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_70629_76696 | describe('datepicker that opens on focus', () => {
let fixture: ComponentFixture<DatepickerOpeningOnFocus>;
let testComponent: DatepickerOpeningOnFocus;
let input: HTMLInputElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(DatepickerOpeningOnFocus, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
input = fixture.debugElement.query(By.css('input'))!.nativeElement;
}));
it('should not reopen if the browser fires the focus event asynchronously', fakeAsync(() => {
// Stub out the real focus method so we can call it reliably.
spyOn(input, 'focus').and.callFake(() => {
// Dispatch the event handler async to simulate the IE11 behavior.
Promise.resolve().then(() => dispatchFakeEvent(input, 'focus'));
});
// Open initially by focusing.
input.focus();
fixture.detectChanges();
tick();
flush();
// Due to some browser limitations we can't install a stub on `document.activeElement`
// so instead we have to override the previously-focused element manually.
(fixture.componentInstance.datepicker as any)._focusedElementBeforeOpen = input;
// Ensure that the datepicker is actually open.
// Ensure that the datepicker is actually open.
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to be open.')
.toBe(true);
// Close the datepicker.
testComponent.datepicker.close();
fixture.detectChanges();
// Schedule the input to be focused asynchronously.
input.focus();
fixture.detectChanges();
tick();
// Flush out the scheduled tasks.
flush();
expect(testComponent.datepicker.opened)
.withContext('Expected datepicker to be closed.')
.toBe(false);
}));
});
describe('datepicker directionality', () => {
it('should pass along the directionality to the popup', fakeAsync(() => {
const fixture = createComponent(
StandardDatepicker,
[MatNativeDateModule],
[
{
provide: Directionality,
useValue: {value: 'rtl'},
},
],
);
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
const overlay = document.querySelector('.cdk-overlay-connected-position-bounding-box')!;
expect(overlay.getAttribute('dir')).toBe('rtl');
}));
it('should update the popup direction if the directionality value changes', fakeAsync(() => {
const dirProvider = {value: 'ltr'};
const fixture = createComponent(
StandardDatepicker,
[MatNativeDateModule],
[
{
provide: Directionality,
useFactory: () => dirProvider,
},
],
);
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
let overlay = document.querySelector('.cdk-overlay-connected-position-bounding-box')!;
expect(overlay.getAttribute('dir')).toBe('ltr');
fixture.componentInstance.datepicker.close();
fixture.detectChanges();
flush();
dirProvider.value = 'rtl';
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
overlay = document.querySelector('.cdk-overlay-connected-position-bounding-box')!;
expect(overlay.getAttribute('dir')).toBe('rtl');
}));
it('should pass along the directionality to the dialog in touch mode', fakeAsync(() => {
const fixture = createComponent(
StandardDatepicker,
[MatNativeDateModule],
[
{
provide: Directionality,
useValue: {value: 'rtl'},
},
],
);
fixture.componentInstance.touch = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.datepicker.open();
fixture.detectChanges();
tick();
const overlay = document.querySelector('.cdk-global-overlay-wrapper')!;
expect(overlay.getAttribute('dir')).toBe('rtl');
}));
});
});
describe('with missing DateAdapter and MAT_DATE_FORMATS', () => {
it('should throw when created', () => {
expect(() => createComponent(StandardDatepicker)).toThrowError(
/MatDatepicker: No provider found for .*/,
);
});
});
describe('datepicker directives without a datepicker', () => {
it('should not throw on init if toggle does not have a datepicker', () => {
expect(() => {
const fixture = createComponent(DatepickerToggleWithNoDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
}).not.toThrow();
});
it('should not set aria-haspopup if toggle does not have a datepicker', () => {
const fixture = createComponent(DatepickerToggleWithNoDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
const toggle = fixture.nativeElement.querySelector('.mat-datepicker-toggle button');
expect(toggle.hasAttribute('aria-haspopup')).toBe(false);
});
it('should not throw on init if input does not have a datepicker', () => {
expect(() => {
const fixture = createComponent(DatepickerInputWithNoDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
}).not.toThrow();
});
it('should not set aria-haspopup if input does not have a datepicker', () => {
const fixture = createComponent(DatepickerInputWithNoDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
const toggle = fixture.nativeElement.querySelector('input');
expect(toggle.hasAttribute('aria-haspopup')).toBe(false);
});
}); | {
"end_byte": 76696,
"start_byte": 70629,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_76700_86162 | describe('popup positioning', () => {
let fixture: ComponentFixture<StandardDatepicker>;
let testComponent: StandardDatepicker;
let input: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(StandardDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
input = fixture.debugElement.query(By.css('input'))!.nativeElement;
input.style.position = 'fixed';
}));
it('should be below and to the right when there is plenty of space', fakeAsync(() => {
input.style.top = input.style.left = '20px';
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.top))
.withContext('Expected popup to align to input bottom.')
.toBe(Math.floor(inputRect.bottom));
expect(Math.floor(overlayRect.left))
.withContext('Expected popup to align to input left.')
.toBe(Math.floor(inputRect.left));
}));
it('should be above and to the right when there is no space below', fakeAsync(() => {
input.style.bottom = input.style.left = '20px';
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom))
.withContext('Expected popup to align to input top.')
.toBe(Math.floor(inputRect.top));
expect(Math.floor(overlayRect.left))
.withContext('Expected popup to align to input left.')
.toBe(Math.floor(inputRect.left));
}));
it('should be below and to the left when there is no space on the right', fakeAsync(() => {
input.style.top = input.style.right = '20px';
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.top))
.withContext('Expected popup to align to input bottom.')
.toBe(Math.floor(inputRect.bottom));
expect(Math.floor(overlayRect.right))
.withContext('Expected popup to align to input right.')
.toBe(Math.floor(inputRect.right));
}));
it('should be above and to the left when there is no space on the bottom', fakeAsync(() => {
input.style.bottom = input.style.right = '20px';
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom))
.withContext('Expected popup to align to input top.')
.toBe(Math.floor(inputRect.top));
expect(Math.floor(overlayRect.right))
.withContext('Expected popup to align to input right.')
.toBe(Math.floor(inputRect.right));
}));
it('should be able to customize the calendar position along the X axis', fakeAsync(() => {
input.style.top = input.style.left = '200px';
testComponent.xPosition = 'end';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.right))
.withContext('Expected popup to align to input right.')
.toBe(Math.floor(inputRect.right));
}));
it('should be able to customize the calendar position along the Y axis', fakeAsync(() => {
input.style.bottom = input.style.left = '100px';
testComponent.yPosition = 'above';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const overlayRect = document.querySelector('.cdk-overlay-pane')!.getBoundingClientRect();
const inputRect = input.getBoundingClientRect();
expect(Math.floor(overlayRect.bottom))
.withContext('Expected popup to align to input top.')
.toBe(Math.floor(inputRect.top));
}));
});
describe('internationalization', () => {
let fixture: ComponentFixture<DatepickerWithi18n>;
let testComponent: DatepickerWithi18n;
let input: HTMLInputElement;
beforeEach(() => {
fixture = createComponent(
DatepickerWithi18n,
[MatNativeDateModule, NativeDateModule],
[{provide: MAT_DATE_LOCALE, useValue: 'de-DE'}],
);
fixture.detectChanges();
testComponent = fixture.componentInstance;
input = fixture.nativeElement.querySelector('input') as HTMLInputElement;
});
it('should have the correct input value even when inverted date format', fakeAsync(() => {
if (typeof Intl === 'undefined') {
// Skip this test if the internationalization API is not supported in the current
// browser. Browsers like Safari 9 do not support the "Intl" API.
return;
}
const selected = new Date(2017, SEP, 1);
testComponent.date = selected;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
// Normally the proper date format would 01.09.2017, but some browsers seem format the
// date without the leading zero. (e.g. 1.9.2017).
expect(input.value).toMatch(/0?1\.0?9\.2017/);
expect(testComponent.datepickerInput.value).toBe(selected);
}));
});
describe('datepicker with custom header', () => {
let fixture: ComponentFixture<DatepickerWithCustomHeader>;
let testComponent: DatepickerWithCustomHeader;
beforeEach(fakeAsync(() => {
fixture = createComponent(
DatepickerWithCustomHeader,
[MatNativeDateModule],
[],
[CustomHeaderForDatepicker],
);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
it('should instantiate a datepicker with a custom header', fakeAsync(() => {
expect(testComponent).toBeTruthy();
}));
it('should find the standard header element', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
fixture.detectChanges();
expect(document.querySelector('mat-calendar-header')).toBeTruthy();
}));
it('should find the custom element', fakeAsync(() => {
testComponent.datepicker.open();
fixture.detectChanges();
tick();
flush();
fixture.detectChanges();
expect(document.querySelector('.custom-element')).toBeTruthy();
}));
});
it('should not trigger validators if new date object for same date is set for `min`', () => {
const fixture = createComponent(
DatepickerInputWithCustomValidator,
[MatNativeDateModule],
undefined,
[CustomValidator],
);
fixture.detectChanges();
const minDate = new Date(2019, 0, 1);
const validator = fixture.componentInstance.validator;
validator.validate.calls.reset();
fixture.componentInstance.min = minDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
fixture.componentInstance.min = new Date(minDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
});
it('should not trigger validators if new date object for same date is set for `max`', () => {
const fixture = createComponent(
DatepickerInputWithCustomValidator,
[MatNativeDateModule],
undefined,
[CustomValidator],
);
fixture.detectChanges();
const maxDate = new Date(2120, 0, 1);
const validator = fixture.componentInstance.validator;
validator.validate.calls.reset();
fixture.componentInstance.max = maxDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
fixture.componentInstance.max = new Date(maxDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
});
it('should not emit to `stateChanges` if new date object for same date is set for `min`', () => {
const fixture = createComponent(StandardDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
const minDate = new Date(2019, 0, 1);
const spy = jasmine.createSpy('stateChanges spy');
const subscription = fixture.componentInstance.datepickerInput.stateChanges.subscribe(spy);
fixture.componentInstance.min = minDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
fixture.componentInstance.min = new Date(minDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
}); | {
"end_byte": 86162,
"start_byte": 76700,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_86166_94043 | it('should not emit to `stateChanges` if new date object for same date is set for `max`', () => {
const fixture = createComponent(StandardDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
const maxDate = new Date(2120, 0, 1);
const spy = jasmine.createSpy('stateChanges spy');
const subscription = fixture.componentInstance.datepickerInput.stateChanges.subscribe(spy);
fixture.componentInstance.max = maxDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
fixture.componentInstance.max = new Date(maxDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
});
describe('panelClass input', () => {
let fixture: ComponentFixture<PanelClassDatepicker>;
let testComponent: PanelClassDatepicker;
beforeEach(fakeAsync(() => {
fixture = createComponent(PanelClassDatepicker, [MatNativeDateModule]);
fixture.detectChanges();
testComponent = fixture.componentInstance;
}));
afterEach(fakeAsync(() => {
testComponent.datepicker.close();
fixture.detectChanges();
flush();
}));
it('should accept a single class', () => {
testComponent.panelClass = 'foobar';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testComponent.datepicker.panelClass).toEqual(['foobar']);
});
it('should accept multiple classes', () => {
testComponent.panelClass = 'foo bar';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testComponent.datepicker.panelClass).toEqual(['foo', 'bar']);
});
it('should work with ngClass', fakeAsync(() => {
testComponent.panelClass = ['foo', 'bar'];
fixture.changeDetectorRef.markForCheck();
testComponent.datepicker.open();
fixture.detectChanges();
tick();
const actualClasses = document.querySelector(
'.mat-datepicker-content .mat-calendar',
)!.classList;
expect(actualClasses.contains('foo')).toBe(true);
expect(actualClasses.contains('bar')).toBe(true);
}));
});
});
/**
* Styles that set input elements to a fixed width. This helps with client rect measurements
* (i.e. that the datepicker aligns properly). Inputs have different dimensions in different
* browsers. e.g. in Firefox the input width is uneven, causing unexpected deviations in measuring.
* Note: The input should be able to shrink as on iOS the viewport width is very little but the
* datepicker inputs should not leave the viewport (as that throws off measuring too).
*/
const inputFixedWidthStyles = `
input {
width: 100%;
max-width: 150px;
border: none;
box-sizing: border-box;
}
`;
@Component({
template: `
<input [matDatepicker]="d" [value]="date" [min]="min" [max]="max">
<mat-datepicker
#d
[touchUi]="touch"
[disabled]="disabled"
[opened]="opened"
[xPosition]="xPosition"
[yPosition]="yPosition"></mat-datepicker>
`,
styles: inputFixedWidthStyles,
standalone: false,
})
class StandardDatepicker {
opened = false;
touch = false;
disabled = false;
date: Date | null = new Date(2020, JAN, 1);
min: Date;
max: Date;
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
xPosition: DatepickerDropdownPositionX;
yPosition: DatepickerDropdownPositionY;
}
@Component({
template: `
<input [matDatepicker]="d"><input [matDatepicker]="d"><mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class MultiInputDatepicker {}
@Component({
template: `<mat-datepicker #d></mat-datepicker>`,
standalone: false,
})
class NoInputDatepicker {
@ViewChild('d') datepicker: MatDatepicker<Date>;
}
@Component({
template: `
<input [matDatepicker]="d" [value]="date">
<mat-datepicker #d [startAt]="startDate"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithStartAt {
date = new Date(2020, JAN, 1);
startDate = new Date(2010, JAN, 1);
@ViewChild('d') datepicker: MatDatepicker<Date>;
}
@Component({
template: `
<input [matDatepicker]="d" [value]="date">
<mat-datepicker #d startView="year" (monthSelected)="onYearSelection()"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithStartViewYear {
date = new Date(2020, JAN, 1);
@ViewChild('d') datepicker: MatDatepicker<Date>;
onYearSelection() {}
}
@Component({
template: `
<input [matDatepicker]="d" [value]="date">
<mat-datepicker #d startView="multi-year"
(yearSelected)="onMultiYearSelection()"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithStartViewMultiYear {
date = new Date(2020, JAN, 1);
@ViewChild('d') datepicker: MatDatepicker<Date>;
onMultiYearSelection() {}
}
@Component({
template: `
<input [(ngModel)]="selected" [matDatepicker]="d">
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithNgModel {
selected: Date | null = null;
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
}
@Component({
template: `
<input [formControl]="formControl" [matDatepicker]="d">
<mat-datepicker-toggle [for]="d"></mat-datepicker-toggle>
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithFormControl {
formControl = new FormControl<Date | null>(null);
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
@ViewChild(MatDatepickerToggle) datepickerToggle: MatDatepickerToggle<Date>;
}
@Component({
template: `
<input [matDatepicker]="d">
<mat-datepicker-toggle [for]="d" [aria-label]="ariaLabel"></mat-datepicker-toggle>
<mat-datepicker #d [touchUi]="touchUI" [restoreFocus]="restoreFocus"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithToggle {
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) input: MatDatepickerInput<Date>;
touchUI = true;
restoreFocus = true;
ariaLabel: string;
}
@Component({
encapsulation: ViewEncapsulation.ShadowDom,
template: `
<input [matDatepicker]="d">
<mat-datepicker-toggle [for]="d" [aria-label]="ariaLabel"></mat-datepicker-toggle>
<mat-datepicker #d [touchUi]="touchUI" [restoreFocus]="restoreFocus"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithToggleInShadowDom extends DatepickerWithToggle {}
@Component({
template: `
<input [matDatepicker]="d">
<mat-datepicker-toggle [for]="d">
<div class="custom-icon" matDatepickerToggleIcon></div>
</mat-datepicker-toggle>
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithCustomIcon {}
@Component({
template: `
<mat-form-field>
<mat-label>Pick a date</mat-label>
<input matInput [matDatepicker]="d">
<mat-datepicker #d></mat-datepicker>
</mat-form-field>
`,
standalone: false,
})
class FormFieldDatepicker {
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
@ViewChild(MatFormField) formField: MatFormField;
}
@Component({
template: `
<input [matDatepicker]="d" [(ngModel)]="date" [min]="minDate" [max]="maxDate">
<mat-datepicker-toggle [for]="d"></mat-datepicker-toggle>
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithMinAndMaxValidation {
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(NgModel) model: NgModel;
date: Date | null;
minDate = new Date(2010, JAN, 1);
maxDate = new Date(2020, JAN, 1);
} | {
"end_byte": 94043,
"start_byte": 86166,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker.spec.ts_94045_98997 | @Component({
template: `
<input [matDatepicker]="d" [(ngModel)]="date" [matDatepickerFilter]="filter">
<mat-datepicker-toggle [for]="d"></mat-datepicker-toggle>
<mat-datepicker #d [touchUi]="true"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithFilterAndValidation {
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(NgModel) model: NgModel;
date: Date;
filter = (date: Date | null) => date?.getDate() != 1;
}
@Component({
template: `
<input [matDatepicker]="d" (change)="onChange()" (input)="onInput()"
(dateChange)="onDateChange()" (dateInput)="onDateInput()">
<mat-datepicker #d [touchUi]="true"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithChangeAndInputEvents {
@ViewChild('d') datepicker: MatDatepicker<Date>;
onChange() {}
onInput() {}
onDateChange() {}
onDateInput() {}
}
@Component({
template: `
<input [matDatepicker]="d" [(ngModel)]="date">
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithi18n {
date: Date | null = new Date(2010, JAN, 1);
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
}
@Component({
template: `
<input [matDatepicker]="d" [(ngModel)]="value" [min]="min" [max]="max">
<mat-datepicker #d [startAt]="startAt"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithISOStrings {
value = new Date(2017, JUN, 1).toISOString();
min = new Date(2017, JAN, 1).toISOString();
max = new Date(2017, DEC, 31).toISOString();
startAt = new Date(2017, JUL, 1).toISOString();
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
}
@Component({
template: `
<input [(ngModel)]="selected" [matDatepicker]="d">
<mat-datepicker (opened)="openedSpy()" (closed)="closedSpy()" #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithEvents {
selected: Date | null = null;
openedSpy = jasmine.createSpy('opened spy');
closedSpy = jasmine.createSpy('closed spy');
@ViewChild('d') datepicker: MatDatepicker<Date>;
}
@Component({
template: `
<input (focus)="d.open()" [matDatepicker]="d">
<mat-datepicker #d="matDatepicker"></mat-datepicker>
`,
standalone: false,
})
class DatepickerOpeningOnFocus {
@ViewChild(MatDatepicker) datepicker: MatDatepicker<Date>;
}
@Component({
template: `
<input [matDatepicker]="ch">
<mat-datepicker #ch [calendarHeaderComponent]="customHeaderForDatePicker"></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithCustomHeader {
@ViewChild('ch') datepicker: MatDatepicker<Date>;
customHeaderForDatePicker = CustomHeaderForDatepicker;
}
@Component({
template: `
<div class="custom-element">Custom element</div>
<mat-calendar-header></mat-calendar-header>
`,
standalone: false,
})
class CustomHeaderForDatepicker {}
@Component({
template: `
<input [matDatepicker]="assignedDatepicker" [value]="date">
<mat-datepicker #d [touchUi]="touch"></mat-datepicker>
`,
standalone: false,
})
class DelayedDatepicker {
@ViewChild('d') datepicker: MatDatepicker<Date>;
@ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<Date>;
date: Date | null;
assignedDatepicker: MatDatepicker<Date>;
}
@Component({
template: `
<input [matDatepicker]="d">
<mat-datepicker-toggle tabIndex="7" [for]="d" [disabled]="disabled">
<div class="custom-icon" matDatepickerToggleIcon></div>
</mat-datepicker-toggle>
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerWithTabindexOnToggle {
disabled = false;
}
@Component({
template: `
<mat-datepicker-toggle></mat-datepicker-toggle>
`,
standalone: false,
})
class DatepickerToggleWithNoDatepicker {}
@Component({
template: `
<input [matDatepicker]="d">
`,
standalone: false,
})
class DatepickerInputWithNoDatepicker {}
@Directive({
selector: '[customValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomValidator,
multi: true,
},
],
standalone: false,
})
class CustomValidator implements Validator {
validate = jasmine.createSpy('validate spy').and.returnValue(null);
}
@Component({
template: `
<input [matDatepicker]="d" [(ngModel)]="value" [min]="min" [max]="max" customValidator>
<mat-datepicker #d></mat-datepicker>
`,
standalone: false,
})
class DatepickerInputWithCustomValidator {
@ViewChild(CustomValidator) validator: CustomValidator;
value: Date;
min: Date;
max: Date;
}
@Component({
template: `
<input [matDatepicker]="d" [value]="date">
<mat-datepicker [panelClass]="panelClass" touchUi #d></mat-datepicker>
`,
standalone: false,
})
class PanelClassDatepicker {
date = new Date(0);
panelClass: any;
@ViewChild('d') datepicker: MatDatepicker<Date>;
} | {
"end_byte": 98997,
"start_byte": 94045,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.spec.ts"
} |
components/src/material/datepicker/datepicker-toggle.ts_0_4516 | /**
* @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,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
Directive,
Input,
OnChanges,
OnDestroy,
SimpleChanges,
ViewEncapsulation,
ViewChild,
booleanAttribute,
inject,
HostAttributeToken,
} from '@angular/core';
import {MatButton, MatIconButton} from '@angular/material/button';
import {merge, Observable, of as observableOf, Subscription} from 'rxjs';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatDatepickerControl, MatDatepickerPanel} from './datepicker-base';
/** Can be used to override the icon of a `matDatepickerToggle`. */
@Directive({
selector: '[matDatepickerToggleIcon]',
})
export class MatDatepickerToggleIcon {}
@Component({
selector: 'mat-datepicker-toggle',
templateUrl: 'datepicker-toggle.html',
styleUrl: 'datepicker-toggle.css',
host: {
'class': 'mat-datepicker-toggle',
'[attr.tabindex]': 'null',
'[class.mat-datepicker-toggle-active]': 'datepicker && datepicker.opened',
'[class.mat-accent]': 'datepicker && datepicker.color === "accent"',
'[class.mat-warn]': 'datepicker && datepicker.color === "warn"',
// Used by the test harness to tie this toggle to its datepicker.
'[attr.data-mat-calendar]': 'datepicker ? datepicker.id : null',
// Bind the `click` on the host, rather than the inner `button`, so that we can call
// `stopPropagation` on it without affecting the user's `click` handlers. We need to stop
// it so that the input doesn't get focused automatically by the form field (See #21836).
'(click)': '_open($event)',
},
exportAs: 'matDatepickerToggle',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatIconButton],
})
export class MatDatepickerToggle<D> implements AfterContentInit, OnChanges, OnDestroy {
_intl = inject(MatDatepickerIntl);
private _changeDetectorRef = inject(ChangeDetectorRef);
private _stateChanges = Subscription.EMPTY;
/** Datepicker instance that the button will toggle. */
@Input('for') datepicker: MatDatepickerPanel<MatDatepickerControl<any>, D>;
/** Tabindex for the toggle. */
@Input() tabIndex: number | null;
/** Screen-reader label for the button. */
@Input('aria-label') ariaLabel: string;
/** Whether the toggle button is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
if (this._disabled === undefined && this.datepicker) {
return this.datepicker.disabled;
}
return !!this._disabled;
}
set disabled(value: boolean) {
this._disabled = value;
}
private _disabled: boolean;
/** Whether ripples on the toggle should be disabled. */
@Input() disableRipple: boolean;
/** Custom icon set by the consumer. */
@ContentChild(MatDatepickerToggleIcon) _customIcon: MatDatepickerToggleIcon;
/** Underlying button element. */
@ViewChild('button') _button: MatButton;
constructor(...args: unknown[]);
constructor() {
const defaultTabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
const parsedTabIndex = Number(defaultTabIndex);
this.tabIndex = parsedTabIndex || parsedTabIndex === 0 ? parsedTabIndex : null;
}
ngOnChanges(changes: SimpleChanges) {
if (changes['datepicker']) {
this._watchStateChanges();
}
}
ngOnDestroy() {
this._stateChanges.unsubscribe();
}
ngAfterContentInit() {
this._watchStateChanges();
}
_open(event: Event): void {
if (this.datepicker && !this.disabled) {
this.datepicker.open();
event.stopPropagation();
}
}
private _watchStateChanges() {
const datepickerStateChanged = this.datepicker ? this.datepicker.stateChanges : observableOf();
const inputStateChanged =
this.datepicker && this.datepicker.datepickerInput
? this.datepicker.datepickerInput.stateChanges
: observableOf();
const datepickerToggled = this.datepicker
? merge(this.datepicker.openedStream, this.datepicker.closedStream)
: observableOf();
this._stateChanges.unsubscribe();
this._stateChanges = merge(
this._intl.changes,
datepickerStateChanged as Observable<void>,
inputStateChanged,
datepickerToggled,
).subscribe(() => this._changeDetectorRef.markForCheck());
}
}
| {
"end_byte": 4516,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-toggle.ts"
} |
components/src/material/datepicker/BUILD.bazel_0_3237 | 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 = "datepicker",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":datepicker-content.css",
":datepicker-actions.css",
":datepicker-toggle.css",
":date-range-input.css",
":calendar-body.css",
":calendar.css",
] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/coercion",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/platform",
"//src/cdk/portal",
"//src/material/button",
"//src/material/core",
"//src/material/form-field",
"//src/material/input",
"@npm//@angular/animations",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//@angular/forms",
"@npm//rxjs",
],
)
sass_library(
name = "datepicker_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/button:button_scss_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "datepicker_content_scss",
src = "datepicker-content.scss",
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "datepicker_toggle_scss",
src = "datepicker-toggle.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "calendar_scss",
src = "calendar.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "calendar_body_scss",
src = "calendar-body.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "date_range_input_scss",
src = "date-range-input.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "datepicker_actions_scss",
src = "datepicker-actions.scss",
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":datepicker",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/platform",
"//src/cdk/scrolling",
"//src/cdk/testing/private",
"//src/material/core",
"//src/material/form-field",
"//src/material/input",
"//src/material/testing",
"@npm//@angular/common",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":datepicker.md"],
)
extract_tokens(
name = "tokens",
srcs = [":datepicker_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 3237,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/BUILD.bazel"
} |
components/src/material/datepicker/datepicker-toggle.html_0_731 | <button
#button
mat-icon-button
type="button"
[attr.aria-haspopup]="datepicker ? 'dialog' : null"
[attr.aria-label]="ariaLabel || _intl.openCalendarLabel"
[attr.tabindex]="disabled ? -1 : tabIndex"
[disabled]="disabled"
[disableRipple]="disableRipple">
@if (!_customIcon) {
<svg
class="mat-datepicker-toggle-default-icon"
viewBox="0 0 24 24"
width="24px"
height="24px"
fill="currentColor"
focusable="false"
aria-hidden="true">
<path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/>
</svg>
}
<ng-content select="[matDatepickerToggleIcon]"></ng-content>
</button>
| {
"end_byte": 731,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-toggle.html"
} |
components/src/material/datepicker/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/datepicker/index.ts"
} |
components/src/material/datepicker/year-view.ts_0_1352 | /**
* @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,
} from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
Output,
ViewChild,
ViewEncapsulation,
OnDestroy,
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';
/**
* An internal component used to display a single year in the datepicker.
* @docs-private
*/
@Component({
selector: 'mat-year-view',
templateUrl: 'year-view.html',
exportAs: 'matYearView',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatCalendarBody],
})
export | {
"end_byte": 1352,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.ts"
} |
components/src/material/datepicker/year-view.ts_1353_9680 | class MatYearView<D> implements AfterContentInit, 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 _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 year view (everything other than the year is ignored). */
@Input()
get activeDate(): D {
return this._activeDate;
}
set activeDate(value: D) {
let 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._dateAdapter.getYear(oldActiveDate) !== this._dateAdapter.getYear(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._setSelectedMonth(value);
}
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;
/** A function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Function that can be used to add custom CSS classes to date cells. */
@Input() dateClass: MatCalendarCellClassFunction<D>;
/** Emits when a new month is selected. */
@Output() readonly selectedChange: EventEmitter<D> = new EventEmitter<D>();
/** Emits the selected month. This doesn't imply a change on the selected date */
@Output() readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();
/** Emits when any date is activated. */
@Output() readonly activeDateChange: EventEmitter<D> = new EventEmitter<D>();
/** The body of calendar table */
@ViewChild(MatCalendarBody) _matCalendarBody: MatCalendarBody;
/** Grid of calendar cells representing the months of the year. */
_months: MatCalendarCell[][];
/** The label for this year (e.g. "2017"). */
_yearLabel: string;
/** The month in this year that today falls on. Null if today is in a different year. */
_todayMonth: number | null;
/**
* The month in this year that the selected Date falls on.
* Null if the selected Date is in a different year.
*/
_selectedMonth: number | null;
constructor(...args: unknown[]);
constructor() {
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());
}
ngOnDestroy() {
this._rerenderSubscription.unsubscribe();
}
/** Handles when a new month is selected. */
_monthSelected(event: MatCalendarUserEvent<number>) {
const month = event.value;
const selectedMonth = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
month,
1,
);
this.monthSelected.emit(selectedMonth);
const selectedDate = this._getDateFromMonth(month);
this.selectedChange.emit(selectedDate);
}
/**
* 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._getDateFromMonth(month);
if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
this.activeDateChange.emit(this.activeDate);
}
}
/** Handles keydown events on the calendar body when calendar is in year view. */
_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.addCalendarMonths(this._activeDate, isRtl ? 1 : -1);
break;
case RIGHT_ARROW:
this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, isRtl ? -1 : 1);
break;
case UP_ARROW:
this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, -4);
break;
case DOWN_ARROW:
this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, 4);
break;
case HOME:
this.activeDate = this._dateAdapter.addCalendarMonths(
this._activeDate,
-this._dateAdapter.getMonth(this._activeDate),
);
break;
case END:
this.activeDate = this._dateAdapter.addCalendarMonths(
this._activeDate,
11 - this._dateAdapter.getMonth(this._activeDate),
);
break;
case PAGE_UP:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
event.altKey ? -10 : -1,
);
break;
case PAGE_DOWN:
this.activeDate = this._dateAdapter.addCalendarYears(
this._activeDate,
event.altKey ? 10 : 1,
);
break;
case ENTER:
case SPACE:
// 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).
this._selectionKeyPressed = true;
break;
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 year view. */
_handleCalendarBodyKeyup(event: KeyboardEvent): void {
if (event.keyCode === SPACE || event.keyCode === ENTER) {
if (this._selectionKeyPressed) {
this._monthSelected({value: this._dateAdapter.getMonth(this._activeDate), event});
}
this._selectionKeyPressed = false;
}
}
/** Initializes this year view. */ | {
"end_byte": 9680,
"start_byte": 1353,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.ts"
} |
components/src/material/datepicker/year-view.ts_9683_14433 | _init() {
this._setSelectedMonth(this.selected);
this._todayMonth = this._getMonthInCurrentYear(this._dateAdapter.today());
this._yearLabel = this._dateAdapter.getYearName(this.activeDate);
let monthNames = this._dateAdapter.getMonthNames('short');
// First row of months only contains 5 elements so we can fit the year label on the same row.
this._months = [
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
].map(row => row.map(month => this._createCellForMonth(month, monthNames[month])));
this._changeDetectorRef.markForCheck();
}
/** Focuses the active cell after the microtask queue is empty. */
_focusActiveCell() {
this._matCalendarBody._focusActiveCell();
}
/** Schedules the matCalendarBody to focus the active cell after change detection has run */
_focusActiveCellAfterViewChecked() {
this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
}
/**
* Gets the month in this year that the given Date falls on.
* Returns null if the given Date is in another year.
*/
private _getMonthInCurrentYear(date: D | null) {
return date && this._dateAdapter.getYear(date) == this._dateAdapter.getYear(this.activeDate)
? this._dateAdapter.getMonth(date)
: null;
}
/**
* Takes a month and returns a new date in the same day and year as the currently active date.
* The returned date will have the same month as the argument date.
*/
private _getDateFromMonth(month: number) {
const normalizedDate = this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
month,
1,
);
const daysInMonth = this._dateAdapter.getNumDaysInMonth(normalizedDate);
return this._dateAdapter.createDate(
this._dateAdapter.getYear(this.activeDate),
month,
Math.min(this._dateAdapter.getDate(this.activeDate), daysInMonth),
);
}
/** Creates an MatCalendarCell for the given month. */
private _createCellForMonth(month: number, monthName: string) {
const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1);
const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.monthYearA11yLabel);
const cellClasses = this.dateClass ? this.dateClass(date, 'year') : undefined;
return new MatCalendarCell(
month,
monthName.toLocaleUpperCase(),
ariaLabel,
this._shouldEnableMonth(month),
cellClasses,
);
}
/** Whether the given month is enabled. */
private _shouldEnableMonth(month: number) {
const activeYear = this._dateAdapter.getYear(this.activeDate);
if (
month === undefined ||
month === null ||
this._isYearAndMonthAfterMaxDate(activeYear, month) ||
this._isYearAndMonthBeforeMinDate(activeYear, month)
) {
return false;
}
if (!this.dateFilter) {
return true;
}
const firstOfMonth = this._dateAdapter.createDate(activeYear, month, 1);
// If any date in the month is enabled count the month as enabled.
for (
let date = firstOfMonth;
this._dateAdapter.getMonth(date) == month;
date = this._dateAdapter.addCalendarDays(date, 1)
) {
if (this.dateFilter(date)) {
return true;
}
}
return false;
}
/**
* Tests whether the combination month/year is after this.maxDate, considering
* just the month and year of this.maxDate
*/
private _isYearAndMonthAfterMaxDate(year: number, month: number) {
if (this.maxDate) {
const maxYear = this._dateAdapter.getYear(this.maxDate);
const maxMonth = this._dateAdapter.getMonth(this.maxDate);
return year > maxYear || (year === maxYear && month > maxMonth);
}
return false;
}
/**
* Tests whether the combination month/year is before this.minDate, considering
* just the month and year of this.minDate
*/
private _isYearAndMonthBeforeMinDate(year: number, month: number) {
if (this.minDate) {
const minYear = this._dateAdapter.getYear(this.minDate);
const minMonth = this._dateAdapter.getMonth(this.minDate);
return year < minYear || (year === minYear && month < minMonth);
}
return false;
}
/** Determines whether the user has the RTL layout direction. */
private _isRtl() {
return this._dir && this._dir.value === 'rtl';
}
/** Sets the currently-selected month based on a model value. */
private _setSelectedMonth(value: DateRange<D> | D | null) {
if (value instanceof DateRange) {
this._selectedMonth =
this._getMonthInCurrentYear(value.start) || this._getMonthInCurrentYear(value.end);
} else {
this._selectedMonth = this._getMonthInCurrentYear(value);
}
}
} | {
"end_byte": 14433,
"start_byte": 9683,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.ts"
} |
components/src/material/datepicker/datepicker-input.ts_0_6590 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Directive, ElementRef, forwardRef, Input, OnDestroy, signal, inject} from '@angular/core';
import {NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidatorFn, Validators} from '@angular/forms';
import {ThemePalette} from '@angular/material/core';
import {MAT_FORM_FIELD} from '@angular/material/form-field';
import {MAT_INPUT_VALUE_ACCESSOR} from '@angular/material/input';
import {Subscription} from 'rxjs';
import {DateSelectionModelChange} from './date-selection-model';
import {MatDatepickerControl, MatDatepickerPanel} from './datepicker-base';
import {_MatFormFieldPartial, DateFilterFn, MatDatepickerInputBase} from './datepicker-input-base';
/** @docs-private */
export const MAT_DATEPICKER_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatDatepickerInput),
multi: true,
};
/** @docs-private */
export const MAT_DATEPICKER_VALIDATORS: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MatDatepickerInput),
multi: true,
};
/** Directive used to connect an input to a MatDatepicker. */
@Directive({
selector: 'input[matDatepicker]',
providers: [
MAT_DATEPICKER_VALUE_ACCESSOR,
MAT_DATEPICKER_VALIDATORS,
{provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: MatDatepickerInput},
],
host: {
'class': 'mat-datepicker-input',
'[attr.aria-haspopup]': '_datepicker ? "dialog" : null',
'[attr.aria-owns]': '_ariaOwns()',
'[attr.min]': 'min ? _dateAdapter.toIso8601(min) : null',
'[attr.max]': 'max ? _dateAdapter.toIso8601(max) : null',
// 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]': '_datepicker ? _datepicker.id : null',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(blur)': '_onBlur()',
'(keydown)': '_onKeydown($event)',
},
exportAs: 'matDatepickerInput',
})
export class MatDatepickerInput<D>
extends MatDatepickerInputBase<D | null, D>
implements MatDatepickerControl<D | null>, OnDestroy
{
private _formField = inject<_MatFormFieldPartial>(MAT_FORM_FIELD, {optional: true});
private _closedSubscription = Subscription.EMPTY;
private _openedSubscription = Subscription.EMPTY;
/** The datepicker that this input is associated with. */
@Input()
set matDatepicker(datepicker: MatDatepickerPanel<MatDatepickerControl<D>, D | null, D>) {
if (datepicker) {
this._datepicker = datepicker;
this._ariaOwns.set(datepicker.opened ? datepicker.id : null);
this._closedSubscription = datepicker.closedStream.subscribe(() => {
this._onTouched();
this._ariaOwns.set(null);
});
this._openedSubscription = datepicker.openedStream.subscribe(() => {
this._ariaOwns.set(datepicker.id);
});
this._registerModel(datepicker.registerInput(this));
}
}
_datepicker: MatDatepickerPanel<MatDatepickerControl<D>, D | null, D>;
/** The id of the panel owned by this input. */
protected _ariaOwns = signal<string | null>(null);
/** 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._validatorOnChange();
}
}
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._validatorOnChange();
}
}
private _max: D | null;
/** Function that can be used to filter out dates within the datepicker. */
@Input('matDatepickerFilter')
get dateFilter() {
return this._dateFilter;
}
set dateFilter(value: DateFilterFn<D | null>) {
const wasMatchingValue = this._matchesFilter(this.value);
this._dateFilter = value;
if (this._matchesFilter(this.value) !== wasMatchingValue) {
this._validatorOnChange();
}
}
private _dateFilter: DateFilterFn<D | null>;
/** The combined form control validator for this input. */
protected _validator: ValidatorFn | null;
constructor(...args: unknown[]);
constructor() {
super();
this._validator = Validators.compose(super._getValidators());
}
/**
* Gets the element that the datepicker popup should be connected to.
* @return The element to connect the popup to.
*/
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 {
if (this._formField) {
return this._formField.getLabelId();
}
return this._elementRef.nativeElement.getAttribute('aria-labelledby');
}
/** Returns the palette used by the input's form field, if any. */
getThemePalette(): ThemePalette {
return this._formField ? this._formField.color : undefined;
}
/** Gets the value at which the calendar should start. */
getStartValue(): D | null {
return this.value;
}
override ngOnDestroy() {
super.ngOnDestroy();
this._closedSubscription.unsubscribe();
this._openedSubscription.unsubscribe();
}
/** Opens the associated datepicker. */
protected _openPopup(): void {
if (this._datepicker) {
this._datepicker.open();
}
}
protected _getValueFromModel(modelValue: D | null): D | null {
return modelValue;
}
protected _assignValueToModel(value: D | null): void {
if (this._model) {
this._model.updateSelection(value, this);
}
}
/** Gets the input's minimum date. */
_getMinDate() {
return this._min;
}
/** Gets the input's maximum date. */
_getMaxDate() {
return this._max;
}
/** Gets the input's date filtering function. */
protected _getDateFilter() {
return this._dateFilter;
}
protected _shouldHandleChangeEvent(event: DateSelectionModelChange<D>) {
return event.source !== this;
}
}
| {
"end_byte": 6590,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-input.ts"
} |
components/src/material/datepicker/year-view.html_0_790 | <table class="mat-calendar-table" role="grid">
<thead aria-hidden="true" class="mat-calendar-table-header">
<tr><th class="mat-calendar-table-header-divider" colspan="4"></th></tr>
</thead>
<tbody mat-calendar-body
[label]="_yearLabel"
[rows]="_months"
[todayValue]="_todayMonth!"
[startValue]="_selectedMonth!"
[endValue]="_selectedMonth!"
[labelMinRequiredCells]="2"
[numCols]="4"
[cellAspectRatio]="4 / 7"
[activeCell]="_dateAdapter.getMonth(activeDate)"
(selectedValueChange)="_monthSelected($event)"
(activeDateChange)="_updateActiveDate($event)"
(keyup)="_handleCalendarBodyKeyup($event)"
(keydown)="_handleCalendarBodyKeydown($event)">
</tbody>
</table>
| {
"end_byte": 790,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/year-view.html"
} |
components/src/material/datepicker/multi-year-view.html_0_700 | <table class="mat-calendar-table" role="grid">
<thead aria-hidden="true" class="mat-calendar-table-header">
<tr><th class="mat-calendar-table-header-divider" colspan="4"></th></tr>
</thead>
<tbody mat-calendar-body
[rows]="_years"
[todayValue]="_todayYear"
[startValue]="_selectedYear!"
[endValue]="_selectedYear!"
[numCols]="4"
[cellAspectRatio]="4 / 7"
[activeCell]="_getActiveCell()"
(selectedValueChange)="_yearSelected($event)"
(activeDateChange)="_updateActiveDate($event)"
(keyup)="_handleCalendarBodyKeyup($event)"
(keydown)="_handleCalendarBodyKeydown($event)">
</tbody>
</table>
| {
"end_byte": 700,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/multi-year-view.html"
} |
components/src/material/datepicker/date-range-selection-strategy.ts_0_5631 | /**
* @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 {Injectable, InjectionToken, Optional, SkipSelf, FactoryProvider} from '@angular/core';
import {DateAdapter} from '@angular/material/core';
import {DateRange} from './date-selection-model';
/** Injection token used to customize the date range selection behavior. */
export const MAT_DATE_RANGE_SELECTION_STRATEGY = new InjectionToken<
MatDateRangeSelectionStrategy<any>
>('MAT_DATE_RANGE_SELECTION_STRATEGY');
/** Object that can be provided in order to customize the date range selection behavior. */
export interface MatDateRangeSelectionStrategy<D> {
/**
* Called when the user has finished selecting a value.
* @param date Date that was selected. Will be null if the user cleared the selection.
* @param currentRange Range that is currently show in the calendar.
* @param event DOM event that triggered the selection. Currently only corresponds to a `click`
* event, but it may get expanded in the future.
*/
selectionFinished(date: D | null, currentRange: DateRange<D>, event: Event): DateRange<D>;
/**
* Called when the user has activated a new date (e.g. by hovering over
* it or moving focus) and the calendar tries to display a date range.
*
* @param activeDate Date that the user has activated. Will be null if the user moved
* focus to an element that's no a calendar cell.
* @param currentRange Range that is currently shown in the calendar.
* @param event DOM event that caused the preview to be changed. Will be either a
* `mouseenter`/`mouseleave` or `focus`/`blur` depending on how the user is navigating.
*/
createPreview(activeDate: D | null, currentRange: DateRange<D>, event: Event): DateRange<D>;
/**
* Called when the user has dragged a date in the currently selected range to another
* date. Returns the date updated range that should result from this interaction.
*
* @param dateOrigin The date the user started dragging from.
* @param originalRange The originally selected date range.
* @param newDate The currently targeted date in the drag operation.
* @param event DOM event that triggered the updated drag state. Will be
* `mouseenter`/`mouseup` or `touchmove`/`touchend` depending on the device type.
*/
createDrag?(
dragOrigin: D,
originalRange: DateRange<D>,
newDate: D,
event: Event,
): DateRange<D> | null;
}
/** Provides the default date range selection behavior. */
@Injectable()
export class DefaultMatCalendarRangeStrategy<D> implements MatDateRangeSelectionStrategy<D> {
constructor(private _dateAdapter: DateAdapter<D>) {}
selectionFinished(date: D, currentRange: DateRange<D>) {
let {start, end} = currentRange;
if (start == null) {
start = date;
} else if (end == null && date && this._dateAdapter.compareDate(date, start) >= 0) {
end = date;
} else {
start = date;
end = null;
}
return new DateRange<D>(start, end);
}
createPreview(activeDate: D | null, currentRange: DateRange<D>) {
let start: D | null = null;
let end: D | null = null;
if (currentRange.start && !currentRange.end && activeDate) {
start = currentRange.start;
end = activeDate;
}
return new DateRange<D>(start, end);
}
createDrag(dragOrigin: D, originalRange: DateRange<D>, newDate: D) {
let start = originalRange.start;
let end = originalRange.end;
if (!start || !end) {
// Can't drag from an incomplete range.
return null;
}
const adapter = this._dateAdapter;
const isRange = adapter.compareDate(start, end) !== 0;
const diffYears = adapter.getYear(newDate) - adapter.getYear(dragOrigin);
const diffMonths = adapter.getMonth(newDate) - adapter.getMonth(dragOrigin);
const diffDays = adapter.getDate(newDate) - adapter.getDate(dragOrigin);
if (isRange && adapter.sameDate(dragOrigin, originalRange.start)) {
start = newDate;
if (adapter.compareDate(newDate, end) > 0) {
end = adapter.addCalendarYears(end, diffYears);
end = adapter.addCalendarMonths(end, diffMonths);
end = adapter.addCalendarDays(end, diffDays);
}
} else if (isRange && adapter.sameDate(dragOrigin, originalRange.end)) {
end = newDate;
if (adapter.compareDate(newDate, start) < 0) {
start = adapter.addCalendarYears(start, diffYears);
start = adapter.addCalendarMonths(start, diffMonths);
start = adapter.addCalendarDays(start, diffDays);
}
} else {
start = adapter.addCalendarYears(start, diffYears);
start = adapter.addCalendarMonths(start, diffMonths);
start = adapter.addCalendarDays(start, diffDays);
end = adapter.addCalendarYears(end, diffYears);
end = adapter.addCalendarMonths(end, diffMonths);
end = adapter.addCalendarDays(end, diffDays);
}
return new DateRange<D>(start, end);
}
}
/** @docs-private */
export function MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY(
parent: MatDateRangeSelectionStrategy<unknown>,
adapter: DateAdapter<unknown>,
) {
return parent || new DefaultMatCalendarRangeStrategy(adapter);
}
/** @docs-private */
export const MAT_CALENDAR_RANGE_STRATEGY_PROVIDER: FactoryProvider = {
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
deps: [[new Optional(), new SkipSelf(), MAT_DATE_RANGE_SELECTION_STRATEGY], DateAdapter],
useFactory: MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY,
};
| {
"end_byte": 5631,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-selection-strategy.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_0_1234 | import {FocusMonitor} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {BACKSPACE, LEFT_ARROW, RIGHT_ARROW} from '@angular/cdk/keycodes';
import {OverlayContainer} from '@angular/cdk/overlay';
import {dispatchFakeEvent, dispatchKeyboardEvent} from '@angular/cdk/testing/private';
import {Component, Directive, ElementRef, Provider, Type, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, inject, tick} from '@angular/core/testing';
import {
FormControl,
FormGroup,
FormsModule,
NG_VALIDATORS,
NgModel,
ReactiveFormsModule,
Validator,
Validators,
} from '@angular/forms';
import {ErrorStateMatcher, MatNativeDateModule} from '@angular/material/core';
import {MatFormField, MatFormFieldModule, MatLabel} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subscription} from 'rxjs';
import {MatDateRangeInput} from './date-range-input';
import {MatEndDate, MatStartDate} from './date-range-input-parts';
import {MatDateRangePicker} from './date-range-picker';
import {MatDatepickerModule} from './datepicker-module';
describe | {
"end_byte": 1234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_1234_11340 | ('MatDateRangeInput', () => {
function createComponent<T>(component: Type<T>, providers: Provider[] = []): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [
FormsModule,
MatDatepickerModule,
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
MatNativeDateModule,
component,
],
providers,
});
return TestBed.createComponent(component);
}
it('should mirror the input value from the start into the mirror element', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const mirror = fixture.nativeElement.querySelector('.mat-date-range-input-mirror');
const startInput = fixture.componentInstance.start.nativeElement;
expect(mirror.textContent).toBe('Start Date');
startInput.value = 'hello';
dispatchFakeEvent(startInput, 'input');
fixture.detectChanges();
expect(mirror.textContent).toBe('hello');
startInput.value = 'h';
dispatchFakeEvent(startInput, 'input');
fixture.detectChanges();
expect(mirror.textContent).toBe('h');
startInput.value = '';
dispatchFakeEvent(startInput, 'input');
fixture.detectChanges();
expect(mirror.textContent).toBe('Start Date');
});
it('should hide the mirror value from assistive technology', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const mirror = fixture.nativeElement.querySelector('.mat-date-range-input-mirror');
expect(mirror.getAttribute('aria-hidden')).toBe('true');
});
it('should be able to customize the separator', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const separator = fixture.nativeElement.querySelector('.mat-date-range-input-separator');
expect(separator.textContent).toBe('–');
fixture.componentInstance.separator = '/';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(separator.textContent).toBe('/');
});
it('should set the proper type on the input elements', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
expect(fixture.componentInstance.start.nativeElement.getAttribute('type')).toBe('text');
expect(fixture.componentInstance.end.nativeElement.getAttribute('type')).toBe('text');
});
it('should set the correct role on the range input', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const rangeInput = fixture.nativeElement.querySelector('.mat-date-range-input');
expect(rangeInput.getAttribute('role')).toBe('group');
});
it('should mark the entire range input as disabled if both inputs are disabled', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {rangeInput, range, start, end} = fixture.componentInstance;
expect(rangeInput.disabled).toBe(false);
expect(start.nativeElement.disabled).toBe(false);
expect(end.nativeElement.disabled).toBe(false);
range.controls.start.disable();
fixture.detectChanges();
expect(rangeInput.disabled).toBe(false);
expect(start.nativeElement.disabled).toBe(true);
expect(end.nativeElement.disabled).toBe(false);
range.controls.end.disable();
fixture.detectChanges();
expect(rangeInput.disabled).toBe(true);
expect(start.nativeElement.disabled).toBe(true);
expect(end.nativeElement.disabled).toBe(true);
});
it('should disable both inputs if the range is disabled', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
expect(start.nativeElement.disabled).toBe(false);
expect(end.nativeElement.disabled).toBe(false);
fixture.componentInstance.rangeDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(start.nativeElement.disabled).toBe(true);
expect(end.nativeElement.disabled).toBe(true);
});
it('should hide the placeholders once the start input has a value', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const hideClass = 'mat-date-range-input-hide-placeholders';
const rangeInput = fixture.nativeElement.querySelector('.mat-date-range-input');
const startInput = fixture.componentInstance.start.nativeElement;
expect(rangeInput.classList).not.toContain(hideClass);
startInput.value = 'hello';
dispatchFakeEvent(startInput, 'input');
fixture.detectChanges();
expect(rangeInput.classList).toContain(hideClass);
});
it('should point the range input aria-labelledby to the form field label', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const labelId = fixture.nativeElement.querySelector('label').id;
const rangeInput = fixture.nativeElement.querySelector('.mat-date-range-input');
expect(labelId).toBeTruthy();
expect(rangeInput.getAttribute('aria-labelledby')).toBe(labelId);
});
it('should point the range input aria-labelledby to the form field hint element', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const labelId = fixture.nativeElement.querySelector('.mat-mdc-form-field-hint').id;
const rangeInput = fixture.nativeElement.querySelector('.mat-date-range-input');
expect(labelId).toBeTruthy();
expect(rangeInput.getAttribute('aria-describedby')).toBe(labelId);
});
it('should not set aria-labelledby if the form field does not have a label', () => {
const fixture = createComponent(RangePickerNoLabel);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
expect(start.nativeElement.getAttribute('aria-labelledby')).toBeFalsy();
expect(end.nativeElement.getAttribute('aria-labelledby')).toBeFalsy();
});
it('should set aria-labelledby of the overlay to the form field label', fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const label: HTMLElement = fixture.nativeElement.querySelector('label');
expect(label).toBeTruthy();
expect(label.getAttribute('id')).toBeTruthy();
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const popup = document.querySelector('.cdk-overlay-pane .mat-datepicker-content-container')!;
expect(popup).toBeTruthy();
expect(popup.getAttribute('aria-labelledby')).toBe(label.getAttribute('id'));
}));
it('should float the form field label when either input is focused', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {rangeInput, end} = fixture.componentInstance;
let focusMonitor: FocusMonitor;
inject([FocusMonitor], (fm: FocusMonitor) => {
focusMonitor = fm;
})();
expect(rangeInput.shouldLabelFloat).toBe(false);
focusMonitor!.focusVia(end, 'keyboard');
fixture.detectChanges();
expect(rangeInput.shouldLabelFloat).toBe(true);
});
it('should float the form field label when either input has a value', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {rangeInput, end} = fixture.componentInstance;
expect(rangeInput.shouldLabelFloat).toBe(false);
end.nativeElement.value = 'hello';
dispatchFakeEvent(end.nativeElement, 'input');
fixture.detectChanges();
expect(rangeInput.shouldLabelFloat).toBe(true);
});
it('should consider the entire input as empty if both inputs are empty', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {rangeInput, end} = fixture.componentInstance;
expect(rangeInput.empty).toBe(true);
end.nativeElement.value = 'hello';
dispatchFakeEvent(end.nativeElement, 'input');
fixture.detectChanges();
expect(rangeInput.empty).toBe(false);
});
it('should mark the range controls as invalid if the start value is after the end value', fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
tick();
const {start, end} = fixture.componentInstance.range.controls;
// The default error state matcher only checks if the controls have been touched.
// Set it manually here so we can assert `rangeInput.errorState` correctly.
fixture.componentInstance.range.markAllAsTouched();
expect(fixture.componentInstance.rangeInput.errorState).toBe(false);
expect(start.errors?.['matStartDateInvalid']).toBeFalsy();
expect(end.errors?.['matEndDateInvalid']).toBeFalsy();
start.setValue(new Date(2020, 2, 2));
end.setValue(new Date(2020, 1, 2));
fixture.detectChanges();
expect(fixture.componentInstance.rangeInput.errorState).toBe(true);
expect(start.errors?.['matStartDateInvalid']).toBeTruthy();
expect(end.errors?.['matEndDateInvalid']).toBeTruthy();
end.setValue(new Date(2020, 3, 2));
fixture.detectChanges();
expect(fixture.componentInstance.rangeInput.errorState).toBe(false);
expect(start.errors?.['matStartDateInvalid']).toBeFalsy();
expect(end.errors?.['matEndDateInvalid']).toBeFalsy();
}));
it('should pass the minimum date from the range input to the inner inputs', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.minDate = new Date(2020, 3, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
expect(start.errors?.['matDatepickerMin']).toBeFalsy();
expect(end.errors?.['matDatepickerMin']).toBeFalsy();
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
expect(start.errors?.['matDatepickerMin']).toBeTruthy();
expect(end.errors?.['matDatepickerMin']).toBeTruthy();
});
| {
"end_byte": 11340,
"start_byte": 1234,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_11344_20357 | ('should pass the maximum date from the range input to the inner inputs', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.maxDate = new Date(2020, 1, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
expect(start.errors?.['matDatepickerMax']).toBeFalsy();
expect(end.errors?.['matDatepickerMax']).toBeFalsy();
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
expect(start.errors?.['matDatepickerMax']).toBeTruthy();
expect(end.errors?.['matDatepickerMax']).toBeTruthy();
});
it('should pass the date filter function from the range input to the inner inputs', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.dateFilter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
expect(start.errors?.['matDatepickerFilter']).toBeFalsy();
expect(end.errors?.['matDatepickerFilter']).toBeFalsy();
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
expect(start.errors?.['matDatepickerFilter']).toBeTruthy();
expect(end.errors?.['matDatepickerFilter']).toBeTruthy();
});
it('should should revalidate when a new date filter function is assigned', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
const spy = jasmine.createSpy('change spy');
const subscription = new Subscription();
subscription.add(start.valueChanges.subscribe(spy));
subscription.add(end.valueChanges.subscribe(spy));
fixture.componentInstance.dateFilter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(2);
fixture.componentInstance.dateFilter = () => true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(4);
subscription.unsubscribe();
});
it(
'should not dispatch the change event if a new filter function with the same result ' +
'is assigned',
() => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
const spy = jasmine.createSpy('change spy');
const subscription = new Subscription();
subscription.add(start.valueChanges.subscribe(spy));
subscription.add(end.valueChanges.subscribe(spy));
fixture.componentInstance.dateFilter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(2);
fixture.componentInstance.dateFilter = () => false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(2);
subscription.unsubscribe();
},
);
it('should throw if there is no start input', () => {
expect(() => {
const fixture = createComponent(RangePickerNoStart);
fixture.detectChanges();
}).toThrowError('mat-date-range-input must contain a matStartDate input');
});
it('should throw if there is no end input', () => {
expect(() => {
const fixture = createComponent(RangePickerNoEnd);
fixture.detectChanges();
}).toThrowError('mat-date-range-input must contain a matEndDate input');
});
it('should focus the start input when clicking on the form field', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const startInput = fixture.componentInstance.start.nativeElement;
const formFieldContainer = fixture.nativeElement.querySelector('.mat-mdc-text-field-wrapper');
spyOn(startInput, 'focus').and.callThrough();
formFieldContainer.click();
fixture.detectChanges();
expect(startInput.focus).toHaveBeenCalled();
});
it('should focus the end input when clicking on the form field when start has a value', fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
tick();
const endInput = fixture.componentInstance.end.nativeElement;
const formFieldContainer = fixture.nativeElement.querySelector('.mat-mdc-text-field-wrapper');
spyOn(endInput, 'focus').and.callThrough();
fixture.componentInstance.range.controls.start.setValue(new Date());
fixture.detectChanges();
formFieldContainer.click();
fixture.detectChanges();
tick();
expect(endInput.focus).toHaveBeenCalled();
}));
it('should revalidate if a validation field changes', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.minDate = new Date(2020, 3, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {start, end} = fixture.componentInstance.range.controls;
const date = new Date(2020, 2, 2);
start.setValue(date);
end.setValue(date);
fixture.detectChanges();
expect(start.errors?.['matDatepickerMin']).toBeTruthy();
expect(end.errors?.['matDatepickerMin']).toBeTruthy();
fixture.componentInstance.minDate = new Date(2019, 3, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(start.errors?.['matDatepickerMin']).toBeFalsy();
expect(end.errors?.['matDatepickerMin']).toBeFalsy();
});
it('should set the formatted date value as the input value', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.minDate = new Date(2020, 3, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const date = new Date(2020, 1, 2);
const {start, end, range} = fixture.componentInstance;
range.controls.start.setValue(date);
range.controls.end.setValue(date);
fixture.detectChanges();
expect(start.nativeElement.value).toBe('2/2/2020');
expect(end.nativeElement.value).toBe('2/2/2020');
});
it('should parse the value typed into an input to a date', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const expectedDate = new Date(2020, 1, 2);
const {start, end, range} = fixture.componentInstance;
start.nativeElement.value = '2/2/2020';
dispatchFakeEvent(start.nativeElement, 'input');
fixture.detectChanges();
expect(range.controls.start.value).toEqual(expectedDate);
end.nativeElement.value = '2/2/2020';
dispatchFakeEvent(end.nativeElement, 'input');
fixture.detectChanges();
expect(range.controls.end.value).toEqual(expectedDate);
});
it('should set the min and max attributes on inputs based on the values from the wrapper', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.minDate = new Date(2020, 1, 2);
fixture.componentInstance.maxDate = new Date(2020, 1, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
// Use `toContain` for the asserts here, because different browsers format the value
// differently and we only care that some kind of date value made it to the attribute.
expect(start.nativeElement.getAttribute('min')).toContain('2020');
expect(start.nativeElement.getAttribute('max')).toContain('2020');
expect(end.nativeElement.getAttribute('min')).toContain('2020');
expect(end.nativeElement.getAttribute('max')).toContain('2020');
});
it('should pass the range input value through to the calendar', fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
const {start, end} = fixture.componentInstance.range.controls;
let overlayContainerElement: HTMLElement;
start.setValue(new Date(2020, 1, 2));
end.setValue(new Date(2020, 1, 5));
inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
overlayContainerElement = overlayContainer.getContainerElement();
})();
fixture.detectChanges();
tick();
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const rangeTexts = Array.from(
overlayContainerElement!.querySelectorAll(
[
'.mat-calendar-body-range-start',
'.mat-calendar-body-in-range',
'.mat-calendar-body-range-end',
].join(','),
),
).map(cell => cell.textContent!.trim());
expect(rangeTexts).toEqual(['2', '3', '4', '5']);
}));
| {
"end_byte": 20357,
"start_byte": 11344,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_20361_28750 | ("should have aria-desciredby on start and end date cells that point to the <input/>'s accessible name", fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
const {start, end} = fixture.componentInstance.range.controls;
let overlayContainerElement: HTMLElement;
start.setValue(new Date(2020, 1, 2));
end.setValue(new Date(2020, 1, 5));
inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
overlayContainerElement = overlayContainer.getContainerElement();
})();
fixture.detectChanges();
tick();
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const rangeStart = overlayContainerElement!.querySelector('.mat-calendar-body-range-start');
const rangeEnd = overlayContainerElement!.querySelector('.mat-calendar-body-range-end');
// query for targets of `aria-describedby`. Query from document instead of fixture.nativeElement as calendar UI is rendered in an overlay.
const rangeStartDescriptions = Array.from(
document.querySelectorAll(
rangeStart!
.getAttribute('aria-describedby')!
.split(/\s+/g)
.map(x => `#${x}`)
.join(' '),
),
);
const rangeEndDescriptions = Array.from(
document.querySelectorAll(
rangeEnd!
.getAttribute('aria-describedby')!
.split(/\s+/g)
.map(x => `#${x}`)
.join(' '),
),
);
expect(rangeStartDescriptions)
.withContext('target of aria-descriedby should exist')
.not.toBeNull();
expect(rangeEndDescriptions)
.withContext('target of aria-descriedby should exist')
.not.toBeNull();
expect(
rangeStartDescriptions
.map(x => x.textContent)
.join(' ')
.trim(),
).toEqual('Start date');
expect(
rangeEndDescriptions
.map(x => x.textContent)
.join(' ')
.trim(),
).toEqual('End date');
}));
it('should pass the comparison range through to the calendar', fakeAsync(() => {
const fixture = createComponent(StandardRangePicker);
let overlayContainerElement: HTMLElement;
// Set startAt to guarantee that the calendar opens on the proper month.
fixture.componentInstance.comparisonStart = fixture.componentInstance.startAt = new Date(
2020,
1,
2,
);
fixture.componentInstance.comparisonEnd = new Date(2020, 1, 5);
fixture.changeDetectorRef.markForCheck();
inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
overlayContainerElement = overlayContainer.getContainerElement();
})();
fixture.detectChanges();
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const rangeTexts = Array.from(
overlayContainerElement!.querySelectorAll(
[
'.mat-calendar-body-comparison-start',
'.mat-calendar-body-in-comparison-range',
'.mat-calendar-body-comparison-end',
].join(','),
),
).map(cell => cell.textContent!.trim());
expect(rangeTexts).toEqual(['2', '3', '4', '5']);
}));
it('should preserve the preselected values when assigning through ngModel', fakeAsync(() => {
const start = new Date(2020, 1, 2);
const end = new Date(2020, 1, 2);
const fixture = createComponent(RangePickerNgModel);
fixture.componentInstance.start = start;
fixture.componentInstance.end = end;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(fixture.componentInstance.start).toBe(start);
expect(fixture.componentInstance.end).toBe(end);
}));
it('should preserve the values when assigning both together through ngModel', fakeAsync(() => {
const assignAndAssert = (start: Date, end: Date) => {
fixture.componentInstance.start = start;
fixture.componentInstance.end = end;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(fixture.componentInstance.start).toBe(start);
expect(fixture.componentInstance.end).toBe(end);
};
const fixture = createComponent(RangePickerNgModel);
fixture.detectChanges();
assignAndAssert(new Date(2020, 1, 2), new Date(2020, 1, 5));
assignAndAssert(new Date(2020, 2, 2), new Date(2020, 2, 5));
}));
it('should not be dirty on init when there is no value', fakeAsync(() => {
const fixture = createComponent(RangePickerNgModel);
fixture.detectChanges();
flush();
const {startModel, endModel} = fixture.componentInstance;
expect(startModel.dirty).toBe(false);
expect(startModel.touched).toBe(false);
expect(endModel.dirty).toBe(false);
expect(endModel.touched).toBe(false);
}));
it('should not be dirty on init when there is a value', fakeAsync(() => {
const fixture = createComponent(RangePickerNgModel);
fixture.componentInstance.start = new Date(2020, 1, 2);
fixture.componentInstance.end = new Date(2020, 2, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
const {startModel, endModel} = fixture.componentInstance;
expect(startModel.dirty).toBe(false);
expect(startModel.touched).toBe(false);
expect(endModel.dirty).toBe(false);
expect(endModel.touched).toBe(false);
}));
it('should mark the input as dirty once the user types in it', fakeAsync(() => {
const fixture = createComponent(RangePickerNgModel);
fixture.componentInstance.start = new Date(2020, 1, 2);
fixture.componentInstance.end = new Date(2020, 2, 2);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
const {startModel, endModel, startInput, endInput} = fixture.componentInstance;
expect(startModel.dirty).toBe(false);
expect(endModel.dirty).toBe(false);
endInput.nativeElement.value = '30/12/2020';
dispatchFakeEvent(endInput.nativeElement, 'input');
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(startModel.dirty).toBe(false);
expect(endModel.dirty).toBe(true);
startInput.nativeElement.value = '12/12/2020';
dispatchFakeEvent(startInput.nativeElement, 'input');
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(startModel.dirty).toBe(true);
expect(endModel.dirty).toBe(true);
}));
it('should mark both inputs as touched when the range picker is closed', fakeAsync(() => {
const fixture = createComponent(RangePickerNgModel);
fixture.detectChanges();
flush();
const {startModel, endModel, rangePicker} = fixture.componentInstance;
expect(startModel.dirty).toBe(false);
expect(startModel.touched).toBe(false);
expect(endModel.dirty).toBe(false);
expect(endModel.touched).toBe(false);
rangePicker.open();
fixture.detectChanges();
tick();
flush();
expect(startModel.dirty).toBe(false);
expect(startModel.touched).toBe(false);
expect(endModel.dirty).toBe(false);
expect(endModel.touched).toBe(false);
rangePicker.close();
fixture.detectChanges();
flush();
expect(startModel.dirty).toBe(false);
expect(startModel.touched).toBe(true);
expect(endModel.dirty).toBe(false);
expect(endModel.touched).toBe(true);
}));
it('should move focus to the start input when pressing backspace on an empty end input', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
spyOn(start.nativeElement, 'focus').and.callThrough();
end.nativeElement.value = '';
dispatchKeyboardEvent(end.nativeElement, 'keydown', BACKSPACE);
fixture.detectChanges();
expect(start.nativeElement.focus).toHaveBeenCalled();
});
it('should move not move focus when pressing backspace if the end input has a value', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
spyOn(start.nativeElement, 'focus').and.callThrough();
end.nativeElement.value = '10/10/2020';
dispatchKeyboardEvent(end.nativeElement, 'keydown', BACKSPACE);
fixture.detectChanges();
expect(start.nativeElement.focus).not.toHaveBeenCalled();
});
| {
"end_byte": 28750,
"start_byte": 20361,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_28754_38466 | ('moves focus between fields with arrow keys when cursor is at edge (LTR)', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
start.nativeElement.value = '09/10/2020';
end.nativeElement.value = '10/10/2020';
start.nativeElement.focus();
start.nativeElement.setSelectionRange(9, 9);
dispatchKeyboardEvent(start.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
start.nativeElement.setSelectionRange(10, 10);
dispatchKeyboardEvent(start.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
start.nativeElement.setSelectionRange(10, 10);
dispatchKeyboardEvent(start.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(end.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(0, 0);
dispatchKeyboardEvent(end.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(0, 0);
dispatchKeyboardEvent(end.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
});
it('moves focus between fields with arrow keys when cursor is at edge (RTL)', () => {
class RTL extends Directionality {
override readonly value = 'rtl';
}
const fixture = createComponent(StandardRangePicker, [
{
provide: Directionality,
useFactory: () => new RTL(null),
},
]);
fixture.detectChanges();
const {start, end} = fixture.componentInstance;
start.nativeElement.value = '09/10/2020';
end.nativeElement.value = '10/10/2020';
start.nativeElement.focus();
start.nativeElement.setSelectionRange(9, 9);
dispatchKeyboardEvent(start.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
start.nativeElement.setSelectionRange(10, 10);
dispatchKeyboardEvent(start.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
start.nativeElement.setSelectionRange(10, 10);
dispatchKeyboardEvent(start.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(1, 1);
dispatchKeyboardEvent(end.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(0, 0);
dispatchKeyboardEvent(end.nativeElement, 'keydown', LEFT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(end.nativeElement);
end.nativeElement.setSelectionRange(0, 0);
dispatchKeyboardEvent(end.nativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(start.nativeElement);
});
it('should be able to get the input placeholder', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
expect(fixture.componentInstance.rangeInput.placeholder).toBe('Start Date – End Date');
});
it('should emit to the stateChanges stream when typing a value into an input', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {start, rangeInput} = fixture.componentInstance;
const spy = jasmine.createSpy('stateChanges spy');
const subscription = rangeInput.stateChanges.subscribe(spy);
start.nativeElement.value = '10/10/2020';
dispatchFakeEvent(start.nativeElement, 'input');
fixture.detectChanges();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
it('should emit to the dateChange event only when typing in the relevant input', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {startInput, endInput, start, end} = fixture.componentInstance;
const startSpy = jasmine.createSpy('matStartDate spy');
const endSpy = jasmine.createSpy('matEndDate spy');
const startSubscription = startInput.dateChange.subscribe(startSpy);
const endSubscription = endInput.dateChange.subscribe(endSpy);
start.nativeElement.value = '10/10/2020';
dispatchFakeEvent(start.nativeElement, 'change');
fixture.detectChanges();
expect(startSpy).toHaveBeenCalledTimes(1);
expect(endSpy).not.toHaveBeenCalled();
start.nativeElement.value = '11/10/2020';
dispatchFakeEvent(start.nativeElement, 'change');
fixture.detectChanges();
expect(startSpy).toHaveBeenCalledTimes(2);
expect(endSpy).not.toHaveBeenCalled();
end.nativeElement.value = '11/10/2020';
dispatchFakeEvent(end.nativeElement, 'change');
fixture.detectChanges();
expect(startSpy).toHaveBeenCalledTimes(2);
expect(endSpy).toHaveBeenCalledTimes(1);
end.nativeElement.value = '12/10/2020';
dispatchFakeEvent(end.nativeElement, 'change');
fixture.detectChanges();
expect(startSpy).toHaveBeenCalledTimes(2);
expect(endSpy).toHaveBeenCalledTimes(2);
startSubscription.unsubscribe();
endSubscription.unsubscribe();
});
it('should emit to the dateChange event when setting the value programmatically', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const {startInput, endInput} = fixture.componentInstance;
const {start, end} = fixture.componentInstance.range.controls;
const startSpy = jasmine.createSpy('matStartDate spy');
const endSpy = jasmine.createSpy('matEndDate spy');
const startSubscription = startInput.dateChange.subscribe(startSpy);
const endSubscription = endInput.dateChange.subscribe(endSpy);
start.setValue(new Date(2020, 1, 2));
end.setValue(new Date(2020, 2, 2));
fixture.detectChanges();
expect(startSpy).not.toHaveBeenCalled();
expect(endSpy).not.toHaveBeenCalled();
start.setValue(new Date(2020, 3, 2));
end.setValue(new Date(2020, 4, 2));
fixture.detectChanges();
expect(startSpy).not.toHaveBeenCalled();
expect(endSpy).not.toHaveBeenCalled();
startSubscription.unsubscribe();
endSubscription.unsubscribe();
});
it('should not trigger validators if new date object for same date is set for `min`', () => {
const fixture = createComponent(RangePickerWithCustomValidator, [CustomValidator]);
fixture.detectChanges();
const minDate = new Date(2019, 0, 1);
const validator = fixture.componentInstance.validator;
validator.validate.calls.reset();
fixture.componentInstance.min = minDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
fixture.componentInstance.min = new Date(minDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
});
it('should not trigger validators if new date object for same date is set for `max`', () => {
const fixture = createComponent(RangePickerWithCustomValidator, [CustomValidator]);
fixture.detectChanges();
const maxDate = new Date(2120, 0, 1);
const validator = fixture.componentInstance.validator;
validator.validate.calls.reset();
fixture.componentInstance.max = maxDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
fixture.componentInstance.max = new Date(maxDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(validator.validate).toHaveBeenCalledTimes(1);
});
it('should not emit to `stateChanges` if new date object for same date is set for `min`', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const minDate = new Date(2019, 0, 1);
const spy = jasmine.createSpy('stateChanges spy');
const subscription = fixture.componentInstance.rangeInput.stateChanges.subscribe(spy);
fixture.componentInstance.minDate = minDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
fixture.componentInstance.minDate = new Date(minDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
});
it('should not emit to `stateChanges` if new date object for same date is set for `max`', () => {
const fixture = createComponent(StandardRangePicker);
fixture.detectChanges();
const maxDate = new Date(2120, 0, 1);
const spy = jasmine.createSpy('stateChanges spy');
const subscription = fixture.componentInstance.rangeInput.stateChanges.subscribe(spy);
fixture.componentInstance.maxDate = maxDate;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
fixture.componentInstance.maxDate = new Date(maxDate);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
});
| {
"end_byte": 38466,
"start_byte": 28754,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_38470_46907 | should be able to pass in a different error state matcher through an input', () => {
const fixture = createComponent(RangePickerErrorStateMatcher);
fixture.detectChanges();
const {startInput, endInput, matcher} = fixture.componentInstance;
expect(startInput.errorStateMatcher).toBe(matcher);
expect(endInput.errorStateMatcher).toBe(matcher);
});
it('should only update model for input that changed', fakeAsync(() => {
const fixture = createComponent(RangePickerNgModel);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.startDateModelChangeCount).toBe(0);
expect(fixture.componentInstance.endDateModelChangeCount).toBe(0);
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const fromDate = new Date(2020, 0, 1);
const toDate = new Date(2020, 0, 2);
fixture.componentInstance.rangePicker.select(fromDate);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.startDateModelChangeCount)
.withContext('Start Date set once')
.toBe(1);
expect(fixture.componentInstance.endDateModelChangeCount)
.withContext('End Date not set')
.toBe(0);
fixture.componentInstance.rangePicker.select(toDate);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.startDateModelChangeCount)
.withContext('Start Date unchanged (set once)')
.toBe(1);
expect(fixture.componentInstance.endDateModelChangeCount)
.withContext('End Date set once')
.toBe(1);
fixture.componentInstance.rangePicker.open();
fixture.detectChanges();
tick();
const fromDate2 = new Date(2021, 0, 1);
const toDate2 = new Date(2021, 0, 2);
fixture.componentInstance.rangePicker.select(fromDate2);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.startDateModelChangeCount)
.withContext('Start Date set twice')
.toBe(2);
expect(fixture.componentInstance.endDateModelChangeCount)
.withContext('End Date set twice (nulled)')
.toBe(2);
fixture.componentInstance.rangePicker.select(toDate2);
fixture.detectChanges();
tick();
expect(fixture.componentInstance.startDateModelChangeCount)
.withContext('Start Date unchanged (set twice)')
.toBe(2);
expect(fixture.componentInstance.endDateModelChangeCount)
.withContext('End date set three times')
.toBe(3);
}));
it('should mark the range picker as required when the entire group has the required validator', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.range = new FormGroup(
{
start: new FormControl<Date | null>(null),
end: new FormControl<Date | null>(null),
},
Validators.required,
);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.rangeInput.required).toBe(true);
});
it('should mark the range picker as required when one part is required', () => {
const fixture = createComponent(StandardRangePicker);
fixture.componentInstance.range = new FormGroup({
start: new FormControl<Date | null>(null, Validators.required),
end: new FormControl<Date | null>(null),
});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.rangeInput.required).toBe(true);
});
});
@Component({
template: `
<mat-form-field hintLabel="Pick between a start and an end">
<mat-label>Enter a date</mat-label>
<mat-date-range-input
[rangePicker]="rangePicker"
[formGroup]="range"
[disabled]="rangeDisabled"
[separator]="separator"
[min]="minDate"
[max]="maxDate"
[dateFilter]="dateFilter"
[comparisonStart]="comparisonStart"
[comparisonEnd]="comparisonEnd">
<input #start formControlName="start" matStartDate aria-label="Start date"
placeholder="Start Date"/>
<input #end formControlName="end" matEndDate aria-labelledby="end-date-label-1 end-date-label-2"
placeholder="End Date"/>
</mat-date-range-input>
<label id='end-date-label-1' class="cdk-visually-hidden">End</label>
<label id='end-date-label-2' class="cdk-visually-hidden">date</label>
<mat-date-range-picker
[startAt]="startAt"
#rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatFormField,
MatLabel,
MatDateRangePicker,
ReactiveFormsModule,
],
})
class StandardRangePicker {
@ViewChild('start') start: ElementRef<HTMLInputElement>;
@ViewChild('end') end: ElementRef<HTMLInputElement>;
@ViewChild(MatStartDate) startInput: MatStartDate<Date>;
@ViewChild(MatEndDate) endInput: MatEndDate<Date>;
@ViewChild(MatDateRangeInput) rangeInput: MatDateRangeInput<Date>;
@ViewChild(MatDateRangePicker) rangePicker: MatDateRangePicker<Date>;
separator = '–';
rangeDisabled = false;
minDate: Date | null = null;
maxDate: Date | null = null;
comparisonStart: Date | null = null;
comparisonEnd: Date | null = null;
startAt: Date | null = null;
dateFilter = () => true;
range = new FormGroup({
start: new FormControl<Date | null>(null),
end: new FormControl<Date | null>(null),
});
}
@Component({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker">
<input matEndDate/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [MatDateRangeInput, MatStartDate, MatEndDate, MatFormField, MatDateRangePicker],
})
class RangePickerNoStart {}
@Component({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker">
<input matStartDate/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [MatDateRangeInput, MatStartDate, MatEndDate, MatFormField, MatDateRangePicker],
})
class RangePickerNoEnd {}
@Component({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker">
<input matStartDate [(ngModel)]="start"/>
<input matEndDate [(ngModel)]="end"/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatFormField,
MatDateRangePicker,
FormsModule,
],
})
class RangePickerNgModel {
@ViewChild(MatStartDate, {read: NgModel}) startModel: NgModel;
@ViewChild(MatEndDate, {read: NgModel}) endModel: NgModel;
@ViewChild(MatStartDate, {read: ElementRef}) startInput: ElementRef<HTMLInputElement>;
@ViewChild(MatEndDate, {read: ElementRef}) endInput: ElementRef<HTMLInputElement>;
@ViewChild(MatDateRangePicker) rangePicker: MatDateRangePicker<Date>;
private _start: Date | null = null;
get start(): Date | null {
return this._start;
}
set start(aStart: Date | null) {
this.startDateModelChangeCount++;
this._start = aStart;
}
private _end: Date | null = null;
get end(): Date | null {
return this._end;
}
set end(anEnd: Date | null) {
this.endDateModelChangeCount++;
this._end = anEnd;
}
startDateModelChangeCount = 0;
endDateModelChangeCount = 0;
}
@Component({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker">
<input #start matStartDate/>
<input #end matEndDate/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [MatDateRangeInput, MatStartDate, MatEndDate, MatFormField, MatDateRangePicker],
})
class RangePickerNoLabel {
@ViewChild('start') start: ElementRef<HTMLInputElement>;
@ViewChild('end') end: ElementRef<HTMLInputElement>;
}
@Directive({
selector: '[customValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomValidator,
multi: true,
},
],
standalone: true,
})
class CustomValidator implements Validator {
validate = jasmine.createSpy('validate spy').and.returnValue(null);
}
@Com | {
"end_byte": 46907,
"start_byte": 38470,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/date-range-input.spec.ts_46909_48324 | nent({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker" [min]="min" [max]="max">
<input matStartDate [(ngModel)]="start" customValidator/>
<input matEndDate [(ngModel)]="end" customValidator/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatFormField,
MatDateRangePicker,
CustomValidator,
FormsModule,
],
})
class RangePickerWithCustomValidator {
@ViewChild(CustomValidator) validator: CustomValidator;
start: Date | null = null;
end: Date | null = null;
min: Date;
max: Date;
}
@Component({
template: `
<mat-form-field>
<mat-date-range-input [rangePicker]="rangePicker">
<input matStartDate [errorStateMatcher]="matcher"/>
<input matEndDate [errorStateMatcher]="matcher"/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [MatDateRangeInput, MatStartDate, MatEndDate, MatFormField, MatDateRangePicker],
})
class RangePickerErrorStateMatcher {
@ViewChild(MatStartDate) startInput: MatStartDate<Date>;
@ViewChild(MatEndDate) endInput: MatEndDate<Date>;
matcher: ErrorStateMatcher = {isErrorState: () => false};
}
| {
"end_byte": 48324,
"start_byte": 46909,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/date-range-input.spec.ts"
} |
components/src/material/datepicker/datepicker-toggle.scss_0_1014 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/datepicker' as tokens-mat-datepicker;
@use '../core/tokens/token-utils';
$_tokens: (tokens-mat-datepicker.$prefix, tokens-mat-datepicker.get-token-slots());
// We support the case where the form field is disabled, but the datepicker is not.
// MDC sets `pointer-events: none` on disabled form fields which prevents clicks on the toggle.
.mat-datepicker-toggle {
pointer-events: auto;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, toggle-icon-color);
}
}
.mat-datepicker-toggle-active {
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, toggle-active-state-icon-color);
}
}
@include cdk.high-contrast {
.mat-datepicker-toggle-default-icon {
// On Chromium-based browsers the icon doesn't appear to inherit the text color in high
// contrast mode so we have to set it explicitly. This is a no-op on IE and Firefox.
color: CanvasText;
}
}
| {
"end_byte": 1014,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/datepicker-toggle.scss"
} |
components/src/material/datepicker/testing/datepicker-input-harness.ts_0_2979 | /**
* @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, TestKey} from '@angular/cdk/testing';
import {DatepickerInputHarnessFilters, CalendarHarnessFilters} from './datepicker-harness-filters';
import {MatDatepickerInputHarnessBase, getInputPredicate} from './datepicker-input-harness-base';
import {MatCalendarHarness} from './calendar-harness';
import {
DatepickerTrigger,
closeCalendar,
getCalendarId,
getCalendar,
} from './datepicker-trigger-harness-base';
/** Harness for interacting with a standard Material datepicker inputs in tests. */
export class MatDatepickerInputHarness
extends MatDatepickerInputHarnessBase
implements DatepickerTrigger
{
static hostSelector = '.mat-datepicker-input';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDatepickerInputHarness`
* 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: DatepickerInputHarnessFilters = {},
): HarnessPredicate<MatDatepickerInputHarness> {
return getInputPredicate(MatDatepickerInputHarness, options);
}
/** Gets whether the calendar associated with the input is open. */
async isCalendarOpen(): Promise<boolean> {
// `aria-owns` is set only if there's an open datepicker so we can use it as an indicator.
const host = await this.host();
return (await host.getAttribute('aria-owns')) != null;
}
/** Opens the calendar associated with the input. */
async openCalendar(): Promise<void> {
const [isDisabled, hasCalendar] = await parallel(() => [this.isDisabled(), this.hasCalendar()]);
if (!isDisabled && hasCalendar) {
// Alt + down arrow is the combination for opening the calendar with the keyboard.
const host = await this.host();
return host.sendKeys({alt: true}, TestKey.DOWN_ARROW);
}
}
/** Closes the calendar associated with the input. */
async closeCalendar(): Promise<void> {
if (await this.isCalendarOpen()) {
await closeCalendar(getCalendarId(this.host()), this.documentRootLocatorFactory());
// This is necessary so that we wait for the closing animation to finish in touch UI mode.
await this.forceStabilize();
}
}
/** Whether a calendar is associated with the input. */
async hasCalendar(): Promise<boolean> {
return (await getCalendarId(this.host())) != null;
}
/**
* Gets the `MatCalendarHarness` that is associated with the trigger.
* @param filter Optionally filters which calendar is included.
*/
async getCalendar(filter: CalendarHarnessFilters = {}): Promise<MatCalendarHarness> {
return getCalendar(filter, this.host(), this.documentRootLocatorFactory());
}
}
| {
"end_byte": 2979,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-input-harness.ts"
} |
components/src/material/datepicker/testing/datepicker-harness-filters.ts_0_2056 | /**
* @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 datepicker input instances. */
export interface DatepickerInputHarnessFilters 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;
}
/** A set of criteria that can be used to filter a list of datepicker toggle instances. */
export interface DatepickerToggleHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of calendar instances. */
export interface CalendarHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of calendar cell instances. */
export interface CalendarCellHarnessFilters extends BaseHarnessFilters {
/** Filters based on the text of the cell. */
text?: string | RegExp;
/** Filters based on whether the cell is selected. */
selected?: boolean;
/** Filters based on whether the cell is activated using keyboard navigation */
active?: boolean;
/** Filters based on whether the cell is disabled. */
disabled?: boolean;
/** Filters based on whether the cell represents today's date. */
today?: boolean;
/** Filters based on whether the cell is inside of the main range. */
inRange?: boolean;
/** Filters based on whether the cell is inside of the comparison range. */
inComparisonRange?: boolean;
/** Filters based on whether the cell is inside of the preview range. */
inPreviewRange?: boolean;
}
/** A set of criteria that can be used to filter a list of date range input instances. */
export interface DateRangeInputHarnessFilters extends BaseHarnessFilters {
/** Filters based on the value of the input. */
value?: string | RegExp;
}
| {
"end_byte": 2056,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-harness-filters.ts"
} |
components/src/material/datepicker/testing/datepicker-input-harness-base.ts_0_3276 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate} from '@angular/cdk/testing';
import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
import {DatepickerInputHarnessFilters} from './datepicker-harness-filters';
/** Sets up the filter predicates for a datepicker input harness. */
export function getInputPredicate<T extends MatDatepickerInputHarnessBase>(
type: ComponentHarnessConstructor<T>,
options: DatepickerInputHarnessFilters,
): HarnessPredicate<T> {
return new HarnessPredicate(type, 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);
});
}
/** Base class for datepicker input harnesses. */
export abstract class MatDatepickerInputHarnessBase extends MatFormFieldControlHarness {
/** Whether the input is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Whether the input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('required');
}
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is always defined.
return await (await this.host()).getProperty<string>('value');
}
/**
* 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);
}
await inputEl.dispatchEvent('change');
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
return await (await this.host()).getProperty<string>('placeholder');
}
/**
* 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();
}
/** Gets the formatted minimum date for the input's value. */
async getMin(): Promise<string | null> {
return (await this.host()).getAttribute('min');
}
/** Gets the formatted maximum date for the input's value. */
async getMax(): Promise<string | null> {
return (await this.host()).getAttribute('max');
}
}
| {
"end_byte": 3276,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-input-harness-base.ts"
} |
components/src/material/datepicker/testing/datepicker-input-harness.spec.ts_0_8353 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {DateAdapter, MatNativeDateModule} from '@angular/material/core';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatCalendarHarness} from './calendar-harness';
import {MatDatepickerInputHarness} from './datepicker-input-harness';
describe('MatDatepickerInputHarness', () => {
let fixture: ComponentFixture<DatepickerInputHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NoopAnimationsModule,
MatNativeDateModule,
MatDatepickerModule,
FormsModule,
DatepickerInputHarnessTest,
],
});
fixture = TestBed.createComponent(DatepickerInputHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all datepicker input harnesses', async () => {
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness);
expect(inputs.length).toBe(2);
});
it('should filter inputs based on their value', async () => {
fixture.componentInstance.date = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness.with({value: /2020/}));
expect(inputs.length).toBe(1);
});
it('should filter inputs based on their placeholder', async () => {
const inputs = await loader.getAllHarnesses(
MatDatepickerInputHarness.with({
placeholder: /^Type/,
}),
);
expect(inputs.length).toBe(1);
});
it('should get whether the input has an associated calendar', async () => {
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness);
expect(await parallel(() => inputs.map(input => input.hasCalendar()))).toEqual([true, false]);
});
it('should get whether the input is disabled', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(await input.isDisabled()).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
expect(await input.isDisabled()).toBe(true);
});
it('should get whether the input is required', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(await input.isRequired()).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
expect(await input.isRequired()).toBe(true);
});
it('should get the input value', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
fixture.componentInstance.date = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('1/1/2020');
});
it('should set the input value', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(await input.getValue()).toBeFalsy();
await input.setValue('1/1/2020');
expect(await input.getValue()).toBe('1/1/2020');
});
it('should set the input value based on date adapter validation and formatting', async () => {
const adapter = fixture.debugElement.injector.get(DateAdapter);
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
const validValues: any[] = [new Date(0), '', 0, false];
const invalidValues: any[] = [null, undefined];
spyOn(adapter, 'format').and.returnValue('FORMATTED_VALUE');
spyOn(adapter, 'isValid').and.callFake(value => validValues.includes(value));
spyOn(adapter, 'deserialize').and.callFake(value =>
validValues.includes(value) ? value : null,
);
spyOn(adapter, 'getValidDateOrNull').and.callFake(value =>
adapter.isValid(value) ? value : null,
);
for (let value of validValues) {
fixture.componentInstance.date = value;
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('FORMATTED_VALUE');
}
for (let value of invalidValues) {
fixture.componentInstance.date = value;
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('');
}
});
it('should get the input placeholder', async () => {
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness);
expect(
await parallel(() =>
inputs.map(input => {
return input.getPlaceholder();
}),
),
).toEqual(['Type a date', '']);
});
it('should be able to change the input focused state', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
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 get the minimum date of the input', async () => {
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness);
fixture.componentInstance.minDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(await parallel(() => inputs.map(input => input.getMin()))).toEqual(['2020-01-01', null]);
});
it('should get the maximum date of the input', async () => {
const inputs = await loader.getAllHarnesses(MatDatepickerInputHarness);
fixture.componentInstance.maxDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(await parallel(() => inputs.map(input => input.getMax()))).toEqual(['2020-01-01', null]);
});
it('should be able to open and close a calendar in popup mode', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(await input.isCalendarOpen()).toBe(false);
await input.openCalendar();
expect(await input.isCalendarOpen()).toBe(true);
await input.closeCalendar();
expect(await input.isCalendarOpen()).toBe(false);
});
it('should be able to open and close a calendar in touch mode', async () => {
fixture.componentInstance.touchUi = true;
fixture.changeDetectorRef.markForCheck();
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(await input.isCalendarOpen()).toBe(false);
await input.openCalendar();
expect(await input.isCalendarOpen()).toBe(true);
await input.closeCalendar();
expect(await input.isCalendarOpen()).toBe(false);
});
it('should be able to get the harness for the associated calendar', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
await input.openCalendar();
expect(await input.getCalendar()).toBeInstanceOf(MatCalendarHarness);
});
it('should emit the `dateChange` event when the value is changed', async () => {
const input = await loader.getHarness(MatDatepickerInputHarness.with({selector: '#basic'}));
expect(fixture.componentInstance.dateChangeCount).toBe(0);
await input.setValue('1/1/2020');
expect(fixture.componentInstance.dateChangeCount).toBe(1);
});
});
@Component({
template: `
<input
id="basic"
matInput
[matDatepicker]="picker"
(dateChange)="dateChangeCount = dateChangeCount + 1"
[(ngModel)]="date"
[min]="minDate"
[max]="maxDate"
[disabled]="disabled"
[required]="required"
placeholder="Type a date">
<mat-datepicker #picker [touchUi]="touchUi"></mat-datepicker>
<input id="no-datepicker" matDatepicker>
`,
standalone: true,
imports: [MatNativeDateModule, MatDatepickerModule, FormsModule],
})
class DatepickerInputHarnessTest {
date: Date | null = null;
minDate: Date | null = null;
maxDate: Date | null = null;
touchUi = false;
disabled = false;
required = false;
dateChangeCount = 0;
}
| {
"end_byte": 8353,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-input-harness.spec.ts"
} |
components/src/material/datepicker/testing/datepicker-trigger-harness-base.ts_0_3926 | /**
* @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, LocatorFactory, parallel, TestElement} from '@angular/cdk/testing';
import {CalendarHarnessFilters} from './datepicker-harness-filters';
import {MatCalendarHarness} from './calendar-harness';
/** Interface for a test harness that can open and close a calendar. */
export interface DatepickerTrigger {
isCalendarOpen(): Promise<boolean>;
openCalendar(): Promise<void>;
closeCalendar(): Promise<void>;
hasCalendar(): Promise<boolean>;
getCalendar(filter?: CalendarHarnessFilters): Promise<MatCalendarHarness>;
}
/** Base class for harnesses that can trigger a calendar. */
export abstract class DatepickerTriggerHarnessBase
extends ComponentHarness
implements DatepickerTrigger
{
/** Whether the trigger is disabled. */
abstract isDisabled(): Promise<boolean>;
/** Whether the calendar associated with the trigger is open. */
abstract isCalendarOpen(): Promise<boolean>;
/** Opens the calendar associated with the trigger. */
protected abstract _openCalendar(): Promise<void>;
/** Opens the calendar if the trigger is enabled and it has a calendar. */
async openCalendar(): Promise<void> {
const [isDisabled, hasCalendar] = await parallel(() => [this.isDisabled(), this.hasCalendar()]);
if (!isDisabled && hasCalendar) {
return this._openCalendar();
}
}
/** Closes the calendar if it is open. */
async closeCalendar(): Promise<void> {
if (await this.isCalendarOpen()) {
await closeCalendar(getCalendarId(this.host()), this.documentRootLocatorFactory());
// This is necessary so that we wait for the closing animation to finish in touch UI mode.
await this.forceStabilize();
}
}
/** Gets whether there is a calendar associated with the trigger. */
async hasCalendar(): Promise<boolean> {
return (await getCalendarId(this.host())) != null;
}
/**
* Gets the `MatCalendarHarness` that is associated with the trigger.
* @param filter Optionally filters which calendar is included.
*/
async getCalendar(filter: CalendarHarnessFilters = {}): Promise<MatCalendarHarness> {
return getCalendar(filter, this.host(), this.documentRootLocatorFactory());
}
}
/** Gets the ID of the calendar that a particular test element can trigger. */
export async function getCalendarId(host: Promise<TestElement>): Promise<string | null> {
return (await host).getAttribute('data-mat-calendar');
}
/** Closes the calendar with a specific ID. */
export async function closeCalendar(
calendarId: Promise<string | null>,
documentLocator: LocatorFactory,
) {
// We close the calendar by clicking on the backdrop, even though all datepicker variants
// have the ability to close by pressing escape. The backdrop is preferrable, because the
// escape key has multiple functions inside a range picker (either cancel the current range
// or close the calendar). Since we don't have access to set the ID on the backdrop in all
// cases, we set a unique class instead which is the same as the calendar's ID and suffixed
// with `-backdrop`.
const backdropSelector = `.${await calendarId}-backdrop`;
return (await documentLocator.locatorFor(backdropSelector)()).click();
}
/** Gets the test harness for a calendar associated with a particular host. */
export async function getCalendar(
filter: CalendarHarnessFilters,
host: Promise<TestElement>,
documentLocator: LocatorFactory,
): Promise<MatCalendarHarness> {
const calendarId = await getCalendarId(host);
if (!calendarId) {
throw Error(`Element is not associated with a calendar`);
}
return documentLocator.locatorFor(
MatCalendarHarness.with({
...filter,
selector: `#${calendarId}`,
}),
)();
}
| {
"end_byte": 3926,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-trigger-harness-base.ts"
} |
components/src/material/datepicker/testing/public-api.ts_0_460 | /**
* @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 './datepicker-harness-filters';
export * from './datepicker-input-harness';
export * from './datepicker-toggle-harness';
export * from './date-range-input-harness';
export * from './calendar-harness';
export * from './calendar-cell-harness';
| {
"end_byte": 460,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/public-api.ts"
} |
components/src/material/datepicker/testing/calendar-harness.spec.ts_0_612 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatNativeDateModule} from '@angular/material/core';
import {
DateRange,
DefaultMatCalendarRangeStrategy,
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDatepickerModule,
} from '@angular/material/datepicker';
import {CalendarView, MatCalendarHarness} from './calendar-harness';
/** Date at which the calendars are set. */
const calendarDate = new Date(2020, 7, 1); | {
"end_byte": 612,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/calendar-harness.spec.ts"
} |
components/src/material/datepicker/testing/calendar-harness.spec.ts_614_8892 | describe('MatCalendarHarness', () => {
let fixture: ComponentFixture<CalendarHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatNativeDateModule, MatDatepickerModule, CalendarHarnessTest],
providers: [
{
// Usually it's the date range picker that provides the default range selection strategy,
// but since we're testing the calendar on its own, we have to provide it manually.
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useClass: DefaultMatCalendarRangeStrategy,
},
],
});
fixture = TestBed.createComponent(CalendarHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all calendar harnesses', async () => {
const calendars = await loader.getAllHarnesses(MatCalendarHarness);
expect(calendars.length).toBe(2);
});
it('should go to a different view', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
expect(await calendar.getCurrentView()).toBe(CalendarView.MONTH);
await calendar.changeView();
expect(await calendar.getCurrentView()).toBe(CalendarView.MULTI_YEAR);
});
it('should get the current view label', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
expect(await calendar.getCurrentViewLabel()).toBe('AUG 2020');
await calendar.changeView();
expect(await calendar.getCurrentViewLabel()).toBe('2016 – 2039');
});
it('should go to the next page in the view', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
expect(await calendar.getCurrentViewLabel()).toBe('AUG 2020');
await calendar.next();
expect(await calendar.getCurrentViewLabel()).toBe('SEP 2020');
});
it('should go to the previous page in the view', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
expect(await calendar.getCurrentViewLabel()).toBe('AUG 2020');
await calendar.previous();
expect(await calendar.getCurrentViewLabel()).toBe('JUL 2020');
});
it('should get all of the date cells inside the calendar', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
expect((await calendar.getCells()).length).toBe(31);
});
it('should get the text of a calendar cell', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells();
expect(await cells[0].getText()).toBe('1');
expect(await cells[15].getText()).toBe('16');
expect(await cells[30].getText()).toBe('31');
});
it('should be able to select a specific cell through the calendar', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const targetCell = (await calendar.getCells({text: '16'}))[0];
expect(await targetCell.isSelected()).toBe(false);
await calendar.selectCell({text: '16'});
expect(await targetCell.isSelected()).toBe(true);
});
it('should get the aria-label of a cell', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells();
expect(await cells[0].getAriaLabel()).toBe('August 1, 2020');
expect(await cells[15].getAriaLabel()).toBe('August 16, 2020');
expect(await cells[30].getAriaLabel()).toBe('August 31, 2020');
});
it('should get the disabled state of a cell', async () => {
fixture.componentInstance.minDate = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
20,
);
fixture.changeDetectorRef.markForCheck();
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells();
expect(await cells[0].isDisabled()).toBe(true);
expect(await cells[15].isDisabled()).toBe(true);
expect(await cells[30].isDisabled()).toBe(false);
});
it('should select a cell', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cell = (await calendar.getCells())[10];
expect(await cell.isSelected()).toBe(false);
await cell.select();
expect(await cell.isSelected()).toBe(true);
});
it('should get whether a cell is active', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells();
expect(await cells[0].isActive()).toBe(true);
expect(await cells[15].isActive()).toBe(false);
});
it('should get the state of the cell within the main range', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#range'}));
const allCells = await calendar.getCells();
const [initialStartStates, initialInRangeStates, initialEndStates] = await parallel(() => [
parallel(() => allCells.map(cell => cell.isRangeStart())),
parallel(() => allCells.map(cell => cell.isInRange())),
parallel(() => allCells.map(cell => cell.isRangeEnd())),
]);
expect(initialStartStates.every(state => state === false)).toBe(true);
expect(initialInRangeStates.every(state => state === false)).toBe(true);
expect(initialEndStates.every(state => state === false)).toBe(true);
await (await calendar.getCells({text: '5'}))[0].select();
await (await calendar.getCells({text: '8'}))[0].select();
expect(await allCells[4].isRangeStart()).toBe(true);
expect(await allCells[4].isInRange()).toBe(true);
expect(await allCells[4].isRangeEnd()).toBe(false);
expect(await allCells[5].isRangeStart()).toBe(false);
expect(await allCells[5].isInRange()).toBe(true);
expect(await allCells[5].isRangeEnd()).toBe(false);
expect(await allCells[6].isRangeStart()).toBe(false);
expect(await allCells[6].isInRange()).toBe(true);
expect(await allCells[6].isRangeEnd()).toBe(false);
expect(await allCells[7].isRangeStart()).toBe(false);
expect(await allCells[7].isInRange()).toBe(true);
expect(await allCells[7].isRangeEnd()).toBe(true);
});
it('should get the state of the cell within the comparison range', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#range'}));
const allCells = await calendar.getCells();
const [initialStartStates, initialInRangeStates, initialEndStates] = await parallel(() => [
parallel(() => allCells.map(cell => cell.isComparisonRangeStart())),
parallel(() => allCells.map(cell => cell.isInComparisonRange())),
parallel(() => allCells.map(cell => cell.isComparisonRangeEnd())),
]);
expect(initialStartStates.every(state => state === false)).toBe(true);
expect(initialInRangeStates.every(state => state === false)).toBe(true);
expect(initialEndStates.every(state => state === false)).toBe(true);
fixture.componentInstance.comparisonStart = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
5,
);
fixture.componentInstance.comparisonEnd = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
8,
);
fixture.changeDetectorRef.markForCheck();
expect(await allCells[4].isComparisonRangeStart()).toBe(true);
expect(await allCells[4].isInComparisonRange()).toBe(true);
expect(await allCells[4].isComparisonRangeEnd()).toBe(false);
expect(await allCells[5].isComparisonRangeStart()).toBe(false);
expect(await allCells[5].isInComparisonRange()).toBe(true);
expect(await allCells[5].isComparisonRangeEnd()).toBe(false);
expect(await allCells[6].isComparisonRangeStart()).toBe(false);
expect(await allCells[6].isInComparisonRange()).toBe(true);
expect(await allCells[6].isComparisonRangeEnd()).toBe(false);
expect(await allCells[7].isComparisonRangeStart()).toBe(false);
expect(await allCells[7].isInComparisonRange()).toBe(true);
expect(await allCells[7].isComparisonRangeEnd()).toBe(true);
});
| {
"end_byte": 8892,
"start_byte": 614,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/calendar-harness.spec.ts"
} |
components/src/material/datepicker/testing/calendar-harness.spec.ts_8896_14439 | ('should get the state of the cell within the preview range', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#range'}));
const allCells = await calendar.getCells();
const [initialStartStates, initialInRangeStates, initialEndStates] = await parallel(() => [
parallel(() => allCells.map(cell => cell.isPreviewRangeStart())),
parallel(() => allCells.map(cell => cell.isInPreviewRange())),
parallel(() => allCells.map(cell => cell.isPreviewRangeEnd())),
]);
expect(initialStartStates.every(state => state === false)).toBe(true);
expect(initialInRangeStates.every(state => state === false)).toBe(true);
expect(initialEndStates.every(state => state === false)).toBe(true);
await (await calendar.getCells({text: '5'}))[0].select();
await (await calendar.getCells({text: '8'}))[0].hover();
expect(await allCells[4].isPreviewRangeStart()).toBe(true);
expect(await allCells[4].isInPreviewRange()).toBe(true);
expect(await allCells[4].isPreviewRangeEnd()).toBe(false);
expect(await allCells[5].isPreviewRangeStart()).toBe(false);
expect(await allCells[5].isInPreviewRange()).toBe(true);
expect(await allCells[5].isPreviewRangeEnd()).toBe(false);
expect(await allCells[6].isPreviewRangeStart()).toBe(false);
expect(await allCells[6].isInPreviewRange()).toBe(true);
expect(await allCells[6].isPreviewRangeEnd()).toBe(false);
expect(await allCells[7].isPreviewRangeStart()).toBe(false);
expect(await allCells[7].isInPreviewRange()).toBe(true);
expect(await allCells[7].isPreviewRangeEnd()).toBe(true);
});
it('should filter cells by their text', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells({text: /^3/});
expect(await parallel(() => cells.map(cell => cell.getText()))).toEqual(['3', '30', '31']);
});
it('should filter cells by their selected state', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const allCells = await calendar.getCells();
await allCells[0].select();
const selectedCells = await calendar.getCells({selected: true});
expect(await parallel(() => selectedCells.map(cell => cell.getText()))).toEqual(['1']);
});
it('should filter cells by their active state', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells({active: true});
expect(await parallel(() => cells.map(cell => cell.getText()))).toEqual(['1']);
});
it('should filter cells by their disabled state', async () => {
fixture.componentInstance.minDate = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
3,
);
fixture.changeDetectorRef.markForCheck();
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#single'}));
const cells = await calendar.getCells({disabled: true});
expect(await parallel(() => cells.map(cell => cell.getText()))).toEqual(['1', '2']);
});
it('should filter cells based on whether they are inside the comparison range', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#range'}));
fixture.componentInstance.comparisonStart = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
5,
);
fixture.componentInstance.comparisonEnd = new Date(
calendarDate.getFullYear(),
calendarDate.getMonth(),
8,
);
fixture.changeDetectorRef.markForCheck();
const cells = await calendar.getCells({inComparisonRange: true});
expect(await parallel(() => cells.map(cell => cell.getText()))).toEqual(['5', '6', '7', '8']);
});
it('should filter cells based on whether they are inside the preview range', async () => {
const calendar = await loader.getHarness(MatCalendarHarness.with({selector: '#range'}));
await (await calendar.getCells({text: '5'}))[0].select();
await (await calendar.getCells({text: '8'}))[0].hover();
const cells = await calendar.getCells({inPreviewRange: true});
expect(await parallel(() => cells.map(cell => cell.getText()))).toEqual(['5', '6', '7', '8']);
});
});
@Component({
template: `
<mat-calendar
id="single"
[startAt]="startAt"
[minDate]="minDate"
[selected]="singleValue"
(selectedChange)="singleValue = $event"></mat-calendar>
<mat-calendar
id="range"
[startAt]="startAt"
[minDate]="minDate"
[selected]="rangeValue"
[comparisonStart]="comparisonStart"
[comparisonEnd]="comparisonEnd"
(selectedChange)="rangeChanged($event)"></mat-calendar>
`,
standalone: true,
imports: [MatNativeDateModule, MatDatepickerModule],
})
class CalendarHarnessTest {
// Start the datepickers off at a specific date so tests
// run consistently no matter what the current date is.
readonly startAt = new Date(calendarDate);
minDate: Date | null;
singleValue: Date | null = null;
rangeValue = new DateRange<Date>(null, null);
comparisonStart: Date | null = null;
comparisonEnd: Date | null = null;
rangeChanged(selectedDate: Date) {
let {start, end} = this.rangeValue;
if (start == null || end != null) {
start = selectedDate;
} else if (end == null) {
end = selectedDate;
}
this.rangeValue = new DateRange<Date>(start, end);
}
}
| {
"end_byte": 14439,
"start_byte": 8896,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/calendar-harness.spec.ts"
} |
components/src/material/datepicker/testing/calendar-cell-harness.ts_0_5692 | /**
* @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, ComponentHarness} from '@angular/cdk/testing';
import {CalendarCellHarnessFilters} from './datepicker-harness-filters';
/** Harness for interacting with a standard Material calendar cell in tests. */
export class MatCalendarCellHarness extends ComponentHarness {
static hostSelector = '.mat-calendar-body-cell';
/** Reference to the inner content element inside the cell. */
private _content = this.locatorFor('.mat-calendar-body-cell-content');
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatCalendarCellHarness`
* that meets certain criteria.
* @param options Options for filtering which cell instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: CalendarCellHarnessFilters = {}): HarnessPredicate<MatCalendarCellHarness> {
return new HarnessPredicate(MatCalendarCellHarness, options)
.addOption('text', options.text, (harness, text) => {
return HarnessPredicate.stringMatches(harness.getText(), text);
})
.addOption('selected', options.selected, async (harness, selected) => {
return (await harness.isSelected()) === selected;
})
.addOption('active', options.active, async (harness, active) => {
return (await harness.isActive()) === active;
})
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
})
.addOption('today', options.today, async (harness, today) => {
return (await harness.isToday()) === today;
})
.addOption('inRange', options.inRange, async (harness, inRange) => {
return (await harness.isInRange()) === inRange;
})
.addOption(
'inComparisonRange',
options.inComparisonRange,
async (harness, inComparisonRange) => {
return (await harness.isInComparisonRange()) === inComparisonRange;
},
)
.addOption('inPreviewRange', options.inPreviewRange, async (harness, inPreviewRange) => {
return (await harness.isInPreviewRange()) === inPreviewRange;
});
}
/** Gets the text of the calendar cell. */
async getText(): Promise<string> {
return (await this._content()).text();
}
/** Gets the aria-label of the calendar cell. */
async getAriaLabel(): Promise<string> {
// We're guaranteed for the `aria-label` to be defined
// since this is a private element that we control.
return (await this.host()).getAttribute('aria-label') as Promise<string>;
}
/** Whether the cell is selected. */
async isSelected(): Promise<boolean> {
const host = await this.host();
return (await host.getAttribute('aria-pressed')) === 'true';
}
/** Whether the cell is disabled. */
async isDisabled(): Promise<boolean> {
return this._hasState('disabled');
}
/** Whether the cell is currently activated using keyboard navigation. */
async isActive(): Promise<boolean> {
return this._hasState('active');
}
/** Whether the cell represents today's date. */
async isToday(): Promise<boolean> {
return (await this._content()).hasClass('mat-calendar-body-today');
}
/** Selects the calendar cell. Won't do anything if the cell is disabled. */
async select(): Promise<void> {
return (await this.host()).click();
}
/** Hovers over the calendar cell. */
async hover(): Promise<void> {
return (await this.host()).hover();
}
/** Moves the mouse away from the calendar cell. */
async mouseAway(): Promise<void> {
return (await this.host()).mouseAway();
}
/** Focuses the calendar cell. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Removes focus from the calendar cell. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the cell is the start of the main range. */
async isRangeStart(): Promise<boolean> {
return this._hasState('range-start');
}
/** Whether the cell is the end of the main range. */
async isRangeEnd(): Promise<boolean> {
return this._hasState('range-end');
}
/** Whether the cell is part of the main range. */
async isInRange(): Promise<boolean> {
return this._hasState('in-range');
}
/** Whether the cell is the start of the comparison range. */
async isComparisonRangeStart(): Promise<boolean> {
return this._hasState('comparison-start');
}
/** Whether the cell is the end of the comparison range. */
async isComparisonRangeEnd(): Promise<boolean> {
return this._hasState('comparison-end');
}
/** Whether the cell is inside of the comparison range. */
async isInComparisonRange(): Promise<boolean> {
return this._hasState('in-comparison-range');
}
/** Whether the cell is the start of the preview range. */
async isPreviewRangeStart(): Promise<boolean> {
return this._hasState('preview-start');
}
/** Whether the cell is the end of the preview range. */
async isPreviewRangeEnd(): Promise<boolean> {
return this._hasState('preview-end');
}
/** Whether the cell is inside of the preview range. */
async isInPreviewRange(): Promise<boolean> {
return this._hasState('in-preview');
}
/** Returns whether the cell has a particular CSS class-based state. */
private async _hasState(name: string): Promise<boolean> {
return (await this.host()).hasClass(`mat-calendar-body-${name}`);
}
}
| {
"end_byte": 5692,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/calendar-cell-harness.ts"
} |
components/src/material/datepicker/testing/BUILD.bazel_0_871 | 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/testing",
"//src/cdk/testing/testbed",
"//src/material/core",
"//src/material/datepicker",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 871,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/BUILD.bazel"
} |
components/src/material/datepicker/testing/calendar-harness.ts_0_3203 | /**
* @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, ComponentHarness} from '@angular/cdk/testing';
import {CalendarHarnessFilters, CalendarCellHarnessFilters} from './datepicker-harness-filters';
import {MatCalendarCellHarness} from './calendar-cell-harness';
/** Possible views of a `MatCalendarHarness`. */
export enum CalendarView {
MONTH,
YEAR,
MULTI_YEAR,
}
/** Harness for interacting with a standard Material calendar in tests. */
export class MatCalendarHarness extends ComponentHarness {
static hostSelector = '.mat-calendar';
/** Queries for the calendar's period toggle button. */
private _periodButton = this.locatorFor('.mat-calendar-period-button');
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatCalendarHarness`
* that meets certain criteria.
* @param options Options for filtering which calendar instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: CalendarHarnessFilters = {}): HarnessPredicate<MatCalendarHarness> {
return new HarnessPredicate(MatCalendarHarness, options);
}
/**
* Gets a list of cells inside the calendar.
* @param filter Optionally filters which cells are included.
*/
async getCells(filter: CalendarCellHarnessFilters = {}): Promise<MatCalendarCellHarness[]> {
return this.locatorForAll(MatCalendarCellHarness.with(filter))();
}
/** Gets the current view that is being shown inside the calendar. */
async getCurrentView(): Promise<CalendarView> {
if (await this.locatorForOptional('mat-multi-year-view')()) {
return CalendarView.MULTI_YEAR;
}
if (await this.locatorForOptional('mat-year-view')()) {
return CalendarView.YEAR;
}
return CalendarView.MONTH;
}
/** Gets the label of the current calendar view. */
async getCurrentViewLabel(): Promise<string> {
return (await this._periodButton()).text();
}
/** Changes the calendar view by clicking on the view toggle button. */
async changeView(): Promise<void> {
return (await this._periodButton()).click();
}
/** Goes to the next page of the current view (e.g. next month when inside the month view). */
async next(): Promise<void> {
return (await this.locatorFor('.mat-calendar-next-button')()).click();
}
/**
* Goes to the previous page of the current view
* (e.g. previous month when inside the month view).
*/
async previous(): Promise<void> {
return (await this.locatorFor('.mat-calendar-previous-button')()).click();
}
/**
* Selects a cell in the current calendar view.
* @param filter An optional filter to apply to the cells. The first cell matching the filter
* will be selected.
*/
async selectCell(filter: CalendarCellHarnessFilters = {}): Promise<void> {
const cells = await this.getCells(filter);
if (!cells.length) {
throw Error(`Cannot find calendar cell matching filter ${JSON.stringify(filter)}`);
}
await cells[0].select();
}
}
| {
"end_byte": 3203,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/calendar-harness.ts"
} |
components/src/material/datepicker/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/datepicker/testing/index.ts"
} |
components/src/material/datepicker/testing/date-range-input-harness.ts_0_5057 | /**
* @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, TestKey} from '@angular/cdk/testing';
import {MatDatepickerInputHarnessBase, getInputPredicate} from './datepicker-input-harness-base';
import {DatepickerTriggerHarnessBase} from './datepicker-trigger-harness-base';
import {
DatepickerInputHarnessFilters,
DateRangeInputHarnessFilters,
} from './datepicker-harness-filters';
/** Harness for interacting with a standard Material date range start input in tests. */
export class MatStartDateHarness extends MatDatepickerInputHarnessBase {
static hostSelector = '.mat-start-date';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatStartDateHarness`
* 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: DatepickerInputHarnessFilters = {}): HarnessPredicate<MatStartDateHarness> {
return getInputPredicate(MatStartDateHarness, options);
}
}
/** Harness for interacting with a standard Material date range end input in tests. */
export class MatEndDateHarness extends MatDatepickerInputHarnessBase {
static hostSelector = '.mat-end-date';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatEndDateHarness`
* 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: DatepickerInputHarnessFilters = {}): HarnessPredicate<MatEndDateHarness> {
return getInputPredicate(MatEndDateHarness, options);
}
}
/** Harness for interacting with a standard Material date range input in tests. */
export class MatDateRangeInputHarness extends DatepickerTriggerHarnessBase {
static hostSelector = '.mat-date-range-input';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDateRangeInputHarness`
* 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: DateRangeInputHarnessFilters = {},
): HarnessPredicate<MatDateRangeInputHarness> {
return new HarnessPredicate(MatDateRangeInputHarness, options).addOption(
'value',
options.value,
(harness, value) => HarnessPredicate.stringMatches(harness.getValue(), value),
);
}
/** Gets the combined value of the start and end inputs, including the separator. */
async getValue(): Promise<string> {
const [start, end, separator] = await parallel(() => [
this.getStartInput().then(input => input.getValue()),
this.getEndInput().then(input => input.getValue()),
this.getSeparator(),
]);
return start + `${end ? ` ${separator} ${end}` : ''}`;
}
/** Gets the inner start date input inside the range input. */
async getStartInput(): Promise<MatStartDateHarness> {
// Don't pass in filters here since the start input is required and there can only be one.
return this.locatorFor(MatStartDateHarness)();
}
/** Gets the inner start date input inside the range input. */
async getEndInput(): Promise<MatEndDateHarness> {
// Don't pass in filters here since the end input is required and there can only be one.
return this.locatorFor(MatEndDateHarness)();
}
/** Gets the separator text between the values of the two inputs. */
async getSeparator(): Promise<string> {
return (await this.locatorFor('.mat-date-range-input-separator')()).text();
}
/** Gets whether the range input is disabled. */
async isDisabled(): Promise<boolean> {
// We consider the input as disabled if both of the sub-inputs are disabled.
const [startDisabled, endDisabled] = await parallel(() => [
this.getStartInput().then(input => input.isDisabled()),
this.getEndInput().then(input => input.isDisabled()),
]);
return startDisabled && endDisabled;
}
/** Gets whether the range input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).hasClass('mat-date-range-input-required');
}
/** Opens the calendar associated with the input. */
async isCalendarOpen(): Promise<boolean> {
// `aria-owns` is set on both inputs only if there's an
// open range picker so we can use it as an indicator.
const startHost = await (await this.getStartInput()).host();
return (await startHost.getAttribute('aria-owns')) != null;
}
protected async _openCalendar(): Promise<void> {
// Alt + down arrow is the combination for opening the calendar with the keyboard.
const startHost = await (await this.getStartInput()).host();
return startHost.sendKeys({alt: true}, TestKey.DOWN_ARROW);
}
}
| {
"end_byte": 5057,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/date-range-input-harness.ts"
} |
components/src/material/datepicker/testing/datepicker-toggle-harness.ts_0_1784 | /**
* @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} from '@angular/cdk/testing';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {DatepickerToggleHarnessFilters} from './datepicker-harness-filters';
import {DatepickerTriggerHarnessBase} from './datepicker-trigger-harness-base';
/** Harness for interacting with a standard Material datepicker toggle in tests. */
export class MatDatepickerToggleHarness extends DatepickerTriggerHarnessBase {
static hostSelector = '.mat-datepicker-toggle';
/** The clickable button inside the toggle. */
private _button = this.locatorFor('button');
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatDatepickerToggleHarness` that
* meets certain criteria.
* @param options Options for filtering which datepicker toggle instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(
options: DatepickerToggleHarnessFilters = {},
): HarnessPredicate<MatDatepickerToggleHarness> {
return new HarnessPredicate(MatDatepickerToggleHarness, options);
}
/** Gets whether the calendar associated with the toggle is open. */
async isCalendarOpen(): Promise<boolean> {
return (await this.host()).hasClass('mat-datepicker-toggle-active');
}
/** Whether the toggle is disabled. */
async isDisabled(): Promise<boolean> {
const button = await this._button();
return coerceBooleanProperty(await button.getAttribute('disabled'));
}
protected async _openCalendar(): Promise<void> {
return (await this._button()).click();
}
}
| {
"end_byte": 1784,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-toggle-harness.ts"
} |
components/src/material/datepicker/testing/date-range-input-harness.spec.ts_0_735 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {MatNativeDateModule} from '@angular/material/core';
import {
MatDateRangeInput,
MatDateRangePicker,
MatDatepickerModule,
MatEndDate,
MatStartDate,
} from '@angular/material/datepicker';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatCalendarHarness} from './calendar-harness';
import {
MatDateRangeInputHarness,
MatEndDateHarness,
MatStartDateHarness,
} from './date-range-input-harness'; | {
"end_byte": 735,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/date-range-input-harness.spec.ts"
} |
components/src/material/datepicker/testing/date-range-input-harness.spec.ts_737_9004 | describe('matDateRangeInputHarness', () => {
let fixture: ComponentFixture<DateRangeInputHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NoopAnimationsModule,
MatNativeDateModule,
MatDatepickerModule,
FormsModule,
DateRangeInputHarnessTest,
],
});
fixture = TestBed.createComponent(DateRangeInputHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all date range input harnesses', async () => {
const inputs = await loader.getAllHarnesses(MatDateRangeInputHarness);
expect(inputs.length).toBe(2);
});
it('should get whether the input is disabled', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
expect(await input.isDisabled()).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
expect(await input.isDisabled()).toBe(true);
});
it('should get whether the input is required', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
expect(await input.isRequired()).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
expect(await input.isRequired()).toBe(true);
});
it('should get the input separator', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
expect(await input.getSeparator()).toBe('–');
});
it('should get the combined input value including the separator', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
fixture.componentInstance.startDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.componentInstance.endDate = new Date(2020, 1, 2, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(await input.getValue()).toBe('1/1/2020 – 2/2/2020');
});
it('should get harnesses for the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(start).toBeInstanceOf(MatStartDateHarness);
expect(end).toBeInstanceOf(MatEndDateHarness);
});
it('should be able to open and close a calendar in popup mode', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
expect(await input.isCalendarOpen()).toBe(false);
await input.openCalendar();
expect(await input.isCalendarOpen()).toBe(true);
await input.closeCalendar();
expect(await input.isCalendarOpen()).toBe(false);
});
it('should be able to open and close a calendar in touch mode', async () => {
fixture.componentInstance.touchUi = true;
fixture.changeDetectorRef.markForCheck();
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
expect(await input.isCalendarOpen()).toBe(false);
await input.openCalendar();
expect(await input.isCalendarOpen()).toBe(true);
await input.closeCalendar();
expect(await input.isCalendarOpen()).toBe(false);
});
it('should be able to get the harness for the associated calendar', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
await input.openCalendar();
expect(await input.getCalendar()).toBeInstanceOf(MatCalendarHarness);
});
it('should get whether the inner inputs are disabled', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.isDisabled(), end.isDisabled()])).toEqual([false, false]);
fixture.componentInstance.subInputsDisabled = true;
fixture.changeDetectorRef.markForCheck();
expect(await parallel(() => [start.isDisabled(), end.isDisabled()])).toEqual([true, true]);
});
it('should get whether the inner inputs are required', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.isRequired(), end.isRequired()])).toEqual([false, false]);
fixture.componentInstance.subInputsRequired = true;
fixture.changeDetectorRef.markForCheck();
expect(await parallel(() => [start.isRequired(), end.isRequired()])).toEqual([true, true]);
});
it('should get the values of the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
fixture.componentInstance.startDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.componentInstance.endDate = new Date(2020, 1, 2, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(
await parallel(() => {
return [start.getValue(), end.getValue()];
}),
).toEqual(['1/1/2020', '2/2/2020']);
});
it('should set the values of the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.getValue(), end.getValue()])).toEqual(['', '']);
await parallel(() => [start.setValue('1/1/2020'), end.setValue('2/2/2020')]);
expect(
await parallel(() => {
return [start.getValue(), end.getValue()];
}),
).toEqual(['1/1/2020', '2/2/2020']);
});
it('should get the placeholders of the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.getPlaceholder(), end.getPlaceholder()])).toEqual([
'Start date',
'End date',
]);
});
it('should be able to change the inner input focused state', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await start.isFocused()).toBe(false);
await start.focus();
expect(await start.isFocused()).toBe(true);
await start.blur();
expect(await start.isFocused()).toBe(false);
expect(await end.isFocused()).toBe(false);
await end.focus();
expect(await end.isFocused()).toBe(true);
await end.blur();
expect(await end.isFocused()).toBe(false);
});
it('should get the minimum date of the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.getMin(), end.getMin()])).toEqual([null, null]);
fixture.componentInstance.minDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(
await parallel(() => {
return [start.getMin(), end.getMin()];
}),
).toEqual(['2020-01-01', '2020-01-01']);
});
it('should get the maximum date of the inner inputs', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(await parallel(() => [start.getMax(), end.getMax()])).toEqual([null, null]);
fixture.componentInstance.maxDate = new Date(2020, 0, 1, 12, 0, 0);
fixture.changeDetectorRef.markForCheck();
expect(
await parallel(() => {
return [start.getMax(), end.getMax()];
}),
).toEqual(['2020-01-01', '2020-01-01']);
});
| {
"end_byte": 9004,
"start_byte": 737,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/date-range-input-harness.spec.ts"
} |
components/src/material/datepicker/testing/date-range-input-harness.spec.ts_9008_11076 | should dispatch the dateChange event when the inner input values have changed', async () => {
const input = await loader.getHarness(MatDateRangeInputHarness.with({selector: '[basic]'}));
const [start, end] = await parallel(() => [input.getStartInput(), input.getEndInput()]);
expect(fixture.componentInstance.startDateChangeCount).toBe(0);
expect(fixture.componentInstance.endDateChangeCount).toBe(0);
await parallel(() => [start.setValue('1/1/2020'), end.setValue('2/2/2020')]);
expect(fixture.componentInstance.startDateChangeCount).toBe(1);
expect(fixture.componentInstance.endDateChangeCount).toBe(1);
});
});
@Component({
template: `
<mat-date-range-input
basic
[disabled]="disabled"
[required]="required"
[min]="minDate"
[max]="maxDate"
[rangePicker]="picker">
<input
matStartDate
[(ngModel)]="startDate"
(dateChange)="startDateChangeCount = startDateChangeCount + 1"
[disabled]="subInputsDisabled"
[required]="subInputsRequired"
placeholder="Start date">
<input
matEndDate
[(ngModel)]="endDate"
(dateChange)="endDateChangeCount = endDateChangeCount + 1"
[disabled]="subInputsDisabled"
[required]="subInputsRequired"
placeholder="End date">
</mat-date-range-input>
<mat-date-range-picker #picker [touchUi]="touchUi"></mat-date-range-picker>
<mat-date-range-input no-range-picker>
<input matStartDate>
<input matEndDate>
</mat-date-range-input>
`,
standalone: true,
imports: [
MatNativeDateModule,
MatDateRangeInput,
MatStartDate,
MatEndDate,
MatDateRangePicker,
FormsModule,
],
})
class DateRangeInputHarnessTest {
startDate: Date | null = null;
endDate: Date | null = null;
minDate: Date | null = null;
maxDate: Date | null = null;
touchUi = false;
disabled = false;
required = false;
subInputsDisabled = false;
subInputsRequired = false;
startDateChangeCount = 0;
endDateChangeCount = 0;
}
| {
"end_byte": 11076,
"start_byte": 9008,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/date-range-input-harness.spec.ts"
} |
components/src/material/datepicker/testing/datepicker-toggle-harness.spec.ts_0_3631 | import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatNativeDateModule} from '@angular/material/core';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatCalendarHarness} from './calendar-harness';
import {MatDatepickerToggleHarness} from './datepicker-toggle-harness';
describe('MatDatepickerToggleHarness', () => {
let fixture: ComponentFixture<DatepickerToggleHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NoopAnimationsModule,
MatNativeDateModule,
MatDatepickerModule,
DatepickerToggleHarnessTest,
],
});
fixture = TestBed.createComponent(DatepickerToggleHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load all toggle harnesses', async () => {
const toggles = await loader.getAllHarnesses(MatDatepickerToggleHarness);
expect(toggles.length).toBe(2);
});
it('should get whether the toggle is disabled', async () => {
const toggle = await loader.getHarness(MatDatepickerToggleHarness.with({selector: '#basic'}));
expect(await toggle.isDisabled()).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
expect(await toggle.isDisabled()).toBe(true);
});
it('should get whether the toggle has a calendar associated with it', async () => {
const toggles = await loader.getAllHarnesses(MatDatepickerToggleHarness);
expect(
await parallel(() => {
return toggles.map(toggle => toggle.hasCalendar());
}),
).toEqual([true, false]);
});
it('should be able to open and close a calendar in popup mode', async () => {
const toggle = await loader.getHarness(MatDatepickerToggleHarness.with({selector: '#basic'}));
expect(await toggle.isCalendarOpen()).toBe(false);
await toggle.openCalendar();
expect(await toggle.isCalendarOpen()).toBe(true);
await toggle.closeCalendar();
expect(await toggle.isCalendarOpen()).toBe(false);
});
it('should be able to open and close a calendar in touch mode', async () => {
fixture.componentInstance.touchUi = true;
fixture.changeDetectorRef.markForCheck();
const toggle = await loader.getHarness(MatDatepickerToggleHarness.with({selector: '#basic'}));
expect(await toggle.isCalendarOpen()).toBe(false);
await toggle.openCalendar();
expect(await toggle.isCalendarOpen()).toBe(true);
await toggle.closeCalendar();
expect(await toggle.isCalendarOpen()).toBe(false);
});
it('should be able to get the harness for the associated calendar', async () => {
const toggle = await loader.getHarness(MatDatepickerToggleHarness.with({selector: '#basic'}));
await toggle.openCalendar();
expect(await toggle.getCalendar()).toBeInstanceOf(MatCalendarHarness);
});
});
@Component({
template: `
<input [matDatepicker]="picker">
<mat-datepicker-toggle id="basic" [for]="picker" [disabled]="disabled"></mat-datepicker-toggle>
<mat-datepicker #picker [touchUi]="touchUi"></mat-datepicker>
<mat-datepicker-toggle id="no-calendar"></mat-datepicker-toggle>
`,
standalone: true,
imports: [MatNativeDateModule, MatDatepickerModule],
})
class DatepickerToggleHarnessTest {
touchUi = false;
disabled = false;
}
| {
"end_byte": 3631,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/datepicker/testing/datepicker-toggle-harness.spec.ts"
} |
components/src/material/toolbar/_toolbar-theme.scss_0_3618 | @use 'sass:map';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/tokens/m2/mat/toolbar' as tokens-mat-toolbar;
@use '../core/tokens/token-utils';
@use '../core/style/sass-utils';
@mixin _palette-styles($theme, $palette-name) {
@include token-utils.create-token-values(
tokens-mat-toolbar.$prefix,
tokens-mat-toolbar.private-get-color-palette-color-tokens(
$background-color: inspection.get-theme-color($theme, $palette-name),
$text-color: inspection.get-theme-color($theme, $palette-name, default-contrast)
)
);
}
@mixin base($theme) {
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-toolbar.$prefix,
tokens-mat-toolbar.get-color-tokens($theme)
);
}
.mat-toolbar {
&.mat-primary {
@include _palette-styles($theme, primary);
}
&.mat-accent {
@include _palette-styles($theme, accent);
}
&.mat-warn {
@include _palette-styles($theme, warn);
}
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
// TODO(mmalerba): Stop calling this and resolve resulting screen diffs.
$theme: inspection.private-get-typography-back-compat-theme($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-toolbar.$prefix,
tokens-mat-toolbar.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-toolbar.$prefix,
tokens-mat-toolbar.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-toolbar.$prefix,
tokens: tokens-mat-toolbar.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()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-toolbar') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-toolbar.$prefix,
map.get($tokens, tokens-mat-toolbar.$prefix)
);
}
}
| {
"end_byte": 3618,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/_toolbar-theme.scss"
} |
components/src/material/toolbar/toolbar.md_0_1862 | `<mat-toolbar>` is a container for headers, titles, or actions.
<!-- example(toolbar-overview) -->
### Single row
In the simplest case, a toolbar may be placed at the top of your application and
have a single row that includes the title of your application.
<!-- example(toolbar-simple) -->
### Multiple rows
The Material Design spec used to describe toolbars with multiple rows. This can
be done by placing `<mat-toolbar-row>` elements inside a `<mat-toolbar>`.
<!-- example({"example":"toolbar-multirow",
"file":"toolbar-multirow-example.html",
"region":"toolbar-row"}) -->
**Note**: Placing content outside a `<mat-toolbar-row>` when multiple rows are specified is not
supported.
### Positioning toolbar content
The toolbar does not perform any positioning of its content. This gives the user full power to
position the content as it suits their application.
A common pattern is to position a title on the left with some actions on the right. This can be
easily accomplished with `display: flex`:
<!-- example({"example":"toolbar-multirow",
"file":"toolbar-multirow-example.html",
"region":"toolbar-position-content"}) -->
<!-- example({"example":"toolbar-multirow",
"file":"toolbar-multirow-example.css",
"region":"toolbar-position-content-style"}) -->
### Accessibility
By default, the toolbar assumes that it will be used in a purely decorative fashion and thus sets
no roles, ARIA attributes, or keyboard shortcuts. This is equivalent to having a sequence of `<div>`
elements on the page.
Generally, the toolbar is used as a header where `role="heading"` would be appropriate.
Only if the use-case of the toolbar match that of role="toolbar", the user should add the role and
an appropriate label via `aria-label` or `aria-labelledby`.
| {
"end_byte": 1862,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/toolbar/toolbar.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.