index.js 2.2 KB

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