Skip to content

Commit

Permalink
Fix FocusTrap in Dialog when there is only 1 focusable element (#…
Browse files Browse the repository at this point in the history
…2172)

* add tests to guarantee `FocusTrap` with a single element works as expected

* it should keep the focus in the Dialog

Even if there is only 1 element. We were skipping the current active
element so the container didn't have any elements anymore and just
continued to the next focusable element in line. This will prevent that
and ensure that we can only skip elements if there are multiple ones.

* update changelog
  • Loading branch information
RobinMalfait authored Jan 25, 2023
1 parent 6f205f0 commit dbcfb23
Show file tree
Hide file tree
Showing 10 changed files with 386 additions and 12 deletions.
1 change: 1 addition & 0 deletions packages/@headlessui-react/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Don’t overwrite classes during SSR when rendering fragments ([#2173](https://github.com/tailwindlabs/headlessui/pull/2173))
- Improve `Combobox` accessibility ([#2153](https://github.com/tailwindlabs/headlessui/pull/2153))
- Fix crash when reading `headlessuiFocusGuard` of `relatedTarget` in the `FocusTrap` component ([#2203](https://github.com/tailwindlabs/headlessui/pull/2203))
- Fix `FocusTrap` in `Dialog` when there is only 1 focusable element ([#2172](https://github.com/tailwindlabs/headlessui/pull/2172))

## [1.7.7] - 2022-12-16

Expand Down
102 changes: 101 additions & 1 deletion packages/@headlessui-react/src/components/dialog/dialog.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
getDialogs,
getDialogOverlays,
} from '../../test-utils/accessibility-assertions'
import { click, mouseDrag, press, Keys } from '../../test-utils/interactions'
import { click, mouseDrag, press, Keys, shift } from '../../test-utils/interactions'
import { PropsOf } from '../../types'
import { Transition } from '../transitions/transition'
import { createPortal } from 'react-dom'
Expand Down Expand Up @@ -797,6 +797,106 @@ describe('Keyboard interactions', () => {
assertActiveElement(document.getElementById('a'))
})
)

it(
'should not escape the FocusTrap when there is only 1 focusable element (going forwards)',
suppressConsoleLogs(async () => {
function Example() {
let [isOpen, setIsOpen] = useState(false)
return (
<>
<button id="trigger" onClick={() => setIsOpen((v) => !v)}>
Trigger
</button>
<button>Before</button>
<Dialog open={isOpen} onClose={setIsOpen}>
<Dialog.Panel>
<input type="text" id="a" />
</Dialog.Panel>
</Dialog>
<button>After</button>
</>
)
}
render(<Example />)

assertDialog({ state: DialogState.InvisibleUnmounted })

// Open dialog
await click(document.getElementById('trigger'))

// Verify it is open
assertDialog({
state: DialogState.Visible,
attributes: { id: 'headlessui-dialog-1' },
})

// Verify that the input field is focused
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(Keys.Tab)
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(Keys.Tab)
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(Keys.Tab)
assertActiveElement(document.getElementById('a'))
})
)

it(
'should not escape the FocusTrap when there is only 1 focusable element (going backwards)',
suppressConsoleLogs(async () => {
function Example() {
let [isOpen, setIsOpen] = useState(false)
return (
<>
<button id="trigger" onClick={() => setIsOpen((v) => !v)}>
Trigger
</button>
<button>Before</button>
<Dialog open={isOpen} onClose={setIsOpen}>
<Dialog.Panel>
<input type="text" id="a" />
</Dialog.Panel>
</Dialog>
<button>After</button>
</>
)
}
render(<Example />)

assertDialog({ state: DialogState.InvisibleUnmounted })

// Open dialog
await click(document.getElementById('trigger'))

// Verify it is open
assertDialog({
state: DialogState.Visible,
attributes: { id: 'headlessui-dialog-1' },
})

// Verify that the input field is focused
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(shift(Keys.Tab))
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(shift(Keys.Tab))
assertActiveElement(document.getElementById('a'))

// Verify that we stay within the Dialog
await press(shift(Keys.Tab))
assertActiveElement(document.getElementById('a'))
})
)
})
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,50 @@ it('should warn when there is no focusable element inside the FocusTrap', async
spy.mockReset()
})

it(
'should not be possible to programmatically escape the focus trap (if there is only 1 focusable element)',
suppressConsoleLogs(async () => {
function Example() {
return (
<>
<input id="a" autoFocus />

<FocusTrap>
<input id="b" />
</FocusTrap>
</>
)
}

render(<Example />)

await nextFrame()

let [a, b] = Array.from(document.querySelectorAll('input'))

// Ensure that input-b is the active element
assertActiveElement(b)

// Tab to the next item
await press(Keys.Tab)

// Ensure that input-b is still the active element
assertActiveElement(b)

// Try to move focus
a?.focus()

// Ensure that input-b is still the active element
assertActiveElement(b)

// Click on an element within the FocusTrap
await click(b)

// Ensure that input-b is the active element
assertActiveElement(b)
})
)

it(
'should not be possible to programmatically escape the focus trap',
suppressConsoleLogs(async () => {
Expand Down Expand Up @@ -214,6 +258,56 @@ it('should restore the previously focused element, before entering the FocusTrap
assertActiveElement(document.getElementById('item-2'))
})

it('should stay in the FocusTrap when using `tab`, if there is only 1 focusable element', async () => {
render(
<>
<button>Before</button>
<FocusTrap>
<button id="item-a">Item A</button>
</FocusTrap>
<button>After</button>
</>
)

await nextFrame()

// Item A should be focused because the FocusTrap will focus the first item
assertActiveElement(document.getElementById('item-a'))

// Next
await press(Keys.Tab)
assertActiveElement(document.getElementById('item-a'))

// Next
await press(Keys.Tab)
assertActiveElement(document.getElementById('item-a'))
})

it('should stay in the FocusTrap when using `shift+tab`, if there is only 1 focusable element', async () => {
render(
<>
<button>Before</button>
<FocusTrap>
<button id="item-a">Item A</button>
</FocusTrap>
<button>After</button>
</>
)

await nextFrame()

// Item A should be focused because the FocusTrap will focus the first item
assertActiveElement(document.getElementById('item-a'))

// Previous (loop around!)
await press(shift(Keys.Tab))
assertActiveElement(document.getElementById('item-a'))

// Previous
await press(shift(Keys.Tab))
assertActiveElement(document.getElementById('item-a'))
})

it('should be possible tab to the next focusable element within the focus trap', async () => {
render(
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,12 @@ export let FocusTrap = Object.assign(
let wrapper = process.env.NODE_ENV === 'test' ? microTask : (cb: Function) => cb()
wrapper(() => {
match(direction.current, {
[TabDirection.Forwards]: () =>
focusIn(el, Focus.First, { skipElements: [e.relatedTarget as HTMLElement] }),
[TabDirection.Backwards]: () =>
focusIn(el, Focus.Last, { skipElements: [e.relatedTarget as HTMLElement] }),
[TabDirection.Forwards]: () => {
focusIn(el, Focus.First, { skipElements: [e.relatedTarget as HTMLElement] })
},
[TabDirection.Backwards]: () => {
focusIn(el, Focus.Last, { skipElements: [e.relatedTarget as HTMLElement] })
},
})
})
})
Expand Down
2 changes: 1 addition & 1 deletion packages/@headlessui-react/src/utils/focus-management.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ export function focusIn(
: container
: getFocusableElements(container)

if (skipElements.length > 0) {
if (skipElements.length > 0 && elements.length > 1) {
elements = elements.filter((x) => !skipElements.includes(x))
}

Expand Down
1 change: 1 addition & 0 deletions packages/@headlessui-vue/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Don’t overwrite classes during SSR when rendering fragments ([#2173](https://github.com/tailwindlabs/headlessui/pull/2173))
- Improve `Combobox` accessibility ([#2153](https://github.com/tailwindlabs/headlessui/pull/2153))
- Fix crash when reading `headlessuiFocusGuard` of `relatedTarget` in the `FocusTrap` component ([#2203](https://github.com/tailwindlabs/headlessui/pull/2203))
- Fix `FocusTrap` in `Dialog` when there is only 1 focusable element ([#2172](https://github.com/tailwindlabs/headlessui/pull/2172))

## [1.7.7] - 2022-12-16

Expand Down
Loading

0 comments on commit dbcfb23

Please sign in to comment.