Skip to content

Commit

Permalink
fix(material/datepicker): always move caret to the end of the start i…
Browse files Browse the repository at this point in the history
…nput on backspace (#28669)

When the user presses backspace on an empty end input of a range picker, we move focus to the start input and assume that the caret will be at the end. It appears that in some cases the browser decides to move it to the beginning instead so these changes reuse the logic from the left/right arrow handling to explicitly move it to the end on backspace as well.

Fixes #28665.
  • Loading branch information
crisbeto committed Mar 4, 2024
1 parent b169320 commit fa2687f
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/material/datepicker/date-range-input-parts.ts
Expand Up @@ -421,14 +421,24 @@ export class MatEndDate<D> extends MatDateRangeInputPartBase<D> {
}
}

private _moveCaretToEndOfStartInput() {
const startInput = this._rangeInput._startInput._elementRef.nativeElement;
const value = startInput.value;

if (value.length > 0) {
startInput.setSelectionRange(value.length, value.length);
}

startInput.focus();
}

override _onKeydown(event: KeyboardEvent) {
const startInput = this._rangeInput._startInput;
const element = this._elementRef.nativeElement;
const isLtr = this._dir?.value !== 'rtl';

// If the user is pressing backspace on an empty end input, move focus back to the start.
if (event.keyCode === BACKSPACE && !element.value) {
startInput.focus();
this._moveCaretToEndOfStartInput();
}
// If the user hits LEFT (LTR) when at the start of the input (and no
// selection), move the cursor to the end of the start input.
Expand All @@ -438,9 +448,7 @@ export class MatEndDate<D> extends MatDateRangeInputPartBase<D> {
element.selectionEnd === 0
) {
event.preventDefault();
const endPosition = startInput._elementRef.nativeElement.value.length;
startInput._elementRef.nativeElement.setSelectionRange(endPosition, endPosition);
startInput.focus();
this._moveCaretToEndOfStartInput();
} else {
super._onKeydown(event);
}
Expand Down

0 comments on commit fa2687f

Please sign in to comment.