Skip to content
Merged
Changes from 3 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
16 changes: 15 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 windowLostFocus = React.useRef(false);
const [anchorEl, setAnchorEl] = React.useState(null);

const [focusedItem, setFocusedItem] = React.useState(-1);
Expand Down Expand Up @@ -995,9 +996,15 @@ function useAutocomplete(props) {
focusItem(-1);
}

if (openOnFocus && !ignoreFocus.current) {
// Prevent popup from reopening when window regains focus
// relatedTarget is null when focus comes from outside of document (window regain)
// For Tab/keyboard navigation, relatedTarget will be the previous element
const isWindowRegainingFocus = windowLostFocus.current && event?.relatedTarget === null;
if (openOnFocus && !ignoreFocus.current && !isWindowRegainingFocus) {
handleOpen(event);
}

windowLostFocus.current = false;
};

const handleBlur = (event) => {
Expand All @@ -1009,6 +1016,12 @@ function useAutocomplete(props) {

setFocused(false);
firstFocus.current = true;
// Track when window loses focus (relatedTarget is null)
// Only set if popup is open, to prevent preventing legitimate re-opens when popup is already closed
if (event?.relatedTarget === null && popupOpen) {
Comment thread
ZeeshanTamboli marked this conversation as resolved.
Outdated
Comment thread
ZeeshanTamboli marked this conversation as resolved.
Outdated
windowLostFocus.current = true;
}

ignoreFocus.current = false;

if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
Expand Down Expand Up @@ -1111,6 +1124,7 @@ function useAutocomplete(props) {
if (!event.currentTarget.contains(event.target)) {
return;
}
ignoreFocus.current = false;
Comment thread
ZeeshanTamboli marked this conversation as resolved.
Outdated
inputRef.current.focus();

if (
Expand Down
Loading