import type { ObjectDirective } from 'vue'

export const clickOutside = {
  beforeMount(element, binding) {
    element.clickOutsideEvent = (e: MouseEvent) => {
      if (!(element === e.target || element.contains(e.target))) {
        binding.value(e)
      }
    }
    document.addEventListener('click', element.clickOutsideEvent)
  },
  unmounted(element) {
    document.removeEventListener('click', element.clickOutsideEvent)
  },
} satisfies ObjectDirective
