|
| 1 | +import userEvent from '@testing-library/user-event' |
| 2 | +import { render, screen } from '@testing-library/vue' |
| 3 | +import { describe, expect, it } from 'vitest' |
| 4 | +import { defineComponent, h } from 'vue' |
| 5 | + |
| 6 | +import { usePopoverExclusivity } from '@/components/load3d/menubar/usePopoverExclusivity' |
| 7 | + |
| 8 | +const Toggle = defineComponent({ |
| 9 | + props: { popoverId: { type: String, required: true } }, |
| 10 | + setup(props) { |
| 11 | + const open = usePopoverExclusivity()(props.popoverId) |
| 12 | + return () => |
| 13 | + h('div', [ |
| 14 | + h( |
| 15 | + 'span', |
| 16 | + { 'data-testid': `${props.popoverId}-state` }, |
| 17 | + open.value ? 'open' : 'closed' |
| 18 | + ), |
| 19 | + h( |
| 20 | + 'button', |
| 21 | + { onClick: () => (open.value = true) }, |
| 22 | + `open ${props.popoverId}` |
| 23 | + ), |
| 24 | + h( |
| 25 | + 'button', |
| 26 | + { onClick: () => (open.value = false) }, |
| 27 | + `close ${props.popoverId}` |
| 28 | + ) |
| 29 | + ]) |
| 30 | + } |
| 31 | +}) |
| 32 | + |
| 33 | +const Menubar = defineComponent({ |
| 34 | + setup() { |
| 35 | + usePopoverExclusivity() |
| 36 | + return () => [h(Toggle, { popoverId: 'a' }), h(Toggle, { popoverId: 'b' })] |
| 37 | + } |
| 38 | +}) |
| 39 | + |
| 40 | +function renderMenubar() { |
| 41 | + render(Menubar) |
| 42 | + return userEvent.setup() |
| 43 | +} |
| 44 | + |
| 45 | +describe('usePopoverExclusivity', () => { |
| 46 | + it('keeps popovers across components mutually exclusive', async () => { |
| 47 | + const user = renderMenubar() |
| 48 | + |
| 49 | + await user.click(screen.getByRole('button', { name: 'open a' })) |
| 50 | + expect(screen.getByTestId('a-state')).toHaveTextContent('open') |
| 51 | + |
| 52 | + await user.click(screen.getByRole('button', { name: 'open b' })) |
| 53 | + expect(screen.getByTestId('b-state')).toHaveTextContent('open') |
| 54 | + expect(screen.getByTestId('a-state')).toHaveTextContent('closed') |
| 55 | + }) |
| 56 | + |
| 57 | + it('ignores a close from a popover that is not the open one', async () => { |
| 58 | + const user = renderMenubar() |
| 59 | + |
| 60 | + await user.click(screen.getByRole('button', { name: 'open a' })) |
| 61 | + await user.click(screen.getByRole('button', { name: 'close b' })) |
| 62 | + |
| 63 | + expect(screen.getByTestId('a-state')).toHaveTextContent('open') |
| 64 | + }) |
| 65 | +}) |
0 commit comments