refun
Version:
A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:
74 lines (58 loc) • 3.06 kB
JavaScript
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mapThrottledHandlerAnimationFrame = exports.mapThrottledHandlerTimeout = exports.mapThrottledHandlerFactory = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _react = require("react");
var _tsfn = require("tsfn");
var mapThrottledHandlerFactory = function mapThrottledHandlerFactory(setFn, clearFn) {
return function (handlerName) {
for (var _len = arguments.length, setFnArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
setFnArgs[_key - 1] = arguments[_key];
}
return function (props) {
var timerId = (0, _react.useRef)(null);
var throttledHandlerRef = (0, _react.useRef)();
var onUnmountRef = (0, _react.useRef)();
var currentPropsHandlerRef = (0, _react.useRef)();
var handlerArgsRef = (0, _react.useRef)(_tsfn.EMPTY_ARRAY);
currentPropsHandlerRef.current = props[handlerName];
if (throttledHandlerRef.current === _tsfn.UNDEFINED) {
var timeoutCallback = function timeoutCallback() {
timerId.current = null;
if ((0, _tsfn.isFunction)(currentPropsHandlerRef.current)) {
currentPropsHandlerRef.current.apply(currentPropsHandlerRef, (0, _toConsumableArray2.default)(handlerArgsRef.current));
}
};
throttledHandlerRef.current = function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
handlerArgsRef.current = args;
if (timerId.current === null && (0, _tsfn.isFunction)(currentPropsHandlerRef.current)) {
timerId.current = setFn.apply(void 0, [timeoutCallback].concat(setFnArgs));
}
};
onUnmountRef.current = function () {
return function () {
if (timerId.current !== null) {
clearFn(timerId.current);
timerId.current = null;
}
};
};
}
(0, _react.useEffect)(onUnmountRef.current, _tsfn.EMPTY_ARRAY);
return (0, _extends3.default)({}, props, (0, _defineProperty2.default)({}, handlerName, throttledHandlerRef.current));
};
};
};
exports.mapThrottledHandlerFactory = mapThrottledHandlerFactory;
var mapThrottledHandlerTimeout = mapThrottledHandlerFactory(setTimeout, clearTimeout);
exports.mapThrottledHandlerTimeout = mapThrottledHandlerTimeout;
var mapThrottledHandlerAnimationFrame = mapThrottledHandlerFactory(_tsfn.requestAnimationFrame, _tsfn.cancelAnimationFrame);
exports.mapThrottledHandlerAnimationFrame = mapThrottledHandlerAnimationFrame;
//# sourceMappingURL=map-throttled-handler.js.map