'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var vue = require('vue');
var core = require('@vueuse/core');
var aria = require('../../utils/dom/aria.js');
var shared = require('@vue/shared');

function useFocusController(target, {
  disabled,
  beforeFocus,
  afterFocus,
  beforeBlur,
  afterBlur
} = {}) {
  const instance = vue.getCurrentInstance();
  const { emit } = instance;
  const wrapperRef = vue.shallowRef();
  const isFocused = vue.ref(false);
  const handleFocus = (event) => {
    const cancelFocus = shared.isFunction(beforeFocus) ? beforeFocus(event) : false;
    if (vue.unref(disabled) || isFocused.value || cancelFocus)
      return;
    isFocused.value = true;
    emit("focus", event);
    afterFocus == null ? void 0 : afterFocus();
  };
  const handleBlur = (event) => {
    var _a;
    const cancelBlur = shared.isFunction(beforeBlur) ? beforeBlur(event) : false;
    if (vue.unref(disabled) || event.relatedTarget && ((_a = wrapperRef.value) == null ? void 0 : _a.contains(event.relatedTarget)) || cancelBlur)
      return;
    isFocused.value = false;
    emit("blur", event);
    afterBlur == null ? void 0 : afterBlur();
  };
  const handleClick = (event) => {
    var _a, _b;
    if (vue.unref(disabled) || aria.isFocusable(event.target) || ((_a = wrapperRef.value) == null ? void 0 : _a.contains(document.activeElement)) && wrapperRef.value !== document.activeElement)
      return;
    (_b = target.value) == null ? void 0 : _b.focus();
  };
  vue.watch([wrapperRef, () => vue.unref(disabled)], ([el, disabled2]) => {
    if (!el)
      return;
    if (disabled2) {
      el.removeAttribute("tabindex");
    } else {
      el.setAttribute("tabindex", "-1");
    }
  });
  core.useEventListener(wrapperRef, "focus", handleFocus, true);
  core.useEventListener(wrapperRef, "blur", handleBlur, true);
  core.useEventListener(wrapperRef, "click", handleClick, true);
  return {
    isFocused,
    wrapperRef,
    handleFocus,
    handleBlur
  };
}

exports.useFocusController = useFocusController;
//# sourceMappingURL=index.js.map
