index.mjs 2.1 KB

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