UNPKG

vue-hooks-plus

Version:
97 lines (96 loc) 3.14 kB
import { getTargetElement } from "../utils/domTarget"; import { ref, readonly } from "vue"; import useEffectWithTarget from "../utils/useEffectWithTarget"; const getSupportedMouseEvents = () => { const hasPointEvent = "PointerEvent" in window; if (hasPointEvent) { return { mouseDown: "pointerdown", mouseUp: "pointerup", mouseMove: "pointermove" }; } const isTouch = "ontouchstart" in window || navigator.maxTouchPoints > 0; if (isTouch) { return { mouseDown: "touchstart", mouseUp: "touchend", mouseMove: "touchmove" }; } return { mouseDown: "mousedown", mouseUp: "mouseup", mouseMove: "mousemove" }; }; const useLongPress = (target, options = {}) => { var _a, _b; const DEFAULT_DELAY_TIME = 500; const DEFAULT_UPDATE_TIME = 100; const isPressing = ref(false); const pressingTime = ref(0); let pressingTimer; let timeoutTimer; const eventOptions = { capture: (_a = options == null ? void 0 : options.modifiers) == null ? void 0 : _a.capture, once: (_b = options == null ? void 0 : options.modifiers) == null ? void 0 : _b.once }; useEffectWithTarget( () => { var _a2; const targetElement = getTargetElement(target); if (!targetElement) { return; } const { mouseDown, mouseUp, mouseMove } = getSupportedMouseEvents(); function clear() { if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = void 0; } if (pressingTimer) { clearInterval(pressingTimer); pressingTimer = void 0; } pressingTime.value = 0; isPressing.value = false; } function onDown(ev) { var _a3, _b2, _c; if (((_a3 = options.modifiers) == null ? void 0 : _a3.self) && ev.target !== targetElement) return; clear(); if ((_b2 = options.modifiers) == null ? void 0 : _b2.prevent) ev.preventDefault(); if ((_c = options.modifiers) == null ? void 0 : _c.stop) ev.stopPropagation(); timeoutTimer = setTimeout(() => { isPressing.value = true; pressingTimer = setInterval(() => { pressingTime.value += options.minUpdateTime || DEFAULT_UPDATE_TIME; }, options.minUpdateTime || DEFAULT_UPDATE_TIME); }, options.delay || DEFAULT_DELAY_TIME); } targetElement.addEventListener(mouseDown, onDown, eventOptions); targetElement.addEventListener(mouseUp, clear, eventOptions); if ((_a2 = options.cancelOnMove) != null ? _a2 : true) { targetElement.addEventListener(mouseMove, clear, eventOptions); } return () => { var _a3; targetElement.removeEventListener(mouseDown, onDown); targetElement.removeEventListener(mouseUp, clear); if ((_a3 = options.cancelOnMove) != null ? _a3 : true) { targetElement.removeEventListener(mouseMove, clear); } }; }, [], target ); return { isPressing: readonly(isPressing), pressingTime: readonly(pressingTime) }; }; export { useLongPress as default };