import * as i5 from '@angular/cdk/a11y'; import { A11yModule } from '@angular/cdk/a11y'; import * as i9 from '@angular/cdk/overlay'; import { Overlay, FlexibleConnectedPositionStrategy, OverlayConfig, OverlayModule } from '@angular/cdk/overlay'; import * as i6 from '@angular/cdk/portal'; import { ComponentPortal, TemplatePortal, PortalModule } from '@angular/cdk/portal'; import * as i1 from '@angular/common'; import { DOCUMENT, CommonModule } from '@angular/common'; import * as i0 from '@angular/core'; import { Injectable, inject, EventEmitter, Component, ViewEncapsulation, ChangeDetectionStrategy, Input, Output, Optional, SkipSelf, InjectionToken, Inject, ViewChild, forwardRef, Directive, Attribute, ContentChild, Self, TemplateRef, NgModule } from '@angular/core'; import * as i3 from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button'; import { CdkScrollableModule } from '@angular/cdk/scrolling'; import * as i1$1 from '@angular/material/core'; import { DateAdapter, MAT_DATE_FORMATS, mixinColor, 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 * as i2 from '@angular/cdk/bidi'; import { Directionality } from '@angular/cdk/bidi'; import { normalizePassiveListenerOptions, Platform, _getFocusedElementPierceShadowDom } from '@angular/cdk/platform'; import { take, startWith, filter } from 'rxjs/operators'; import { coerceBooleanProperty, coerceStringArray } from '@angular/cdk/coercion'; import { trigger, transition, animate, keyframes, style, state } from '@angular/animations'; import * as i2$1 from '@angular/forms'; import { NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators, NgControl } from '@angular/forms'; import { MAT_FORM_FIELD, MatFormFieldControl } from '@angular/material/form-field'; import { MAT_INPUT_VALUE_ACCESSOR } from '@angular/material/input'; /** @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.`); } /** 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 24 years'; /** A label for the next multi-year button (used by screen readers). */ this.nextMultiYearLabel = 'Next 24 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'; /** * 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 */ this.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 */ this.endDateLabel = 'End date'; } /** Formats a range of years (used for visuals). */ formatYearRange(start, end) { return `${start} \u2013 ${end}`; } /** Formats a label for a range of years (used by screen readers). */ formatYearRangeLabel(start, end) { return `${start} to ${end}`; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }] }); /** * 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; } } 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 */ class MatCalendarBody { ngAfterViewChecked() { if (this._focusActiveCellAfterViewChecked) { this._focusActiveCell(); this._focusActiveCellAfterViewChecked = false; } } constructor(_elementRef, _ngZone) { this._elementRef = _elementRef; this._ngZone = _ngZone; this._platform = inject(Platform); /** * Used to focus the active cell after change detection has run. */ this._focusActiveCellAfterViewChecked = false; /** 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(); this.activeDateChange = new EventEmitter(); /** Emits the date at the possible start of a drag event. */ this.dragStarted = new EventEmitter(); /** Emits the date at the conclusion of a drag, or null if mouse was not released on a date. */ this.dragEnded = new EventEmitter(); this._didDragSinceMouseDown = false; /** * 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 })); } } }; this._touchmoveHandler = (event) => { if (!this.isRange) return; const target = getActualTouchTarget(event); const cell = target ? this._getCellFromElement(target) : 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)) { 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). */ this._leaveHandler = (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) && !(event.relatedTarget && this._getCellFromElement(event.relatedTarget))) { this._ngZone.run(() => this.previewChange.emit({ value: null, event })); } } }; /** * Triggered on mousedown or touchstart on a date cell. * Respsonsible for starting a drag sequence. */ this._mousedownHandler = (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); if (!cell || !this._isInRange(cell.rawValue)) { return; } this._ngZone.run(() => { this.dragStarted.emit({ value: cell.rawValue, event, }); }); }; /** Triggered on mouseup anywhere. Respsonsible for ending a drag sequence. */ this._mouseupHandler = (event) => { if (!this.isRange) return; const cellElement = getCellElement(event.target); 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. */ this._touchendHandler = (event) => { const target = getActualTouchTarget(event); if (target) { this._mouseupHandler({ target }); } }; this._id = `mat-calendar-body-${calendarBodyId++}`; this._startDateLabelId = `${this._id}-start-date`; this._endDateLabelId = `${this._id}-end-date`; _ngZone.runOutsideAngular(() => { const element = _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, event) { // 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, event) { if (cell.enabled) { this.activeDateChange.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('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, 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. * * 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. */ _focusActiveCell(movePreview = true) { this._ngZone.runOutsideAngular(() => { this._ngZone.onStable.pipe(take(1)).subscribe(() => { setTimeout(() => { const activeCell = this._elementRef.nativeElement.querySelector('.mat-calendar-body-active'); if (activeCell) { if (!movePreview) { this._skipNextFocus = true; } activeCell.focus(); } }); }); }); } /** 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) { 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); } /** Gets ids of aria descriptions for the start and end of a date range. */ _getDescribedby(value) { 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; } /** Finds the MatCalendarCell that corresponds to a DOM node. */ _getCellFromElement(element) { 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; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarBody, deps: [{ token: i0.ElementRef }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: { label: "label", rows: "rows", todayValue: "todayValue", startValue: "startValue", endValue: "endValue", labelMinRequiredCells: "labelMinRequiredCells", numCols: "numCols", activeCell: "activeCell", isRange: "isRange", cellAspectRatio: "cellAspectRatio", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", previewStart: "previewStart", previewEnd: "previewEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName" }, outputs: { selectedValueChange: "selectedValueChange", previewChange: "previewChange", activeDateChange: "activeDateChange", dragStarted: "dragStarted", dragEnded: "dragEnded" }, host: { classAttribute: "mat-calendar-body" }, exportAs: ["matCalendarBody"], usesOnChanges: true, ngImport: i0, template: "\n\n \n {{label}}\n \n\n\n\n\n \n \n {{_firstRowOffset >= labelMinRequiredCells ? label : ''}}\n \n \n \n \n \n {{item.displayValue}}\n \n \n \n \n\n\n\n\n", 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-hidden-label{display:none}.mat-calendar-body-cell-container{position:relative;height:0;line-height:0}.mat-calendar-body-cell{-webkit-user-select:none;user-select:none;cursor:pointer;outline:none;border:none;-webkit-tap-highlight-color:rgba(0,0,0,0);position:absolute;top:0;left:0;width:100%;height:100%;background:none;text-align:center;outline:none;font-family:inherit;margin:0}.mat-calendar-body-cell::-moz-focus-inner{border:0}.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;display:block;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}.cdk-high-contrast-active .mat-datepicker-popup:not(:empty),.cdk-high-contrast-active .mat-calendar-body-cell:not(.mat-calendar-body-in-range) .mat-calendar-body-selected{outline:solid 1px}.cdk-high-contrast-active .mat-calendar-body-today{outline:dotted 1px}.cdk-high-contrast-active .mat-calendar-body-cell::before,.cdk-high-contrast-active .mat-calendar-body-cell::after,.cdk-high-contrast-active .mat-calendar-body-selected{background:none}.cdk-high-contrast-active .mat-calendar-body-in-range::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-start::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-end::before{border-top:solid 1px;border-bottom:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:0;border-right:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:0;border-left:solid 1px}.cdk-high-contrast-active .mat-calendar-body-in-comparison-range::before{border-top:dashed 1px;border-bottom:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:0;border-right:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:0;border-left:dashed 1px}[dir=rtl] .mat-calendar-body-label{text-align:right}"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarBody, decorators: [{ type: Component, args: [{ selector: '[mat-calendar-body]', host: { 'class': 'mat-calendar-body', }, exportAs: 'matCalendarBody', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "\n\n \n {{label}}\n \n\n\n\n\n \n \n {{_firstRowOffset >= labelMinRequiredCells ? label : ''}}\n \n \n \n \n \n {{item.displayValue}}\n \n \n \n \n\n\n\n\n", 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-hidden-label{display:none}.mat-calendar-body-cell-container{position:relative;height:0;line-height:0}.mat-calendar-body-cell{-webkit-user-select:none;user-select:none;cursor:pointer;outline:none;border:none;-webkit-tap-highlight-color:rgba(0,0,0,0);position:absolute;top:0;left:0;width:100%;height:100%;background:none;text-align:center;outline:none;font-family:inherit;margin:0}.mat-calendar-body-cell::-moz-focus-inner{border:0}.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;display:block;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}.cdk-high-contrast-active .mat-datepicker-popup:not(:empty),.cdk-high-contrast-active .mat-calendar-body-cell:not(.mat-calendar-body-in-range) .mat-calendar-body-selected{outline:solid 1px}.cdk-high-contrast-active .mat-calendar-body-today{outline:dotted 1px}.cdk-high-contrast-active .mat-calendar-body-cell::before,.cdk-high-contrast-active .mat-calendar-body-cell::after,.cdk-high-contrast-active .mat-calendar-body-selected{background:none}.cdk-high-contrast-active .mat-calendar-body-in-range::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-start::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-end::before{border-top:solid 1px;border-bottom:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:0;border-right:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:0;border-left:solid 1px}.cdk-high-contrast-active .mat-calendar-body-in-comparison-range::before{border-top:dashed 1px;border-bottom:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:0;border-right:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:0;border-left:dashed 1px}[dir=rtl] .mat-calendar-body-label{text-align:right}"] }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.NgZone }]; }, 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 }], startDateAccessibleName: [{ type: Input }], endDateAccessibleName: [{ type: Input }], selectedValueChange: [{ type: Output }], previewChange: [{ type: Output }], activeDateChange: [{ type: Output }], dragStarted: [{ type: Output }], dragEnded: [{ type: Output }] } }); /** Checks whether a node is a table cell element. */ function isTableCell(node) { 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) { let cell; if (isTableCell(element)) { cell = element; } else if (isTableCell(element.parentNode)) { cell = element.parentNode; } else if (isTableCell(element.parentNode?.parentNode)) { cell = element.parentNode.parentNode; } return cell?.getAttribute('data-mat-row') != null ? cell : null; } /** 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); } /** * 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) { const touchLocation = event.changedTouches[0]; return document.elementFromPoint(touchLocation.clientX, touchLocation.clientY); } /** 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) { const oldValue = this.selection; this.selection = value; this._selectionChanged.next({ selection: value, source, oldValue }); } ngOnDestroy() { this._selectionChanged.complete(); } _isValidDateInstance(date) { return this._adapter.isDateInstance(date) && this._adapter.isValid(date); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel, deps: "invalid", target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: undefined }, { type: i1$1.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; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: i1$1.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; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: i1$1.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, }; /** 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); } createDrag(dragOrigin, originalRange, newDate) { 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(start, end); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy, decorators: [{ type: Injectable }], ctorParameters: function () { return [{ type: i1$1.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, }; const DAYS_PER_WEEK = 7; /** * An internal component used to display a single month in the datepicker. * @docs-private */ class MatMonthView { /** * 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)); } 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; /** Origin of active drag, or null when dragging is not active. */ this.activeDrag = null; /** Emits when a new date is selected. */ this.selectedChange = new EventEmitter(); /** Emits when any date is selected. */ this._userSelection = new EventEmitter(); /** Emits when the user initiates a date range drag via mouse or touch. */ this.dragStarted = new EventEmitter(); /** * Emits when the user completes or cancels a date range drag. * Emits null when the drag was canceled or the newly selected date range if completed. */ this.dragEnded = 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(); } 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); } if (changes['activeDrag'] && !this.activeDrag) { this._clearPreview(); } } ngOnDestroy() { this._rerenderSubscription.unsubscribe(); } /** Handles when a new date is selected. */ _dateSelected(event) { const date = event.value; const selectedDate = this._getDateFromDayOfMonth(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._clearPreview(); this._changeDetectorRef.markForCheck(); } /** * Takes the index of a calendar body cell wrapped in 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) { const month = event.value; const oldActiveDate = this._activeDate; this.activeDate = this._getDateFromDayOfMonth(month); if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) { this.activeDateChange.emit(this._activeDate); } } /** Handles keydown events on the calendar body when calendar is in month view. */ _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: this._selectionKeyPressed = true; if (this._canSelect(this._activeDate)) { // Prevent unexpected default actions such as form submission. // Note that we only prevent the default action here while the selection happens in // `keyup` below. We can't do the selection here, because it can cause the calendar to // reopen if focus is restored immediately. We also can't call `preventDefault` on `keyup` // because it's too late (see #23305). event.preventDefault(); } return; case ESCAPE: // Abort the current range selection if the user presses escape mid-selection. if (this._previewEnd != null && !hasModifierKey(event)) { this._clearPreview(); // If a drag is in progress, cancel the drag without changing the // current selection. if (this.activeDrag) { this.dragEnded.emit({ value: null, event }); } else { this.selectedChange.emit(null); this._userSelection.emit({ value: null, event }); } event.preventDefault(); event.stopPropagation(); // Prevents the overlay from closing. } return; default: // Don't prevent default or focus active cell on keys that we don't explicitly handle. return; } if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) { this.activeDateChange.emit(this.activeDate); this._focusActiveCellAfterViewChecked(); } // Prevent unexpected default actions such as form submission. event.preventDefault(); } /** Handles keyup events on the calendar body when calendar is in month view. */ _handleCalendarBodyKeyup(event) { if (event.keyCode === SPACE || event.keyCode === ENTER) { if (this._selectionKeyPressed && this._canSelect(this._activeDate)) { this._dateSelected({ value: this._dateAdapter.getDate(this._activeDate), event }); } this._selectionKeyPressed = false; } } /** Initializes this month view. */ _init() { this._setRanges(this.selected); this._todayDate = this._getCellCompareValue(this._dateAdapter.today()); this._monthLabel = this._dateFormats.display.monthLabel ? this._dateAdapter.format(this.activeDate, this._dateFormats.display.monthLabel) : this._dateAdapter .getMonthNames('short')[this._dateAdapter.getMonth(this.activeDate)].toLocaleUpperCase(); let firstOfMonth = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), 1); this._firstWeekOffset = (DAYS_PER_WEEK + this._dateAdapter.getDayOfWeek(firstOfMonth) - this._dateAdapter.getFirstDayOfWeek()) % DAYS_PER_WEEK; this._initWeekdays(); this._createWeekCells(); this._changeDetectorRef.markForCheck(); } /** Focuses the active cell after the microtask queue is empty. */ _focusActiveCell(movePreview) { this._matCalendarBody._focusActiveCell(movePreview); } /** Focuses the active cell after change detection has run and the microtask queue is empty. */ _focusActiveCellAfterViewChecked() { this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked(); } /** Called when the user has activated a new cell and the preview needs to be updated. */ _previewChanged({ event, value: cell }) { 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); if (this.activeDrag && value) { const dragRange = this._rangeStrategy.createDrag?.(this.activeDrag.value, this.selected, value, event); if (dragRange) { this._previewStart = this._getCellCompareValue(dragRange.start); this._previewEnd = this._getCellCompareValue(dragRange.end); } } // Note that here we need to use `detectChanges`, rather than `markForCheck`, because // the way `_focusActiveCell` is set up at the moment makes it fire at the wrong time // when navigating one month back using the keyboard which will cause this handler // to throw a "changed after checked" error when updating the preview state. this._changeDetectorRef.detectChanges(); } } /** * Called when the user has ended a drag. If the drag/drop was successful, * computes and emits the new range selection. */ _dragEnded(event) { if (!this.activeDrag) return; if (event.value) { // Propagate drag effect const dragDropResult = this._rangeStrategy?.createDrag?.(this.activeDrag.value, this.selected, event.value, event.event); this.dragEnded.emit({ value: dragDropResult ?? null, event: event.event }); } else { this.dragEnded.emit({ value: null, event: event.event }); } } /** * Takes a day of the month and returns a new date in the same month and year as the currently * active date. The returned date will have the same day of the month as the argument date. */ _getDateFromDayOfMonth(dayOfMonth) { return this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), dayOfMonth); } /** 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); } /** Gets whether a date can be selected in the month view. */ _canSelect(date) { return !this.dateFilter || this.dateFilter(date); } /** Clears out preview state. */ _clearPreview() { this._previewStart = this._previewEnd = null; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMonthView, deps: [{ token: i0.ChangeDetectorRef }, { token: MAT_DATE_FORMATS, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }, { token: MAT_DATE_RANGE_SELECTION_STRATEGY, optional: true }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatMonthView, selector: "mat-month-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName", activeDrag: "activeDrag" }, outputs: { selectedChange: "selectedChange", _userSelection: "_userSelection", dragStarted: "dragStarted", dragEnded: "dragEnded", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matMonthView"], usesOnChanges: true, ngImport: i0, template: "\n \n \n \n \n \n \n \n \n
\n {{day.long}}\n {{day.narrow}}\n
\n", dependencies: [{ kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMonthView, decorators: [{ type: Component, args: [{ selector: 'mat-month-view', exportAs: 'matMonthView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "\n \n \n \n \n \n \n \n \n
\n {{day.long}}\n {{day.narrow}}\n
\n" }] }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: i2.Directionality, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Inject, args: [MAT_DATE_RANGE_SELECTION_STRATEGY] }, { type: Optional }] }]; }, 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 }], startDateAccessibleName: [{ type: Input }], endDateAccessibleName: [{ type: Input }], activeDrag: [{ type: Input }], selectedChange: [{ type: Output }], _userSelection: [{ type: Output }], dragStarted: [{ type: Output }], dragEnded: [{ type: Output }], activeDateChange: [{ type: Output }], _matCalendarBody: [{ type: ViewChild, args: [MatCalendarBody] }] } }); const yearsPerPage = 24; const yearsPerRow = 4; /** * An internal component used to display a year selector in the datepicker. * @docs-private */ class MatMultiYearView { /** The date to display in this multi-year view (everything other than the year is ignored). */ get activeDate() { return this._activeDate; } set activeDate(value) { 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(); } } /** 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._setSelectedYear(value); } /** 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)); } 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 EventEmitter(); /** Emits the selected year. This doesn't imply a change on the selected date */ this.yearSelected = new EventEmitter(); /** Emits when any date is activated. */ this.activeDateChange = new EventEmitter(); 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 = []; 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) { 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 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) { 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. */ _handleCalendarBodyKeydown(event) { 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) { if (event.keyCode === SPACE || event.keyCode === ENTER) { if (this._selectionKeyPressed) { this._yearSelected({ value: this._dateAdapter.getYear(this._activeDate), event }); } this._selectionKeyPressed = false; } } _getActiveCell() { 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. */ _getDateFromYear(year) { 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. */ _createCellForYear(year) { 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. */ _shouldEnableYear(year) { // 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. */ _isRtl() { return this._dir && this._dir.value === 'rtl'; } /** Sets the currently-highlighted year based on a model value. */ _setSelectedYear(value) { 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); } } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMultiYearView, deps: [{ token: i0.ChangeDetectorRef }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatMultiYearView, selector: "mat-multi-year-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass" }, outputs: { selectedChange: "selectedChange", yearSelected: "yearSelected", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matMultiYearView"], ngImport: i0, template: "\n \n \n \n \n \n
\n", dependencies: [{ kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMultiYearView, decorators: [{ type: Component, args: [{ selector: 'mat-multi-year-view', exportAs: 'matMultiYearView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "\n \n \n \n \n \n
\n" }] }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: i2.Directionality, decorators: [{ type: Optional }] }]; }, propDecorators: { activeDate: [{ type: Input }], selected: [{ type: Input }], minDate: [{ type: Input }], maxDate: [{ type: Input }], dateFilter: [{ type: Input }], dateClass: [{ type: Input }], selectedChange: [{ type: Output }], yearSelected: [{ type: Output }], activeDateChange: [{ type: Output }], _matCalendarBody: [{ type: ViewChild, args: [MatCalendarBody] }] } }); function isSameMultiYearView(dateAdapter, date1, date2, minDate, maxDate) { 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. */ function getActiveOffset(dateAdapter, activeDate, minDate, maxDate) { 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(dateAdapter, minDate, maxDate) { 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, b) { return ((a % b) + b) % b; } /** * An internal component used to display a single year in the datepicker. * @docs-private */ class MatYearView { /** The date to display in this year view (everything other than the year is ignored). */ get activeDate() { return this._activeDate; } set activeDate(value) { 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(); } } /** 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._setSelectedMonth(value); } /** 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)); } constructor(_changeDetectorRef, _dateFormats, _dateAdapter, _dir) { this._changeDetectorRef = _changeDetectorRef; this._dateFormats = _dateFormats; this._dateAdapter = _dateAdapter; this._dir = _dir; this._rerenderSubscription = Subscription.EMPTY; /** Emits when a new month is selected. */ this.selectedChange = new EventEmitter(); /** Emits the selected month. This doesn't imply a change on the selected date */ this.monthSelected = 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(); } 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) { 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 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) { 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) { // 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) { 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. */ _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. */ _getMonthInCurrentYear(date) { 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. */ _getDateFromMonth(month) { 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. */ _createCellForMonth(month, monthName) { 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. */ _shouldEnableMonth(month) { 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 */ _isYearAndMonthAfterMaxDate(year, month) { 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 */ _isYearAndMonthBeforeMinDate(year, month) { 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. */ _isRtl() { return this._dir && this._dir.value === 'rtl'; } /** Sets the currently-selected month based on a model value. */ _setSelectedMonth(value) { if (value instanceof DateRange) { this._selectedMonth = this._getMonthInCurrentYear(value.start) || this._getMonthInCurrentYear(value.end); } else { this._selectedMonth = this._getMonthInCurrentYear(value); } } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatYearView, deps: [{ token: i0.ChangeDetectorRef }, { token: MAT_DATE_FORMATS, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatYearView, selector: "mat-year-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass" }, outputs: { selectedChange: "selectedChange", monthSelected: "monthSelected", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matYearView"], ngImport: i0, template: "\n \n \n \n \n \n
\n", dependencies: [{ kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatYearView, decorators: [{ type: Component, args: [{ selector: 'mat-year-view', exportAs: 'matYearView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "\n \n \n \n \n \n
\n" }] }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: i2.Directionality, decorators: [{ type: Optional }] }]; }, propDecorators: { activeDate: [{ type: Input }], selected: [{ type: Input }], minDate: [{ type: Input }], maxDate: [{ type: Input }], dateFilter: [{ type: Input }], dateClass: [{ type: Input }], selectedChange: [{ type: Output }], monthSelected: [{ type: Output }], activeDateChange: [{ type: Output }], _matCalendarBody: [{ type: ViewChild, args: [MatCalendarBody] }] } }); let calendarHeaderId = 1; /** Default header for MatCalendar */ class MatCalendarHeader { constructor(_intl, calendar, _dateAdapter, _dateFormats, changeDetectorRef) { this._intl = _intl; this.calendar = calendar; this._dateAdapter = _dateAdapter; this._dateFormats = _dateFormats; this._id = `mat-calendar-header-${calendarHeaderId++}`; this._periodButtonLabelId = `${this._id}-period-label`; this.calendar.stateChanges.subscribe(() => changeDetectorRef.markForCheck()); } /** The display text for the current calendar view. */ get periodButtonText() { 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() { 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() { return this.calendar.currentView == 'month' ? this._intl.switchToMultiYearViewLabel : this._intl.switchToMonthViewLabel; } /** The label for the previous button. */ get prevButtonLabel() { 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() { 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() { this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month'; } /** Handles user clicks on the previous button. */ previousClicked() { 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() { 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() { 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() { 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). */ _isSameView(date1, date2) { 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. */ _formatMinAndMaxYearLabels() { // 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]; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarHeader, deps: [{ token: MatDatepickerIntl }, { token: forwardRef(() => MatCalendar) }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendarHeader, selector: "mat-calendar-header", exportAs: ["matCalendarHeader"], ngImport: i0, template: "
\n
\n \n\n
\n\n \n\n \n\n \n
\n
\n\n", dependencies: [{ kind: "component", type: i3.MatButton, selector: " button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button] ", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { kind: "component", type: i3.MatIconButton, selector: "button[mat-icon-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarHeader, decorators: [{ type: Component, args: [{ selector: 'mat-calendar-header', exportAs: 'matCalendarHeader', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "
\n
\n \n\n
\n\n \n\n \n\n \n
\n
\n\n" }] }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: MatCalendar, decorators: [{ type: Inject, args: [forwardRef(() => MatCalendar)] }] }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }, { type: i0.ChangeDetectorRef }]; } }); /** A calendar that is used as part of the datepicker. */ class MatCalendar { /** A date representing the period (month or year) to start the calendar in. */ get startAt() { return this._startAt; } set startAt(value) { this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** 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)); } } /** 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)); } /** * The current active date. This determines which time period is shown and which date is * highlighted when using keyboard navigation. */ get activeDate() { return this._clampedActiveDate; } set activeDate(value) { this._clampedActiveDate = this._dateAdapter.clampDate(value, this.minDate, this.maxDate); this.stateChanges.next(); this._changeDetectorRef.markForCheck(); } /** Whether the calendar is in month view. */ get currentView() { return this._currentView; } set currentView(value) { const viewChangedResult = this._currentView !== value ? value : null; this._currentView = value; this._moveFocusOnNextTick = true; this._changeDetectorRef.markForCheck(); if (viewChangedResult) { this.viewChanged.emit(viewChangedResult); } } constructor(_intl, _dateAdapter, _dateFormats, _changeDetectorRef) { this._dateAdapter = _dateAdapter; this._dateFormats = _dateFormats; this._changeDetectorRef = _changeDetectorRef; /** * 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. */ this._moveFocusOnNextTick = false; /** Whether the calendar should be started in month or year view. */ this.startView = 'month'; /** Emits when the currently selected date changes. */ this.selectedChange = new EventEmitter(); /** * Emits the year chosen in multiyear view. * This doesn't imply a change on the selected date. */ this.yearSelected = new EventEmitter(); /** * Emits the month chosen in year view. * This doesn't imply a change on the selected date. */ this.monthSelected = new EventEmitter(); /** * Emits when the current view changes. */ this.viewChanged = new EventEmitter(true); /** Emits when any date is selected. */ this._userSelection = new EventEmitter(); /** Emits a new date range value when the user completes a drag drop operation. */ this._userDragDrop = new EventEmitter(); /** Origin of active drag, or null when dragging is not active. */ this._activeDrag = null; /** * Emits whenever there is a state change that the header may need to respond to. */ this.stateChanges = new Subject(); if (typeof ngDevMode === 'undefined' || ngDevMode) { if (!this._dateAdapter) { throw createMissingDateImplError('DateAdapter'); } if (!this._dateFormats) { throw createMissingDateImplError('MAT_DATE_FORMATS'); } } this._intlChanges = _intl.changes.subscribe(() => { _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) { // 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 = changes['minDate'] && !this._dateAdapter.sameDate(changes['minDate'].previousValue, changes['minDate'].currentValue) ? changes['minDate'] : undefined; const maxDateChange = changes['maxDate'] && !this._dateAdapter.sameDate(changes['maxDate'].previousValue, changes['maxDate'].currentValue) ? changes['maxDate'] : undefined; const change = minDateChange || maxDateChange || changes['dateFilter']; if (change && !change.firstChange) { const view = this._getCurrentViewComponent(); if (view) { // 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. */ _dateSelected(event) { 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) { this.yearSelected.emit(normalizedYear); } /** Handles month selection in the year view. */ _monthSelectedInYearView(normalizedMonth) { this.monthSelected.emit(normalizedMonth); } /** Handles year/month selection in the multi-year/year views. */ _goToDateInView(date, view) { this.activeDate = date; this.currentView = view; } /** Called when the user starts dragging to change a date range. */ _dragStarted(event) { this._activeDrag = event; } /** * Called when a drag completes. It may end in cancelation or in the selection * of a new range. */ _dragEnded(event) { if (!this._activeDrag) return; if (event.value) { this._userDragDrop.emit(event); } this._activeDrag = null; } /** Returns the component instance that corresponds to the current calendar view. */ _getCurrentViewComponent() { // 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; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendar, deps: [{ token: MatDatepickerIntl }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendar, selector: "mat-calendar", inputs: { headerComponent: "headerComponent", startAt: "startAt", startView: "startView", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName" }, outputs: { selectedChange: "selectedChange", yearSelected: "yearSelected", monthSelected: "monthSelected", viewChanged: "viewChanged", _userSelection: "_userSelection", _userDragDrop: "_userDragDrop" }, host: { classAttribute: "mat-calendar" }, providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER], viewQueries: [{ propertyName: "monthView", first: true, predicate: MatMonthView, descendants: true }, { propertyName: "yearView", first: true, predicate: MatYearView, descendants: true }, { propertyName: "multiYearView", first: true, predicate: MatMultiYearView, descendants: true }], exportAs: ["matCalendar"], usesOnChanges: true, ngImport: i0, template: "\n\n
\n \n \n\n \n \n\n \n \n
\n", styles: [".mat-calendar{display:block}.mat-calendar-header{padding:8px 8px 0 8px}.mat-calendar-content{padding:0 8px 8px 8px;outline:none}.mat-calendar-controls{display:flex;align-items:center;margin:5% calc(4.7142857143% - 16px)}.mat-calendar-spacer{flex:1 1 auto}.mat-calendar-period-button{min-width:0;margin:0 8px}.mat-calendar-arrow{display:inline-block;width:10px;height:5px;margin:0 0 0 5px;vertical-align:middle}.mat-calendar-arrow.mat-calendar-invert{transform:rotate(180deg)}[dir=rtl] .mat-calendar-arrow{margin:0 5px 0 0}.cdk-high-contrast-active .mat-calendar-arrow{fill:CanvasText}.mat-calendar-previous-button,.mat-calendar-next-button{position:relative}.mat-calendar-previous-button::after,.mat-calendar-next-button::after{top:0;left:0;right:0;bottom:0;position:absolute;content:\"\";margin:15.5px;border:0 solid currentColor;border-top-width:2px}[dir=rtl] .mat-calendar-previous-button,[dir=rtl] .mat-calendar-next-button{transform:rotate(180deg)}.mat-calendar-previous-button::after{border-left-width:2px;transform:translateX(2px) rotate(-45deg)}.mat-calendar-next-button::after{border-right-width:2px;transform:translateX(-2px) rotate(45deg)}.mat-calendar-table{border-spacing:0;border-collapse:collapse;width:100%}.mat-calendar-table-header th{text-align:center;padding:0 0 8px 0}.mat-calendar-table-header-divider{position:relative;height:1px}.mat-calendar-table-header-divider::after{content:\"\";position:absolute;top:0;left:-8px;right:-8px;height:1px}.mat-calendar-body-cell-content::before{margin:calc(calc(var(--mat-focus-indicator-border-width, 3px) + 3px) * -1)}.mat-calendar-body-cell:focus .mat-focus-indicator::before{content:\"\"}.mat-calendar-hidden-label{display:none}"], dependencies: [{ kind: "directive", type: i1.NgSwitch, selector: "[ngSwitch]", inputs: ["ngSwitch"] }, { kind: "directive", type: i1.NgSwitchCase, selector: "[ngSwitchCase]", inputs: ["ngSwitchCase"] }, { kind: "directive", type: i5.CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }, { kind: "directive", type: i6.CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { kind: "component", type: MatMonthView, selector: "mat-month-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass", "comparisonStart", "comparisonEnd", "startDateAccessibleName", "endDateAccessibleName", "activeDrag"], outputs: ["selectedChange", "_userSelection", "dragStarted", "dragEnded", "activeDateChange"], exportAs: ["matMonthView"] }, { kind: "component", type: MatYearView, selector: "mat-year-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass"], outputs: ["selectedChange", "monthSelected", "activeDateChange"], exportAs: ["matYearView"] }, { kind: "component", type: MatMultiYearView, selector: "mat-multi-year-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass"], outputs: ["selectedChange", "yearSelected", "activeDateChange"], exportAs: ["matMultiYearView"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendar, decorators: [{ type: Component, args: [{ selector: 'mat-calendar', host: { 'class': 'mat-calendar', }, exportAs: 'matCalendar', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER], template: "\n\n
\n \n \n\n \n \n\n \n \n
\n", styles: [".mat-calendar{display:block}.mat-calendar-header{padding:8px 8px 0 8px}.mat-calendar-content{padding:0 8px 8px 8px;outline:none}.mat-calendar-controls{display:flex;align-items:center;margin:5% calc(4.7142857143% - 16px)}.mat-calendar-spacer{flex:1 1 auto}.mat-calendar-period-button{min-width:0;margin:0 8px}.mat-calendar-arrow{display:inline-block;width:10px;height:5px;margin:0 0 0 5px;vertical-align:middle}.mat-calendar-arrow.mat-calendar-invert{transform:rotate(180deg)}[dir=rtl] .mat-calendar-arrow{margin:0 5px 0 0}.cdk-high-contrast-active .mat-calendar-arrow{fill:CanvasText}.mat-calendar-previous-button,.mat-calendar-next-button{position:relative}.mat-calendar-previous-button::after,.mat-calendar-next-button::after{top:0;left:0;right:0;bottom:0;position:absolute;content:\"\";margin:15.5px;border:0 solid currentColor;border-top-width:2px}[dir=rtl] .mat-calendar-previous-button,[dir=rtl] .mat-calendar-next-button{transform:rotate(180deg)}.mat-calendar-previous-button::after{border-left-width:2px;transform:translateX(2px) rotate(-45deg)}.mat-calendar-next-button::after{border-right-width:2px;transform:translateX(-2px) rotate(45deg)}.mat-calendar-table{border-spacing:0;border-collapse:collapse;width:100%}.mat-calendar-table-header th{text-align:center;padding:0 0 8px 0}.mat-calendar-table-header-divider{position:relative;height:1px}.mat-calendar-table-header-divider::after{content:\"\";position:absolute;top:0;left:-8px;right:-8px;height:1px}.mat-calendar-body-cell-content::before{margin:calc(calc(var(--mat-focus-indicator-border-width, 3px) + 3px) * -1)}.mat-calendar-body-cell:focus .mat-focus-indicator::before{content:\"\"}.mat-calendar-hidden-label{display:none}"] }] }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { headerComponent: [{ type: Input }], startAt: [{ type: Input }], startView: [{ type: Input }], selected: [{ type: Input }], minDate: [{ type: Input }], maxDate: [{ type: Input }], dateFilter: [{ type: Input }], dateClass: [{ type: Input }], comparisonStart: [{ type: Input }], comparisonEnd: [{ type: Input }], startDateAccessibleName: [{ type: Input }], endDateAccessibleName: [{ type: Input }], selectedChange: [{ type: Output }], yearSelected: [{ type: Output }], monthSelected: [{ type: Output }], viewChanged: [{ type: Output }], _userSelection: [{ type: Output }], _userDragDrop: [{ type: Output }], monthView: [{ type: ViewChild, args: [MatMonthView] }], yearView: [{ type: ViewChild, args: [MatYearView] }], multiYearView: [{ type: ViewChild, args: [MatMultiYearView] }] } }); /** * Animations used by the Material datepicker. * @docs-private */ const matDatepickerAnimations = { /** Transforms the height of the datepicker's calendar. */ transformPanel: trigger('transformPanel', [ transition('void => enter-dropdown', animate('120ms cubic-bezier(0, 0, 0.2, 1)', keyframes([ style({ opacity: 0, transform: 'scale(1, 0.8)' }), style({ opacity: 1, transform: 'scale(1, 1)' }), ]))), transition('void => enter-dialog', animate('150ms cubic-bezier(0, 0, 0.2, 1)', keyframes([ style({ opacity: 0, transform: 'scale(0.7)' }), style({ transform: 'none', opacity: 1 }), ]))), transition('* => void', animate('100ms linear', style({ opacity: 0 }))), ]), /** Fades in the content of the calendar. */ fadeInCalendar: trigger('fadeInCalendar', [ state('void', style({ opacity: 0 })), state('enter', style({ opacity: 1 })), // TODO(crisbeto): this animation should be removed since it isn't quite on spec, but we // need to keep it until #12440 gets in, otherwise the exit animation will look glitchy. transition('void => *', animate('120ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)')), ]), }; /** 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. */ const MAT_DATEPICKER_SCROLL_STRATEGY = new InjectionToken('mat-datepicker-scroll-strategy'); /** @docs-private */ function MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY(overlay) { return () => overlay.scrollStrategies.reposition(); } /** @docs-private */ const MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = { provide: MAT_DATEPICKER_SCROLL_STRATEGY, deps: [Overlay], useFactory: MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY, }; // Boilerplate for applying mixins to MatDatepickerContent. /** @docs-private */ const _MatDatepickerContentBase = mixinColor(class { constructor(_elementRef) { this._elementRef = _elementRef; } }); /** * 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 */ class MatDatepickerContent extends _MatDatepickerContentBase { constructor(elementRef, _changeDetectorRef, _globalModel, _dateAdapter, _rangeSelectionStrategy, intl) { super(elementRef); this._changeDetectorRef = _changeDetectorRef; this._globalModel = _globalModel; this._dateAdapter = _dateAdapter; this._rangeSelectionStrategy = _rangeSelectionStrategy; this._subscriptions = new Subscription(); /** Emits when an animation has finished. */ this._animationDone = new Subject(); /** Whether there is an in-progress animation. */ this._isAnimating = false; /** Portal with projected action buttons. */ this._actionsPortal = null; 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) { 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, event.event); this._model.updateSelection(newSelection, this); } else if (value && (isRange || !this._dateAdapter.sameDate(value, selection))) { this._model.add(value); } // Delegate closing the overlay to the actions. if ((!this._model || this._model.isComplete()) && !this._actionsPortal) { this.datepicker.close(); } } _handleUserDragDrop(event) { this._model.updateSelection(event.value, this); } _startExitAnimation() { this._animationState = 'void'; this._changeDetectorRef.markForCheck(); } _handleAnimationEvent(event) { this._isAnimating = event.phaseName === 'start'; if (!this._isAnimating) { this._animationDone.next(); } } _getSelected() { return this._model.selection; } /** 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, forceRerender) { // 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(); } } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerContent, deps: [{ token: i0.ElementRef }, { token: i0.ChangeDetectorRef }, { token: MatDateSelectionModel }, { token: i1$1.DateAdapter }, { token: MAT_DATE_RANGE_SELECTION_STRATEGY, optional: true }, { token: MatDatepickerIntl }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerContent, selector: "mat-datepicker-content", inputs: { color: "color" }, host: { listeners: { "@transformPanel.start": "_handleAnimationEvent($event)", "@transformPanel.done": "_handleAnimationEvent($event)" }, properties: { "@transformPanel": "_animationState", "class.mat-datepicker-content-touch": "datepicker.touchUi" }, classAttribute: "mat-datepicker-content" }, viewQueries: [{ propertyName: "_calendar", first: true, predicate: MatCalendar, descendants: true }], exportAs: ["matDatepickerContent"], usesInheritance: true, ngImport: i0, template: "\n \n\n \n\n \n {{ _closeButtonText }}\n\n", styles: [".mat-datepicker-content{display:block;border-radius:4px}.mat-datepicker-content .mat-calendar{width:296px;height:354px}.mat-datepicker-content .mat-datepicker-content-container-with-custom-header .mat-calendar{height:auto}.mat-datepicker-content .mat-datepicker-close-button{position:absolute;top:100%;left:0;margin-top:8px}.ng-animating .mat-datepicker-content .mat-datepicker-close-button{display:none}.mat-datepicker-content-container{display:flex;flex-direction:column;justify-content:space-between}.mat-datepicker-content-touch{display:block;max-height:80vh;position:relative;overflow:visible}.mat-datepicker-content-touch .mat-datepicker-content-container{min-height:312px;max-height:788px;min-width:250px;max-width:750px}.mat-datepicker-content-touch .mat-calendar{width:100%;height:auto}@media all and (orientation: landscape){.mat-datepicker-content-touch .mat-datepicker-content-container{width:64vh;height:80vh}}@media all and (orientation: portrait){.mat-datepicker-content-touch .mat-datepicker-content-container{width:80vw;height:100vw}.mat-datepicker-content-touch .mat-datepicker-content-container-with-actions{height:115vw}}"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "component", type: i3.MatButton, selector: " button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button] ", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { kind: "directive", type: i5.CdkTrapFocus, selector: "[cdkTrapFocus]", inputs: ["cdkTrapFocus", "cdkTrapFocusAutoCapture"], exportAs: ["cdkTrapFocus"] }, { kind: "directive", type: i6.CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { kind: "component", type: MatCalendar, selector: "mat-calendar", inputs: ["headerComponent", "startAt", "startView", "selected", "minDate", "maxDate", "dateFilter", "dateClass", "comparisonStart", "comparisonEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedChange", "yearSelected", "monthSelected", "viewChanged", "_userSelection", "_userDragDrop"], exportAs: ["matCalendar"] }], animations: [matDatepickerAnimations.transformPanel, matDatepickerAnimations.fadeInCalendar], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerContent, decorators: [{ type: Component, args: [{ selector: 'mat-datepicker-content', host: { 'class': 'mat-datepicker-content', '[@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, inputs: ['color'], template: "\n \n\n \n\n \n {{ _closeButtonText }}\n\n", styles: [".mat-datepicker-content{display:block;border-radius:4px}.mat-datepicker-content .mat-calendar{width:296px;height:354px}.mat-datepicker-content .mat-datepicker-content-container-with-custom-header .mat-calendar{height:auto}.mat-datepicker-content .mat-datepicker-close-button{position:absolute;top:100%;left:0;margin-top:8px}.ng-animating .mat-datepicker-content .mat-datepicker-close-button{display:none}.mat-datepicker-content-container{display:flex;flex-direction:column;justify-content:space-between}.mat-datepicker-content-touch{display:block;max-height:80vh;position:relative;overflow:visible}.mat-datepicker-content-touch .mat-datepicker-content-container{min-height:312px;max-height:788px;min-width:250px;max-width:750px}.mat-datepicker-content-touch .mat-calendar{width:100%;height:auto}@media all and (orientation: landscape){.mat-datepicker-content-touch .mat-datepicker-content-container{width:64vh;height:80vh}}@media all and (orientation: portrait){.mat-datepicker-content-touch .mat-datepicker-content-container{width:80vw;height:100vw}.mat-datepicker-content-touch .mat-datepicker-content-container-with-actions{height:115vw}}"] }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.ChangeDetectorRef }, { type: MatDateSelectionModel }, { type: i1$1.DateAdapter }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_RANGE_SELECTION_STRATEGY] }] }, { type: MatDatepickerIntl }]; }, propDecorators: { _calendar: [{ type: ViewChild, args: [MatCalendar] }] } }); /** Base class for a datepicker. */ class MatDatepickerBase { /** The date to open the calendar to initially. */ get startAt() { // 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) { this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); } /** Color palette to use on the datepicker's calendar. */ get color() { return (this._color || (this.datepickerInput ? this.datepickerInput.getThemePalette() : undefined)); } set color(value) { this._color = value; } /** * 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. */ get touchUi() { return this._touchUi; } set touchUi(value) { this._touchUi = coerceBooleanProperty(value); } /** Whether the datepicker pop-up should be disabled. */ get disabled() { return this._disabled === undefined && this.datepickerInput ? this.datepickerInput.disabled : !!this._disabled; } set disabled(value) { const newValue = coerceBooleanProperty(value); if (newValue !== this._disabled) { this._disabled = newValue; this.stateChanges.next(undefined); } } /** * 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. */ get restoreFocus() { return this._restoreFocus; } set restoreFocus(value) { this._restoreFocus = coerceBooleanProperty(value); } /** * Classes to be passed to the date picker panel. * Supports string and string array values, similar to `ngClass`. */ get panelClass() { return this._panelClass; } set panelClass(value) { this._panelClass = coerceStringArray(value); } /** Whether the calendar is open. */ get opened() { return this._opened; } set opened(value) { coerceBooleanProperty(value) ? this.open() : this.close(); } /** The minimum selectable date. */ _getMinDate() { return this.datepickerInput && this.datepickerInput.min; } /** The maximum selectable date. */ _getMaxDate() { return this.datepickerInput && this.datepickerInput.max; } _getDateFilter() { return this.datepickerInput && this.datepickerInput.dateFilter; } constructor(_overlay, _ngZone, _viewContainerRef, scrollStrategy, _dateAdapter, _dir, _model) { this._overlay = _overlay; this._ngZone = _ngZone; this._viewContainerRef = _viewContainerRef; this._dateAdapter = _dateAdapter; this._dir = _dir; this._model = _model; this._inputStateChanges = Subscription.EMPTY; this._document = inject(DOCUMENT); /** The view that the calendar should start in. */ this.startView = 'month'; this._touchUi = false; /** Preferred position of the datepicker in the X axis. */ this.xPosition = 'start'; /** Preferred position of the datepicker in the Y axis. */ this.yPosition = 'below'; this._restoreFocus = true; /** * Emits selected year in multiyear view. * This doesn't imply a change on the selected date. */ this.yearSelected = new EventEmitter(); /** * Emits selected month in year view. * This doesn't imply a change on the selected date. */ this.monthSelected = new EventEmitter(); /** * Emits when the current view changes. */ this.viewChanged = new EventEmitter(true); /** Emits when the datepicker has been opened. */ this.openedStream = new EventEmitter(); /** Emits when the datepicker has been closed. */ this.closedStream = new EventEmitter(); this._opened = false; /** The id for the datepicker calendar. */ this.id = `mat-datepicker-${datepickerUid++}`; /** The element that was focused before the datepicker was opened. */ this._focusedElementBeforeOpen = null; /** Unique class that will be added to the backdrop so that the test harnesses can look it up. */ this._backdropHarnessClass = `${this.id}-backdrop`; /** Emits when the datepicker's state changes. */ this.stateChanges = new Subject(); if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw createMissingDateImplError('DateAdapter'); } this._scrollStrategy = scrollStrategy; } ngOnChanges(changes) { 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) { this._model.add(date); } /** Emits the selected year in multiyear view */ _selectYear(normalizedYear) { this.yearSelected.emit(normalizedYear); } /** Emits selected month in year view */ _selectMonth(normalizedMonth) { this.monthSelected.emit(normalizedMonth); } /** Emits changed view */ _viewChanged(view) { 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) { 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. */ registerActions(portal) { 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) { if (portal === this._actionsPortal) { this._actionsPortal = null; this._componentRef?.instance._assignActions(null, true); } } /** Open the calendar. */ open() { // 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() { // 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. */ _forwardContentValues(instance) { instance.datepicker = this; instance.color = this.color; instance._dialogLabelId = this.datepickerInput.getOverlayLabelId(); instance._assignActions(this._actionsPortal, false); } /** Opens the overlay with the calendar. */ _openOverlay() { this._destroyOverlay(); const isDialog = this.touchUi; const portal = new ComponentPortal(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, 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) { this._ngZone.onStable.pipe(take(1)).subscribe(() => overlayRef.updatePosition()); } } /** Destroys the current overlay. */ _destroyOverlay() { if (this._overlayRef) { this._overlayRef.dispose(); this._overlayRef = this._componentRef = null; } } /** Gets a position strategy that will open the calendar as a dropdown. */ _getDialogStrategy() { return this._overlay.position().global().centerHorizontally().centerVertically(); } /** Gets a position strategy that will open the calendar as a dropdown. */ _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. */ _setConnectedPositions(strategy) { 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. */ _getCloseStream(overlayRef) { const ctrlShiftMetaModifiers = ['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) => !hasModifierKey(event, modifier)))); }))); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerBase, deps: [{ token: i9.Overlay }, { token: i0.NgZone }, { token: i0.ViewContainerRef }, { token: MAT_DATEPICKER_SCROLL_STRATEGY }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }, { token: MatDateSelectionModel }], target: i0.ɵɵFactoryTarget.Directive }); } static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerBase, inputs: { calendarHeaderComponent: "calendarHeaderComponent", startAt: "startAt", startView: "startView", color: "color", touchUi: "touchUi", disabled: "disabled", xPosition: "xPosition", yPosition: "yPosition", restoreFocus: "restoreFocus", dateClass: "dateClass", panelClass: "panelClass", opened: "opened" }, outputs: { yearSelected: "yearSelected", monthSelected: "monthSelected", viewChanged: "viewChanged", openedStream: "opened", closedStream: "closed" }, usesOnChanges: true, ngImport: i0 }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerBase, decorators: [{ type: Directive }], ctorParameters: function () { return [{ type: i9.Overlay }, { type: i0.NgZone }, { type: i0.ViewContainerRef }, { type: undefined, decorators: [{ type: Inject, args: [MAT_DATEPICKER_SCROLL_STRATEGY] }] }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: i2.Directionality, decorators: [{ type: Optional }] }, { type: MatDateSelectionModel }]; }, propDecorators: { calendarHeaderComponent: [{ type: Input }], startAt: [{ type: Input }], startView: [{ type: Input }], color: [{ type: Input }], touchUi: [{ type: Input }], disabled: [{ type: Input }], xPosition: [{ type: Input }], yPosition: [{ type: Input }], restoreFocus: [{ type: Input }], yearSelected: [{ type: Output }], monthSelected: [{ type: Output }], viewChanged: [{ type: Output }], dateClass: [{ type: Input }], openedStream: [{ type: Output, args: ['opened'] }], closedStream: [{ type: Output, args: ['closed'] }], panelClass: [{ type: Input }], opened: [{ type: Input }] } }); // 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. */ class MatDatepicker extends MatDatepickerBase { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepicker, deps: null, target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepicker, selector: "mat-datepicker", providers: [ MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER, { provide: MatDatepickerBase, useExisting: MatDatepicker }, ], exportAs: ["matDatepicker"], usesInheritance: true, ngImport: i0, template: '', isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepicker, decorators: [{ type: Component, args: [{ selector: 'mat-datepicker', template: '', exportAs: 'matDatepicker', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [ MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER, { provide: MatDatepickerBase, useExisting: MatDatepicker }, ], }] }] }); /** * 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. */ class MatDatepickerInputEvent { constructor( /** Reference to the datepicker input component that emitted the event. */ target, /** Reference to the native input element associated with the datepicker input. */ targetElement) { this.target = target; this.targetElement = targetElement; this.value = this.target.value; } } /** Base class for datepicker inputs. */ class MatDatepickerInputBase { /** The value of the input. */ get value() { return this._model ? this._getValueFromModel(this._model.selection) : this._pendingValue; } set value(value) { this._assignValueProgrammatically(value); } /** Whether the datepicker-input is disabled. */ get disabled() { return !!this._disabled || this._parentDisabled(); } set disabled(value) { const newValue = coerceBooleanProperty(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(); } } /** Gets the base validator functions. */ _getValidators() { return [this._parseValidator, this._minValidator, this._maxValidator, this._filterValidator]; } /** Registers a date selection model with the input. */ _registerModel(model) { 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)); } }); } constructor(_elementRef, _dateAdapter, _dateFormats) { this._elementRef = _elementRef; this._dateAdapter = _dateAdapter; this._dateFormats = _dateFormats; /** Emits when a `change` event is fired on this ``. */ this.dateChange = new EventEmitter(); /** Emits when an `input` event is fired on this ``. */ this.dateInput = new EventEmitter(); /** Emits when the internal state has changed */ this.stateChanges = new Subject(); this._onTouched = () => { }; this._validatorOnChange = () => { }; this._cvaOnChange = () => { }; this._valueChangesSubscription = Subscription.EMPTY; this._localeSubscription = Subscription.EMPTY; /** The form control validator for whether the input parses. */ this._parseValidator = () => { return this._lastValueValid ? null : { 'matDatepickerParse': { 'text': this._elementRef.nativeElement.value } }; }; /** The form control validator for the date filter. */ this._filterValidator = (control) => { 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. */ this._minValidator = (control) => { 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. */ this._maxValidator = (control) => { 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 } }; }; /** Whether the last value set on the input was valid. */ this._lastValueValid = false; 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 = _dateAdapter.localeChanges.subscribe(() => { this._assignValueProgrammatically(this.value); }); } ngAfterViewInit() { this._isInitialized = true; } ngOnChanges(changes) { if (dateInputsHaveChanged(changes, this._dateAdapter)) { this.stateChanges.next(undefined); } } ngOnDestroy() { this._valueChangesSubscription.unsubscribe(); this._localeSubscription.unsubscribe(); this.stateChanges.complete(); } /** @docs-private */ registerOnValidatorChange(fn) { this._validatorOnChange = fn; } /** @docs-private */ validate(c) { return this._validator ? this._validator(c) : null; } // Implemented as part of ControlValueAccessor. writeValue(value) { this._assignValueProgrammatically(value); } // Implemented as part of ControlValueAccessor. registerOnChange(fn) { this._cvaOnChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn) { this._onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled) { this.disabled = isDisabled; } _onKeydown(event) { const ctrlShiftMetaModifiers = ['ctrlKey', 'shiftKey', 'metaKey']; const isAltDownArrow = hasModifierKey(event, 'altKey') && event.keyCode === DOWN_ARROW && ctrlShiftMetaModifiers.every((modifier) => !hasModifierKey(event, modifier)); if (isAltDownArrow && !this._elementRef.nativeElement.readOnly) { this._openPopup(); event.preventDefault(); } } _onInput(value) { 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. */ _formatValue(value) { this._elementRef.nativeElement.value = value != null ? this._dateAdapter.format(value, this._dateFormats.display.dateInput) : ''; } /** Assigns a value to the model. */ _assignValue(value) { // 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. */ _isValidValue(value) { 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. */ _parentDisabled() { return false; } /** Programmatically assigns a value to the input. */ _assignValueProgrammatically(value) { 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) { const filter = this._getDateFilter(); return !filter || filter(value); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInputBase, deps: [{ token: i0.ElementRef }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); } static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerInputBase, inputs: { value: "value", disabled: "disabled" }, outputs: { dateChange: "dateChange", dateInput: "dateInput" }, usesOnChanges: true, ngImport: i0 }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInputBase, decorators: [{ type: Directive }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }]; }, propDecorators: { value: [{ type: Input }], disabled: [{ type: Input }], dateChange: [{ type: Output }], dateInput: [{ type: Output }] } }); /** * Checks whether the `SimpleChanges` object from an `ngOnChanges` * callback has any changes, accounting for date objects. */ function dateInputsHaveChanged(changes, adapter) { 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; } /** @docs-private */ const MAT_DATEPICKER_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatDatepickerInput), multi: true, }; /** @docs-private */ const MAT_DATEPICKER_VALIDATORS = { provide: NG_VALIDATORS, useExisting: forwardRef(() => MatDatepickerInput), multi: true, }; /** Directive used to connect an input to a MatDatepicker. */ class MatDatepickerInput extends MatDatepickerInputBase { /** The datepicker that this input is associated with. */ set matDatepicker(datepicker) { if (datepicker) { this._datepicker = datepicker; this._closedSubscription = datepicker.closedStream.subscribe(() => this._onTouched()); this._registerModel(datepicker.registerInput(this)); } } /** The minimum valid date. */ get min() { return this._min; } set min(value) { const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); if (!this._dateAdapter.sameDate(validValue, this._min)) { this._min = validValue; this._validatorOnChange(); } } /** The maximum valid date. */ get max() { return this._max; } set max(value) { const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)); if (!this._dateAdapter.sameDate(validValue, this._max)) { this._max = validValue; this._validatorOnChange(); } } /** Function that can be used to filter out dates within the datepicker. */ get dateFilter() { return this._dateFilter; } set dateFilter(value) { const wasMatchingValue = this._matchesFilter(this.value); this._dateFilter = value; if (this._matchesFilter(this.value) !== wasMatchingValue) { this._validatorOnChange(); } } constructor(elementRef, dateAdapter, dateFormats, _formField) { super(elementRef, dateAdapter, dateFormats); this._formField = _formField; this._closedSubscription = Subscription.EMPTY; 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() { 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() { 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() { return this._formField ? this._formField.color : undefined; } /** Gets the value at which the calendar should start. */ getStartValue() { return this.value; } ngOnDestroy() { super.ngOnDestroy(); this._closedSubscription.unsubscribe(); } /** Opens the associated datepicker. */ _openPopup() { if (this._datepicker) { this._datepicker.open(); } } _getValueFromModel(modelValue) { return modelValue; } _assignValueToModel(value) { 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. */ _getDateFilter() { return this._dateFilter; } _shouldHandleChangeEvent(event) { return event.source !== this; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInput, deps: [{ token: i0.ElementRef }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: MAT_FORM_FIELD, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); } static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerInput, selector: "input[matDatepicker]", inputs: { matDatepicker: "matDatepicker", min: "min", max: "max", dateFilter: ["matDatepickerFilter", "dateFilter"] }, host: { listeners: { "input": "_onInput($event.target.value)", "change": "_onChange()", "blur": "_onBlur()", "keydown": "_onKeydown($event)" }, properties: { "attr.aria-haspopup": "_datepicker ? \"dialog\" : null", "attr.aria-owns": "(_datepicker?.opened && _datepicker.id) || null", "attr.min": "min ? _dateAdapter.toIso8601(min) : null", "attr.max": "max ? _dateAdapter.toIso8601(max) : null", "attr.data-mat-calendar": "_datepicker ? _datepicker.id : null", "disabled": "disabled" }, classAttribute: "mat-datepicker-input" }, providers: [ MAT_DATEPICKER_VALUE_ACCESSOR, MAT_DATEPICKER_VALIDATORS, { provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: MatDatepickerInput }, ], exportAs: ["matDatepickerInput"], usesInheritance: true, ngImport: i0 }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInput, decorators: [{ type: Directive, args: [{ 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]': '(_datepicker?.opened && _datepicker.id) || null', '[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', }] }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1$1.DateAdapter, decorators: [{ type: Optional }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_DATE_FORMATS] }] }, { type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [MAT_FORM_FIELD] }] }]; }, propDecorators: { matDatepicker: [{ type: Input }], min: [{ type: Input }], max: [{ type: Input }], dateFilter: [{ type: Input, args: ['matDatepickerFilter'] }] } }); /** Can be used to override the icon of a `matDatepickerToggle`. */ class MatDatepickerToggleIcon { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggleIcon, deps: [], target: i0.ɵɵFactoryTarget.Directive }); } static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerToggleIcon, selector: "[matDatepickerToggleIcon]", ngImport: i0 }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggleIcon, decorators: [{ type: Directive, args: [{ selector: '[matDatepickerToggleIcon]', }] }] }); class MatDatepickerToggle { /** Whether the toggle button is disabled. */ get disabled() { if (this._disabled === undefined && this.datepicker) { return this.datepicker.disabled; } return !!this._disabled; } set disabled(value) { this._disabled = coerceBooleanProperty(value); } constructor(_intl, _changeDetectorRef, defaultTabIndex) { this._intl = _intl; this._changeDetectorRef = _changeDetectorRef; this._stateChanges = Subscription.EMPTY; const parsedTabIndex = Number(defaultTabIndex); this.tabIndex = parsedTabIndex || parsedTabIndex === 0 ? parsedTabIndex : null; } ngOnChanges(changes) { if (changes['datepicker']) { this._watchStateChanges(); } } ngOnDestroy() { this._stateChanges.unsubscribe(); } ngAfterContentInit() { this._watchStateChanges(); } _open(event) { if (this.datepicker && !this.disabled) { this.datepicker.open(); event.stopPropagation(); } } _watchStateChanges() { const datepickerStateChanged = this.datepicker ? this.datepicker.stateChanges : of(); const inputStateChanged = this.datepicker && this.datepicker.datepickerInput ? this.datepicker.datepickerInput.stateChanges : of(); const datepickerToggled = this.datepicker ? merge(this.datepicker.openedStream, this.datepicker.closedStream) : of(); this._stateChanges.unsubscribe(); this._stateChanges = merge(this._intl.changes, datepickerStateChanged, inputStateChanged, datepickerToggled).subscribe(() => this._changeDetectorRef.markForCheck()); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggle, deps: [{ token: MatDatepickerIntl }, { token: i0.ChangeDetectorRef }, { token: 'tabindex', attribute: true }], target: i0.ɵɵFactoryTarget.Component }); } static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerToggle, selector: "mat-datepicker-toggle", inputs: { datepicker: ["for", "datepicker"], tabIndex: "tabIndex", ariaLabel: ["aria-label", "ariaLabel"], disabled: "disabled", disableRipple: "disableRipple" }, host: { listeners: { "click": "_open($event)" }, properties: { "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\"", "attr.data-mat-calendar": "datepicker ? datepicker.id : null" }, classAttribute: "mat-datepicker-toggle" }, queries: [{ propertyName: "_customIcon", first: true, predicate: MatDatepickerToggleIcon, descendants: true }], viewQueries: [{ propertyName: "_button", first: true, predicate: ["button"], descendants: true }], exportAs: ["matDatepickerToggle"], usesOnChanges: true, ngImport: i0, template: "\n\n \n \n \n\n \n\n", styles: [".mat-datepicker-toggle{pointer-events:auto}.cdk-high-contrast-active .mat-datepicker-toggle-default-icon{color:CanvasText}"], dependencies: [{ kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i3.MatIconButton, selector: "button[mat-icon-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggle, decorators: [{ type: Component, args: [{ selector: 'mat-datepicker-toggle', 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, template: "\n\n \n \n \n\n \n\n", styles: [".mat-datepicker-toggle{pointer-events:auto}.cdk-high-contrast-active .mat-datepicker-toggle-default-icon{color:CanvasText}"] }] }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{ type: Attribute, args: ['tabindex'] }] }]; }, propDecorators: { datepicker: [{ type: Input, args: ['for'] }], tabIndex: [{ type: Input }], ariaLabel: [{ type: Input, args: ['aria-label'] }], disabled: [{ type: Input }], disableRipple: [{ type: Input }], _customIcon: [{ type: ContentChild, args: [MatDatepickerToggleIcon] }], _button: [{ type: ViewChild, args: ['button'] }] } }); // 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 // ``` // // // // ``` // 2. `aria-label` attribute (e.g. ``) // 3. Label with `for`/`id` // ``` // // // // ``` // 4. `placeholder` attribute (e.g. ``) // 5. `title` attribute (e.g. ``) // 6. text content // ``` // // // // ``` /** * 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/> */ function _computeAriaAccessibleName(element) { 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) { 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) { 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) { 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, isDirectlyReferenced) { // 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 = currentNode.getAttribute?.('aria-labelledby')?.split(/\s+/g) || []; const validIdRefs = labelledbyIds.reduce((validIds, id) => { const elem = document.getElementById(id); if (elem) { validIds.push(elem); } return validIds; }, []); 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 `