UNPKG

refun

Version:

A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:

57 lines (49 loc) 2.38 kB
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import { useRef, useEffect } from 'react'; import { requestAnimationFrame, cancelAnimationFrame, UNDEFINED, EMPTY_ARRAY, isFunction } from 'tsfn'; export 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 = useRef(null); var throttledHandlerRef = useRef(); var onUnmountRef = useRef(); var currentPropsHandlerRef = useRef(); var handlerArgsRef = useRef(EMPTY_ARRAY); currentPropsHandlerRef.current = props[handlerName]; if (throttledHandlerRef.current === UNDEFINED) { var timeoutCallback = function timeoutCallback() { timerId.current = null; if (isFunction(currentPropsHandlerRef.current)) { currentPropsHandlerRef.current.apply(currentPropsHandlerRef, _toConsumableArray(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 && 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; } }; }; } useEffect(onUnmountRef.current, EMPTY_ARRAY); return Object.assign({}, props, _defineProperty({}, handlerName, throttledHandlerRef.current)); }; }; }; export var mapThrottledHandlerTimeout = mapThrottledHandlerFactory(setTimeout, clearTimeout); export var mapThrottledHandlerAnimationFrame = mapThrottledHandlerFactory(requestAnimationFrame, cancelAnimationFrame); //# sourceMappingURL=map-throttled-handler.js.map