From 242d77e8a2400ef7aa913c3a0bac6fa83f4adca4 Mon Sep 17 00:00:00 2001 From: Radoslav Karaivanov Date: Wed, 25 Nov 2026 11:14:57 +0200 Subject: [PATCH] feat(date-picker, date-range-picker): select the typed date in the calendar While you type, the calendar now selects a complete typed date. While the date is incomplete or not valid, it keeps its last selection, and an empty input clears it. In the date range picker, each end follows its own text. The value still changes only when the edit is committed. Fixes: - A prompt that is also a separator of the input format, such as "-" with yyyy-MM-dd, no longer makes a complete date look incomplete. - In the date picker, the input and change events of slotted content go on to the application and no longer change the value. Also cleans up the date editors and parsers. The range parser uses one date parser for both ends, the editor's "draft" methods are now named "edit", and the comments are shorter. --- CHANGELOG.md | 3 + .../date-picker/date-picker-form.spec.ts | 19 ++ .../date-picker/date-picker.base.ts | 56 +++++- .../date-picker/date-picker.spec.ts | 180 ++++++++++++++++++ src/components/date-picker/date-picker.ts | 34 +++- src/components/date-picker/spec.md | 20 +- src/components/date-picker/value-shape.ts | 5 +- .../date-range-picker/date-range-input.ts | 22 +-- .../date-range-mask-parser.property.spec.ts | 50 +++++ .../date-range-mask-parser.spec.ts | 13 ++ .../date-range-mask-parser.ts | 132 ++++++------- .../date-range-picker-single.spec.ts | 46 +++++ .../date-range-picker-two-inputs.spec.ts | 88 +++++++++ .../date-range-picker.form.spec.ts | 36 ++++ .../date-range-picker/date-range-picker.ts | 44 +++-- .../date-range-picker/range-editors.spec.ts | 30 +++ .../date-range-picker/range-editors.ts | 52 ++--- .../date-range-picker/range-shape.spec.ts | 6 + .../date-range-picker/range-shape.ts | 5 +- src/components/date-range-picker/spec.md | 28 ++- src/components/date-time-input/date-part.ts | 43 ++--- .../date-time-input/date-time-input.base.ts | 43 +++-- .../datetime-mask-parser.property.spec.ts | 46 +++++ .../datetime-mask-parser.spec.ts | 42 ++++ .../date-time-input/datetime-mask-parser.ts | 36 ++-- src/components/date-time-input/spec.md | 6 +- src/internals/mixins/mask-behavior.ts | 5 +- src/internals/testing/simulate.spec.ts | 17 ++ 28 files changed, 882 insertions(+), 225 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13f680b4c..5ede17f05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - Without `activeDate`, a value set from code brings its month into view in the calendar, also while the calendar is open. Before, the calendar stayed on its month until the next open from the calendar icon or the keyboard. - With `visibleMonths` above 1, an open by the user, from the calendar icon, Alt + Arrow Down or a click on the input or the label in dialog mode, shows the value in the first month. Before, the value could open in another month. - #### Date picker, Date range picker + - While you type, the calendar selects a complete typed date. While the date is incomplete or not valid, the calendar keeps its last selection, and an empty input clears it. In the date range picker, each end follows its own text. The value still changes only when the edit is committed. Before, the date picker calendar showed the committed date until the blur. The date range picker calendar dropped an end while its text was incomplete, and the whole range in single input mode. - In editable dropdown mode, a clear through the clear icon is reported with `igcChange` when the focus leaves the picker. Before, the input reported it when the focus left the input, also on a move to the calendar or to the other input of a date range picker. - #### Date picker, Date time input - `stepUp(DatePart.AmPm)` and `stepDown(DatePart.AmPm)` move the time 12 hours also when the input format has no AM/PM part, as a step does for the other parts that the format does not show. Before, they did nothing. @@ -82,6 +83,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - In multiple selection, a change of `name` moves the submitted values to the new name at once. Before, the form submitted them under the old name. - #### Date picker - The first render no longer logs a Lit development warning that a cached field was read before the first update. + - The `igcInput` and `igcChange` events of slotted content, such as an input in the `suffix` slot, go on to the application and do not change the value. Before, the picker stopped them, and an `igcChange` from slotted content could change the value. - #### Date picker, Date range picker - An editor no longer shows the invalid styles when the focus moves from it to other content of the picker, such as the other editor of a date range picker. The editors show the invalid state of the picker, together with its validation message. - When you clear the value and then open and close the picker before you leave it, the picker now emits `igcChange` for the clear. @@ -92,6 +94,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - A form reset discards the text that you typed and did not commit yet, as for a native date input. Before, a partly typed date stayed in the focused input, and in a picker the next blur committed it as a date, also over the restored default value. - An empty value that code or a form reset sets while the input has focus replaces the date that the input shows. Before, the input kept showing the old date, and a spin started from it. - A year spin stops at year 9999 and at year 1, and a year outside them, such as one set from code, only moves toward them. Before, a spin past year 9999 gave a five digit year that did not fit the input. + - A `prompt` that is also a separator of the input format no longer makes a typed date incomplete. Examples are `-` with `yyyy-MM-dd`, and `-` with the ` - ` of the date range picker. Before, the `igcInput` detail of a complete date was `null`, and an arrow key or a spin started again from today. - Ctrl + Arrow Left and Ctrl + Arrow Right stop at each date part in an input format without separators, such as `yyyyMMdd`, and do not stop inside a separator of more than one character, such as `, `. Before, the date time input went to the start or the end of the input, and the single input of the date range picker skipped a part. - #### Date picker, Date time input - `stepUp(DatePart.AmPm)` and `stepDown(DatePart.AmPm)` read AM or PM from the value. Before, while the input did not have focus and the display format was different from the input format, they read the display text, so they did nothing or switched only from PM to AM. diff --git a/src/components/date-picker/date-picker-form.spec.ts b/src/components/date-picker/date-picker-form.spec.ts index 0c719d4e1..24f85765a 100644 --- a/src/components/date-picker/date-picker-form.spec.ts +++ b/src/components/date-picker/date-picker-form.spec.ts @@ -19,6 +19,7 @@ import { type ValidationContainerTestsParams, ValidityHelpers, } from '#internals/testing/validity-helpers.spec.js'; +import IgcCalendarComponent from '../calendar/calendar.js'; import { type DateRangeDescriptor, DateRangeType } from '../calendar/types.js'; import IgcDateTimeInputComponent from '../date-time-input/date-time-input.js'; import IgcInputComponent from '../input/input.js'; @@ -194,6 +195,24 @@ describe('igc-datepicker form integration', () => { spec.assertSubmitHasValue(defaultDate.toISOString()); }); + it('drops the typed calendar selection when the reset keeps the value', async () => { + const defaultDate = new Date(2024, 0, 15); + spec.setAttributes({ value: defaultDate.toISOString() }); + await elementUpdated(spec.element); + const calendar = spec.element.renderRoot.querySelector( + IgcCalendarComponent.tagName + )!; + + await simulateTypingOver(editor, '12122024'); + await elementUpdated(spec.element); + checkDatesEqual(calendar.value!, new Date(2024, 11, 12)); + + await reset(); + + checkDatesEqual(spec.element.value!, defaultDate); + checkDatesEqual(calendar.value!, defaultDate); + }); + it('shows the empty mask when the reset empties the value', async () => { spec.setProperties({ value: new Date(2024, 2, 3) }); await elementUpdated(spec.element); diff --git a/src/components/date-picker/date-picker.base.ts b/src/components/date-picker/date-picker.base.ts index 052058878..e3ca4bc08 100644 --- a/src/components/date-picker/date-picker.base.ts +++ b/src/components/date-picker/date-picker.base.ts @@ -139,14 +139,16 @@ export abstract class IgcDatePickerBaseComponent< read: () => this._value, write: (value) => this._writeFrom('edit', () => { + // A pick or a commit replaces the edit, also with the same value. + this._editValue = undefined; this._value = value; }), report: (force) => this._reportChange(this._value, force), }); - /** The value as the user types it. Without a draft, the calendar shows the value. */ + /** The calendar selection while the user types. Wrapped, so a blank edit (`null`) differs from no edit. */ @state({ hasChanged: (value, old) => !equal(value, old) }) - protected _draft?: { value: T | null }; + protected _editValue?: { value: T | null }; protected _activeDate: Date | null = null; protected _min: Date | null = null; @@ -163,10 +165,12 @@ export abstract class IgcDatePickerBaseComponent< @query(IgcDialogComponent.tagName) private readonly _dialog?: IgcDialogComponent; + protected get _calendarValue(): T | null { + return this._editValue ? this._editValue.value : this._value; + } + private get _calendarSelection(): CalendarBinding { - return this._shape.toCalendar( - this._draft ? this._draft.value : this._value - ); + return this._shape.toCalendar(this._calendarValue); } private get _startDate(): Date | null { @@ -181,7 +185,10 @@ export abstract class IgcDatePickerBaseComponent< protected set _value(value: T | null) { const previous = this._value; this._formValue.setValueAndFormState(value); - this._draft = undefined; + // A same-value write, such as a re-render, keeps the edit, as the editor does. + if (!this._formValue.isSameValue(previous, this._value)) { + this._editValue = this._editAfterValueChange(previous); + } if (!this._activeDate) { this._setCalendarActiveDate(this._startDate); } @@ -241,6 +248,13 @@ export abstract class IgcDatePickerBaseComponent< //#region Overridable hooks + /** The edit after a value change. The editor drops its edit for a new value, so the calendar shows the value. */ + protected _editAfterValueChange( + _previous: T | null + ): { value: T | null } | undefined { + return undefined; + } + protected get _calendarIconTitle(): string | undefined { return undefined; } @@ -503,6 +517,17 @@ export abstract class IgcDatePickerBaseComponent< .set(escapeKey, this._onEscapeKey, { when: () => this.open }); } + protected override createRenderRoot(): HTMLElement | DocumentFragment { + const root = super.createRenderRoot(); + + // Any editor blur ends the edit, also a commit that emits nothing. Focus moves inside the picker never reach the host. + root.addEventListener('focusout', () => { + this._editValue = undefined; + }); + + return root; + } + protected override willUpdate(props: PropertyValues): void { super.willUpdate(props); @@ -532,6 +557,12 @@ export abstract class IgcDatePickerBaseComponent< ); } + /** A reset discards the edit of the editors, also when the restored value is the same. */ + protected override formResetCallback(): void { + super.formResetCallback(); + this._editValue = undefined; + } + protected _setDateConstraints(): void { this._dateConstraints = createDateConstraints( this._min, @@ -617,6 +648,19 @@ export abstract class IgcDatePickerBaseComponent< this._calendar.values = values; } + /** + * Stops the inner event of an editor, and returns whether the picker owns the editor. An editor that a layout + * change removes commits nothing, as its typed text goes with it. The events of slotted content go on to the + * application. + */ + protected _acceptEditorEvent(event: Event): boolean { + const target = event.target as PickerEditor; + if (target.getRootNode() !== this.renderRoot) return false; + + event.stopPropagation(); + return this._ownedEditors.includes(target); + } + /** Commits a value from an editor. An edit back to the reported value emits nothing. */ protected _commitEditorValue(value: T | null): void { this._writeFrom('user', () => this._session.commitEdit(value)); diff --git a/src/components/date-picker/date-picker.spec.ts b/src/components/date-picker/date-picker.spec.ts index eb6dc752a..1c7b964e7 100644 --- a/src/components/date-picker/date-picker.spec.ts +++ b/src/components/date-picker/date-picker.spec.ts @@ -37,12 +37,14 @@ import { withDocumentSheets, } from '#internals/testing/helpers.spec.js'; import { + simulateBackspaceOver, simulateCancelableKeydown, simulateClick, simulateComposingKeys, simulateInput, simulateKeyboard, simulateScroll, + simulateTypingOver, } from '#internals/testing/simulate.spec.js'; import { isUserChange } from '#internals/user-change.js'; import { formatString } from '#internals/utils/strings.js'; @@ -1062,6 +1064,158 @@ describe('Date picker', () => { }); }); + describe('Calendar selection while typing', () => { + const march3 = new Date(2020, 2, 3); + const october10 = new Date(2020, 9, 10); + let input: HTMLInputElement; + + const typeOver = async (text: string) => { + await simulateTypingOver(dateTimeInput, text); + await elementUpdated(picker); + }; + + const deleteText = async (start: number, end: number) => { + await simulateBackspaceOver(dateTimeInput, start, end); + await elementUpdated(picker); + }; + + beforeEach(async () => { + input = dateTimeInput.renderRoot.querySelector('input')!; + picker.inputFormat = 'MM/dd/yyyy'; + picker.value = march3; + await picker.show(); + }); + + it('selects a complete typed date and keeps the value', async () => { + await typeOver('10102020'); + + expect(input.value).to.equal('10/10/2020'); + checkDatesEqual(calendar.value!, october10); + checkDatesEqual(picker.value!, march3); + }); + + it('keeps the last selection while the date is incomplete', async () => { + const eventSpy = spy(picker, 'emitEvent'); + + await typeOver('1010'); + + expect(input.value).to.equal('10/10/____'); + checkDatesEqual(calendar.value!, march3); + expect(eventSpy).calledWith('igcInput', { detail: null }); + + await typeOver('10102020'); + await deleteText(6, 10); + + expect(input.value).to.equal('10/10/____'); + checkDatesEqual(calendar.value!, october10); + }); + + it('keeps the last selection for an invalid date', async () => { + await typeOver('02302020'); + + expect(input.value).to.equal('02/30/2020'); + checkDatesEqual(calendar.value!, march3); + }); + + it('clears the selection when the input is emptied', async () => { + dateTimeInput.focus(); + await elementUpdated(picker); + + await deleteText(0, input.value.length); + + expect(input.value).to.equal('__/__/____'); + expect(calendar.value).to.be.null; + checkDatesEqual(picker.value!, march3); + }); + + it('keeps the typed selection when code sets the same value', async () => { + await typeOver('10102020'); + + picker.value = new Date(march3.getTime()); + await elementUpdated(picker); + + expect(input.value).to.equal('10/10/2020'); + checkDatesEqual(calendar.value!, october10); + }); + + it('selects a new value set from code', async () => { + const january1 = new Date(2021, 0, 1); + await typeOver('10102020'); + + picker.value = january1; + await elementUpdated(picker); + + checkDatesEqual(calendar.value!, january1); + }); + + it('drops the typed selection on clear()', async () => { + picker.value = null; + await typeOver('10102020'); + checkDatesEqual(calendar.value!, october10); + + picker.clear(); + await elementUpdated(picker); + + expect(calendar.value).to.be.null; + }); + + it('selects the value after a blur that commits the same value', async () => { + const january1 = new Date(2020, 0, 1); + picker.value = january1; + await typeOver('10102020'); + + // The year stays, so the commit fills the month and the day: January 1. + await deleteText(0, 5); + expect(input.value).to.equal('__/__/2020'); + checkDatesEqual(calendar.value!, october10); + + const eventSpy = spy(picker, 'emitEvent'); + dateTimeInput.blur(); + await elementUpdated(picker); + + expect(eventSpy).not.calledWith('igcChange'); + checkDatesEqual(picker.value!, january1); + checkDatesEqual(calendar.value!, january1); + }); + + it('selects the value after stepUp and setRangeText', async () => { + const march2 = new Date(2020, 2, 2); + + await typeOver('03022020'); + checkDatesEqual(calendar.value!, march2); + + picker.stepUp(DatePart.Date); + await elementUpdated(picker); + + expect(input.value).to.equal('03/03/2020'); + checkDatesEqual(picker.value!, march3); + checkDatesEqual(calendar.value!, march3); + + await typeOver('03022020'); + checkDatesEqual(calendar.value!, march2); + + picker.setRangeText('03', 3, 5); + await elementUpdated(picker); + + expect(input.value).to.equal('03/03/2020'); + checkDatesEqual(calendar.value!, march3); + }); + + it('selects the value when the focus moves to the calendar', async () => { + const january1 = new Date(2020, 0, 1); + picker.value = january1; + await typeOver('10102020'); + await deleteText(0, 5); + checkDatesEqual(calendar.value!, october10); + + calendar[focusActiveDate](); + await elementUpdated(picker); + + checkDatesEqual(picker.value!, january1); + checkDatesEqual(calendar.value!, january1); + }); + }); + describe('Calendar view', () => { it('brings the month of a value set from code into view', async () => { const march1 = new Date(2025, 2, 1); @@ -1531,6 +1685,32 @@ describe('Date picker', () => { checkDatesEqual(picker.value!, today); }); + it('leaves the input and change events of slotted content alone', async () => { + const value = new Date(2020, 2, 3); + const slotted = document.createElement('span'); + slotted.slot = 'suffix'; + picker.append(slotted); + picker.value = value; + await elementUpdated(picker); + + const eventSpy = spy(picker, 'emitEvent'); + const reached: string[] = []; + const record = ({ type }: Event) => reached.push(type); + picker.addEventListener('igcInput', record); + picker.addEventListener('igcChange', record); + + for (const type of ['igcInput', 'igcChange']) { + slotted.dispatchEvent( + new CustomEvent(type, { bubbles: true, composed: true, detail: '' }) + ); + } + await elementUpdated(picker); + + expect(reached).to.eql(['igcInput', 'igcChange']); + expect(eventSpy).not.called; + checkDatesEqual(picker.value!, value); + }); + it('should emit or not igcInput according to nonEditable property', async () => { const expectedValue = new Date(); const eventSpy = spy(picker, 'emitEvent'); diff --git a/src/components/date-picker/date-picker.ts b/src/components/date-picker/date-picker.ts index 2c8b22a4d..7ab9011a3 100644 --- a/src/components/date-picker/date-picker.ts +++ b/src/components/date-picker/date-picker.ts @@ -297,13 +297,15 @@ export default class IgcDatePickerComponent extends I18nMixin( //#region Event handlers protected _handleInputChangeEvent(event: CustomEvent): void { - event.stopPropagation(); - - this._commitEditorValue((event.target as IgcDateTimeInputComponent).value); + if (this._acceptEditorEvent(event)) { + this._commitEditorValue( + (event.target as IgcDateTimeInputComponent).value + ); + } } protected _handleInputEvent(event: CustomEvent): void { - event.stopPropagation(); + if (!this._acceptEditorEvent(event)) return; this._setTouchedState(); @@ -312,10 +314,22 @@ export default class IgcDatePickerComponent extends I18nMixin( return; } - const draft = (event.target as IgcDateTimeInputComponent)._uncommittedValue; + const input = event.target as IgcDateTimeInputComponent; + const typed = input._uncommittedValue; - this._setCalendarActiveDate(draft); - this.emitEvent('igcInput', { detail: draft }); + this._editValue = { value: input._parseEdit(this._calendarValue) }; + this._setCalendarActiveDate(typed); + this.emitEvent('igcInput', { detail: typed }); + } + + //#endregion + + //#region Internal API + + /** Takes the value of the input after a call that ends its edit, so the calendar shows it too. */ + private _takeInputValue(): void { + this.value = this._input.value; + this._editValue = undefined; } //#endregion @@ -328,7 +342,7 @@ export default class IgcDatePickerComponent extends I18nMixin( */ public stepUp(datePart?: DatePart, delta?: number): void { this._input.stepUp(datePart, delta); - this.value = this._input.value; + this._takeInputValue(); } /** @@ -337,7 +351,7 @@ export default class IgcDatePickerComponent extends I18nMixin( */ public stepDown(datePart?: DatePart, delta?: number): void { this._input.stepDown(datePart, delta); - this.value = this._input.value; + this._takeInputValue(); } /** Selects the text in the input of the component. */ @@ -367,7 +381,7 @@ export default class IgcDatePickerComponent extends I18nMixin( mode?: RangeTextSelectMode ): void { this._input.setRangeText(replacement, start, end, mode); - this.value = this._input.value; + this._takeInputValue(); } //#endregion diff --git a/src/components/date-picker/spec.md b/src/components/date-picker/spec.md index df8b412a8..d69925cf0 100644 --- a/src/components/date-picker/spec.md +++ b/src/components/date-picker/spec.md @@ -52,6 +52,7 @@ - [Date value shape](#date-value-shape) - [Disabled popup](#disabled-popup) - [Value state motion](#value-state-motion) + - [Calendar selection while typing](#calendar-selection-while-typing) - [Assumptions and limitations](#assumptions-and-limitations) - [Accessibility](#accessibility) - [ARIA roles and properties](#aria-roles-and-properties) @@ -85,6 +86,7 @@ | 21 | 2026-11-20 | The value accepts an ISO string with a signed six digit year | | 22 | 2026-11-23 | A disabled picker stays closed; the shared disabled popup suite | | 23 | 2026-11-20 | A date that the user picks animates the input; a value from code, also from an `igcChange` handler, shows at once | +| 24 | 2026-11-25 | The calendar selects a complete typed date, keeps the last selection while the date is incomplete or invalid, and clears it for an empty input; the calendar shows the value again when the edit ends; the input and change events of slotted content go on to the application | ## Overview @@ -228,7 +230,9 @@ As a developer, I expect to be able to: than what the user types, for example `Tuesday, July 9, 2024`. - **On focus**: the text flips to the input format. An empty editor shows the empty mask and selects it. - **While typing**: only the mask positions accept input and literals are skipped over automatically. The calendar - view follows along - typing a date in another month brings that month into view. + view follows along - typing a date in another month brings that month into view. The calendar selects a complete + typed date. While the date is incomplete or invalid, the calendar keeps its last selection, and an empty input + clears it. The value does not change until the edit is committed. - **On blur**: the edit is committed and `igcChange` is emitted if the committed value differs from the one the editor was focused with. A mask that cannot resolve to a valid date clears the value. @@ -767,7 +771,8 @@ Grouped as `Uncommitted edits - issue #1346` in the suite. 38. A user change renders at once: a calendar pick with `keepOpenOnSelect` updates the input, and `clear` removes the clear icon. 39. A calendar selection in a non-editable dropdown emits `igcChange` once, also after a later blur. -40. `igcInput` is emitted according to the `nonEditable` property. +40. `igcInput` is emitted according to the `nonEditable` property. The input and change events of slotted content go + on to the application and do not change the value. 41. Clicking the calendar icon opens the picker in both modes. 42. Clicking the input opens the picker in dialog mode only; clicking the label likewise. 43. Clicking the clear icon does not open the picker, in either mode. @@ -798,7 +803,8 @@ Grouped as `Uncommitted edits - issue #1346` in the suite. 52. Resets to its default value on form reset, resets to a new default after a `setAttribute` call, and clears the invalid styles of the inner editor on reset. A reset during an edit discards the typed text, with and without a default, and the next blur keeps the restored value. A reset that empties the value shows the empty mask in the - focused editor. The inner editor shows the invalid state of the picker at once, and none of its own. + focused editor, and a reset that keeps the value drops the typed calendar selection. The inner editor shows the + invalid state of the picker at once, and none of its own. 53. Submits on Enter when valid, and does not when invalid. A real Enter submits once. Enter in a field in the `suffix` slot submits once, and on a button in the slot it does not submit. 54. Reflects the disabled state of an ancestor `fieldset` or form. @@ -869,6 +875,14 @@ Generated by `runExternalLabelAssociationTests` and `runAriaProjectionTests`. 70. A pick from the calendar marks the input as a user change. 71. A value that an `igcChange` handler sets ends the user change, so the input shows it at once. +### Calendar selection while typing + +72. The calendar selects a complete typed date and the value stays. An incomplete or invalid date keeps the last + selection, while the `igcInput` detail is `null`; an empty input clears the selection. A value from code that is + the same keeps the typed selection, a new value and `clear()` replace it. A blur, or a move of the focus to the + calendar, shows the value again, also when the commit keeps the value and emits nothing. `stepUp` and + `setRangeText`, which end the edit, show the value too. + ## Assumptions and limitations - Only a single date value is edited per component; ranges are covered by diff --git a/src/components/date-picker/value-shape.ts b/src/components/date-picker/value-shape.ts index 41f974471..cbc7a432f 100644 --- a/src/components/date-picker/value-shape.ts +++ b/src/components/date-picker/value-shape.ts @@ -18,9 +18,12 @@ export interface PickerValueShape { closesOnPick(dates: Date[]): boolean; } +// One array, so Lit skips the binding on each render. +const noDates: Date[] = []; + export const dateShape: PickerValueShape = { selection: 'single', - toCalendar: (value) => ({ value, values: [] }), + toCalendar: (value) => ({ value, values: noDates }), fromCalendar: (dates) => firstOf(dates) ?? null, closesOnPick: () => true, }; diff --git a/src/components/date-range-picker/date-range-input.ts b/src/components/date-range-picker/date-range-input.ts index fe7bcdf6b..ccc2dd0be 100644 --- a/src/components/date-range-picker/date-range-input.ts +++ b/src/components/date-range-picker/date-range-input.ts @@ -58,15 +58,7 @@ export default class IgcDateRangeInputComponent extends EventEmitterMixin< // #region Public attributes and properties /* @tsTwoWayProperty(true, "igcChange", "detail", false, true) */ - /** - * The value of the date range input. - * - * Only ever holds a committed value. While the user is typing, the intermediate - * state lives in the masked text and is committed - together with an `igcChange` - * event - when the edit is committed on blur. - * - * @attr - */ + /** The committed range. The typed text commits on blur. */ @property({ attribute: false }) public override set value(value: DateRangeValue | null) { this._applyValue(value); @@ -107,18 +99,6 @@ export default class IgcDateRangeInputComponent extends EventEmitterMixin< this._parser.prompt = this.prompt; } - // #region Public API Overrides - - /** Increments a date/time portion. The `value` updates at once. */ - public override stepUp(datePart?: DateRangePart, delta?: number): void { - super.stepUp(datePart, delta); - } - - /** Decrements a date/time portion. The `value` updates at once. */ - public override stepDown(datePart?: DateRangePart, delta?: number): void { - super.stepDown(datePart, delta); - } - // #endregion } diff --git a/src/components/date-range-picker/date-range-mask-parser.property.spec.ts b/src/components/date-range-picker/date-range-mask-parser.property.spec.ts index 5f7ef1423..0e4538240 100644 --- a/src/components/date-range-picker/date-range-mask-parser.property.spec.ts +++ b/src/components/date-range-picker/date-range-mask-parser.property.spec.ts @@ -164,6 +164,56 @@ describe('Date range mask parser properties', () => { ); }); + it('parses an edit by end: a complete end, the previous end while incomplete, and no end while blank', () => { + const optionalDate = fc.option(date, { nil: null }); + + fc.assert( + fc.property( + options, + date, + date, + textKind, + textKind, + optionalDate, + optionalDate, + (opts, start, end, startKind, endKind, previousStart, previousEnd) => { + assumeWallClock(opts.format, start); + assumeWallClock(opts.format, end); + + const parser = new DateRangeMaskParser(opts); + const single = new DateTimeMaskParser({ format: opts.format }); + const startText = textOf(single, start, startKind); + const endText = textOf(single, end, endKind); + const masked = startText + parser.separator + endText; + + const expectedEnd = ( + text: string, + kind: TextKind, + previous: Date | null + ) => + kind === 'full' + ? single.parseDate(text) + : kind === 'partial' + ? previous + : null; + + const ends = { + start: expectedEnd(startText, startKind, previousStart), + end: expectedEnd(endText, endKind, previousEnd), + }; + + expect( + parser.parseEdit(masked, { + start: previousStart, + end: previousEnd, + }), + masked + ).to.deep.equal(ends.start || ends.end ? ends : null); + } + ) + ); + }); + it('lays out the two dates around the separator', () => { fc.assert( fc.property(looseOptions, looseOptions, (initial, next) => { diff --git a/src/components/date-range-picker/date-range-mask-parser.spec.ts b/src/components/date-range-picker/date-range-mask-parser.spec.ts index a54555065..57bd14e2f 100644 --- a/src/components/date-range-picker/date-range-mask-parser.spec.ts +++ b/src/components/date-range-picker/date-range-mask-parser.spec.ts @@ -86,6 +86,19 @@ describe('DateRangeMaskParser', () => { expect(parser.mask).to.equal('MM/dd/yyyy - MM/dd/yyyy'); }); + it('parses a complete range strictly when the separator holds the prompt', () => { + const parser = new DateRangeMaskParser({ + format: 'MM/dd/yyyy', + promptCharacter: '-', + }); + + expect(parser.parseValue('12/25/2026 - 12/31/2026', true)).to.eql({ + start: new Date(2026, 11, 25), + end: new Date(2026, 11, 31), + }); + expect(parser.parseValue('12/25/2026 - 12/31/20--', true)).to.be.null; + }); + it('builds range parts with position information', () => { const parser = new DateRangeMaskParser({ format: 'MM/dd/yyyy' }); const parts = parser.parts; diff --git a/src/components/date-range-picker/date-range-mask-parser.ts b/src/components/date-range-picker/date-range-mask-parser.ts index f5ed21769..ac44c089d 100644 --- a/src/components/date-range-picker/date-range-mask-parser.ts +++ b/src/components/date-range-picker/date-range-mask-parser.ts @@ -26,7 +26,7 @@ export interface DateRangePart { } /** - * Position of a date part within the date range + * The end of the range that a date part belongs to. * @hidden */ export enum DateRangePosition { @@ -35,7 +35,6 @@ export enum DateRangePosition { } /** - * Extended date part with range position information * @hidden */ export interface IDateRangePart extends IDatePart { @@ -76,17 +75,14 @@ function offsetParts( ); } -/** - * A mask parser for date range inputs. A single date format (e.g. 'MM/dd/yyyy') creates - * two internal DateTimeMaskParser instances, one for each end of the range. - */ +/** A date range mask: one date format on each side of the separator. */ export class DateRangeMaskParser extends DateFormatMaskParser< IDateRangePart, DateRangeValue, DateRangePart > { - private _startParser: DateTimeMaskParser; - private _endParser: DateTimeMaskParser; + /** Parses, formats and spins the text of either end. */ + private readonly _dateParser: DateTimeMaskParser; private _separator: string; @@ -94,7 +90,6 @@ export class DateRangeMaskParser extends DateFormatMaskParser< private _separatorEnd!: number; - /** The separator between start and end dates. */ public get separator(): string { return this._separator; } @@ -102,16 +97,15 @@ export class DateRangeMaskParser extends DateFormatMaskParser< constructor(options?: DateRangeMaskOptions) { const separator = options?.separator || DEFAULT_SEPARATOR; const promptCharacter = options?.promptCharacter; - const startParser = new DateTimeMaskParser({ + const dateParser = new DateTimeMaskParser({ format: options?.format, promptCharacter, }); - const format = startParser.mask; + const format = dateParser.mask; super({ format: `${format}${separator}${format}`, promptCharacter }); - this._startParser = startParser; - this._endParser = new DateTimeMaskParser({ format, promptCharacter }); + this._dateParser = dateParser; this._separator = separator; this._setSeparatorBounds(); @@ -120,10 +114,17 @@ export class DateRangeMaskParser extends DateFormatMaskParser< } private _setSeparatorBounds(): void { - this._separatorStart = this._startParser.mask.length; + this._separatorStart = this._dateParser.mask.length; this._separatorEnd = this._separatorStart + this._separator.length; } + private _endTexts(masked: string): Record { + return { + start: masked.substring(0, this._separatorStart), + end: masked.substring(this._separatorEnd), + }; + } + /** * Converts each date as a single date format and escapes the separator letters. * Returns an empty pattern while the base constructor runs. @@ -141,28 +142,20 @@ export class DateRangeMaskParser extends DateFormatMaskParser< } protected override _buildParts(): IDateRangePart[] { + const parts = this._dateParser.parts; + return [ - ...offsetParts(this._startParser.parts, 0, DateRangePosition.Start), - ...offsetParts( - this._endParser.parts, - this._separatorEnd, - DateRangePosition.End - ), + ...offsetParts(parts, 0, DateRangePosition.Start), + ...offsetParts(parts, this._separatorEnd, DateRangePosition.End), ]; } - /** - * Sets a new date format and updates both parsers. - * - * @remarks - * Takes the format of a *single* date; the getter returns the combined range format. - */ + /** Takes the format of one date; the getter returns the range format. */ public override set mask(value: string) { - this._startParser.mask = value; - this._endParser.mask = value; + this._dateParser.mask = value; this._setSeparatorBounds(); - const format = this._startParser.mask; + const format = this._dateParser.mask; super.mask = `${format}${this._separator}${format}`; } @@ -170,18 +163,10 @@ export class DateRangeMaskParser extends DateFormatMaskParser< return super.mask; } - /** - * Sets the prompt character and updates both parsers. - * - * @remarks - * All three parsers must agree on the prompt. It is read back through `super`, because - * the base setter normalizes the value. - */ + /** The date parser reads the prompt back through `super`, which normalizes it. */ public override set prompt(value: string) { super.prompt = value; - - this._startParser.prompt = this.prompt; - this._endParser.prompt = this.prompt; + this._dateParser.prompt = this.prompt; } public override get prompt(): string { @@ -190,18 +175,18 @@ export class DateRangeMaskParser extends DateFormatMaskParser< //#region Date Range Parsing - /** Parses a masked string into a DateRangeValue. Returns null if parsing fails. */ + /** Parses each end leniently. Gives `null` only for an empty mask. */ public parseDateRange(masked: string): DateRangeValue | null { if (!masked || masked === this.emptyMask) { return null; } - const start = this._startParser.parseDate( - masked.substring(0, this._separatorStart) - ); - const end = this._endParser.parseDate(masked.substring(this._separatorEnd)); + const text = this._endTexts(masked); - return { start, end }; + return { + start: this._dateParser.parseDate(text.start), + end: this._dateParser.parseDate(text.end), + }; } /** @@ -212,7 +197,7 @@ export class DateRangeMaskParser extends DateFormatMaskParser< masked: string, strict: boolean ): DateRangeValue | null { - if (strict && masked.includes(this.prompt)) { + if (strict && !this.isComplete(masked)) { return null; } @@ -220,16 +205,31 @@ export class DateRangeMaskParser extends DateFormatMaskParser< return parsed?.start || parsed?.end ? parsed : null; } + /** Parses each end alone, so an incomplete end keeps the end of `previous`. */ + public override parseEdit( + masked: string, + previous: DateRangeValue | null + ): DateRangeValue | null { + const text = this._endTexts(masked); + const start = this._dateParser.parseEdit( + text.start, + previous?.start ?? null + ); + const end = this._dateParser.parseEdit(text.end, previous?.end ?? null); + + return start || end ? { start, end } : null; + } + //#endregion //#region Date Range Formatting - /** Formats each end with its own parser. */ public override formatValue(range: DateRangeValue | null): string { - const start = this._startParser.formatValue(range?.start ?? null); - const end = this._endParser.formatValue(range?.end ?? null); - - return start + this._separator + end; + return ( + this._dateParser.formatValue(range?.start ?? null) + + this._separator + + this._dateParser.formatValue(range?.end ?? null) + ); } //#endregion @@ -245,7 +245,7 @@ export class DateRangeMaskParser extends DateFormatMaskParser< } public override defaultPart(): DateRangePart | undefined { - const part = this._startParser.defaultPart(); + const part = this._dateParser.defaultPart(); return part ? { part, position: DateRangePosition.Start } : undefined; } @@ -261,7 +261,7 @@ export class DateRangeMaskParser extends DateFormatMaskParser< return { ...value, - [position]: this._parserOf(position).spin(value[position], part, request), + [position]: this._dateParser.spin(value[position], part, request), }; } @@ -276,35 +276,25 @@ export class DateRangeMaskParser extends DateFormatMaskParser< return { masked: this.formatValue(value), value }; } - const text = { - start: masked.substring(0, this._separatorStart), - end: masked.substring(this._separatorEnd), - }; - const spun = this._parserOf(position).spinText( - text[position], - part, - request - ); + const text = this._endTexts(masked); + const spun = this._dateParser.spinText(text[position], part, request); text[position] = spun.masked; return { masked: text.start + this._separator + text.end, value: { - start: this._startParser.parseValue(text.start, true), - end: this._endParser.parseValue(text.end, true), + start: this._dateParser.parseValue(text.start, true), + end: this._dateParser.parseValue(text.end, true), [position]: spun.value, }, }; } public override seeded(seed: Date): DateRangeValue { - return { start: new Date(seed.getTime()), end: new Date(seed.getTime()) }; - } - - private _parserOf(position: DateRangePosition): DateTimeMaskParser { - return position === DateRangePosition.Start - ? this._startParser - : this._endParser; + return { + start: this._dateParser.seeded(seed), + end: this._dateParser.seeded(seed), + }; } //#endregion diff --git a/src/components/date-range-picker/date-range-picker-single.spec.ts b/src/components/date-range-picker/date-range-picker-single.spec.ts index 15f2a31b7..317b84580 100644 --- a/src/components/date-range-picker/date-range-picker-single.spec.ts +++ b/src/components/date-range-picker/date-range-picker-single.spec.ts @@ -17,6 +17,7 @@ import { } from '#internals/testing/form-testbed.spec.js'; import { checkDatesEqual, isFocused } from '#internals/testing/helpers.spec.js'; import { + simulateBackspaceOver, simulateCancelableKeydown, simulateInput, simulateKeyboard, @@ -705,6 +706,51 @@ describe('Date range picker - single input', () => { checkDatesEqual(calendar.activeDate, new Date(2025, 5, 20)); }); + it('selects a complete typed end and keeps it while the end is incomplete', async () => { + const eventSpy = spy(picker, 'emitEvent'); + const typed = [new Date(2025, 0, 10), new Date(2025, 5, 20)]; + + typeAt(input, '6', 14); + await elementUpdated(picker); + expect(calendar.values).to.eql(typed); + + // The year of the end. + await simulateBackspaceOver(rangeInput, 19, 23); + await elementUpdated(picker); + + expect(input.value).to.equal('01/10/2025 - 06/20/____'); + expect(calendar.values).to.eql(typed); + expect(eventSpy).calledWith('igcInput', { detail: null }); + expect(picker.value).to.eql({ + start: new Date(2025, 0, 10), + end: new Date(2025, 2, 20), + }); + }); + + it('keeps a typed start after the end while the start is incomplete', async () => { + // June 10 is after the end, so the calendar swaps the ends. + const typed = [new Date(2025, 2, 20), new Date(2025, 5, 10)]; + + typeAt(input, '6', 1); + await elementUpdated(picker); + expect(input.value).to.equal('06/10/2025 - 03/20/2025'); + expect(calendar.values).to.eql(typed); + + await simulateBackspaceOver(rangeInput, 6, 10); + await elementUpdated(picker); + + expect(input.value).to.equal('06/10/____ - 03/20/2025'); + expect(calendar.values).to.eql(typed); + }); + + it('drops a blank end from the selection', async () => { + await simulateBackspaceOver(rangeInput, 13, 23); + await elementUpdated(picker); + + expect(input.value).to.equal('01/10/2025 - __/__/____'); + expect(calendar.values).to.eql([new Date(2025, 0, 10)]); + }); + it('brings the start into view while the caret is in the separator', async () => { const eventSpy = spy(picker, 'emitEvent'); calendar.activeDate = new Date(2025, 8, 1); diff --git a/src/components/date-range-picker/date-range-picker-two-inputs.spec.ts b/src/components/date-range-picker/date-range-picker-two-inputs.spec.ts index dbba3a5ad..29b3e0d7e 100644 --- a/src/components/date-range-picker/date-range-picker-two-inputs.spec.ts +++ b/src/components/date-range-picker/date-range-picker-two-inputs.spec.ts @@ -10,6 +10,7 @@ import { } from '#internals/testing/form-testbed.spec.js'; import { checkDatesEqual, isFocused } from '#internals/testing/helpers.spec.js'; import { + simulateBackspaceOver, simulateBlur, simulateClick, simulateInput, @@ -24,6 +25,7 @@ import { checkSelectedRange, getIcon, selectDates, + typeAt, } from './date-range-picker.utils.spec.js'; describe('Date range picker - two inputs', () => { @@ -648,6 +650,92 @@ describe('Date range picker - two inputs', () => { checkDatesEqual(calendar.activeDate, june3rd2025); }); + + it('keeps the selected end while the typed date is incomplete, and drops it while blank', async () => { + const start = new Date(2025, 0, 10); + const end = new Date(2025, 2, 20); + const june10 = new Date(2025, 5, 10); + picker.inputFormat = 'MM/dd/yyyy'; + picker.value = { start, end }; + picker.open = true; + await elementUpdated(picker); + + const input = dateTimeInputs[0].renderRoot.querySelector('input')!; + dateTimeInputs[0].focus(); + await elementUpdated(dateTimeInputs[0]); + + // June 10 is after the end, so the calendar swaps the ends. + typeAt(input, '6', 1); + await elementUpdated(picker); + expect(calendar.values).to.eql([end, june10]); + + // The year of the start. + await simulateBackspaceOver(dateTimeInputs[0], 6, 10); + await elementUpdated(picker); + + expect(input.value).to.equal('06/10/____'); + expect(calendar.values).to.eql([end, june10]); + + await simulateBackspaceOver(dateTimeInputs[0], 0, 10); + await elementUpdated(picker); + + expect(calendar.values).to.eql([end]); + expect(picker.value).to.eql({ start, end }); + }); + + it('keeps the edit of an end that keeps its date when code sets a new range', async () => { + const start = new Date(2025, 0, 10); + const end = new Date(2025, 2, 20); + const april1 = new Date(2025, 3, 1); + const june10 = new Date(2025, 5, 10); + picker.inputFormat = 'MM/dd/yyyy'; + picker.value = { start, end }; + picker.open = true; + await elementUpdated(picker); + + const input = dateTimeInputs[0].renderRoot.querySelector('input')!; + dateTimeInputs[0].focus(); + await elementUpdated(dateTimeInputs[0]); + + typeAt(input, '6', 1); + await elementUpdated(picker); + expect(calendar.values).to.eql([end, june10]); + + picker.value = { start: new Date(start.getTime()), end: april1 }; + await elementUpdated(picker); + + expect(input.value).to.equal('06/10/2025'); + expect(calendar.values).to.eql([april1, june10]); + }); + + it('selects the value when the focus moves to the other input', async () => { + const start = new Date(2025, 0, 1); + const end = new Date(2025, 2, 20); + picker.inputFormat = 'MM/dd/yyyy'; + picker.value = { start, end }; + picker.open = true; + await elementUpdated(picker); + + const input = dateTimeInputs[0].renderRoot.querySelector('input')!; + dateTimeInputs[0].focus(); + await elementUpdated(dateTimeInputs[0]); + + typeAt(input, '6', 1); + await elementUpdated(picker); + + // Only the year stays, so the commit fills the month and the day: January 1, the same start. + await simulateBackspaceOver(dateTimeInputs[0], 0, 5); + await elementUpdated(picker); + expect(calendar.values).to.eql([end, new Date(2025, 5, 1)]); + + const eventSpy = spy(picker, 'emitEvent'); + dateTimeInputs[1].focus(); + await elementUpdated(picker); + + expect(eventSpy).not.calledWith('igcChange'); + expect(picker.value).to.eql({ start, end }); + expect(calendar.values).to.eql([start, end]); + }); }); describe('Readonly state', () => { beforeEach(async () => { diff --git a/src/components/date-range-picker/date-range-picker.form.spec.ts b/src/components/date-range-picker/date-range-picker.form.spec.ts index daf3fe67f..477d18219 100644 --- a/src/components/date-range-picker/date-range-picker.form.spec.ts +++ b/src/components/date-range-picker/date-range-picker.form.spec.ts @@ -11,6 +11,7 @@ import { type ValidationContainerTestsParams, ValidityHelpers, } from '#internals/testing/validity-helpers.spec.js'; +import IgcCalendarComponent from '../calendar/calendar.js'; import { type DateRangeDescriptor, DateRangeType } from '../calendar/types.js'; import IgcDateTimeInputComponent from '../date-time-input/date-time-input.js'; import IgcDateRangeInputComponent from './date-range-input.js'; @@ -192,6 +193,41 @@ describe('Date range picker - Form integration', () => { ); }); + it('drops the typed calendar selection on a form reset that keeps the value', async () => { + const defaultRange = { + start: new Date(2024, 0, 15), + end: new Date(2024, 0, 20), + }; + spec.setProperties({ defaultValue: defaultRange }); + await elementUpdated(spec.element); + + const [editor] = getEditors(spec.element); + const input = getInput(spec.element); + const calendar = spec.element.renderRoot.querySelector( + IgcCalendarComponent.tagName + )!; + + editor.focus(); + await elementUpdated(editor); + + // January 17 as the start. + typeAt(input, '7', 4); + await elementUpdated(spec.element); + expect(calendar.values).to.eql([ + new Date(2024, 0, 17), + defaultRange.end, + ]); + + spec.reset(); + await elementUpdated(spec.element); + + expect(spec.element.value).to.eql(defaultRange); + expect(calendar.values).to.eql([ + defaultRange.start, + defaultRange.end, + ]); + }); + it('should not be in invalid state on reset for a required control which previously had value', async () => { spec.setProperties({ value }); spec.setProperties({ required: true }); diff --git a/src/components/date-range-picker/date-range-picker.ts b/src/components/date-range-picker/date-range-picker.ts index d45dbfb57..994a2e461 100644 --- a/src/components/date-range-picker/date-range-picker.ts +++ b/src/components/date-range-picker/date-range-picker.ts @@ -19,6 +19,7 @@ import { I18nMixin } from '#internals/mixins/i18n.js'; import { isEmpty } from '#internals/utils/arrays.js'; import { bindIf } from '#internals/utils/lit.js'; import { asNumber, clamp } from '#internals/utils/math.js'; +import { equal } from '#internals/utils/objects.js'; import { createIdGenerator } from '#internals/utils/strings.js'; import { all } from '#themes/date-range-picker/themes/themes.js'; import { addThemingController } from '#theming/theming-controller.js'; @@ -270,6 +271,22 @@ export default class IgcDateRangePickerComponent extends I18nMixin( return this.resourceStrings; } + /** With two inputs, the editor of an end that keeps its date keeps its edit. */ + protected override _editAfterValueChange( + previous: DateRangeValue | null + ): { value: DateRangeValue | null } | undefined { + if (!(this.useTwoInputs && this._editValue)) return undefined; + + const edit = this._editValue.value; + const value = this._value; + const end = (key: keyof DateRangeValue): Date | null => + equal(previous?.[key] ?? null, value?.[key] ?? null) + ? (edit?.[key] ?? null) + : (value?.[key] ?? null); + + return { value: { start: end('start'), end: end('end') } }; + } + protected override get _defaultDisplayFormat(): string | undefined { return this._inputFormat ?? getLocaleDateTimeFormats(this.locale).display; } @@ -426,12 +443,12 @@ export default class IgcDateRangePickerComponent extends I18nMixin( } protected override willUpdate(changedProperties: PropertyValues): void { - // The render swaps the editors, so a typed draft goes with them. + // The render swaps the editors, so an edit goes with them. if ( changedProperties.has('useTwoInputs') || changedProperties.has('mode') ) { - this._draft = undefined; + this._editValue = undefined; } super.willUpdate(changedProperties); @@ -479,13 +496,13 @@ export default class IgcDateRangePickerComponent extends I18nMixin( } const editors = this._editors; - const draft = normalizeRange(editors.typed()); - const typed = editors.typedDate(event.target as PickerEditor); + const typed = normalizeRange(editors.typed()); + const typedDate = editors.typedDate(event.target as PickerEditor); - this._draft = { value: draft }; - this._setCalendarActiveDate(typed ?? draft?.start ?? draft?.end); + this._editValue = { value: editors.edit(this._calendarValue) }; + this._setCalendarActiveDate(typedDate ?? typed?.start ?? typed?.end); - this.emitEvent('igcInput', { detail: draft }); + this.emitEvent('igcInput', { detail: typed }); } protected _handleEditorChange(event: Event): void { @@ -498,19 +515,6 @@ export default class IgcDateRangePickerComponent extends I18nMixin( // #region Private methods - /** - * Stops the inner event of an editor, and returns whether the editor belongs to the layout that `useTwoInputs` - * selects. An editor that a layout change removes commits nothing, as its typed text goes with it. The events of - * slotted content go on to the application. - */ - private _acceptEditorEvent(event: Event): boolean { - const target = event.target as PickerEditor; - if (target.getRootNode() !== this.renderRoot) return false; - - event.stopPropagation(); - return this._ownedEditors.includes(target); - } - /** Applies a predefined range like a calendar selection. */ private _handleRangeSelect({ detail }: CustomEvent): void { if (this._isClosing) return; diff --git a/src/components/date-range-picker/range-editors.spec.ts b/src/components/date-range-picker/range-editors.spec.ts index 93e9ee072..4622fdbe1 100644 --- a/src/components/date-range-picker/range-editors.spec.ts +++ b/src/components/date-range-picker/range-editors.spec.ts @@ -2,6 +2,7 @@ import { elementUpdated, expect, fixture, html } from '@open-wc/testing'; import type { TemplateResult } from 'lit'; import { defineComponents } from '#internals/definitions/defineComponents.js'; import { isFocused } from '#internals/testing/helpers.spec.js'; +import { simulateBackspaceOver } from '#internals/testing/simulate.spec.js'; import type { PickerEditor } from '../date-picker/date-picker.base.js'; import IgcDateTimeInputComponent from '../date-time-input/date-time-input.js'; import type { DateRangeValue } from '../types.js'; @@ -110,6 +111,35 @@ describe('Range picker editors', () => { expect(subject().committed()).to.eql({ start, end }); }); + it('gives the range of the editors as the edit without an edit', () => { + expect(subject().edit({ start: june10, end: june10 })).to.eql({ + start, + end, + }); + }); + + it('gives an edit that keeps the typed order, the previous end while incomplete and no end while blank', async () => { + const august1 = new Date(2025, 7, 1); + const previous = { start: august1, end: august1 }; + const input = nativeInput(editors[0]); + + editors[0].focus(); + await elementUpdated(editors[0]); + + // June 10 is after the end. + typeAt(input, '6', 1); + await elementUpdated(editors[0]); + expect(subject().edit(null)).to.eql({ start: june10, end }); + + // The year of the start. + await simulateBackspaceOver(editors[0], 6, 10); + expect(subject().edit(previous)).to.eql({ start: august1, end }); + expect(subject().edit(null)).to.eql({ start: null, end }); + + await simulateBackspaceOver(editors[0], 0, 10); + expect(subject().edit(previous)).to.eql({ start: null, end }); + }); + it('gives the focus to the start editor after a pick', () => { subject().focusAfterPick(); diff --git a/src/components/date-range-picker/range-editors.ts b/src/components/date-range-picker/range-editors.ts index 22bf5262a..5bb5f6e59 100644 --- a/src/components/date-range-picker/range-editors.ts +++ b/src/components/date-range-picker/range-editors.ts @@ -6,17 +6,19 @@ import IgcDateRangeInputComponent, { typedPosition, } from './date-range-input.js'; -/** - * The editors of one layout of the range picker in its render root, which holds the editors of the active layout - * only: a single range input, or a start and an end input. - */ +/** The editors of the active range picker layout. Each instance reads its render root once. */ export interface RangeEditors { /** The editors, the start editor first. */ editors(): PickerEditor[]; - /** The range as the user types it. */ + /** The range as the user types it. A single input gives `null` until both ends are complete. */ typed(): DateRangeValue | null; /** The date that the user types in `target`; in a range input, the end at the caret. */ typedDate(target: PickerEditor): Date | null; + /** + * The range that the calendar selects while the user types. An incomplete end keeps the end of `previous`, a blank + * end is `null`. The ends keep the typed order. + */ + edit(previous: DateRangeValue | null): DateRangeValue | null; /** The range that the editors hold. */ committed(): DateRangeValue | null; /** Gives the focus back to the start editor after a calendar pick. */ @@ -24,14 +26,10 @@ export interface RangeEditors { } class SingleInputEditors implements RangeEditors { - private readonly _root: ParentNode; + private readonly _input: IgcDateRangeInputComponent | null; constructor(root: ParentNode) { - this._root = root; - } - - private get _input(): IgcDateRangeInputComponent | null { - return this._root.querySelector(IgcDateRangeInputComponent.tagName); + this._input = root.querySelector(IgcDateRangeInputComponent.tagName); } public editors(): PickerEditor[] { @@ -51,6 +49,10 @@ class SingleInputEditors implements RangeEditors { return position ? (input._uncommittedValue?.[position] ?? null) : null; } + public edit(previous: DateRangeValue | null): DateRangeValue | null { + return this._input?._parseEdit(previous) ?? null; + } + public committed(): DateRangeValue | null { return this._input?.value ?? null; } @@ -61,25 +63,24 @@ class SingleInputEditors implements RangeEditors { } class TwoInputEditors implements RangeEditors { - private readonly _root: ParentNode; + private readonly _inputs: IgcDateTimeInputComponent[]; constructor(root: ParentNode) { - this._root = root; - } - - private get _inputs(): IgcDateTimeInputComponent[] { - return Array.from( - this._root.querySelectorAll(IgcDateTimeInputComponent.tagName) + this._inputs = Array.from( + root.querySelectorAll(IgcDateTimeInputComponent.tagName) ); } private _readEnds( - read: (input: IgcDateTimeInputComponent) => Date | null + read: ( + input: IgcDateTimeInputComponent, + end: keyof DateRangeValue + ) => Date | null ): DateRangeValue { const [start, end] = this._inputs; return { - start: start ? read(start) : null, - end: end ? read(end) : null, + start: start ? read(start, 'start') : null, + end: end ? read(end, 'end') : null, }; } @@ -87,8 +88,9 @@ class TwoInputEditors implements RangeEditors { return this._inputs; } + /** Without a previous range, the edit of a date-time input is its strict parse. */ public typed(): DateRangeValue { - return this._readEnds((input) => input._uncommittedValue); + return this.edit(null); } public typedDate(target: PickerEditor): Date | null { @@ -97,6 +99,12 @@ class TwoInputEditors implements RangeEditors { ); } + public edit(previous: DateRangeValue | null): DateRangeValue { + return this._readEnds((input, end) => + input._parseEdit(previous?.[end] ?? null) + ); + } + public committed(): DateRangeValue { return this._readEnds((input) => input.value); } diff --git a/src/components/date-range-picker/range-shape.spec.ts b/src/components/date-range-picker/range-shape.spec.ts index 83ab11b2d..8f449a6b5 100644 --- a/src/components/date-range-picker/range-shape.spec.ts +++ b/src/components/date-range-picker/range-shape.spec.ts @@ -94,6 +94,12 @@ describe('Picker value shapes', () => { ).to.eql([june1, june5]); }); + it('gives the ends of a reversed range in order', () => { + expect( + rangeShape.toCalendar({ start: june5, end: june1 }).values + ).to.eql([june1, june5]); + }); + it('gives one date for a range in one day', () => { expect( rangeShape.toCalendar({ start: june5Morning, end: june5Evening }) diff --git a/src/components/date-range-picker/range-shape.ts b/src/components/date-range-picker/range-shape.ts index 554f89e62..aac73d7aa 100644 --- a/src/components/date-range-picker/range-shape.ts +++ b/src/components/date-range-picker/range-shape.ts @@ -64,7 +64,10 @@ function rangeDates(value: DateRangeValue | null): Date[] { export const rangeShape: PickerValueShape = { selection: 'range', - toCalendar: (value) => ({ value: null, values: rangeDates(value) }), + toCalendar: (value) => ({ + value: null, + values: rangeDates(normalizeRange(value)), + }), fromCalendar: (dates) => isEmpty(dates) ? null : { start: firstOf(dates), end: lastOf(dates) }, // The first pick gives one date, the second every date of the range, and a pick of the start again none. diff --git a/src/components/date-range-picker/spec.md b/src/components/date-range-picker/spec.md index dda82c5f6..1592215b6 100644 --- a/src/components/date-range-picker/spec.md +++ b/src/components/date-range-picker/spec.md @@ -88,6 +88,7 @@ | 28 | 2026-11-20 | The ends of a range accept an ISO string with a signed six digit year; the value shape properties use any valid date | | 29 | 2026-11-23 | A disabled picker stays closed and disabling discards a draft; the shared disabled popup suite | | 30 | 2026-11-20 | A range that the user picks animates the inputs; a value from code, also from an `igcChange` handler, shows at once | +| 31 | 2026-11-25 | While the user types, an incomplete or invalid end keeps the end that the calendar selects, and a blank end drops out, in both layouts; the calendar shows the value again when the edit ends, and with two inputs a new range from code keeps the edit of an end whose date stays; a complete range parses strictly when the separator holds the prompt | ## Overview @@ -198,6 +199,9 @@ As a developer, I expect to be able to: - Typing a date selects it in the calendar and brings its month into view. The date is the one in the focused editor with two inputs, and the end at the caret in single input mode. While that date is incomplete, or while the caret is in the separator, the start comes into view, or the end when there is no start. +- Each end of the calendar selection follows its typed date on its own. While a typed end is incomplete or invalid, + the calendar keeps the end that it selects, and a blank end drops out of the selection. The value does not change + until the edit is committed. - In single input mode the field is editable in dropdown mode and read-only in dialog mode. Each end spins like a date-time input, with the same step rules and the day of the start date as the default part. A spin while you type reads the typed text of its end and keeps the text of the other end, also a `stepUp` or `stepDown` from code, @@ -690,7 +694,9 @@ input and two inputs suites run with reduced motion, so the dialog does not fade 13. Interactions - interactions with the input and the open and clear buttons. A closed picker does not cancel Escape. Ctrl + arrow stops at each part edge, also without separators. Arrow keys and `stepUp` in a range with one typed end spin that end and keep the text of the other end. Typing or a spin in the end brings - the end into view; an edit with the caret in the separator brings the start into view. + the end into view; an edit with the caret in the separator brings the start into view. The calendar selects a + complete typed end, keeps the selected end while the typed end is incomplete, also a start typed after the end, + and drops a blank end. 14. Undo and redo of the masked range text. 15. Slots. @@ -703,7 +709,10 @@ input and two inputs suites run with reduced motion, so the dialog does not fade 19. Interactions - selection through the calendar, interactions with the inputs and the open and clear buttons, and the readonly state. An editor commit keeps the time of both ends. A typed end before the start is swapped in the `igcInput` detail and in the calendar, while the editors keep the typed order. A clear through the icon is - reported one time, when the focus leaves the picker, and not when the focus moves to the other input. + reported one time, when the focus leaves the picker, and not when the focus moves to the other input. The + calendar keeps the selected start while the typed start is incomplete and drops a blank one; a move of the focus + to the other input shows the value again, also when the commit keeps the value; a new range from code keeps the + edit of an end whose date stays, as its editor does. 20. Slots. ### Form integration suite @@ -712,7 +721,8 @@ The form suite runs these groups in each layout: 21. Form associated - submission, also under a changed `name`, reset and the disabled ancestor state. A reset during an edit discards the typed text, with and without a default, and the next blur keeps the restored value. A reset - that empties the value shows the empty mask in the focused editor. Enter submits when the range is + that empties the value shows the empty mask in the focused editor, and a reset that keeps the value drops the typed + calendar selection. Enter submits when the range is valid, and a real Enter submits once. Each editor shows the invalid state of the picker. 22. Initial validation - a click on the calendar icon does not make a required picker invalid. 23. `defaultValue` - initial state, submission, reset and validation. @@ -737,14 +747,15 @@ The focus after the form checks and the `invalid` event rules come from the form ### Range mask parser 28. Initialization (a literal separator and a widened year format), range parsing, range formatting, part queries, - spinning, prompt updates and mask updates. + spinning, prompt updates and mask updates. A complete range parses strictly when the separator holds the prompt. ### Range mask parser properties 29. For generated formats, separators and dates: the round-trip, each side parsed like a single date, the layout around the separator after a mask change, and no throw or invalid date for any string. A strict value parse gives a range only when both ends are complete; a lenient one parses each end as typed, and gives `null` when - neither end is a valid date or the mask is blank. For the part editing: + neither end is a valid date or the mask is blank. An edit parse gives each complete end, the end of the previous + range while an end is incomplete, and no end while it is blank. For the part editing: each end spins like a single date, also from its text while the text of the other end stays; an empty range takes the seed at both ends; the part at the caret and the default part name their end. @@ -753,7 +764,8 @@ The focus after the form checks and the `invalid` event rules come from the form 30. Without a DOM: an empty range is `null`; a range in order stays the same object; reversed ends swap, by time also on the same day; a missing end becomes `null`. The form value transformers normalize a value, a default value and an attribute string, and compare ranges by their dates. The calendar dates of a range, a range in one day, a - partial range and no range; the range of a calendar selection; a complete range. + partial range and no range, and the ends of a reversed range in order; the range of a calendar selection; a + complete range. ### Range value shape properties @@ -767,7 +779,9 @@ The focus after the form checks and the `invalid` event rules come from the form 32. For each layout: the editors, the start editor first, and none in a root without them; the range of the editors; the typed range and the typed date during an edit of the start, while the committed range stays; the focus on the - start editor after a pick, which selects its text only with two inputs. In the single input, the end at the + start editor after a pick, which selects its text only with two inputs. The edit is the range of the editors + without an edit; during an edit of the start it keeps the typed order, the start of the previous range while the + start is incomplete, and no start while it is blank. In the single input, the end at the caret, also at the edge of a part and nothing in the separator, gives the typed date; with two inputs, each editor gives its own date. diff --git a/src/components/date-time-input/date-part.ts b/src/components/date-time-input/date-part.ts index 67422d823..00a3e104a 100644 --- a/src/components/date-time-input/date-part.ts +++ b/src/components/date-time-input/date-part.ts @@ -4,7 +4,11 @@ */ import { daysInMonth } from '#internals/date/model.js'; -import { clamp, modulo } from '#internals/utils/math.js'; +import { + clamp, + modulo, + numberInRangeInclusive, +} from '#internals/utils/math.js'; //#region Types and Enums @@ -18,17 +22,8 @@ export enum DatePart { AmPm = 'amPm', } -/** Types of date/time parts that can appear in a format string */ -export const DatePartType = { - Month: 'month', - Year: 'year', - Date: 'date', - Hours: 'hours', - Minutes: 'minutes', - Seconds: 'seconds', - AmPm: 'amPm', - Literal: 'literal', -} as const; +/** The part types of a format string: the date parts and the literals between them. */ +export const DatePartType = { ...DatePart, Literal: 'literal' } as const; export type DatePartType = (typeof DatePartType)[keyof typeof DatePartType]; @@ -65,7 +60,6 @@ export interface DatePartDeltas { seconds?: number; } -/** Options for creating a date part */ export interface DatePartOptions { /** Start position in the masked string */ start: number; @@ -75,13 +69,12 @@ export interface DatePartOptions { format: string; } /* blazorSuppress */ -/** Options for spin operations */ export interface SpinOptions { /** The current date value */ date: Date; /** Whether to loop values at boundaries */ spinLoop: boolean; - /** For AM/PM: the current masked value to determine AM or PM */ + /** For AM/PM: `AM` or `PM`, the side of the value. */ amPmValue?: string; /** For AM/PM: the original date (for rollover prevention) */ originalDate?: Date; @@ -93,22 +86,14 @@ export interface SpinOptions { */ export interface IDatePart { readonly type: DatePartType; - /** Start position in the masked string */ readonly start: number; - /** End position in the masked string */ readonly end: number; readonly format: string; - /** - * Validates a numeric value for this part. - * @param context - Optional context (year, month) for date-dependent validation - */ + /** Whether `value` is valid; `context` gives the month length. */ validate(value: number, context?: DateValidationContext): boolean; - /** - * Spins (increments/decrements) this part's value on the given date. - * @param delta - The amount to spin (positive = up, negative = down) - */ + /** Spins this part of `options.date` by `delta`. */ spin(delta: number, options: SpinOptions): void; /** Returns the formatted value of this part for `date`. */ @@ -272,7 +257,11 @@ class YearPart extends DatePartBase { class MonthPart extends DatePartBase { override validate(value: number): boolean { // Month is 0-based internally, but 1-12 in display - return value >= DATE_BOUNDS.month.min && value <= DATE_BOUNDS.month.max; + return numberInRangeInclusive( + value, + DATE_BOUNDS.month.min, + DATE_BOUNDS.month.max + ); } override spin(delta: number, options: SpinOptions): void { @@ -333,7 +322,7 @@ class TimePart extends DatePartBase { } override validate(value: number): boolean { - return value >= this._config.min && value <= this._config.max; + return numberInRangeInclusive(value, this._config.min, this._config.max); } override spin(delta: number, options: SpinOptions): void { diff --git a/src/components/date-time-input/date-time-input.base.ts b/src/components/date-time-input/date-time-input.base.ts index 0329ed958..1c2e45505 100644 --- a/src/components/date-time-input/date-time-input.base.ts +++ b/src/components/date-time-input/date-time-input.base.ts @@ -116,7 +116,7 @@ export abstract class IgcDateTimeInputBaseComponent< protected _isEditing = false; /** - * The parsed draft during an edit, else the committed value. + * The strict parse of the edit, else the committed value. * * @hidden @internal */ @@ -126,6 +126,17 @@ export abstract class IgcDateTimeInputBaseComponent< : this.value; } + /** + * The calendar selection of a picker during an edit (see `parseEdit`), else the committed value. + * + * @hidden @internal + */ + public _parseEdit(previous: T | null): T | null { + return this._isEditing + ? this._parser.parseEdit(this._maskedValue, previous) + : this.value; + } + // #endregion // #region Public attributes and properties @@ -327,7 +338,7 @@ export abstract class IgcDateTimeInputBaseComponent< } protected _setCurrentDateTime(): void { - this._setDraftValue(this._parser.seeded(this._seedDate())); + this._editTo(this._parser.seeded(this._seedDate())); this._emitInputEvent(); } @@ -376,14 +387,14 @@ export abstract class IgcDateTimeInputBaseComponent< return true; } - /** Keeps the selection. With `commit`, a focused editor also updates `value`, not only the draft. */ + /** Keeps the selection. With `commit`, a focused editor also updates `value`, not only the edit. */ protected _applyStep(value: T, commit: boolean, masked?: string): void { const { start, end } = this._inputSelection; - this._setDraftValue(value, masked); + this._editTo(value, masked); - // A focused editor holds the step as a draft. Commit the exact value: the mask can lack the stepped part. + // A focused editor holds the step as an edit. Commit the exact value: the mask can lack the stepped part. if (commit && this._focused) { - this._applyDraft(value); + this._applyEdit(value); // The value cannot hold a partial range end, so its typed text stays as an edit. if (masked !== undefined && masked !== this._maskedValue) { @@ -416,10 +427,10 @@ export abstract class IgcDateTimeInputBaseComponent< } /** - * Applies a value from a spin or `Ctrl + ;`. A focused editor moves only the draft. + * Applies a value from a spin or `Ctrl + ;`. A focused editor moves only the edit. * An unfocused one commits at once, because no blur follows. */ - protected _setDraftValue(value: T, masked?: string): void { + protected _editTo(value: T, masked?: string): void { if (!this._focused) { this.value = value; return; @@ -438,10 +449,6 @@ export abstract class IgcDateTimeInputBaseComponent< return new Date(); } - /** - * Whether the committed value is empty. Focus then starts the edit from the - * empty mask, not from the formatted value. - */ protected override _isValueEmpty(): boolean { return !this.value; } @@ -468,7 +475,7 @@ export abstract class IgcDateTimeInputBaseComponent< } /** Applies the masked text, or `value`, to the public value without emitting anything. */ - protected _applyDraft( + protected _applyEdit( value: T | null = this._parser.parseValue(this._maskedValue, true) ): void { this._isEditing = false; @@ -477,7 +484,7 @@ export abstract class IgcDateTimeInputBaseComponent< this._updateMaskDisplay(); } - /** Commits the draft to the public value. Emits `igcChange` if the value differs from the reported value. */ + /** Commits the edit to the public value. Emits `igcChange` if the value differs from the reported value. */ protected _commitEdit(): void { // Only a real edit is parsed again. A display-formatted mask parses wrong // under the input format. @@ -512,7 +519,7 @@ export abstract class IgcDateTimeInputBaseComponent< } // A change outside an edit, such as a drop on an unfocused input, gets no blur. - this._applyDraft(); + this._applyEdit(); } /** Drops the typed text, which `_buildMaskedValue` keeps for an empty value. */ @@ -528,9 +535,7 @@ export abstract class IgcDateTimeInputBaseComponent< super._resetValidationState(); } - /** - * Applies a mask pattern to the input, parsing the format string into date parts. - */ + /** Sets the input format. A placeholder that showed the old format follows it. */ protected _applyMask(formatString: string): void { const previous = this._parser.mask; this._parser.mask = formatString; @@ -613,7 +618,7 @@ export abstract class IgcDateTimeInputBaseComponent< selectMode?: RangeTextSelectMode ): void { super.setRangeText(replacement, start, end, selectMode); - this._applyDraft(); + this._applyEdit(); } /** Clears the value and the text of the input. */ diff --git a/src/components/date-time-input/datetime-mask-parser.property.spec.ts b/src/components/date-time-input/datetime-mask-parser.property.spec.ts index c3ad42192..a5594f84f 100644 --- a/src/components/date-time-input/datetime-mask-parser.property.spec.ts +++ b/src/components/date-time-input/datetime-mask-parser.property.spec.ts @@ -136,6 +136,52 @@ describe('Date-time mask parser properties', () => { ); }); + it('reads the prompt only in the parts, also when a literal is the prompt', () => { + const prompts = ['-', '/', '.', ':']; + // Mostly digits, so most masks are complete. Only characters that fit a part, so + // both parsers place them the same. + const partInput = fc.string({ + unit: fc.oneof( + { weight: 9, arbitrary: fc.constantFrom(...'0123456789') }, + { weight: 1, arbitrary: fc.constantFrom(...'APMapm') } + ), + minLength: 8, + maxLength: 24, + }); + + fc.assert( + fc.property( + formatOf(ALL_PARTS, prompts), + partInput, + fc.constantFrom(...prompts), + fc.option(date, { nil: null }), + (format, input, prompt, previous) => { + // No format uses `_`, the default prompt. + const reference = new DateTimeMaskParser({ format }); + const parser = new DateTimeMaskParser({ + format, + promptCharacter: prompt, + }); + const typed = reference.apply(input); + const masked = parser.apply(input); + const strict = reference.parseValue(typed, true); + const edit = reference.isBlank(typed) ? null : (strict ?? previous); + + expect(parser.isComplete(masked), masked).to.equal( + !typed.includes(reference.prompt) + ); + expect(parser.parseValue(masked, true)?.getTime(), masked).to.equal( + strict?.getTime() + ); + expect( + parser.parseEdit(masked, previous)?.getTime(), + masked + ).to.equal(edit?.getTime()); + } + ) + ); + }); + it('round-trips a date through formatValue and parseDate', () => { fc.assert( fc.property(paddedFormat, date, (format, value) => { diff --git a/src/components/date-time-input/datetime-mask-parser.spec.ts b/src/components/date-time-input/datetime-mask-parser.spec.ts index 62a30508f..ef8cb17d2 100644 --- a/src/components/date-time-input/datetime-mask-parser.spec.ts +++ b/src/components/date-time-input/datetime-mask-parser.spec.ts @@ -241,6 +241,48 @@ describe('DateTimeMaskParser', () => { }); }); + describe('Edit Parsing', () => { + const parser = new DateTimeMaskParser({ format: 'MM/dd/yyyy' }); + const previous = new Date(2020, 0, 1); + + it('gives the date of a complete mask', () => { + const date = parser.parseEdit('12/25/2023', previous); + + expect(date?.getTime()).to.equal(new Date(2023, 11, 25).getTime()); + }); + + it('keeps the previous date while the date is incomplete', () => { + expect(parser.parseEdit('12/25/20__', previous)).to.equal(previous); + expect(parser.parseEdit('1_/__/____', previous)).to.equal(previous); + expect(parser.parseEdit('12/25/20__', null)).to.be.null; + }); + + it('keeps the previous date for an invalid date', () => { + expect(parser.parseEdit('02/30/2023', previous)).to.equal(previous); + }); + + it('gives null for a blank mask', () => { + expect(parser.parseEdit('__/__/____', previous)).to.be.null; + expect(parser.parseEdit('', previous)).to.be.null; + }); + + it('parses a complete mask when a literal is the prompt', () => { + const dashed = new DateTimeMaskParser({ + format: 'yyyy-MM-dd', + promptCharacter: '-', + }); + const date = new Date(2023, 11, 25); + + expect(dashed.parseValue('2023-12-25', true)?.getTime()).to.equal( + date.getTime() + ); + expect(dashed.parseEdit('2023-12-25', previous)?.getTime()).to.equal( + date.getTime() + ); + expect(dashed.parseEdit('2023-12---', previous)).to.equal(previous); + }); + }); + describe('Part Queries', () => { it('gets date part at cursor position', () => { const parser = new DateTimeMaskParser({ format: 'MM/dd/yyyy' }); diff --git a/src/components/date-time-input/datetime-mask-parser.ts b/src/components/date-time-input/datetime-mask-parser.ts index 69e6848d9..774f523e6 100644 --- a/src/components/date-time-input/datetime-mask-parser.ts +++ b/src/components/date-time-input/datetime-mask-parser.ts @@ -44,7 +44,6 @@ export interface SpunText { //#region Constants -/** Maps format characters to their corresponding DatePartType */ const FORMAT_CHAR_TO_DATE_PART = new Map([ ['d', DatePartType.Date], ['D', DatePartType.Date], @@ -60,7 +59,6 @@ const FORMAT_CHAR_TO_DATE_PART = new Map([ ['T', DatePartType.AmPm], ]); -/** Century threshold for two-digit year interpretation */ const CENTURY_THRESHOLD = 50; const CENTURY_BASE = 2000; @@ -76,7 +74,6 @@ function resolveYear(year: number, typed: string): number { return year + (year < CENTURY_THRESHOLD ? CENTURY_BASE : CENTURY_BASE - 100); } -/** Default values for missing date parts */ const DEFAULT_DATE_VALUES = { year: 2000, month: 0, @@ -190,7 +187,6 @@ export abstract class DateFormatMaskParser< ); } - /** The first part of the given type, if the format contains one. */ public getPartByType(type: DatePartType): T | undefined { return this.parts.find((part) => part.type === type); } @@ -208,6 +204,15 @@ export abstract class DateFormatMaskParser< ); } + /** Whether no date/time position is a prompt. A literal can match the prompt. */ + public isComplete(masked: string): boolean { + return this.parts.every( + (part) => + part.type === DatePartType.Literal || + !masked.substring(part.start, part.end).includes(this.prompt) + ); + } + /** Whether the format contains a day, month or year part. */ public hasDateParts(): boolean { return this.parts.some((part) => DATE_PART_TYPES.has(part.type)); @@ -244,6 +249,9 @@ export abstract class DateFormatMaskParser< */ public abstract parseValue(masked: string, strict: boolean): V | null; + /** Parses an edit. A blank mask gives `null`; an incomplete or invalid date keeps `previous`. */ + public abstract parseEdit(masked: string, previous: V | null): V | null; + /** Formats a value into the editable mask. */ public abstract formatValue(value: V | null): string; @@ -361,7 +369,7 @@ export class DateTimeMaskParser extends DateFormatMaskParser< /** An invalid date gives `null` in both modes. */ public override parseValue(masked: string, strict: boolean): Date | null { - if ((strict && masked.includes(this.prompt)) || this.isBlank(masked)) { + if ((strict && !this.isComplete(masked)) || this.isBlank(masked)) { return null; } @@ -369,11 +377,19 @@ export class DateTimeMaskParser extends DateFormatMaskParser< return isValidDate(parsed) ? parsed : null; } + public override parseEdit( + masked: string, + previous: Date | null + ): Date | null { + return ( + this.parseValue(masked, true) ?? (this.isBlank(masked) ? null : previous) + ); + } + /** Parses a masked string into a Date. Returns null if it is not a valid date. */ public parseDate(masked: string): Date | null { const parts = this._extractDateValues(masked); - // Convert to zero-based month (only if month is in format) if (parts[DatePartType.Month] !== undefined) { parts[DatePartType.Month]! -= 1; } @@ -432,9 +448,6 @@ export class DateTimeMaskParser extends DateFormatMaskParser< }); } - /** - * Applies AM/PM conversion to hours if format includes AM/PM. - */ private _applyAmPmConversion( parts: Partial>, masked: string @@ -453,9 +466,6 @@ export class DateTimeMaskParser extends DateFormatMaskParser< (hours % 12) + (marker.toLowerCase() === 'pm' ? 12 : 0); } - /** - * Creates a Date object from parsed parts with defaults for missing values. - */ private _createDateFromParts( parts: Partial> ): Date { @@ -505,7 +515,7 @@ export class DateTimeMaskParser extends DateFormatMaskParser< return this.seeded(request.seed); } - const type = part as unknown as DatePartType; + const type: DatePartType = part; const step = request.delta || request.spinDelta?.[part as keyof DatePartDeltas] || 1; const date = new Date(value.getTime()); diff --git a/src/components/date-time-input/spec.md b/src/components/date-time-input/spec.md index 05ed26ac8..6f0adc214 100644 --- a/src/components/date-time-input/spec.md +++ b/src/components/date-time-input/spec.md @@ -76,6 +76,7 @@ | 19 | 2026-11-20 | A form reset discards the text that the user typed and did not commit; a focused input then shows the empty mask or the default; an empty value from code replaces the text of the old value | | 20 | 2026-11-20 | A year spin stops at year 1 and at year 9999 and does not loop; a year outside them only moves toward them; the value accepts an ISO string with a signed six digit year | | 21 | 2026-11-20 | A value from code and the first render show at once, also the Material label that moves up; no transitions with reduced motion; while a change shows at once, the transitions that the app sets on parts and slotted elements stop too | +| 22 | 2026-11-25 | Add the edit parse, which gives a picker calendar the typed date, the previous date while the date is incomplete, or `null` for a blank mask; a strict parse reads the prompt only in the date parts, so a literal can be the prompt | ## Overview @@ -841,8 +842,11 @@ Generated by `runExternalLabelAssociationTests`. toward the years 1 to 9999. 49. [`datetime-mask-parser.spec.ts`](./datetime-mask-parser.spec.ts) covers the parser that turns a format into a mask and back, including the year format normalization with its case kept, a literal that is a mask flag, the - century threshold, the calendar of years below 100, and UTF-16 part positions after an astral literal. + century threshold, the calendar of years below 100, and UTF-16 part positions after an astral literal. The edit + parse for a picker calendar gives the date of a complete mask, the previous date for an incomplete or invalid + date, and `null` for a blank mask. A complete mask parses strictly also when a literal is the prompt. 50. [`datetime-mask-parser.property.spec.ts`](./datetime-mask-parser.property.spec.ts) checks, for generated formats: + a prompt read only in the parts (a prompt that is also a literal parses and edits like the default prompt), the `formatValue` / `parseDate` round-trip for dates from year 0 to 9999, the two-digit year range, no throw or invalid date for any string, the strict and the lenient value parse (a complete mask parses the same in both, a partial mask gives `null` when strict, a blank mask gives `null`), and the parts that tile the mask and agree diff --git a/src/internals/mixins/mask-behavior.ts b/src/internals/mixins/mask-behavior.ts index 8297da85c..44b2cbc90 100644 --- a/src/internals/mixins/mask-behavior.ts +++ b/src/internals/mixins/mask-behavior.ts @@ -67,7 +67,7 @@ export declare class MaskBehaviorElementInterface { /** * Writes a complete masked text into the value pipeline: `igc-mask-input` - * commits to its form value, the date editors keep a draft until blur. + * commits to its form value, the date editors keep an edit until blur. */ protected _commitMaskedValue(value: string): void; @@ -567,7 +567,6 @@ export function MaskBehaviorMixin< this._history.settle(next, caret); } - /** Reconciles the history with the current masked text. */ private _historyResync(): void { this._history.resync(this._historyText); } @@ -596,7 +595,7 @@ export function MaskBehaviorMixin< this.requestUpdate(); // Native inputs announce an undo as an `input` event; the date picker - // hosts read their draft value from it. + // hosts read their typed value from it. this._emitInputEvent(); await this.updateComplete; diff --git a/src/internals/testing/simulate.spec.ts b/src/internals/testing/simulate.spec.ts index 3474d72ee..0a85a10d8 100644 --- a/src/internals/testing/simulate.spec.ts +++ b/src/internals/testing/simulate.spec.ts @@ -160,6 +160,23 @@ export async function simulateTypingOver( await elementUpdated(editor); } +/** Selects the text from `start` to `end` in the focused `editor` and deletes it with Backspace. */ +export async function simulateBackspaceOver( + editor: MaskedEditor, + start: number, + end: number +): Promise { + const input = editor.renderRoot.querySelector('input')!; + + editor.setSelectionRange(start, end); + simulateKeyboard(input, 'Backspace'); + simulateInput(input, { + inputType: 'deleteContentBackward', + skipValueProperty: true, + }); + await elementUpdated(editor); +} + /** * Simulates keyboard interaction on a given element node. *