UNPKG

@forbespro/lead-agent

Version:
66 lines (65 loc) 2.58 kB
import { useRef as a, useState as O, useCallback as W, useEffect as q, useMemo as P } from "react"; function R(u, r, i) { var g = this, c = a(null), f = a(0), n = a(null), o = a([]), l = a(), s = a(), D = a(u), m = a(!0); D.current = u; var h = typeof window != "undefined", d = !r && r !== 0 && h; if (typeof u != "function") throw new TypeError("Expected a function"); r = +r || 0; var F = !!(i = i || {}).leading, E = !("trailing" in i) || !!i.trailing, v = "maxWait" in i, M = "debounceOnServer" in i && !!i.debounceOnServer, x = v ? Math.max(+i.maxWait || 0, r) : null; q(function() { return m.current = !0, function() { m.current = !1; }; }, []); var k = P(function() { var y = function(e) { var t = o.current, b = l.current; return o.current = l.current = null, f.current = e, s.current = D.current.apply(b, t); }, p = function(e, t) { d && cancelAnimationFrame(n.current), n.current = d ? requestAnimationFrame(e) : setTimeout(e, t); }, S = function(e) { if (!m.current) return !1; var t = e - c.current; return !c.current || t >= r || t < 0 || v && e - f.current >= x; }, T = function(e) { return n.current = null, E && o.current ? y(e) : (o.current = l.current = null, s.current); }, A = function e() { var t = Date.now(); if (S(t)) return T(t); if (m.current) { var b = r - (t - c.current), C = v ? Math.min(b, x - (t - f.current)) : b; p(e, C); } }, w = function() { if (h || M) { var e = Date.now(), t = S(e); if (o.current = [].slice.call(arguments), l.current = g, c.current = e, t) { if (!n.current && m.current) return f.current = c.current, p(A, r), F ? y(c.current) : s.current; if (v) return p(A, r), y(c.current); } return n.current || p(A, r), s.current; } }; return w.cancel = function() { n.current && (d ? cancelAnimationFrame(n.current) : clearTimeout(n.current)), f.current = 0, o.current = c.current = l.current = n.current = null; }, w.isPending = function() { return !!n.current; }, w.flush = function() { return n.current ? T(Date.now()) : s.current; }, w; }, [F, v, r, x, E, d, h, M]); return k; } function j(u, r) { return u === r; } function B(u, r, i) { var g = j, c = a(u), f = O({})[1], n = R(W(function(l) { c.current = l, f({}); }, [f]), r, i), o = a(u); return g(o.current, u) || (n(u), o.current = u), [c.current, n]; } export { B as useDebounce, R as useDebouncedCallback };