Skip to content

Commit

Permalink
Merge pull request #399 from primer/fz-strict-mutation
Browse files Browse the repository at this point in the history
Remove options when ending focus management
  • Loading branch information
TylerJDev committed Jun 15, 2024
2 parents 12580f9 + 7d2d85f commit a8e9069
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
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

0 comments on commit a8e9069

Please sign in to comment.