index.mjs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { getCurrentInstance, shallowRef, ref, unref, watch } from 'vue';
  2. import { useEventListener } from '@vueuse/core';
  3. import { isFocusable } from '../../utils/dom/aria.mjs';
  4. import { isFunction } from '@vue/shared';
  5. function useFocusController(target, {
  6. disabled,
  7. beforeFocus,
  8. afterFocus,
  9. beforeBlur,
  10. afterBlur
  11. } = {}) {
  12. const instance = getCurrentInstance();
  13. const { emit } = instance;
  14. const wrapperRef = shallowRef();
  15. const isFocused = ref(false);
  16. const handleFocus = (event) => {
  17. const cancelFocus = isFunction(beforeFocus) ? beforeFocus(event) : false;
  18. if (unref(disabled) || isFocused.value || cancelFocus)
  19. return;
  20. isFocused.value = true;
  21. emit("focus", event);
  22. afterFocus == null ? void 0 : afterFocus();
  23. };
  24. const handleBlur = (event) => {
  25. var _a;
  26. const cancelBlur = isFunction(beforeBlur) ? beforeBlur(event) : false;
  27. if (unref(disabled) || event.relatedTarget && ((_a = wrapperRef.value) == null ? void 0 : _a.contains(event.relatedTarget)) || cancelBlur)
  28. return;
  29. isFocused.value = false;
  30. emit("blur", event);
  31. afterBlur == null ? void 0 : afterBlur();
  32. };
  33. const handleClick = (event) => {
  34. var _a, _b;
  35. if (unref(disabled) || isFocusable(event.target) || ((_a = wrapperRef.value) == null ? void 0 : _a.contains(document.activeElement)) && wrapperRef.value !== document.activeElement)
  36. return;
  37. (_b = target.value) == null ? void 0 : _b.focus();
  38. };
  39. watch([wrapperRef, () => unref(disabled)], ([el, disabled2]) => {
  40. if (!el)
  41. return;
  42. if (disabled2) {
  43. el.removeAttribute("tabindex");
  44. } else {
  45. el.setAttribute("tabindex", "-1");
  46. }
  47. });
  48. useEventListener(wrapperRef, "focus", handleFocus, true);
  49. useEventListener(wrapperRef, "blur", handleBlur, true);
  50. useEventListener(wrapperRef, "click", handleClick, true);
  51. return {
  52. isFocused,
  53. wrapperRef,
  54. handleFocus,
  55. handleBlur
  56. };
  57. }
  58. export { useFocusController };
  59. //# sourceMappingURL=index.mjs.map