export default {
  install(app) {
    app.directive('click-outside', {
      mounted(el, binding) {
        function documentHandler(e) {
          if (el.contains(e.target)) {
            return false
          }
          if (binding.value) {
            binding.value(e)
          }
        }
        el.__vueClickOutside__ = documentHandler
        if (binding.modifiers.click) {
          document.addEventListener('click', documentHandler, {
            capture: binding.modifiers.capture
          })
        }
        if (binding.modifiers.mousedown) {
          document.addEventListener('mousedown', documentHandler, {
            capture: binding.modifiers.capture
          })
        }
        if (binding.modifiers.touchstart) {
          document.addEventListener('touchstart', documentHandler, {
            capture: binding.modifiers.capture
          })
        }
      },
      unMounted(el, binding) {
        document.removeEventListener('click', el.__vueClickOutside__, {
          capture: binding.modifiers.capture
        })
        document.removeEventListener('mousedown', el.__vueClickOutside__, {
          capture: binding.modifiers.capture
        })
        document.removeEventListener('tarchstart', el.__vueClickOutside__, {
          capture: binding.modifiers.capture
        })
        delete el.__vueClickOutside__
      }
    })
  }
}