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

Remove options when ending focus management #399

Merged
merged 3 commits into from
Jun 15, 2024
Merged
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/smooth-terms-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/behaviors': patch
---

Fix bug found when removing nodes in a focus zone with strict mode enabled
39 changes: 39 additions & 0 deletions src/__tests__/focus-zone.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,42 @@ it('Should ignore disabled elements after focus zone is enabled', async () => {

controller.abort()
})

it('Should handle elements being removed if strict', async () => {
const user = userEvent.setup()
const {container} = render(
<div>
<button tabIndex={0} id="outside">
Outside Apple
</button>
<div id="focusZone">
<button tabIndex={0}>Apple</button>
<button tabIndex={0}>Banana</button>
<button tabIndex={0}>Cantaloupe</button>
</div>
</div>,
)

const focusZoneContainer = container.querySelector<HTMLElement>('#focusZone')!
const [firstButton, secondButton, thirdButton] = focusZoneContainer.querySelectorAll('button')
const outsideButton = container.querySelector<HTMLElement>('#outside')!
const controller = focusZone(focusZoneContainer, {strict: true})

firstButton.focus()
await user.keyboard('{arrowdown}')
expect(document.activeElement).toEqual(secondButton)

outsideButton.focus()
focusZoneContainer.removeChild(secondButton)

// The mutation observer fires asynchronously
await nextTick()

await user.tab()
expect(document.activeElement).toEqual(firstButton)

await user.keyboard('{arrowdown}')
expect(document.activeElement).toEqual(thirdButton)

controller.abort()
})
2 changes: 1 addition & 1 deletion src/focus-zone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ export function focusZone(container: HTMLElement, settings?: FocusZoneSettings):
for (const mutation of mutations) {
for (const removedNode of mutation.removedNodes) {
if (removedNode instanceof HTMLElement) {
endFocusManagement(...iterateFocusableElements(removedNode, iterateFocusableElementsOptions))
endFocusManagement(...iterateFocusableElements(removedNode))
}
}
// If an element is hidden or disabled, remove it from the list of focusable elements
Expand Down
Loading