UNPKG

refun

Version:

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

53 lines (43 loc) 1.94 kB
Object.defineProperty(exports, "__esModule", { value: true }); exports.mapThrottledHandlerAnimationFrame = exports.mapThrottledHandlerTimeout = exports.mapThrottledHandlerFactory = void 0; var _react = require("react"); var _tsfn = require("tsfn"); const mapThrottledHandlerFactory = (setFn, clearFn) => (handlerName, ...setFnArgs) => props => { const timerId = (0, _react.useRef)(null); const throttledHandlerRef = (0, _react.useRef)(); const onUnmountRef = (0, _react.useRef)(); const currentPropsHandlerRef = (0, _react.useRef)(); const handlerArgsRef = (0, _react.useRef)(_tsfn.EMPTY_ARRAY); currentPropsHandlerRef.current = props[handlerName]; if (throttledHandlerRef.current === _tsfn.UNDEFINED) { const timeoutCallback = () => { timerId.current = null; if ((0, _tsfn.isFunction)(currentPropsHandlerRef.current)) { currentPropsHandlerRef.current(...handlerArgsRef.current); } }; throttledHandlerRef.current = (...args) => { handlerArgsRef.current = args; if (timerId.current === null && (0, _tsfn.isFunction)(currentPropsHandlerRef.current)) { timerId.current = setFn(timeoutCallback, ...setFnArgs); } }; onUnmountRef.current = () => () => { if (timerId.current !== null) { clearFn(timerId.current); timerId.current = null; } }; } (0, _react.useEffect)(onUnmountRef.current, _tsfn.EMPTY_ARRAY); return { ...props, [handlerName]: throttledHandlerRef.current }; }; exports.mapThrottledHandlerFactory = mapThrottledHandlerFactory; const mapThrottledHandlerTimeout = mapThrottledHandlerFactory(setTimeout, clearTimeout); exports.mapThrottledHandlerTimeout = mapThrottledHandlerTimeout; const mapThrottledHandlerAnimationFrame = mapThrottledHandlerFactory(_tsfn.requestAnimationFrame, _tsfn.cancelAnimationFrame); exports.mapThrottledHandlerAnimationFrame = mapThrottledHandlerAnimationFrame;