<script setup lang="ts">
import { onUnmounted } from 'vue';
import { onMounted } from 'vue';
import { ref } from 'vue';

const open = ref(false);
const element = ref<HTMLElement>();

function click({ target }: MouseEvent) {
  if (!open.value) return;
  if (target instanceof HTMLElement && element.value?.contains(target)) {
    return;
  }
  open.value = false;
}

onMounted(() => {
  window.addEventListener('mouseup', click);
});

onUnmounted(() => {
  window.removeEventListener('mouseup', click);
});
</script>

<template>
  <div class="dropdown" ref="element">
    <button class="dropdown__trigger" @click.stop="open = !open">
      <slot name="trigger" />
    </button>
    <Transition>
      <div class="dropdown__content" v-if="open">
        <slot name="content" />
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.dropdown {
  display: inline-block;
  overflow: visible;
  position: relative;

  & .dropdown__trigger {
    appearance: none;
    background: transparent;
    outline: none;
    border: none;
    padding: 0;
  }

  & .dropdown__content {
    position: absolute;
    z-index: 9999;
    top: 100%;
    left: 0%;
    margin-top: 0.25rem;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-2, 7px);
  }
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.15s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>
