Skip to content

Jdrush89/fix dialog escape #3689

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

Merged
merged 2 commits into from
Aug 30, 2023
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
7 changes: 7 additions & 0 deletions .changeset/long-walls-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@primer/react': patch
---

Fix dialog bug where escape would move focus when dialog was closed

<!-- Changed components: _none_ -->
11 changes: 11 additions & 0 deletions src/__tests__/Dialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,15 @@ describe('Dialog', () => {
const triggerButton = getByTestId('trigger-button')
expect(document.activeElement).toEqual(triggerButton)
})

it('Returns focus to returnFocusRef on escape', async () => {
const {getByTestId, queryByTestId} = HTMLRender(<Component />)

expect(getByTestId('inner')).toBeTruthy()
fireEvent.keyDown(document.body, {key: 'Escape'})

expect(queryByTestId('inner')).toBeNull()
const triggerButton = getByTestId('trigger-button')
expect(document.activeElement).toEqual(triggerButton)
})
})
8 changes: 5 additions & 3 deletions src/hooks/useDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,12 @@ function useDialog({

useOnEscapePress(
(event: KeyboardEvent) => {
onDismiss()
event.preventDefault()
if (isOpen) {
onDismiss()
event.preventDefault()
}
},
[onDismiss],
[isOpen, onDismiss],
)

return {getDialogProps}
Expand Down