import type { Directive } from "vue";

type BindValue = () => void;

const clickhandle = (e: MouseEvent, el: HTMLElement, value: BindValue) => {
  if (!el.contains(e.target) && value) {
    value();
  }
};

let documentClickHandle = null;

export const vEleClickOutsideDirective: Directive<HTMLElement, BindValue> = {
  mounted(el, { value }) {
    documentClickHandle = (e) => clickhandle(e, el, value);
    document.addEventListener("mouseup", documentClickHandle);
  },
  unmounted(el, { value }) {
    document.removeEventListener("mouseup", documentClickHandle);
  },
};
