import { onBeforeUnmount, onMounted } from 'vue';
import { findDOMNode } from '../../_util/props-util';
export default function useSelectTriggerControl(refs, triggerOpen) {
  function onGlobalMouseDown(event) {
    let target = event.target;

    if (target.shadowRoot && event.composed) {
      target = event.composedPath()[0] || target;
    }

    const elements = refs.map(e => findDOMNode(e.value));

    if (elements.every(element => element && !element.contains(target))) {
      // Should trigger close
      triggerOpen(false);
    }
  }

  onMounted(() => {
    window.addEventListener('mousedown', onGlobalMouseDown);
  });
  onBeforeUnmount(() => {
    window.removeEventListener('mousedown', onGlobalMouseDown);
  });
}