[d565449] | 1 | import { useCallback, useRef } from 'react';
|
---|
| 2 | import { off, on } from './misc/util';
|
---|
| 3 | var isTouchEvent = function (ev) {
|
---|
| 4 | return 'touches' in ev;
|
---|
| 5 | };
|
---|
| 6 | var preventDefault = function (ev) {
|
---|
| 7 | if (!isTouchEvent(ev))
|
---|
| 8 | return;
|
---|
| 9 | if (ev.touches.length < 2 && ev.preventDefault) {
|
---|
| 10 | ev.preventDefault();
|
---|
| 11 | }
|
---|
| 12 | };
|
---|
| 13 | var useLongPress = function (callback, _a) {
|
---|
| 14 | var _b = _a === void 0 ? {} : _a, _c = _b.isPreventDefault, isPreventDefault = _c === void 0 ? true : _c, _d = _b.delay, delay = _d === void 0 ? 300 : _d;
|
---|
| 15 | var timeout = useRef();
|
---|
| 16 | var target = useRef();
|
---|
| 17 | var start = useCallback(function (event) {
|
---|
| 18 | // prevent ghost click on mobile devices
|
---|
| 19 | if (isPreventDefault && event.target) {
|
---|
| 20 | on(event.target, 'touchend', preventDefault, { passive: false });
|
---|
| 21 | target.current = event.target;
|
---|
| 22 | }
|
---|
| 23 | timeout.current = setTimeout(function () { return callback(event); }, delay);
|
---|
| 24 | }, [callback, delay, isPreventDefault]);
|
---|
| 25 | var clear = useCallback(function () {
|
---|
| 26 | // clearTimeout and removeEventListener
|
---|
| 27 | timeout.current && clearTimeout(timeout.current);
|
---|
| 28 | if (isPreventDefault && target.current) {
|
---|
| 29 | off(target.current, 'touchend', preventDefault);
|
---|
| 30 | }
|
---|
| 31 | }, [isPreventDefault]);
|
---|
| 32 | return {
|
---|
| 33 | onMouseDown: function (e) { return start(e); },
|
---|
| 34 | onTouchStart: function (e) { return start(e); },
|
---|
| 35 | onMouseUp: clear,
|
---|
| 36 | onMouseLeave: clear,
|
---|
| 37 | onTouchEnd: clear,
|
---|
| 38 | };
|
---|
| 39 | };
|
---|
| 40 | export default useLongPress;
|
---|