import Vue from "vue";

/**
 * Register a specific event: v-click-out
 *
 * Example for some modale div:
 *
 *   <template>
 *     <div v-click-out="onClickOutside">
  *      <slot></slot>
  *    </div>
 *   </template>
 *
 *   <script>
 *     setup() {
 *       const show: Ref<Boolean> = ref(true)
 *       const onClickOutside = (e: any) => { show.value = false }
 *     }
 *   </script>
 */
Vue.directive("click-out", {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        if(vnode.context[binding.expression])
          vnode.context[binding.expression](event)
      }
    };
    document.body.addEventListener("click", el.clickOutsideEvent);
  },
  unbind(el) {
    document.body.removeEventListener("click", el.clickOutsideEvent);
  },
});
