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

improve dialog escape #430

Merged
merged 2 commits into from
Apr 22, 2021
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Improve search, make searching case insensitive ([#385](https://github.com/tailwindlabs/headlessui/pull/385))
- Fix unreachable `RadioGroup` ([#401](https://github.com/tailwindlabs/headlessui/pull/401))
- Fix closing nested `Dialog` components when pressing `Escape` ([#430](https://github.com/tailwindlabs/headlessui/pull/430))

### Added

Expand All @@ -23,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Improve search, make searching case insensitive ([#385](https://github.com/tailwindlabs/headlessui/pull/385))
- Fix unreachable `RadioGroup` ([#401](https://github.com/tailwindlabs/headlessui/pull/401))
- Fix `RadioGroupOption` value type ([#400](https://github.com/tailwindlabs/headlessui/pull/400))
- Fix closing nested `Dialog` components when pressing `Escape` ([#430](https://github.com/tailwindlabs/headlessui/pull/430))

### Added

Expand Down
4 changes: 2 additions & 2 deletions packages/@headlessui-react/pages/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ function Nested({ onClose, level = 0 }) {

return (
<>
<Dialog open={true} onClose={onClose} className="fixed z-10 inset-0 pointer-events-none">
<Dialog open={true} onClose={onClose} className="fixed z-10 inset-0">
{true && <Dialog.Overlay className="fixed inset-0 bg-gray-500 opacity-25" />}
<div
className="z-10 fixed left-12 top-24 bg-white w-96 p-4 pointer-events-auto"
className="z-10 fixed left-12 top-24 bg-white w-96 p-4"
style={{
transform: `translate(calc(50px * ${level}), calc(50px * ${level}))`,
}}
Expand Down
79 changes: 79 additions & 0 deletions packages/@headlessui-react/src/components/dialog/dialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
getDialogOverlay,
getByText,
assertActiveElement,
getDialogs,
} from '../../test-utils/accessibility-assertions'
import { click, press, Keys } from '../../test-utils/interactions'
import { PropsOf } from '../../types'
Expand Down Expand Up @@ -567,3 +568,81 @@ describe('Mouse interactions', () => {
})
)
})

describe('Nesting', () => {
it('should be possible to open nested Dialog components and close them with `Escape`', async () => {
function Nested({ onClose, level = 1 }: { onClose: (value: boolean) => void; level?: number }) {
let [showChild, setShowChild] = useState(false)

return (
<>
<Dialog open={true} onClose={onClose}>
<div>
<p>Level: {level}</p>
<button onClick={() => setShowChild(true)}>Open {level + 1}</button>
</div>
{showChild && <Nested onClose={setShowChild} level={level + 1} />}
</Dialog>
</>
)
}

function Example() {
let [open, setOpen] = useState(false)

return (
<>
<button onClick={() => setOpen(true)}>Open 1</button>
{open && <Nested onClose={setOpen} />}
</>
)
}

render(<Example />)

// Verify we have no open dialogs
expect(getDialogs()).toHaveLength(0)

// Open Dialog 1
await click(getByText('Open 1'))

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)

// Open Dialog 2
await click(getByText('Open 2'))

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)

// Open Dialog 2
await click(getByText('Open 2'))

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Open Dialog 3
await click(getByText('Open 3'))

// Verify that we have 3 open dialogs
expect(getDialogs()).toHaveLength(3)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)
})
})
22 changes: 12 additions & 10 deletions packages/@headlessui-react/src/components/dialog/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import React, {
ContextType,
ElementType,
MouseEvent as ReactMouseEvent,
KeyboardEvent as ReactKeyboardEvent,
MutableRefObject,
Ref,
} from 'react'
Expand Down Expand Up @@ -177,16 +178,6 @@ let DialogRoot = forwardRefWithAs(function Dialog<
close()
})

// Handle `Escape` to close
useWindowEvent('keydown', event => {
if (event.key !== Keys.Escape) return
if (dialogState !== DialogStates.Open) return
if (containers.current.size > 1) return // 1 is myself, otherwise other elements in the Stack
event.preventDefault()
event.stopPropagation()
close()
})

// Scroll lock
useEffect(() => {
if (dialogState !== DialogStates.Open) return
Expand All @@ -198,6 +189,7 @@ let DialogRoot = forwardRefWithAs(function Dialog<

document.documentElement.style.overflow = 'hidden'
document.documentElement.style.paddingRight = `${scrollbarWidth}px`

return () => {
document.documentElement.style.overflow = overflow
document.documentElement.style.paddingRight = paddingRight
Expand Down Expand Up @@ -255,6 +247,16 @@ let DialogRoot = forwardRefWithAs(function Dialog<
event.preventDefault()
event.stopPropagation()
},

// Handle `Escape` to close
onKeyDown(event: ReactKeyboardEvent) {
if (event.key !== Keys.Escape) return
if (dialogState !== DialogStates.Open) return
if (containers.current.size > 1) return // 1 is myself, otherwise other elements in the Stack
event.preventDefault()
event.stopPropagation()
close()
},
}
let passthroughProps = rest

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,10 @@ export function getDialog(): HTMLElement | null {
return document.querySelector('[role="dialog"]')
}

export function getDialogs(): HTMLElement[] {
return Array.from(document.querySelectorAll('[role="dialog"]'))
}

export function getDialogTitle(): HTMLElement | null {
return document.querySelector('[id^="headlessui-dialog-title-"]')
}
Expand Down
104 changes: 103 additions & 1 deletion packages/@headlessui-vue/src/components/dialog/dialog.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineComponent, ref, nextTick } from 'vue'
import { defineComponent, ref, nextTick, h } from 'vue'
import { render } from '../../test-utils/vue-testing-library'

import { Dialog, DialogOverlay, DialogTitle, DialogDescription } from './dialog'
Expand All @@ -13,6 +13,7 @@ import {
getDialogOverlay,
getByText,
assertActiveElement,
getDialogs,
} from '../../test-utils/accessibility-assertions'
import { click, press, Keys } from '../../test-utils/interactions'
import { html } from '../../test-utils/html'
Expand Down Expand Up @@ -694,3 +695,104 @@ describe('Mouse interactions', () => {
})
)
})

describe('Nesting', () => {
it('should be possible to open nested Dialog components and close them with `Escape`', async () => {
let Nested = defineComponent({
components: { Dialog },
emits: ['close'],
props: ['level'],
render() {
let level = this.$props.level ?? 1
return h(Dialog, { open: true, onClose: this.onClose }, () => [
h('div', [
h('p', `Level: ${level}`),
h(
'button',
{
onClick: () => {
this.showChild = true
},
},
`Open ${level + 1}`
),
]),
this.showChild &&
h(Nested, {
onClose: () => {
this.showChild = false
},
level: level + 1,
}),
])
},
setup(_props, { emit }) {
let showChild = ref(false)

return {
showChild,
onClose() {
emit('close', false)
},
}
},
})

renderTemplate({
components: { Nested },
template: `
<button @click="isOpen = true">Open 1</button>
<Nested v-if="isOpen" @close="isOpen = false" />
`,
setup() {
let isOpen = ref(false)
return { isOpen }
},
})

// Verify we have no open dialogs
expect(getDialogs()).toHaveLength(0)

// Open Dialog 1
await click(getByText('Open 1'))

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)

// Open Dialog 2
await click(getByText('Open 2'))

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)

// Open Dialog 2
await click(getByText('Open 2'))

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Open Dialog 3
await click(getByText('Open 3'))

// Verify that we have 3 open dialogs
expect(getDialogs()).toHaveLength(3)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 2 open dialogs
expect(getDialogs()).toHaveLength(2)

// Press escape to close the top most Dialog
await press(Keys.Escape)

// Verify that we have 1 open dialog
expect(getDialogs()).toHaveLength(1)
})
})
21 changes: 11 additions & 10 deletions packages/@headlessui-vue/src/components/dialog/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export let Dialog = defineComponent({
'aria-labelledby': this.titleId,
'aria-describedby': this.describedby,
onClick: this.handleClick,
onKeydown: this.handleKeyDown,
}
let { open, initialFocus, ...passThroughProps } = this.$props
let slot = { open: this.dialogState === DialogStates.Open }
Expand Down Expand Up @@ -184,16 +185,6 @@ export let Dialog = defineComponent({
nextTick(() => target?.focus())
})

// Handle `Escape` to close
useWindowEvent('keydown', event => {
if (event.key !== Keys.Escape) return
if (dialogState.value !== DialogStates.Open) return
if (containers.value.size > 1) return // 1 is myself, otherwise other elements in the Stack
event.preventDefault()
event.stopPropagation()
api.close()
})

// Scroll lock
watchEffect(onInvalidate => {
if (dialogState.value !== DialogStates.Open) return
Expand Down Expand Up @@ -248,6 +239,16 @@ export let Dialog = defineComponent({
event.preventDefault()
event.stopPropagation()
},

// Handle `Escape` to close
handleKeyDown(event: KeyboardEvent) {
if (event.key !== Keys.Escape) return
if (dialogState.value !== DialogStates.Open) return
if (containers.value.size > 1) return // 1 is myself, otherwise other elements in the Stack
event.preventDefault()
event.stopPropagation()
api.close()
},
}
},
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,10 @@ export function getDialog(): HTMLElement | null {
return document.querySelector('[role="dialog"]')
}

export function getDialogs(): HTMLElement[] {
return Array.from(document.querySelectorAll('[role="dialog"]'))
}

export function getDialogTitle(): HTMLElement | null {
return document.querySelector('[id^="headlessui-dialog-title-"]')
}
Expand Down