Skip to content

Commit

Permalink
only prevent focus when component is open
Browse files Browse the repository at this point in the history
Otherwise, prevents focus from returning to given returnFocusRef.
  • Loading branch information
ktravers authored Jan 31, 2025
1 parent 59e0efa commit fb33fed
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions packages/react/src/hooks/useOpenAndCloseFocus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,25 @@ export function useOpenAndCloseFocus({
preventFocusOnOpen,
}: UseOpenAndCloseFocusSettings): void {
useEffect(() => {
if (preventFocusOnOpen) {
const isOpen = containerRef.current || initialFocusRef?.current

// Do nothing if component is open and focus should be prevented on open
if (isOpen && preventFocusOnOpen) {
return
}
const returnRef = returnFocusRef.current

// If initial focus ref is given and present, apply focus
if (initialFocusRef && initialFocusRef.current) {
initialFocusRef.current.focus()
// If container ref is present, apply focus

Check failure on line 29 in packages/react/src/hooks/useOpenAndCloseFocus.ts

View workflow job for this annotation

GitHub Actions / lint

Insert `··`
} else if (containerRef.current) {
const firstItem = iterateFocusableElements(containerRef.current).next().value
firstItem?.focus()
}

// Else, component is closed, and focus should be applied to given returnFocusRef element
return function () {
returnRef?.focus()
returnFocusRef.current?.focus()

Check failure on line 37 in packages/react/src/hooks/useOpenAndCloseFocus.ts

View workflow job for this annotation

GitHub Actions / lint

The ref value 'returnFocusRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'returnFocusRef.current' to a variable inside the effect, and use that variable in the cleanup function
}
}, [initialFocusRef, returnFocusRef, containerRef, preventFocusOnOpen])
}

0 comments on commit fb33fed

Please # to comment.