Skip to content

refactor(datepicker): implement date selection model provider #18090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions src/material/core/datetime/date-selection-model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* @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.io/license
*/

import {FactoryProvider, Injectable, Optional, SkipSelf, OnDestroy} from '@angular/core';
import {DateAdapter} from './date-adapter';
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) {}
}

type ExtractDateTypeFromSelection<T> = T extends DateRange<infer D> ? D : NonNullable<T>;

/** Event emitted by the date selection model when its selection changes. */
export interface DateSelectionModelChange<S> {
/** New value for the selection. */
selection: S;

/** Object that triggered the change. */
source: unknown;
}

/** A selection model containing a date selection. */
export abstract class MatDateSelectionModel<S, D = ExtractDateTypeFromSelection<S>>
implements OnDestroy {
private _selectionChanged = new Subject<DateSelectionModelChange<S>>();

/** Emits when the selection has changed. */
selectionChanged: Observable<DateSelectionModelChange<S>> = this._selectionChanged.asObservable();

protected constructor(
/** Date adapter used when interacting with dates in the model. */
protected readonly adapter: DateAdapter<D>,
/** The current selection. */
readonly selection: S) {
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) {
(this as {selection: S}).selection = value;
this._selectionChanged.next({selection: value, source});
}

ngOnDestroy() {
this._selectionChanged.complete();
}

/** Adds a date to the current selection. */
abstract add(date: D | null): void;

/** Checks whether the current selection is complete. */
abstract isComplete(): boolean;

/** Checks whether the current selection is identical to the passed-in selection. */
abstract isSame(other: S): boolean;

/** Checks whether the current selection is valid. */
abstract isValid(): boolean;

/** Checks whether the current selection overlaps with the given range. */
abstract overlaps(range: DateRange<D>): boolean;
}

/** A selection model that contains a single date. */
@Injectable()
export class MatSingleDateSelectionModel<D> extends MatDateSelectionModel<D | null, D> {
constructor(adapter: DateAdapter<D>) {
super(adapter, null);
}

/**
* 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 complete. In the case of a single date selection, this
* is true if the current selection is not null.
*/
isComplete() { return this.selection != null; }

/** Checks whether the current selection is identical to the passed-in selection. */
isSame(other: D): boolean {
return this.adapter.sameDate(other, this.selection);
}

/**
* Checks whether the current selection is valid. In the case of a single date selection, this
* means that the current selection is not null and is a valid date.
*/
isValid(): boolean {
return this.selection != null && this.adapter.isDateInstance(this.selection) &&
this.adapter.isValid(this.selection);
}

/** Checks whether the current selection overlaps with the given range. */
overlaps(range: DateRange<D>): boolean {
return !!(this.selection && range.start && range.end &&
this.adapter.compareDate(range.start, this.selection) <= 0 &&
this.adapter.compareDate(this.selection, range.end) <= 0);
}
}

/** A selection model that contains a date range. */
@Injectable()
export class MatRangeDateSelectionModel<D> extends MatDateSelectionModel<DateRange<D>, D> {
constructor(adapter: DateAdapter<D>) {
super(adapter, new DateRange<D>(null, null));
}

/**
* 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 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;
}

/** Checks whether the current selection is identical to the passed-in selection. */
isSame(other: DateRange<D>): boolean {
return this.adapter.sameDate(this.selection.start, other.start) &&
this.adapter.sameDate(this.selection.end, other.end);
}

/**
* Checks whether the current selection is valid. In the case of a date range selection, this
* means that the current selection has a `start` and `end` that are both non-null and valid
* dates.
*/
isValid(): boolean {
return this.selection.start != null && this.selection.end != null &&
this.adapter.isValid(this.selection.start!) && this.adapter.isValid(this.selection.end!);
}

/**
* Returns true if the given range and the selection overlap in any way. False if otherwise, that
* includes incomplete selections or ranges.
*/
overlaps(range: DateRange<D>): boolean {
if (!(this.selection.start && this.selection.end && range.start && range.end)) {
return false;
}

return (
this._isBetween(range.start, this.selection.start, this.selection.end) ||
this._isBetween(range.end, this.selection.start, this.selection.end) ||
(
this.adapter.compareDate(range.start, this.selection.start) <= 0 &&
this.adapter.compareDate(this.selection.end, range.end) <= 0
)
);
}

private _isBetween(value: D, from: D, to: D): boolean {
return this.adapter.compareDate(from, value) <= 0 && this.adapter.compareDate(value, to) <= 0;
}
}

/** @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. */
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,
};
1 change: 1 addition & 0 deletions src/material/core/datetime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export * from './date-adapter';
export * from './date-formats';
export * from './native-date-adapter';
export * from './native-date-formats';
export * from './date-selection-model';


@NgModule({
Expand Down
36 changes: 27 additions & 9 deletions src/material/datepicker/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@ import {
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {
DateAdapter,
MAT_DATE_FORMATS,
MatDateFormats,
MatDateSelectionModel,
MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER,
} from '@angular/material/core';
import {Subject, Subscription} from 'rxjs';
import {MatCalendarCellCssClasses} from './calendar-body';
import {createMissingDateImplError} from './datepicker-errors';
Expand Down Expand Up @@ -179,6 +185,7 @@ export class MatCalendarHeader<D> {
exportAs: 'matCalendar',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER]
})
export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDestroy, OnChanges {
/** An input indicating the type of the header component, if set. */
Expand All @@ -188,6 +195,7 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
_calendarHeaderPortal: Portal<any>;

private _intlChanges: Subscription;
private _selectedChanges: Subscription;

/**
* Used for scheduling that focus should be moved to the active cell on the next tick.
Expand All @@ -209,11 +217,11 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes

/** The currently selected date. */
@Input()
get selected(): D | null { return this._selected; }
get selected(): D | null { return this._model.selection; }
set selected(value: D | null) {
this._selected = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
const newValue = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
this._model.updateSelection(newValue, this);
}
private _selected: D | null;

/** The minimum selectable date. */
@Input()
Expand All @@ -237,7 +245,10 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
/** Function that can be used to add custom CSS classes to dates. */
@Input() dateClass: (date: D) => MatCalendarCellCssClasses;

/** Emits when the currently selected date changes. */
/**
* Emits when the currently selected date changes.
* @breaking-change 11.0.0 Emitted value to change to `D | null`.
*/
@Output() readonly selectedChange: EventEmitter<D> = new EventEmitter<D>();

/**
Expand Down Expand Up @@ -293,7 +304,8 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
constructor(_intl: MatDatepickerIntl,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
private _changeDetectorRef: ChangeDetectorRef) {
private _changeDetectorRef: ChangeDetectorRef,
private _model: MatDateSelectionModel<D | null, D>) {

if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
Expand All @@ -307,6 +319,13 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
_changeDetectorRef.markForCheck();
this.stateChanges.next();
});

this._selectedChanges = _model.selectionChanged.subscribe(event => {
// @breaking-change 11.0.0 Remove null check once `event.selection` is allowed to be null.
if (event.selection) {
this.selectedChange.emit(event.selection);
}
});
}

ngAfterContentInit() {
Expand All @@ -325,6 +344,7 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes
}

ngOnDestroy() {
this._selectedChanges.unsubscribe();
this._intlChanges.unsubscribe();
this.stateChanges.complete();
}
Expand Down Expand Up @@ -361,9 +381,7 @@ export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDes

/** Handles date selection in the month view. */
_dateSelected(date: D | null): void {
if (date && !this._dateAdapter.sameDate(date, this.selected)) {
this.selectedChange.emit(date);
}
this._model.add(date);
}

/** Handles year selection in the multiyear view. */
Expand Down
2 changes: 0 additions & 2 deletions src/material/datepicker/datepicker-content.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
[maxDate]="datepicker._maxDate"
[dateFilter]="datepicker._dateFilter"
[headerComponent]="datepicker.calendarHeaderComponent"
[selected]="datepicker._selected"
[dateClass]="datepicker.dateClass"
[@fadeInCalendar]="'enter'"
(selectedChange)="datepicker.select($event)"
(yearSelected)="datepicker._selectYear($event)"
(monthSelected)="datepicker._selectMonth($event)"
(_userSelection)="datepicker.close()">
Expand Down
Loading