Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/mui-material/src/useAutocomplete/useAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ function useAutocomplete(props) {
const firstFocus = React.useRef(true);
const inputRef = React.useRef(null);
const listboxRef = React.useRef(null);
const windowJustFocusedRef = React.useRef(false);
const [anchorEl, setAnchorEl] = React.useState(null);

const [focusedItem, setFocusedItem] = React.useState(-1);
Expand Down Expand Up @@ -619,6 +620,19 @@ function useAutocomplete(props) {
}
}, [syncHighlightedIndex, filteredOptionsChanged, popupOpen, disableCloseOnSelect]);

// Tracks browser window focus state.
React.useEffect(() => {
const handleWindowFocus = () => {
windowJustFocusedRef.current = true;
};

window.addEventListener('focus', handleWindowFocus);

return () => {
window.removeEventListener('focus', handleWindowFocus);
};
}, []);

const handleOpen = (event) => {
if (open) {
return;
Expand Down Expand Up @@ -1100,9 +1114,11 @@ function useAutocomplete(props) {
if (!event.currentTarget.contains(event.target)) {
return;
}
if (event.target.getAttribute('id') !== id) {
if (event.target.getAttribute('id') !== id && !windowJustFocusedRef.current) {
event.preventDefault();
}

windowJustFocusedRef.current = false;
};

// Focus the input when interacting with the combobox
Expand Down
Loading