From 5e8df8a47443f979fd8405bfc8513b80dbf3c795 Mon Sep 17 00:00:00 2001 From: Lukas Date: Fri, 28 Jun 2024 18:17:19 +0300 Subject: [PATCH] [fields] Fix section clearing behavior on Android (#13652) --- .../DateField/tests/editing.DateField.test.tsx | 8 ++++---- .../hooks/useField/useFieldV6TextField.ts | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/x-date-pickers/src/DateField/tests/editing.DateField.test.tsx b/packages/x-date-pickers/src/DateField/tests/editing.DateField.test.tsx index 3d419cdc9240..d68fab6c666c 100644 --- a/packages/x-date-pickers/src/DateField/tests/editing.DateField.test.tsx +++ b/packages/x-date-pickers/src/DateField/tests/editing.DateField.test.tsx @@ -2030,13 +2030,13 @@ describe(' - Editing', () => { fireEvent.change(input, { target: { value: initialValueStr.replace('23', '1') } }); }); - expectFieldValueV6(input, '11/21/2022'); + expectFieldValueV6(input, '11/01/2022'); }); it('should support letter editing', () => { // Test with v6 input const v6Response = renderWithProps({ - defaultValue: adapter.date('2022-05-16'), + defaultValue: adapter.date('2022-01-16'), format: `${adapter.formats.month} ${adapter.formats.year}`, enableAccessibleFieldDOMStructure: false, }); @@ -2057,10 +2057,10 @@ describe(' - Editing', () => { fireEvent.change(input, { target: { value: ' 2022' } }); // Set the key pressed in the selected section - fireEvent.change(input, { target: { value: 'u 2022' } }); + fireEvent.change(input, { target: { value: 'a 2022' } }); }); - expectFieldValueV6(input, 'June 2022'); + expectFieldValueV6(input, 'April 2022'); }); }, ); diff --git a/packages/x-date-pickers/src/internals/hooks/useField/useFieldV6TextField.ts b/packages/x-date-pickers/src/internals/hooks/useField/useFieldV6TextField.ts index f382ec975758..9dd3d684e0d6 100644 --- a/packages/x-date-pickers/src/internals/hooks/useField/useFieldV6TextField.ts +++ b/packages/x-date-pickers/src/internals/hooks/useField/useFieldV6TextField.ts @@ -162,6 +162,18 @@ export const useFieldV6TextField: UseFieldTextField = (params) => { inputRef.current.setSelectionRange(selectionStart, selectionEnd); } } + setTimeout(() => { + // handle case when the selection is not updated correctly + // could happen on Android + if ( + inputRef.current && + inputRef.current === getActiveElement(document) && + (inputRef.current.selectionStart !== selectionStart || + inputRef.current.selectionEnd !== selectionEnd) + ) { + interactions.syncSelectionToDOM(); + } + }); } // Even reading this variable seems to do the trick, but also setting it just to make use of it @@ -377,10 +389,9 @@ export const useFieldV6TextField: UseFieldTextField = (params) => { if (keyPressed.length === 0) { if (isAndroid()) { setTempAndroidValueStr(valueStr); - } else { - resetCharacterQuery(); - clearActiveSection(); } + resetCharacterQuery(); + clearActiveSection(); return; }