Line data Source code
1 : import { useEventListener } from '@vueuse/core'
2 : import { computed, ref, shallowRef } from 'vue'
3 :
4 : import { getMenuAnchorPosition } from './menuAnchor'
5 :
6 : /**
7 : * State for a non-modal menu opened from code at the event's pointer or element.
8 : * Bind `menuProps` to a `Menu`; any outside press closes it, even one stopped before reaching the document.
9 : */
10 2469 : export function usePointMenu(onShow?: (event: Event) => void) {
11 2469 : const open = ref(false)
12 2469 : const reference = shallowRef<{ getBoundingClientRect: () => DOMRect }>()
13 2469 : let shownFrom: EventTarget | null = null
14 2469 : let dismissingPress: Node | null = null
15 :
16 197 : function show(event: Event) {
17 197 : dismissingPress = null
18 197 : shownFrom = event.currentTarget
19 197 : onShow?.(event)
20 197 : const { x, y } = getMenuAnchorPosition(event)
21 197 : reference.value = { getBoundingClientRect: () => new DOMRect(x, y, 1, 1) }
22 197 : open.value = true
23 : }
24 :
25 2 : function hide() {
26 2 : dismissingPress = null
27 2 : open.value = false
28 : }
29 :
30 29 : function toggle(event: Event) {
31 29 : const control = event.currentTarget
32 29 : const pressDismissedMenu =
33 : event instanceof MouseEvent &&
34 : event.detail > 0 &&
35 : control instanceof Node &&
36 : control === shownFrom &&
37 : dismissingPress !== null &&
38 : control.contains(dismissingPress)
39 29 : if (open.value || pressDismissedMenu) hide()
40 27 : else show(event)
41 : }
42 :
43 2469 : useEventListener(
44 : document,
45 : 'pointerdown',
46 : ({ target }) => {
47 5887 : dismissingPress = null
48 5887 : if (!open.value) return
49 5887 : if (target instanceof Element && target.closest('[role="menu"]')) return
50 5887 : dismissingPress = target instanceof Node ? target : null
51 5887 : open.value = false
52 : },
53 : { capture: true }
54 : )
55 :
56 : const menuProps = computed(() => ({
57 : open: open.value,
58 : 'onUpdate:open': (value: boolean) => {
59 152 : open.value = value
60 : },
61 : reference: reference.value,
62 : modal: false,
63 : onFocusOutside: (event: Event) => event.preventDefault()
64 : }))
65 :
66 2469 : return { open, menuProps, show, hide, toggle }
67 : }
|