Skip to content

Commit

Permalink
[fields] Prevent infinite recursion when ensuring selection (#13779)
Browse files Browse the repository at this point in the history
  • Loading branch information
LukasTy committed Jul 11, 2024
1 parent ed833b5 commit 6fb7cb0
Showing 1 changed file with 7 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export const addPositionPropertiesToSections = <TSection extends FieldSection>(
export const useFieldV6TextField: UseFieldTextField<false> = (params) => {
const isRtl = useRtl();
const focusTimeoutRef = React.useRef<ReturnType<typeof setTimeout>>();
const selectionSyncTimeoutRef = React.useRef<ReturnType<typeof setTimeout>>();

const {
forwardedProps: {
Expand Down Expand Up @@ -162,12 +163,16 @@ export const useFieldV6TextField: UseFieldTextField<false> = (params) => {
inputRef.current.setSelectionRange(selectionStart, selectionEnd);
}
}
setTimeout(() => {
clearTimeout(selectionSyncTimeoutRef.current);
selectionSyncTimeoutRef.current = setTimeout(() => {
// handle case when the selection is not updated correctly
// could happen on Android
if (
inputRef.current &&
inputRef.current === getActiveElement(document) &&
// The section might loose all selection, where `selectionStart === selectionEnd`
// https://github.com/mui/mui-x/pull/13652
inputRef.current.selectionStart === inputRef.current.selectionEnd &&
(inputRef.current.selectionStart !== selectionStart ||
inputRef.current.selectionEnd !== selectionEnd)
) {
Expand Down Expand Up @@ -428,6 +433,7 @@ export const useFieldV6TextField: UseFieldTextField<false> = (params) => {

return () => {
clearTimeout(focusTimeoutRef.current);
clearTimeout(selectionSyncTimeoutRef.current);
};
}, []); // eslint-disable-line react-hooks/exhaustive-deps

Expand Down

0 comments on commit 6fb7cb0

Please sign in to comment.