Skip to content

Commit 78089a5

Browse files
authored
fix(ContextMenu): support controlled open state (#2936)
* fix(ContextMenu): support controlled open state * fix(ContextMenu): anchor programmatic open to trigger * fix(ContextMenu): reset rejected pointer open state
1 parent a46be06 commit 78089a5

6 files changed

Lines changed: 270 additions & 17 deletions

File tree

‎docs/content/meta/ContextMenuRoot.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515
'required': false,
1616
'default': 'true'
1717
},
18+
{
19+
'name': 'open',
20+
'description': '<p>The controlled open state of the menu. Can be used as <code>v-model:open</code>.</p>\n',
21+
'type': 'boolean',
22+
'required': false
23+
},
1824
{
1925
'name': 'pressOpenDelay',
2026
'description': '<p>The duration from when the trigger is pressed until the menu opens.</p>\n',
@@ -41,6 +47,7 @@
4147
| --- | --- | --- | --- | --- |
4248
| `dir` | The reading direction of the combobox when applicable. If omitted, inherits globally from ConfigProvider or assumes LTR (left-to-right) reading mode. | `"ltr" \| "rtl"` | No | - |
4349
| `modal` | The modality of the dropdown menu. When set to true, interaction with outside elements will be disabled and only menu content will be visible to screen readers. | `boolean` | No | `true` |
50+
| `open` | The controlled open state of the menu. Can be used as v-model:open. | `boolean` | No | - |
4451
| `pressOpenDelay` | The duration from when the trigger is pressed until the menu opens. | `number` | No | `700` |
4552

4653
**Events**

‎packages/core/src/ContextMenu/ContextMenu.test.ts‎

Lines changed: 148 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
import type { VueWrapper } from '@vue/test-utils'
2-
import { findByRole } from '@testing-library/vue'
2+
import { findByRole, queryByRole, waitFor } from '@testing-library/vue'
33
import { mount } from '@vue/test-utils'
4-
import { beforeEach, describe, expect, it } from 'vitest'
4+
import { beforeEach, describe, expect, it, vi } from 'vitest'
55
import { axe } from 'vitest-axe'
66
import ContextMenu from './story/_ContextMenu.vue'
7+
import ControlledContextMenu from './story/_ControlledContextMenu.vue'
8+
9+
globalThis.ResizeObserver = class ResizeObserver {
10+
observe() {}
11+
unobserve() {}
12+
disconnect() {}
13+
}
14+
globalThis.IntersectionObserver = class IntersectionObserver {
15+
observe() {}
16+
unobserve() {}
17+
disconnect() {}
18+
} as any
719

820
describe('given default ContextMenu', () => {
921
let wrapper: VueWrapper<InstanceType<typeof ContextMenu>>
10-
globalThis.ResizeObserver = class ResizeObserver {
11-
observe() {}
12-
unobserve() {}
13-
disconnect() {}
14-
}
1522

1623
beforeEach(() => {
1724
document.body.innerHTML = ''
@@ -36,3 +43,137 @@ describe('given default ContextMenu', () => {
3643
})
3744
})
3845
})
46+
47+
describe('given controlled ContextMenu', () => {
48+
let wrapper: VueWrapper<InstanceType<typeof ControlledContextMenu>>
49+
50+
beforeEach(() => {
51+
document.body.innerHTML = ''
52+
wrapper = mount(ControlledContextMenu, { attachTo: document.body })
53+
})
54+
55+
describe('when open state is changed programmatically', () => {
56+
it('should render the menu', async () => {
57+
await wrapper.find('#open-button').trigger('click')
58+
59+
expect(await findByRole(document.body, 'menu')).toBeTruthy()
60+
})
61+
62+
it('should close the menu', async () => {
63+
await wrapper.find('#open-button').trigger('click')
64+
65+
expect(await findByRole(document.body, 'menu')).toBeTruthy()
66+
67+
await wrapper.find('#close-button').trigger('click')
68+
69+
expect(queryByRole(document.body, 'menu')).toBeNull()
70+
})
71+
72+
it('should position relative to the trigger when opened programmatically', async () => {
73+
const trigger = wrapper.find('#context-menu-trigger')
74+
75+
vi.spyOn(trigger.element, 'getBoundingClientRect').mockReturnValue({
76+
x: 100,
77+
y: 100,
78+
left: 100,
79+
top: 100,
80+
right: 200,
81+
bottom: 140,
82+
width: 100,
83+
height: 40,
84+
toJSON: () => {},
85+
} as DOMRect)
86+
87+
await wrapper.find('#open-button').trigger('click')
88+
89+
const menu = await findByRole(document.body, 'menu')
90+
const menuWrapper = menu.parentElement
91+
92+
await waitFor(() => {
93+
expect(menuWrapper?.style.transform)
94+
.toContain('translate(98px, 100px)')
95+
})
96+
})
97+
98+
it('should position relative to the trigger when reopened programmatically', async () => {
99+
const trigger = wrapper.find('#context-menu-trigger')
100+
101+
vi.spyOn(trigger.element, 'getBoundingClientRect').mockReturnValue({
102+
x: 100,
103+
y: 100,
104+
left: 100,
105+
top: 100,
106+
right: 200,
107+
bottom: 140,
108+
width: 100,
109+
height: 40,
110+
toJSON: () => {},
111+
} as DOMRect)
112+
113+
// First open from a pointer position.
114+
await trigger.trigger('contextmenu', {
115+
clientX: 300,
116+
clientY: 400,
117+
})
118+
119+
const menu = await findByRole(document.body, 'menu')
120+
const menuWrapper = menu.parentElement
121+
122+
await waitFor(() => {
123+
expect(menuWrapper?.style.transform)
124+
.toContain('translate(298px, 400px)')
125+
})
126+
127+
// Close the pointer-opened menu.
128+
await wrapper.find('#close-button').trigger('click')
129+
130+
expect(queryByRole(document.body, 'menu')).toBeNull()
131+
132+
// Reopen programmatically.
133+
await wrapper.find('#open-button').trigger('click')
134+
135+
const reopenedMenu = await findByRole(document.body, 'menu')
136+
const reopenedMenuWrapper = reopenedMenu.parentElement
137+
138+
await waitFor(() => {
139+
expect(reopenedMenuWrapper?.style.transform)
140+
.toContain('translate(98px, 100px)')
141+
})
142+
})
143+
144+
it('should reset pointer position when a controlled open request is rejected', async () => {
145+
const trigger = wrapper.find('#context-menu-trigger')
146+
147+
vi.spyOn(trigger.element, 'getBoundingClientRect').mockReturnValue({
148+
x: 100,
149+
y: 100,
150+
left: 100,
151+
top: 100,
152+
right: 200,
153+
bottom: 140,
154+
width: 100,
155+
height: 40,
156+
toJSON: () => {},
157+
} as DOMRect)
158+
159+
await wrapper.find('#reject-open-button').trigger('click')
160+
161+
await trigger.trigger('contextmenu', {
162+
clientX: 300,
163+
clientY: 400,
164+
})
165+
166+
expect(queryByRole(document.body, 'menu')).toBeNull()
167+
168+
await wrapper.find('#open-button').trigger('click')
169+
170+
const menu = await findByRole(document.body, 'menu')
171+
const menuWrapper = menu.parentElement
172+
173+
await waitFor(() => {
174+
expect(menuWrapper?.style.transform)
175+
.toContain('translate(98px, 100px)')
176+
})
177+
})
178+
})
179+
})

‎packages/core/src/ContextMenu/ContextMenuRoot.vue‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ type ContextMenuRootContext = {
1313
pressOpenDelay: Ref<number>
1414
}
1515
16-
export interface ContextMenuRootProps extends Omit<MenuProps, 'open'> {
16+
export interface ContextMenuRootProps extends MenuProps {
1717
/**
1818
* The duration from when the trigger is pressed until the menu opens.
1919
*
@@ -28,7 +28,8 @@ export const [injectContextMenuRootContext, provideContextMenuRootContext]
2828
</script>
2929

3030
<script setup lang="ts">
31-
import { ref, toRefs, watch } from 'vue'
31+
import { useVModel } from '@vueuse/core'
32+
import { ref, toRefs } from 'vue'
3233
import { MenuRoot } from '@/Menu'
3334
3435
defineOptions({
@@ -38,13 +39,17 @@ defineOptions({
3839
const props = withDefaults(defineProps<ContextMenuRootProps>(), {
3940
modal: true,
4041
pressOpenDelay: 700,
42+
open: undefined,
4143
})
4244
const emits = defineEmits<ContextMenuRootEmits>()
4345
const { dir: propDir, modal, pressOpenDelay } = toRefs(props)
4446
useForwardExpose()
4547
const dir = useDirection(propDir)
4648
47-
const open = ref(false)
49+
const open = useVModel(props, 'open', emits, {
50+
defaultValue: false,
51+
passive: (props.open === undefined) as false,
52+
}) as Ref<boolean>
4853
const triggerElement = ref<HTMLElement>()
4954
5055
provideContextMenuRootContext({
@@ -57,10 +62,6 @@ provideContextMenuRootContext({
5762
triggerElement,
5863
pressOpenDelay,
5964
})
60-
61-
watch(open, (value) => {
62-
emits('update:open', value)
63-
})
6465
</script>
6566

6667
<template>

‎packages/core/src/ContextMenu/ContextMenuTrigger.vue‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export interface ContextMenuTriggerProps extends PrimitiveProps {
1313
</script>
1414

1515
<script setup lang="ts">
16-
import { computed, nextTick, onMounted, ref, toRefs } from 'vue'
16+
import { computed, nextTick, onMounted, ref, toRefs, watch } from 'vue'
1717
import { MenuAnchor } from '@/Menu'
1818
import { Primitive } from '@/Primitive'
1919
import { useForwardExpose } from '@/shared'
@@ -33,6 +33,7 @@ const { disabled } = toRefs(props)
3333
const { forwardRef, currentElement } = useForwardExpose()
3434
const rootContext = injectContextMenuRootContext()
3535
const point = ref<Point>({ x: 0, y: 0 })
36+
const isPointerOpen = ref(false)
3637
const virtualEl = computed(() => ({
3738
getBoundingClientRect: () =>
3839
({
@@ -46,14 +47,35 @@ const virtualEl = computed(() => ({
4647
} as DOMRect),
4748
}))
4849
50+
const reference = computed(() =>
51+
isPointerOpen.value
52+
? virtualEl.value
53+
: rootContext.triggerElement.value,
54+
)
55+
56+
watch(
57+
() => rootContext.open.value,
58+
(open) => {
59+
if (!open)
60+
isPointerOpen.value = false
61+
},
62+
)
63+
4964
const longPressTimer = ref(0)
5065
function clearLongPress() {
5166
window.clearTimeout(longPressTimer.value)
5267
}
5368
54-
function handleOpen(event: MouseEvent | PointerEvent) {
69+
async function handleOpen(event: MouseEvent | PointerEvent) {
70+
isPointerOpen.value = true
5571
point.value = { x: event.clientX, y: event.clientY }
5672
rootContext.onOpenChange(true)
73+
74+
await nextTick()
75+
76+
// A controlled parent may have refused the request.
77+
if (!rootContext.open.value)
78+
isPointerOpen.value = false
5779
}
5880
5981
async function handleContextMenu(event: PointerEvent) {
@@ -97,7 +119,7 @@ onMounted(() => {
97119
<template>
98120
<MenuAnchor
99121
as="template"
100-
:reference="virtualEl"
122+
:reference="reference"
101123
/>
102124

103125
<Primitive

‎packages/core/src/ContextMenu/story/ContextMenu.story.vue‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
const checkboxOne = ref(false)
2323
const checkboxTwo = ref(false)
2424
const person = ref('pedro')
25+
const open = ref(false)
2526
2627
function handleClick() {
2728
// eslint-disable-next-line no-alert
@@ -346,5 +347,32 @@ function handleClick() {
346347
</ContextMenuPortal>
347348
</ContextMenuRoot>
348349
</Variant>
350+
<Variant title="controlled">
351+
<button
352+
class="block border-2 border-white text-white rounded my-[10px] text-[15px] select-none py-[5px] w-[300px] text-center"
353+
@click="open = !open"
354+
>
355+
{{ open ? 'Close' : 'Open' }}
356+
</button>
357+
358+
<ContextMenuRoot v-model:open="open">
359+
<ContextMenuTrigger
360+
class="block border-2 border-white border-dashed text-white rounded text-[15px] select-none py-[45px] w-[300px] text-center"
361+
>
362+
Right click for contextmenu
363+
</ContextMenuTrigger>
364+
365+
<ContextMenuContent>
366+
<ContextMenuItem>Item 1</ContextMenuItem>
367+
<ContextMenuItem>Item 2</ContextMenuItem>
368+
<button
369+
@click="open = false"
370+
>
371+
Close
372+
</button>
373+
<ContextMenuItem>Item 3</ContextMenuItem>
374+
</ContextMenuContent>
375+
</ContextMenuRoot>
376+
</Variant>
349377
</Story>
350378
</template>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<script setup lang="ts">
2+
import { ref } from 'vue'
3+
import {
4+
ContextMenuContent,
5+
ContextMenuItem,
6+
ContextMenuRoot,
7+
ContextMenuTrigger,
8+
} from '..'
9+
10+
const open = ref(false)
11+
const rejectOpen = ref(false)
12+
13+
function handleOpenChange(value: boolean) {
14+
if (value && rejectOpen.value)
15+
return
16+
17+
open.value = value
18+
}
19+
</script>
20+
21+
<template>
22+
<button
23+
id="open-button"
24+
@click="open = !open"
25+
>
26+
{{ open ? 'Close' : 'Open' }}
27+
</button>
28+
<button
29+
id="reject-open-button"
30+
@click="rejectOpen = true"
31+
>
32+
Reject open
33+
</button>
34+
<ContextMenuRoot
35+
:open="open"
36+
@update:open="handleOpenChange"
37+
>
38+
<ContextMenuTrigger id="context-menu-trigger">
39+
Right click for contextmenu
40+
</ContextMenuTrigger>
41+
42+
<ContextMenuContent>
43+
<ContextMenuItem>Item 1</ContextMenuItem>
44+
<ContextMenuItem>Item 2</ContextMenuItem>
45+
<button
46+
id="close-button"
47+
@click="open = false"
48+
>
49+
close
50+
</button>
51+
<ContextMenuItem>Item 3</ContextMenuItem>
52+
</ContextMenuContent>
53+
</ContextMenuRoot>
54+
</template>

0 commit comments

Comments
 (0)