From c494fa36e9a6299ec8c68a274db4ba271ab31ea6 Mon Sep 17 00:00:00 2001 From: Robin Malfait Date: Mon, 9 May 2022 15:07:57 +0200 Subject: [PATCH] Ignore `Escape` when event got prevented in `Dialog` component (#1424) * ignore `Escape` when event got prevented Some external libraries only use `event.preventDefault()` and not `event.stopPropagation()`. This means that the Dialog can still receive an `Escape` keydown event which closes the Dialog. We can also think about the `Escape` behaviour inside the modal as the "default behaviour" once the Dialog is open. Therefore, we can also check the `event.defaultPrevented` and ignore this event when this is the case. * update changelog --- CHANGELOG.md | 2 ++ packages/@headlessui-react/src/components/dialog/dialog.tsx | 1 + packages/@headlessui-vue/src/components/dialog/dialog.ts | 1 + 3 files changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc180a6..1ba4252 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Ensure `DialogPanel` exposes its ref ([#1404](https://github.com/tailwindlabs/headlessui/pull/1404)) +- Ignore `Escape` when event got prevented in `Dialog` component ([#1424](https://github.com/tailwindlabs/headlessui/pull/1424)) ## [Unreleased - @headlessui/react] ### Fixed - Fix closing of `Popover.Panel` in React 18 ([#1409](https://github.com/tailwindlabs/headlessui/pull/1409)) +- Ignore `Escape` when event got prevented in `Dialog` component ([#1424](https://github.com/tailwindlabs/headlessui/pull/1424)) ## [@headlessui/react@1.6.1] - 2022-05-03 diff --git a/packages/@headlessui-react/src/components/dialog/dialog.tsx b/packages/@headlessui-react/src/components/dialog/dialog.tsx index f5d7424..d7968be 100644 --- a/packages/@headlessui-react/src/components/dialog/dialog.tsx +++ b/packages/@headlessui-react/src/components/dialog/dialog.tsx @@ -237,6 +237,7 @@ let DialogRoot = forwardRefWithAs(function Dialog< // Handle `Escape` to close useEventListener(ownerDocument?.defaultView, 'keydown', (event) => { + if (event.defaultPrevented) return if (event.key !== Keys.Escape) return if (dialogState !== DialogStates.Open) return if (hasNestedDialogs) return diff --git a/packages/@headlessui-vue/src/components/dialog/dialog.ts b/packages/@headlessui-vue/src/components/dialog/dialog.ts index 56dce24..b02897b 100644 --- a/packages/@headlessui-vue/src/components/dialog/dialog.ts +++ b/packages/@headlessui-vue/src/components/dialog/dialog.ts @@ -212,6 +212,7 @@ export let Dialog = defineComponent({ // Handle `Escape` to close useEventListener(ownerDocument.value?.defaultView, 'keydown', (event) => { + if (event.defaultPrevented) return if (event.key !== Keys.Escape) return if (dialogState.value !== DialogStates.Open) return if (hasNestedDialogs.value) return