-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComponentDropdown.vue
More file actions
109 lines (98 loc) · 2.82 KB
/
Copy pathComponentDropdown.vue
File metadata and controls
109 lines (98 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<template>
<div class="relative">
<FoundationButton
:id="triggerId"
ref="triggerEl"
:class="[
'gap-2',
{ 'opacity-50 cursor-not-allowed': disabled }
]"
:aria-haspopup="true"
:aria-expanded="isOpen"
:disabled="disabled"
un-styled
v-bind="$attrs"
@click="toggleDropdown"
@keydown.esc="closeDropdown"
@keydown.arrow-down.prevent="openDropdown"
@keydown.enter.prevent="openDropdown"
>
{{ triggerLabel }}
<FoundationIcon v-show="isOpen" name="chevron-up" />
<FoundationIcon v-show="!isOpen" name="chevron-down" />
</FoundationButton>
<transition
enter-active-class="transition ease-out duration-100"
enter-from-class="transform opacity-0 scale-95"
enter-to-class="transform opacity-100 scale-100"
leave-active-class="transition ease-in duration-75"
leave-from-class="transform opacity-100 scale-100"
leave-to-class="transform opacity-0 scale-95"
>
<div
v-if="isOpen"
ref="contentEl"
:class="[
contentClasses
]"
role="menu"
:aria-labelledby="triggerId"
@keydown.stop.esc="closeDropdown"
>
<slot />
</div>
</transition>
</div>
</template>
<script setup lang="ts">
import { onClickOutside } from '@vueuse/core'
import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'
interface Props {
triggerLabel: string;
disabled?: boolean;
contentClasses?: string;
}
const props = withDefaults(defineProps<Props>(), {
disabled: false,
contentClasses: '',
})
const emit = defineEmits<{
(e: 'open' | 'close'): void;
}>()
defineOptions({
inheritAttrs: false
})
const isOpen = ref(false)
const uuId = useId()
const triggerId = `dropdown-trigger-${uuId}`
const triggerEl = ref()
const contentEl = ref()
onClickOutside(contentEl, () => closeDropdown(), { ignore: [triggerEl] })
const { activate, deactivate } = useFocusTrap(contentEl, { allowOutsideClick: true })
function toggleDropdown (e: MouseEvent) {
if (!props.disabled && e.type === 'click') {
isOpen.value = !isOpen.value
if (isOpen.value) {
emit('open')
} else {
emit('close')
}
}
}
function openDropdown () {
if (!isOpen.value && !props.disabled) {
isOpen.value = true
emit('open')
nextTick(() => {
activate()
})
}
}
function closeDropdown () {
if (isOpen.value) {
isOpen.value = false
emit('close')
deactivate()
}
}
</script>