UNPKG

@angular/material

Version:
961 lines (954 loc) 180 kB
import { A11yModule } from '@angular/cdk/a11y'; import { Overlay, OverlayConfig, OverlayModule } from '@angular/cdk/overlay'; import { ComponentPortal, TemplatePortal, PortalModule } from '@angular/cdk/portal'; import { DOCUMENT, CommonModule } from '@angular/common'; import { ɵɵdefineInjectable, Injectable, EventEmitter, Component, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, NgZone, Input, Output, Optional, SkipSelf, InjectionToken, ChangeDetectorRef, Inject, ViewChild, forwardRef, Directive, ViewContainerRef, Attribute, ContentChild, InjectFlags, Injector, Self, TemplateRef, NgModule } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { CdkScrollableModule } from '@angular/cdk/scrolling'; import { DateAdapter, MAT_DATE_FORMATS, mixinColor, ErrorStateMatcher, mixinErrorState, MatCommonModule } from '@angular/material/core'; import { Subject, Subscription, merge, of } from 'rxjs'; import { ESCAPE, hasModifierKey, SPACE, ENTER, PAGE_DOWN, PAGE_UP, END, HOME, DOWN_ARROW, UP_ARROW, RIGHT_ARROW, LEFT_ARROW, BACKSPACE } from '@angular/cdk/keycodes'; import { Directionality } from '@angular/cdk/bidi'; import { take, startWith, filter } from 'rxjs/operators'; import { coerceBooleanProperty, coerceStringArray } from '@angular/cdk/coercion'; import { trigger, state, style, transition, animate } from '@angular/animations'; import { NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators, NgControl, NgForm, FormGroupDirective, ControlContainer } from '@angular/forms'; import { MatFormField, MAT_FORM_FIELD, MatFormFieldControl } from '@angular/material/form-field'; import { MAT_INPUT_VALUE_ACCESSOR } from '@angular/material/input'; /** * @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 */ /** @docs-private */ function createMissingDateImplError(provider) { return Error(`MatDatepicker: No provider found for ${provider}. You must import one of the following ` + `modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a ` + `custom implementation.`); } /** * @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 */ /** Datepicker data that requires internationalization. */ class MatDatepickerIntl { constructor() { /** * Stream that emits whenever the labels here are changed. Use this to notify * components if the labels have changed after initialization. */ this.changes = new Subject(); /** A label for the calendar popup (used by screen readers). */ this.calendarLabel = 'Calendar'; /** A label for the button used to open the calendar popup (used by screen readers). */ this.openCalendarLabel = 'Open calendar'; /** Label for the button used to close the calendar popup. */ this.closeCalendarLabel = 'Close calendar'; /** A label for the previous month button (used by screen readers). */ this.prevMonthLabel = 'Previous month'; /** A label for the next month button (used by screen readers). */ this.nextMonthLabel = 'Next month'; /** A label for the previous year button (used by screen readers). */ this.prevYearLabel = 'Previous year'; /** A label for the next year button (used by screen readers). */ this.nextYearLabel = 'Next year'; /** A label for the previous multi-year button (used by screen readers). */ this.prevMultiYearLabel = 'Previous 20 years'; /** A label for the next multi-year button (used by screen readers). */ this.nextMultiYearLabel = 'Next 20 years'; /** A label for the 'switch to month view' button (used by screen readers). */ this.switchToMonthViewLabel = 'Choose date'; /** A label for the 'switch to year view' button (used by screen readers). */ this.switchToMultiYearViewLabel = 'Choose month and year'; } /** Formats a range of years. */ formatYearRange(start, end) { return `${start} \u2013 ${end}`; } } MatDatepickerIntl.ɵprov = ɵɵdefineInjectable({ factory: function MatDatepickerIntl_Factory() { return new MatDatepickerIntl(); }, token: MatDatepickerIntl, providedIn: "root" }); MatDatepickerIntl.decorators = [ { type: Injectable, args: [{ providedIn: 'root' },] } ]; /** * @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 */ /** * An internal class that represents the data corresponding to a single calendar cell. * @docs-private */ class MatCalendarCell { constructor(value, displayValue, ariaLabel, enabled, cssClasses = {}, compareValue = value, rawValue) { this.value = value; this.displayValue = displayValue; this.ariaLabel = ariaLabel; this.enabled = enabled; this.cssClasses = cssClasses; this.compareValue = compareValue; this.rawValue = rawValue; } } /** * An internal component used to display calendar data in a table. * @docs-private */ class MatCalendarBody { constructor(_elementRef, _ngZone) { this._elementRef = _elementRef; this._ngZone = _ngZone; /** The number of columns in the table. */ this.numCols = 7; /** The cell number of the active cell in the table. */ this.activeCell = 0; /** Whether a range is being selected. */ this.isRange = 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. */ this.cellAspectRatio = 1; /** Start of the preview range. */ this.previewStart = null; /** End of the preview range. */ this.previewEnd = null; /** Emits when a new value is selected. */ this.selectedValueChange = new EventEmitter(); /** Emits when the preview has changed as a result of a user action. */ this.previewChange = new EventEmitter(); /** * Event handler for when the user enters an element * inside the calendar body (e.g. by hovering in or focus). */ this._enterHandler = (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); if (cell) { 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). */ this._leaveHandler = (event) => { // We only need to hit the zone when we're selecting a range. if (this.previewEnd !== null && this.isRange) { // 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 && isTableCell(event.target)) { this._ngZone.run(() => this.previewChange.emit({ value: null, event })); } } }; _ngZone.runOutsideAngular(() => { const element = _elementRef.nativeElement; element.addEventListener('mouseenter', this._enterHandler, true); element.addEventListener('focus', this._enterHandler, true); element.addEventListener('mouseleave', this._leaveHandler, true); element.addEventListener('blur', this._leaveHandler, true); }); } /** Called when a cell is clicked. */ _cellClicked(cell, event) { if (cell.enabled) { this.selectedValueChange.emit({ value: cell.value, event }); } } /** Returns whether a cell should be marked as selected. */ _isSelected(value) { return this.startValue === value || this.endValue === value; } ngOnChanges(changes) { 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('mouseenter', this._enterHandler, true); element.removeEventListener('focus', this._enterHandler, true); element.removeEventListener('mouseleave', this._leaveHandler, true); element.removeEventListener('blur', this._leaveHandler, true); } /** Returns whether a cell is active. */ _isActiveCell(rowIndex, colIndex) { 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. */ _focusActiveCell(movePreview = true) { this._ngZone.runOutsideAngular(() => { this._ngZone.onStable.pipe(take(1)).subscribe(() => { const activeCell = this._elementRef.nativeElement.querySelector('.mat-calendar-body-active'); if (activeCell) { if (!movePreview) { this._skipNextFocus = true; } activeCell.focus(); } }); }); } /** Gets whether a value is the start of the main range. */ _isRangeStart(value) { return isStart(value, this.startValue, this.endValue); } /** Gets whether a value is the end of the main range. */ _isRangeEnd(value) { return isEnd(value, this.startValue, this.endValue); } /** Gets whether a value is within the currently-selected range. */ _isInRange(value) { return isInRange(value, this.startValue, this.endValue, this.isRange); } /** Gets whether a value is the start of the comparison range. */ _isComparisonStart(value) { return isStart(value, this.comparisonStart, this.comparisonEnd); } /** Whether the cell is a start bridge cell between the main and comparison ranges. */ _isComparisonBridgeStart(value, rowIndex, colIndex) { if (!this._isComparisonStart(value) || this._isRangeStart(value) || !this._isInRange(value)) { return false; } let previousCell = 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, rowIndex, colIndex) { if (!this._isComparisonEnd(value) || this._isRangeEnd(value) || !this._isInRange(value)) { return false; } let nextCell = 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) { return isEnd(value, this.comparisonStart, this.comparisonEnd); } /** Gets whether a value is within the current comparison range. */ _isInComparisonRange(value) { 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) { // 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) { return isStart(value, this.previewStart, this.previewEnd); } /** Gets whether a value is the end of the preview range. */ _isPreviewEnd(value) { return isEnd(value, this.previewStart, this.previewEnd); } /** Gets whether a value is inside the preview range. */ _isInPreview(value) { return isInRange(value, this.previewStart, this.previewEnd, this.isRange); } /** Finds the MatCalendarCell that corresponds to a DOM node. */ _getCellFromElement(element) { let cell; if (isTableCell(element)) { cell = element; } else if (isTableCell(element.parentNode)) { cell = element.parentNode; } 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; } } MatCalendarBody.decorators = [ { type: Component, args: [{ selector: '[mat-calendar-body]', template: "<!--\n If there's not enough space in the first row, create a separate label row. We mark this row as\n aria-hidden because we don't want it to be read out as one of the weeks in the month.\n-->\n<tr *ngIf=\"_firstRowOffset < labelMinRequiredCells\" aria-hidden=\"true\">\n <td class=\"mat-calendar-body-label\"\n [attr.colspan]=\"numCols\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{label}}\n </td>\n</tr>\n\n<!-- Create the first row separately so we can include a special spacer cell. -->\n<tr *ngFor=\"let row of rows; let rowIndex = index\" role=\"row\">\n <!--\n We mark this cell as aria-hidden so it doesn't get read out as one of the days in the week.\n The aspect ratio of the table cells is maintained by setting the top and bottom padding as a\n percentage of the width (a variant of the trick described here:\n https://www.w3schools.com/howto/howto_css_aspect_ratio.asp).\n -->\n <td *ngIf=\"rowIndex === 0 && _firstRowOffset\"\n aria-hidden=\"true\"\n class=\"mat-calendar-body-label\"\n [attr.colspan]=\"_firstRowOffset\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{_firstRowOffset >= labelMinRequiredCells ? label : ''}}\n </td>\n <td *ngFor=\"let item of row; let colIndex = index\"\n role=\"gridcell\"\n class=\"mat-calendar-body-cell\"\n [ngClass]=\"item.cssClasses\"\n [tabindex]=\"_isActiveCell(rowIndex, colIndex) ? 0 : -1\"\n [attr.data-mat-row]=\"rowIndex\"\n [attr.data-mat-col]=\"colIndex\"\n [class.mat-calendar-body-disabled]=\"!item.enabled\"\n [class.mat-calendar-body-active]=\"_isActiveCell(rowIndex, colIndex)\"\n [class.mat-calendar-body-range-start]=\"_isRangeStart(item.compareValue)\"\n [class.mat-calendar-body-range-end]=\"_isRangeEnd(item.compareValue)\"\n [class.mat-calendar-body-in-range]=\"_isInRange(item.compareValue)\"\n [class.mat-calendar-body-comparison-bridge-start]=\"_isComparisonBridgeStart(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-bridge-end]=\"_isComparisonBridgeEnd(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-start]=\"_isComparisonStart(item.compareValue)\"\n [class.mat-calendar-body-comparison-end]=\"_isComparisonEnd(item.compareValue)\"\n [class.mat-calendar-body-in-comparison-range]=\"_isInComparisonRange(item.compareValue)\"\n [class.mat-calendar-body-preview-start]=\"_isPreviewStart(item.compareValue)\"\n [class.mat-calendar-body-preview-end]=\"_isPreviewEnd(item.compareValue)\"\n [class.mat-calendar-body-in-preview]=\"_isInPreview(item.compareValue)\"\n [attr.aria-label]=\"item.ariaLabel\"\n [attr.aria-disabled]=\"!item.enabled || null\"\n [attr.aria-selected]=\"_isSelected(item.compareValue)\"\n (click)=\"_cellClicked(item, $event)\"\n [style.width]=\"_cellWidth\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n <div class=\"mat-calendar-body-cell-content mat-focus-indicator\"\n [class.mat-calendar-body-selected]=\"_isSelected(item.compareValue)\"\n [class.mat-calendar-body-comparison-identical]=\"_isComparisonIdentical(item.compareValue)\"\n [class.mat-calendar-body-today]=\"todayValue === item.compareValue\">\n {{item.displayValue}}\n </div>\n <div class=\"mat-calendar-body-cell-preview\"></div>\n </td>\n</tr>\n", host: { 'class': 'mat-calendar-body', 'role': 'grid', 'aria-readonly': 'true' }, exportAs: 'matCalendarBody', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, styles: [".mat-calendar-body{min-width:224px}.mat-calendar-body-label{height:0;line-height:0;text-align:left;padding-left:4.7142857143%;padding-right:4.7142857143%}.mat-calendar-body-cell{position:relative;height:0;line-height:0;text-align:center;outline:none;cursor:pointer}.mat-calendar-body-cell::before,.mat-calendar-body-cell::after,.mat-calendar-body-cell-preview{content:\"\";position:absolute;top:5%;left:0;z-index:0;box-sizing:border-box;height:90%;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{left:5%;width:95%;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,[dir=rtl] .mat-calendar-body-comparison-start::after,[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{left:0;border-radius:0;border-top-right-radius:999px;border-bottom-right-radius:999px}.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{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}[dir=rtl] .mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,[dir=rtl] .mat-calendar-body-comparison-end::after,[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{left:5%;border-radius:0;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-comparison-bridge-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-bridge-end.mat-calendar-body-range-start::after{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}.mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,.mat-calendar-body-comparison-end.mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-end.mat-calendar-body-range-start::after{width:90%}.mat-calendar-body-in-preview .mat-calendar-body-cell-preview{border-top:dashed 1px;border-bottom:dashed 1px}.mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:dashed 1px}[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:0;border-right:dashed 1px}.mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:dashed 1px}[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:0;border-left:dashed 1px}.mat-calendar-body-disabled{cursor:default}.cdk-high-contrast-active .mat-calendar-body-disabled{opacity:.5}.mat-calendar-body-cell-content{top:5%;left:5%;z-index:1;display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:90%;height:90%;line-height:1;border-width:1px;border-style:solid;border-radius:999px}.mat-calendar-body-cell-content.mat-focus-indicator{position:absolute}.cdk-high-contrast-active .mat-calendar-body-cell-content{border:none}.mat-datepicker-dialog .mat-dialog-container{position:relative;overflow:visible}.cdk-high-contrast-active .mat-datepicker-popup:not(:empty),.cdk-high-contrast-active .mat-calendar-body-selected{outline:solid 1px}.cdk-high-contrast-active .mat-calendar-body-today{outline:dotted 1px}.cdk-high-contrast-active .cdk-keyboard-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected),.cdk-high-contrast-active .cdk-program-focused .mat-calendar-body-active>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){outline:dotted 2px}[dir=rtl] .mat-calendar-body-label{text-align:right}@media(hover: none){.mat-calendar-body-cell:not(.mat-calendar-body-disabled):hover>.mat-calendar-body-cell-content:not(.mat-calendar-body-selected){background-color:transparent}}\n"] },] } ]; MatCalendarBody.ctorParameters = () => [ { type: ElementRef }, { type: NgZone } ]; MatCalendarBody.propDecorators = { label: [{ type: Input }], rows: [{ type: Input }], todayValue: [{ type: Input }], startValue: [{ type: Input }], endValue: [{ type: Input }], labelMinRequiredCells: [{ type: Input }], numCols: [{ type: Input }], activeCell: [{ type: Input }], isRange: [{ type: Input }], cellAspectRatio: [{ type: Input }], comparisonStart: [{ type: Input }], comparisonEnd: [{ type: Input }], previewStart: [{ type: Input }], previewEnd: [{ type: Input }], selectedValueChange: [{ type: Output }], previewChange: [{ type: Output }] }; /** Checks whether a node is a table cell element. */ function isTableCell(node) { return node.nodeName === 'TD'; } /** Checks whether a value is the start of a range. */ function isStart(value, start, end) { return end !== null && start !== end && value < end && value === start; } /** Checks whether a value is the end of a range. */ function isEnd(value, start, end) { return start !== null && start !== end && value >= start && value === end; } /** Checks whether a value is inside of a range. */ function isInRange(value, start, end, rangeEnabled) { return rangeEnabled && start !== null && end !== null && start !== end && value >= start && value <= end; } /** * @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 */ /** A class representing a range of dates. */ class DateRange { constructor( /** The start date of the range. */ start, /** The end date of the range. */ end) { this.start = start; this.end = end; } } /** * A selection model containing a date selection. * @docs-private */ class MatDateSelectionModel { constructor( /** The current selection. */ selection, _adapter) { this.selection = selection; this._adapter = _adapter; this._selectionChanged = new Subject(); /** Emits when the selection has changed. */ this.selectionChanged = this._selectionChanged; 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, source) { this.selection = value; this._selectionChanged.next({ selection: value, source }); } ngOnDestroy() { this._selectionChanged.complete(); } _isValidDateInstance(date) { return this._adapter.isDateInstance(date) && this._adapter.isValid(date); } /** * Clones the selection model. * @deprecated To be turned into an abstract method. * @breaking-change 12.0.0 */ clone() { if (typeof ngDevMode === 'undefined' || ngDevMode) { throw Error('Not implemented'); } return null; } } MatDateSelectionModel.decorators = [ { type: Injectable } ]; MatDateSelectionModel.ctorParameters = () => [ { type: undefined }, { type: DateAdapter } ]; /** * A selection model that contains a single date. * @docs-private */ class MatSingleDateSelectionModel extends MatDateSelectionModel { constructor(adapter) { 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) { super.updateSelection(date, this); } /** Checks whether the current selection is valid. */ isValid() { 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(this._adapter); clone.updateSelection(this.selection, this); return clone; } } MatSingleDateSelectionModel.decorators = [ { type: Injectable } ]; MatSingleDateSelectionModel.ctorParameters = () => [ { type: DateAdapter } ]; /** * A selection model that contains a date range. * @docs-private */ class MatRangeDateSelectionModel extends MatDateSelectionModel { constructor(adapter) { super(new DateRange(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) { 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(start, end), this); } /** Checks whether the current selection is valid. */ isValid() { 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() { return this.selection.start != null && this.selection.end != null; } /** Clones the selection model. */ clone() { const clone = new MatRangeDateSelectionModel(this._adapter); clone.updateSelection(this.selection, this); return clone; } } MatRangeDateSelectionModel.decorators = [ { type: Injectable } ]; MatRangeDateSelectionModel.ctorParameters = () => [ { type: DateAdapter } ]; /** @docs-private */ function MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY(parent, adapter) { return parent || new MatSingleDateSelectionModel(adapter); } /** * Used to provide a single selection model to a component. * @docs-private */ const MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER = { provide: MatDateSelectionModel, deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter], useFactory: MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY, }; /** @docs-private */ function MAT_RANGE_DATE_SELECTION_MODEL_FACTORY(parent, adapter) { return parent || new MatRangeDateSelectionModel(adapter); } /** * Used to provide a range selection model to a component. * @docs-private */ const MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER = { provide: MatDateSelectionModel, deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter], useFactory: MAT_RANGE_DATE_SELECTION_MODEL_FACTORY, }; /** * @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 */ /** Injection token used to customize the date range selection behavior. */ const MAT_DATE_RANGE_SELECTION_STRATEGY = new InjectionToken('MAT_DATE_RANGE_SELECTION_STRATEGY'); /** Provides the default date range selection behavior. */ class DefaultMatCalendarRangeStrategy { constructor(_dateAdapter) { this._dateAdapter = _dateAdapter; } selectionFinished(date, currentRange) { 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(start, end); } createPreview(activeDate, currentRange) { let start = null; let end = null; if (currentRange.start && !currentRange.end && activeDate) { start = currentRange.start; end = activeDate; } return new DateRange(start, end); } } DefaultMatCalendarRangeStrategy.decorators = [ { type: Injectable } ]; DefaultMatCalendarRangeStrategy.ctorParameters = () => [ { type: DateAdapter } ]; /** @docs-private */ function MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY(parent, adapter) { return parent || new DefaultMatCalendarRangeStrategy(adapter); } /** @docs-private */ const MAT_CALENDAR_RANGE_STRATEGY_PROVIDER = { provide: MAT_DATE_RANGE_SELECTION_STRATEGY, deps: [[new Optional(), new SkipSelf(), MAT_DATE_RANGE_SELECTION_STRATEGY], DateAdapter], useFactory: MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY, }; /** * @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 */ const DAYS_PER_WEEK = 7; /** * An internal component used to display a single month in the datepicker. * @docs-private */ class MatMonthView { constructor(_changeDetectorRef, _dateFormats, _dateAdapter, _dir, _rangeStrategy) { this._changeDetectorRef = _changeDetectorRef; this._dateFormats = _dateFormats; this._dateAdapter = _dateAdapter; this._dir = _dir; this._rangeStrategy = _rangeStrategy; this._rerenderSubscription = Subscription.EMPTY; /** Emits when a new date is selected. */ this.selectedChange = new EventEmitter(); /** Emits when any date is selected. */ this._userSelection = new EventEmitter(); /** Emits when any date is activated. */ this.activeDateChange = new EventEmitter(); if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._dateAdapter) { throw createMissingDateImplError('DateAdapter'); } if (!this._dateFormats) { throw createMissingDateImplError('MAT_DATE_FORMATS'); } } this._activeDate = this._dateAdapter.today(); } /** * The date to display in this month view (everything other than the month and year is ignored). */ get activeDate() { return this._activeDate; } set activeDate(value) { const oldActiveDate = this._activeDate; const validDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)) || this._dateAdapter.today(); this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate); if (!this._hasSameMonthAndYear(oldActiveDate, this._activeDate)) { this._init(); } } /** The currently selected date. */ get selected() { return this._selected; } set selected(value) { if (value instanceof DateRange) { this._selected = value; } else { this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); } this._setRanges(this._selected); } /** The minimum selectable date. */ get minDate() { return this._minDate; } set minDate(value) { this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** The maximum selectable date. */ get maxDate() { return this._maxDate; } set maxDate(value) { this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); } ngAfterContentInit() { this._rerenderSubscription = this._dateAdapter.localeChanges .pipe(startWith(null)) .subscribe(() => this._init()); } ngOnChanges(changes) { const comparisonChange = changes['comparisonStart'] || changes['comparisonEnd']; if (comparisonChange && !comparisonChange.firstChange) { this._setRanges(this.selected); } } ngOnDestroy() { this._rerenderSubscription.unsubscribe(); } /** Handles when a new date is selected. */ _dateSelected(event) { const date = event.value; const selectedYear = this._dateAdapter.getYear(this.activeDate); const selectedMonth = this._dateAdapter.getMonth(this.activeDate); const selectedDate = this._dateAdapter.createDate(selectedYear, selectedMonth, date); let rangeStartDate; let rangeEndDate; if (this._selected instanceof DateRange) { rangeStartDate = this._getDateInCurrentMonth(this._selected.start); rangeEndDate = this._getDateInCurrentMonth(this._selected.end); } else { rangeStartDate = rangeEndDate = this._getDateInCurrentMonth(this._selected); } if (rangeStartDate !== date || rangeEndDate !== date) { this.selectedChange.emit(selectedDate); } this._userSelection.emit({ value: selectedDate, event: event.event }); this._previewStart = this._previewEnd = null; this._changeDetectorRef.markForCheck(); } /** Handles keydown events on the calendar body when calendar is in month view. */ _handleCalendarBodyKeydown(event) { // TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent // disabled ones from being selected. This may not be ideal, we should look into whether // navigation should skip over disabled dates, and if so, how to implement that efficiently. const oldActiveDate = this._activeDate; const isRtl = this._isRtl(); switch (event.keyCode) { case LEFT_ARROW: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? 1 : -1); break; case RIGHT_ARROW: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? -1 : 1); break; case UP_ARROW: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, -7); break; case DOWN_ARROW: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 7); break; case HOME: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 1 - this._dateAdapter.getDate(this._activeDate)); break; case END: this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, (this._dateAdapter.getNumDaysInMonth(this._activeDate) - this._dateAdapter.getDate(this._activeDate))); break; case PAGE_UP: this.activeDate = event.altKey ? this._dateAdapter.addCalendarYears(this._activeDate, -1) : this._dateAdapter.addCalendarMonths(this._activeDate, -1); break; case PAGE_DOWN: this.activeDate = event.altKey ? this._dateAdapter.addCalendarYears(this._activeDate, 1) : this._dateAdapter.addCalendarMonths(this._activeDate, 1); break; case ENTER: case SPACE: if (!this.dateFilter || this.dateFilter(this._activeDate)) { this._dateSelected({ value: this._dateAdapter.getDate(this._activeDate), event }); // Prevent unexpected default actions such as form submission. event.preventDefault(); } return; case ESCAPE: // Abort the current range selection if the user presses escape mid-selection. if (this._previewEnd != null && !hasModifierKey(event)) { this._previewStart = this._previewEnd = null; this.selectedChange.emit(null); this._userSelection.emit({ value: null, event }); event.preventDefault(); event.stopPropagation(); // Prevents the overlay from closing. } return; default: // Don't prevent default or focus active cell on keys that we don't explicitly handle. return; } if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) { this.activeDateChange.emit(this.activeDate); } this._focusActiveCell(); // Prevent unexpected default actions such as form submission. event.preventDefault(); } /** Initializes this month view. */ _init() { this._setRanges(this.selected); this._todayDate = this._getCellCompareValue(this._dateAdapter.today()); this._monthLabel = this._dateFormats.display.monthLabel ? this._dateAdapter.format(this.activeDate, this._dateFormats.display.monthLabel) : this._dateAdapter.getMonthNames('short')[this._dateAdapter.getMonth(this.activeDate)] .toLocaleUpperCase(); let firstOfMonth = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), 1); this._firstWeekOffset = (DAYS_PER_WEEK + this._dateAdapter.getDayOfWeek(firstOfMonth) - this._dateAdapter.getFirstDayOfWeek()) % DAYS_PER_WEEK; this._initWeekdays(); this._createWeekCells(); this._changeDetectorRef.markForCheck(); } /** Focuses the active cell after the microtask queue is empty. */ _focusActiveCell(movePreview) { this._matCalendarBody._focusActiveCell(movePreview); } /** Called when the user has activated a new cell and the preview needs to be updated. */ _previewChanged({ event, value: cell }) { if (this._rangeStrategy) { // We can assume that this will be a range, because preview // events aren't fired for single date selections. const value = cell ? cell.rawValue : null; const previewRange = this._rangeStrategy.createPreview(value, this.selected, event); this._previewStart = this._getCellCompareValue(previewRange.start); this._previewEnd = this._getCellCompareValue(previewRange.end); // Note that here we need to use `detectChanges`, rather than `markForCheck`, because // the way `_focusActiveCell` is set up at the moment makes it fire at the wrong time // when navigating one month back using the keyboard which will cause this handler // to throw a "changed after checked" error when updating the preview state. this._changeDetectorRef.detectChanges(); } } /** Initializes the weekdays. */ _initWeekdays() { const firstDayOfWeek = this._dateAdapter.getFirstDayOfWeek(); const narrowWeekdays = this._dateAdapter.getDayOfWeekNames('narrow'); const longWeekdays = this._dateAdapter.getDayOfWeekNames('long'); // Rotate the labels for days of the week based on the configured first day of the week. let weekdays = longWeekdays.map((long, i) => { return { long, narrow: narrowWeekdays[i] }; }); this._weekdays = weekdays.slice(firstDayOfWeek).concat(weekdays.slice(0, firstDayOfWeek)); } /** Creates MatCalendarCells for the dates in this month. */ _createWeekCells() { const daysInMonth = this._dateAdapter.getNumDaysInMonth(this.activeDate); const dateNames = this._dateAdapter.getDateNames(); this._weeks = [[]]; for (let i = 0, cell = this._firstWeekOffset; i < daysInMonth; i++, cell++) { if (cell == DAYS_PER_WEEK) { this._weeks.push([]); cell = 0; } const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), i + 1); const enabled = this._shouldEnableDate(date); const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.dateA11yLabel); const cellClasses = this.dateClass ? this.dateClass(date, 'month') : undefined; this._weeks[this._weeks.length - 1].push(new MatCalendarCell(i + 1, dateNames[i], ariaLabel, enabled, cellClasses, this._getCellCompareValue(date), date)); } } /** Date filter for the month */ _shouldEnableDate(date) { return !!date && (!this.minDate || this._dateAdapter.compareDate(date, this.minDate) >= 0) && (!this.maxDate || this._dateAdapter.compareDate(date, this.maxDate) <= 0) && (!this.dateFilter || this.dateFilter(date)); } /** * Gets the date in this month that the given Date falls on. * Returns null if the given Date is in another month. */ _getDateInCurrentMonth(date) { return date && this._hasSameMonthAndYear(date, this.activeDate) ? this._dateAdapter.getDate(date) : null; } /** Checks whether the 2 dates are non-null and fall within the same month of the same year. */ _hasSameMonthAndYear(d1, d2) { return !!(d1 && d2 && this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) && this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2)); } /** Gets the value that will be used to one cell to another. */ _getCellCompareValue(date) { if (date) { // We use the time since the Unix epoch to compare dates in this view, rather than the // cell values, because we need to support ranges that span across multiple months/years. const year = this._dateAdapter.getYear(date); const month = this._dateAdapter.getMonth(date); const day = this._dateAdapter.getDate(date); return new Date(year, month, day).getTime(); } return null; } /** Determines whether the user has the RTL layout direction. */ _isRtl() { return this._dir && this._dir.value === 'rtl'; } /** Sets the current range based on a model value. */ _setRanges(selectedValue) { if (selectedValue instanceof DateRange) { this._rangeStart = this._getCellCompareValue(selectedValue.start); this._rangeEnd = this._getCellCompareValue(selectedValue.end); this._isRange = true; } else { this._rangeStart = this._rangeEnd = this._getCellCompareValue(selectedValue); this._isRange = false; } this._comparisonRangeStart = this._getCellCompareValue(this.comparisonStart); this._comparisonRangeEnd = this._getCellCompareValue(this.comparisonEnd); } } MatMonthView.decorators = [ { type: Component, args: [{ selector: 'mat-month-view', template: "<table class=\"mat-calendar-table\" role=\"presentation\">\n <thead class=\"mat-calendar-table-header\">\n <tr>\n <th scope=\"col\" *ngFor=\"let day of _weekdays\" [attr.aria-label]=\"day.long\">{{day.narrow}}</th>\n </tr>\n <tr><th class=\"mat-calendar-table-header-divider\" colspan=\"7\" aria-hidden=\"true\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [label]=\"_monthLabel\"\n [rows]=\"_weeks\"\n [todayValue]=\"_todayDate!\"\n [startValue]=\"_rangeStart!\"\n [endValue]=\"_rangeEnd!\"\n [comparisonStart]=\"_comparisonRangeStart\"\n [comparisonEnd]=\"_comparisonRangeEnd\"\n [previewStart]=\"_previewStart\"\n [previewEnd]=\"_previewEnd\"\n [isRange]=\"_isRange\"\n [labelMinRequiredCells]=\"3\"\n [activeCell]=\"_dateAdapter.getDate(activeDate) - 1\"\n (selectedValueChange)=\"_dateSelected($event)\"\n (previewChange)=\"_previewChanged($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n", exportAs: 'matMonthView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush },] } ]; MatMonthView.ctorParameters = () => [ { type: ChangeDetectorRef }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS,] }] }, { type: DateAdapter, decorators: [{ type: Optional }] }, { type: Directionality, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Inject, args: [MAT_DATE_RANGE_SELECTION_STRATEGY,] }, { type: Optional }] } ]; MatMonthView.propDecorators = { activeDate: [{ type: Input }], selected: [{ type: Input }], minDate: [{ type: Input }], maxDate: [{ type: Input }], dateFilter: [{ type: Input }], dateClass: [{ type: Input }], comparisonStart: [{ type: Input }], comparisonEnd: [{ type: Input }], selectedChange: [{ type: Output }], _userSelection: [{ type: Output }], activeDateChange: [{ type: Output }], _matCalendarBody: [{ type: ViewChild, args: [MatCalendarBody,] }] }; /** * @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 */ const yearsPerPage = 24; const yearsPerRow = 4; /** * An internal component used to display a year selector in the datepicker. * @docs-private */ class MatMultiYearView { constructor(_changeDetectorRef, _dateAdapter, _dir) { this._changeDetectorRef = _changeDetectorRef; this._dateAdapter = _dateAdapter; this._dir = _dir; this._rerenderSubscription = Subscription.EMPTY; /** Emits when a new year is selected. */ this.selectedChange = new Eve