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

Ensure page doesn't scroll down when pressing Escape to close the Dialog component #3218

Merged
merged 2 commits into from
May 21, 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
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed

- [internal] Don’t set a focus fallback for Dialog’s in demo mode ([#3194](https://github.com/tailwindlabs/headlessui/pull/3194))
- Ensure page doesn't scroll down when pressing `Escape` to close the `Dialog` component ([#3218](https://github.com/tailwindlabs/headlessui/pull/3218))

## [2.0.3] - 2024-05-07

Expand Down
15 changes: 15 additions & 0 deletions packages/@headlessui-react/src/components/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,21 @@ function DialogFn<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG>(
if (event.key !== Keys.Escape) return
event.preventDefault()
event.stopPropagation()

// Ensure that we blur the current activeElement to prevent maintaining
// focus and potentially scrolling the page to the end (because the Dialog
// is rendered in a Portal at the end of the document.body and the browser
// tries to keep the focused element in view)
//
// Typically only happens in Safari.
if (
document.activeElement &&
'blur' in document.activeElement &&
typeof document.activeElement.blur === 'function'
) {
document.activeElement.blur()
}

close()
})

Expand Down
Loading