From 9bce04ca79e7441f83eabe1a04fd82415a458c6d Mon Sep 17 00:00:00 2001 From: Lukas Tyla Date: Mon, 30 Dec 2024 18:21:16 +0200 Subject: [PATCH] [fields] Handle focusing container with `inputRef.current.focus` on `accessibleFieldDOMStructure` (#15985) --- .../tests/selection.DateField.test.tsx | 20 ++++++++++++++++++- .../PickersInputBase/PickersInputBase.tsx | 7 +++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/x-date-pickers/src/DateField/tests/selection.DateField.test.tsx b/packages/x-date-pickers/src/DateField/tests/selection.DateField.test.tsx index b59aba23f70dd..217ec4d3ded59 100644 --- a/packages/x-date-pickers/src/DateField/tests/selection.DateField.test.tsx +++ b/packages/x-date-pickers/src/DateField/tests/selection.DateField.test.tsx @@ -1,6 +1,7 @@ +import * as React from 'react'; import { expect } from 'chai'; import { DateField } from '@mui/x-date-pickers/DateField'; -import { act, fireEvent } from '@mui/internal-test-utils'; +import { act, fireEvent, screen } from '@mui/internal-test-utils'; import { createPickerRenderer, expectFieldValueV7, @@ -351,5 +352,22 @@ describe(' - Selection', () => { fireEvent.keyDown(input, { key: 'ArrowLeft' }); expect(getCleanedSelectedContent()).to.equal('MM'); }); + + it('should select the first section when `inputRef.current` is focused', () => { + function TestCase() { + const inputRef = React.useRef(null); + return ( + + + + + ); + } + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Focus input' })); + + expect(getCleanedSelectedContent()).to.equal('MM'); + }); }); }); diff --git a/packages/x-date-pickers/src/PickersTextField/PickersInputBase/PickersInputBase.tsx b/packages/x-date-pickers/src/PickersTextField/PickersInputBase/PickersInputBase.tsx index 4ea33c8b59b74..f0b98ce8f9765 100644 --- a/packages/x-date-pickers/src/PickersTextField/PickersInputBase/PickersInputBase.tsx +++ b/packages/x-date-pickers/src/PickersTextField/PickersInputBase/PickersInputBase.tsx @@ -247,6 +247,10 @@ const PickersInputBase = React.forwardRef(function PickersInputBase( onFocus?.(event); }; + const handleHiddenInputFocus = (event: React.FocusEvent) => { + handleInputFocus(event); + }; + const handleInputBlur = (event: React.FocusEvent) => { muiFormControl.onBlur?.(event); onBlur?.(event); @@ -338,6 +342,9 @@ const PickersInputBase = React.forwardRef(function PickersInputBase( readOnly={readOnly} required={muiFormControl.required} disabled={muiFormControl.disabled} + // Hidden input element cannot be focused, trigger the root focus instead + // This allows to maintain the ability to do `inputRef.current.focus()` to focus the field + onFocus={handleHiddenInputFocus} {...inputProps} ref={handleInputRef} />