clicknhold
Version:
React hook for handling click and hold events
78 lines (74 loc) • 3.37 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.clicknhold = {}, global.React));
})(this, (function (exports, react) { 'use strict';
function useClicknHold(_a) {
var _b = _a === void 0 ? {} : _a, _c = _b.duration, duration = _c === void 0 ? 2000 : _c, onComplete = _b.onComplete, onStart = _b.onStart, onCancel = _b.onCancel, onProgress = _b.onProgress, _d = _b.disabled, disabled = _d === void 0 ? false : _d;
var _e = react.useState(false), isHolding = _e[0], setIsHolding = _e[1];
var timerRef = react.useRef();
var startTimeRef = react.useRef();
var cleanup = react.useCallback(function () {
if (timerRef.current) {
window.clearInterval(timerRef.current);
timerRef.current = undefined;
}
startTimeRef.current = undefined;
setIsHolding(false);
}, []);
var startHolding = react.useCallback(function (event) {
if ('preventDefault' in event) {
event.preventDefault();
}
if (disabled)
return;
startTimeRef.current = Date.now();
setIsHolding(true);
onStart === null || onStart === void 0 ? void 0 : onStart();
timerRef.current = window.setInterval(function () {
var elapsedTime = Date.now() - startTimeRef.current;
var progress = Math.min(elapsedTime / duration, 1);
onProgress === null || onProgress === void 0 ? void 0 : onProgress(progress);
if (elapsedTime >= duration) {
cleanup();
onComplete === null || onComplete === void 0 ? void 0 : onComplete();
}
}, 16);
}, [duration, onComplete, onStart, onProgress, cleanup, disabled]);
var stopHolding = react.useCallback(function () {
if (isHolding) {
cleanup();
onCancel === null || onCancel === void 0 ? void 0 : onCancel();
}
}, [isHolding, cleanup, onCancel]);
var handleKeyDown = react.useCallback(function (event) {
if (event.key === 'Enter' || event.key === ' ') {
startHolding(event);
}
}, [startHolding]);
var handleKeyUp = react.useCallback(function (event) {
if (event.key === 'Enter' || event.key === ' ') {
stopHolding();
}
}, [stopHolding]);
react.useEffect(function () {
return cleanup;
}, [cleanup]);
var handlers = {
onMouseDown: startHolding,
onMouseUp: stopHolding,
onMouseLeave: stopHolding,
onTouchStart: startHolding,
onTouchEnd: stopHolding,
onKeyDown: handleKeyDown,
onKeyUp: handleKeyUp,
};
return {
isHolding: isHolding,
handlers: handlers,
startHolding: startHolding,
stopHolding: stopHolding
};
}
exports.useClicknHold = useClicknHold;
}));