Skip to content

Commit 7049190

Browse files
LukasTyA-s-h-o-k
authored andcommitted
[fields] Handle focusing container with inputRef.current.focus on accessibleFieldDOMStructure (mui#15985)
1 parent bd4e5b1 commit 7049190

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

packages/x-date-pickers/src/DateField/tests/selection.DateField.test.tsx

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import * as React from 'react';
12
import { expect } from 'chai';
23
import { DateField } from '@mui/x-date-pickers/DateField';
3-
import { act, fireEvent } from '@mui/internal-test-utils';
4+
import { act, fireEvent, screen } from '@mui/internal-test-utils';
45
import {
56
createPickerRenderer,
67
expectFieldValueV7,
@@ -351,5 +352,22 @@ describe('<DateField /> - Selection', () => {
351352
fireEvent.keyDown(input, { key: 'ArrowLeft' });
352353
expect(getCleanedSelectedContent()).to.equal('MM');
353354
});
355+
356+
it('should select the first section when `inputRef.current` is focused', () => {
357+
function TestCase() {
358+
const inputRef = React.useRef<HTMLInputElement>(null);
359+
return (
360+
<React.Fragment>
361+
<DateField inputRef={inputRef} />
362+
<button onClick={() => inputRef.current?.focus()}>Focus input</button>
363+
</React.Fragment>
364+
);
365+
}
366+
render(<TestCase />);
367+
368+
fireEvent.click(screen.getByRole('button', { name: 'Focus input' }));
369+
370+
expect(getCleanedSelectedContent()).to.equal('MM');
371+
});
354372
});
355373
});

packages/x-date-pickers/src/PickersTextField/PickersInputBase/PickersInputBase.tsx

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,10 @@ const PickersInputBase = React.forwardRef(function PickersInputBase(
247247
onFocus?.(event);
248248
};
249249

250+
const handleHiddenInputFocus = (event: React.FocusEvent<HTMLInputElement>) => {
251+
handleInputFocus(event);
252+
};
253+
250254
const handleInputBlur = (event: React.FocusEvent<HTMLDivElement>) => {
251255
muiFormControl.onBlur?.(event);
252256
onBlur?.(event);
@@ -338,6 +342,9 @@ const PickersInputBase = React.forwardRef(function PickersInputBase(
338342
readOnly={readOnly}
339343
required={muiFormControl.required}
340344
disabled={muiFormControl.disabled}
345+
// Hidden input element cannot be focused, trigger the root focus instead
346+
// This allows to maintain the ability to do `inputRef.current.focus()` to focus the field
347+
onFocus={handleHiddenInputFocus}
341348
{...inputProps}
342349
ref={handleInputRef}
343350
/>

0 commit comments

Comments
 (0)