Skip to content

Commit

Permalink
[fields] Handle focusing container with inputRef.current.focus on `…
Browse files Browse the repository at this point in the history
…accessibleFieldDOMStructure` (#15985)
  • Loading branch information
LukasTy authored Dec 30, 2024
1 parent 3ead503 commit 9bce04c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -351,5 +352,22 @@ describe('<DateField /> - 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<HTMLInputElement>(null);
return (
<React.Fragment>
<DateField inputRef={inputRef} />
<button onClick={() => inputRef.current?.focus()}>Focus input</button>
</React.Fragment>
);
}
render(<TestCase />);

fireEvent.click(screen.getByRole('button', { name: 'Focus input' }));

expect(getCleanedSelectedContent()).to.equal('MM');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ const PickersInputBase = React.forwardRef(function PickersInputBase(
onFocus?.(event);
};

const handleHiddenInputFocus = (event: React.FocusEvent<HTMLInputElement>) => {
handleInputFocus(event);
};

const handleInputBlur = (event: React.FocusEvent<HTMLDivElement>) => {
muiFormControl.onBlur?.(event);
onBlur?.(event);
Expand Down Expand Up @@ -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}
/>
Expand Down

0 comments on commit 9bce04c

Please sign in to comment.