Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Focus-trap: Add delay when a focus trap already exists #500

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/ninety-humans-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/behaviors': patch
---

Adds slight delay to setting focus initially when a focus trap already exists
23 changes: 19 additions & 4 deletions src/focus-trap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,23 +115,38 @@ export function focusTrap(
lastFocusedChild = focusedElement
return
} else {
const focusDelay = suspendedTrapStack.length > 0 ? 50 : undefined

if (lastFocusedChild && isTabbable(lastFocusedChild) && container.contains(lastFocusedChild)) {
lastFocusedChild.focus()
handleFocus(lastFocusedChild, focusDelay)
return
} else if (initialFocus && container.contains(initialFocus)) {
initialFocus.focus()
handleFocus(initialFocus, focusDelay)
return
} else {
const firstFocusableChild = getFocusableChild(container)
firstFocusableChild?.focus()
handleFocus(firstFocusableChild, focusDelay)
return
}
}
}
}

const wrappingController = followSignal(signal)
function handleFocus(focusTarget: HTMLElement | undefined, delay?: number) {
if (!focusTarget) return

if (delay) {
setTimeout(() => {
focusTarget.focus()
}, delay)

return
}

focusTarget.focus()
}

const wrappingController = followSignal(signal)
if (activeTrap) {
const suspendedTrap = activeTrap
activeTrap.container.setAttribute('data-focus-trap', 'suspended')
Expand Down
Loading