-
-
Notifications
You must be signed in to change notification settings - Fork 32.8k
[text field] Fix inconsistent input caret position on focus #47340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
[text field] Fix inconsistent input caret position on focus #47340
Conversation
Netlify deploy previewhttps://deploy-preview-47340--material-ui.netlify.app/ Bundle size report
|
|
|
||
| if ( | ||
| input && | ||
| (input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement) && |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should not use instanceof as it's inconsistent across window contexts
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the feedback!
I’ve removed the instanceof check and replaced it with a safer, window-agnostic guard (checking for .setSelectionRange and .focus).
The updated approach no longer depends on instanceof and works correctly across window contexts.
|
FYI tests would be needed |
I’ve added a unit test to cover caret-position preservation when clicking the wrapper. |
This PR fixes a bug where clicking on the InputBase wrapper (outside the actual element) causes the caret to jump to the beginning of the input value.
Problem
When clicking inside the InputBase container but not directly on the native input, MUI programmatically forwards focus to the input:
inputRef.current.focus();
Some browsers reset the caret position to 0 when focus is forwarded this way, resulting in unexpected cursor behavior.
Solution
This change:
Saves the current caret position before forwarding focus
Restores the caret position on the next animation frame
Adds a safe type guard to ensure setSelectionRange is called only on valid inputs
Removes unnecessary console logging and try/catch blocks
This ensures the caret remains at the correct position when clicking anywhere inside the input container.
Related Issue
Fixes #47336