import type { Directive } from "vue";

type BindValue = () => void;

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

type MouseFunc = (e: MouseEvent) => void;
let documentClickHandle: null | MouseFunc = null;

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