aboutsummaryrefslogtreecommitdiff
path: root/resources/vue/components/Dropdown.vue
blob: 02980eefd381af15b8c47f956d97a66767d09bb4 (plain)
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
<script setup>
import {nextTick, ref, useTemplateRef, watch} from "vue";
import useDetectOutsideClick from "../composables/useDetectOutsideClick";
import StudipIcon from "./StudipIcon.vue";

defineProps({
    title: {
        type: String
    },
    withCloseButton: {
        type: Boolean,
        default: true
    }
});

const isOpen = defineModel({ default: false });
const dropdownStyle = ref({});
const dropdown = useTemplateRef('dropdown');
const dropdownContent = useTemplateRef('dropdownContent');

useDetectOutsideClick(dropdown, () => isOpen.value = false);

watch(isOpen, async (open) => {
    if (open) {
        await nextTick();

        const trigger = dropdown.value?.getBoundingClientRect();
        const content = dropdownContent.value?.getBoundingClientRect();

        dropdownStyle.value = {
            ...(content.width > trigger.left ? {left: '0'} : {right: '0'})
        };
    }
});
</script>

<template>
    <div
        v-bind="$attrs"
        ref="dropdown"
        class="dropdown"
        aria-haspopup="true"
        :aria-expanded="isOpen.toString()"
    >
        <slot name="trigger">
        </slot>

        <Transition name="fade-down">
            <div
                v-if="isOpen"
                ref="dropdownContent"
                class="dropdown__content"
                :style="dropdownStyle"
                aria-labelledby="dropdown-title"
            >
                <button
                    v-if="withCloseButton"
                    @click="isOpen = false"
                    class="dropdown__close-button">
                    <StudipIcon shape="decline" :size="20" />
                </button>
                <div v-if="title" class="dropdown__header">
                    <p id="dropdown-title" class="dropdown__title">
                        {{ title }}
                    </p>
                </div>
                <ul class="dropdown__items" role="menu">
                    <slot name="items">
                    </slot>
                </ul>
                <slot name="content">
                </slot>
            </div>
        </Transition>
    </div>
</template>