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 FocusTrap is only active when the given enabled value is true #2456

Merged
merged 7 commits into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,6 @@ onDocumentReady(() => {

function useRestoreElement(enabled: boolean = true) {
let localHistory = useRef<HTMLElement[]>(history.slice())
let isPreviouslyActive = useRef<boolean>(enabled)

useWatch(
([newEnabled], [oldEnabled]) => {
Expand All @@ -254,21 +253,14 @@ function useRestoreElement(enabled: boolean = true) {
if (oldEnabled === false && newEnabled === true) {
localHistory.current = history.slice()
}

if (oldEnabled !== undefined) {
isPreviouslyActive.current = oldEnabled
}
},
[enabled, history, localHistory]
)

// We want to return the last element that is still connected to the DOM, so we can restore the
// focus to it.
return useEvent(() => {
return (
localHistory.current.find((x) => x != null && x.isConnected && isPreviouslyActive.current) ??
null
)
return localHistory.current.find((x) => x != null && x.isConnected) ?? null
})
}

Expand All @@ -287,6 +279,8 @@ function useRestoreFocus({ ownerDocument }: { ownerDocument: Document | null },
// Restore the focus to the previous element when the component is unmounted
let trulyUnmounted = useRef(false)
useEffect(() => {
if (!enabled) return
RobinMalfait marked this conversation as resolved.
Show resolved Hide resolved

trulyUnmounted.current = false

return () => {
Expand All @@ -297,7 +291,7 @@ function useRestoreFocus({ ownerDocument }: { ownerDocument: Document | null },
focusElement(getRestoreElement())
})
}
}, [])
}, [enabled])
}

function useInitialFocus(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,8 @@ function useRestoreFocus(

// Restore the focus when we unmount the component
onUnmounted(() => {
if (!enabled.value) return

focusElement(getRestoreElement())
})
}
Expand Down
69 changes: 68 additions & 1 deletion packages/@headlessui-vue/src/components/tabs/tabs.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { nextTick, ref } from 'vue'
import { createRenderTemplate, render } from '../../test-utils/vue-testing-library'
import { TabGroup, TabList, Tab, TabPanels, TabPanel } from './tabs'
import { Dialog } from '../dialog/dialog'
import { suppressConsoleLogs } from '../../test-utils/suppress-console-logs'
import {
assertActiveElement,
Expand All @@ -20,7 +21,7 @@ beforeAll(() => {

afterAll(() => jest.restoreAllMocks())

const renderTemplate = createRenderTemplate({ TabGroup, TabList, Tab, TabPanels, TabPanel })
const renderTemplate = createRenderTemplate({ TabGroup, TabList, Tab, TabPanels, TabPanel, Dialog })

describe('safeguards', () => {
it.each([
Expand Down Expand Up @@ -2716,3 +2717,69 @@ it('should trigger the `change` when the tab changes', async () => {
expect(changes).toHaveBeenNthCalledWith(3, 1)
expect(changes).toHaveBeenNthCalledWith(4, 0)
})

describe('Composition', () => {
it(
'should be possible to go to the next item containing a Dialog component',
suppressConsoleLogs(async () => {
renderTemplate({
template: `
<TabGroup>
<TabList>
<Tab>Tab 1</Tab>
<Tab>Tab 2</Tab>
<Tab>Tab 3</Tab>
</TabList>

<TabPanels>
<TabPanel data-panel="0">Content 1</TabPanel>
<TabPanel data-panel="1">
<button>open</button>
<Dialog :open="false" @close="noop" />
</TabPanel>
<TabPanel data-panel="2">Content 3</TabPanel>
</TabPanels>
</TabGroup>
`,
setup: () => ({
noop: console.log,
}),
})

await new Promise<void>(nextTick)

assertActiveElement(document.body)

await press(Keys.Tab)
assertTabs({ active: 0 })

// Navigate to Dialog tab
await press(Keys.ArrowRight)
assertTabs({ active: 1 })

// Focus on to the Dialog panel
await press(Keys.Tab)
assertActiveElement(document.querySelector('[data-panel="1"]'))

// Focus on to the Dialog trigger button
await press(Keys.Tab)
assertActiveElement(getByText('open'))

// Focus back to the panel
await press(shift(Keys.Tab))
assertActiveElement(document.querySelector('[data-panel="1"]'))

// Focus back to tabs
await press(shift(Keys.Tab))
assertTabs({ active: 1 })

// Navigate to the next tab
await press(Keys.ArrowRight)
assertTabs({ active: 2 })

// Focus on to the content panel
await press(Keys.Tab)
assertActiveElement(document.querySelector('[data-panel="2"]'))
})
)
})