import { ref, isRef, watch, onBeforeUnmount } from 'vue';

function useEsc(action) {
  let escClosable = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ref(true);
  let open = arguments.length > 2 ? arguments[2] : undefined;
  const onGlobalKeyDown = event => {
    if (event.code === 'Escape') {
      action(event);
    }
  };

  // 性能优化，减少事件触发次数
  if (isRef(open)) {
    watch(open, () => {
      if (open.value) {
        escClosable.value && window.addEventListener('keydown', onGlobalKeyDown);
      } else {
        window.removeEventListener('keydown', onGlobalKeyDown);
      }
    });
  }
  watch(escClosable, () => {
    if (escClosable.value) {
      window.addEventListener('keydown', onGlobalKeyDown);
    } else {
      window.removeEventListener('keydown', onGlobalKeyDown);
    }
  }, {
    immediate: true
  });
  onBeforeUnmount(() => {
    window.removeEventListener('keydown', onGlobalKeyDown);
  });
}

export { useEsc as default };
