Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rc-hooks

Package Overview
Dependencies
Maintainers
1
Versions
80
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rc-hooks - npm Package Compare versions

Comparing version 2.0.8 to 2.1.0

es/useAsync/Async.d.ts

2

dist/rcHooks.min.js

@@ -1,2 +0,2 @@

!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).rcHooks={},e.React)}(this,(function(e,n){"use strict";function t(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}})),n.default=e,Object.freeze(n)}var r=t(n),u=function(){return u=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var u in n=arguments[t])Object.prototype.hasOwnProperty.call(n,u)&&(e[u]=n[u]);return e},u.apply(this,arguments)};function i(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(t[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(r=Object.getOwnPropertySymbols(e);u<r.length;u++)n.indexOf(r[u])<0&&Object.prototype.propertyIsEnumerable.call(e,r[u])&&(t[r[u]]=e[r[u]])}return t}function o(e){var n="function"==typeof Symbol&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,n){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var r,u,i=t.call(e),o=[];try{for(;(void 0===n||n-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(e){u={error:e}}finally{try{r&&!r.done&&(t=i.return)&&t.call(i)}finally{if(u)throw u.error}}return o}function c(e,n,t){if(t||2===arguments.length)for(var r,u=0,i=n.length;u<i;u++)!r&&u in n||(r||(r=Array.prototype.slice.call(n,0,u)),r[u]=n[u]);return e.concat(r||Array.prototype.slice.call(n))}var f="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var l=function(e){var n=typeof e;return null!=e&&("object"==n||"function"==n)},s="object"==typeof f&&f&&f.Object===Object&&f,d="object"==typeof self&&self&&self.Object===Object&&self,v=s||d||Function("return this")(),p=v,h=function(){return p.Date.now()},y=/\s/;var g=function(e){for(var n=e.length;n--&&y.test(e.charAt(n)););return n},m=/^\s+/;var b=function(e){return e?e.slice(0,g(e)+1).replace(m,""):e},w=v.Symbol,E=w,R=Object.prototype,T=R.hasOwnProperty,S=R.toString,O=E?E.toStringTag:void 0;var C=function(e){var n=T.call(e,O),t=e[O];try{e[O]=void 0;var r=!0}catch(e){}var u=S.call(e);return r&&(n?e[O]=t:delete e[O]),u},j=Object.prototype.toString;var k=C,L=function(e){return j.call(e)},x=w?w.toStringTag:void 0;var P=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":x&&x in Object(e)?k(e):L(e)},A=function(e){return null!=e&&"object"==typeof e};var M=b,N=l,_=function(e){return"symbol"==typeof e||A(e)&&"[object Symbol]"==P(e)},z=/^[-+]0x[0-9a-f]+$/i,D=/^0b[01]+$/i,H=/^0o[0-7]+$/i,I=parseInt;var F=l,W=h,U=function(e){if("number"==typeof e)return e;if(_(e))return NaN;if(N(e)){var n="function"==typeof e.valueOf?e.valueOf():e;e=N(n)?n+"":n}if("string"!=typeof e)return 0===e?e:+e;e=M(e);var t=D.test(e);return t||H.test(e)?I(e.slice(2),t?2:8):z.test(e)?NaN:+e},V=Math.max,$=Math.min;var q=function(e,n,t){var r,u,i,o,a,c,f=0,l=!1,s=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function v(n){var t=r,i=u;return r=u=void 0,f=n,o=e.apply(i,t)}function p(e){return f=e,a=setTimeout(y,n),l?v(e):o}function h(e){var t=e-c;return void 0===c||t>=n||t<0||s&&e-f>=i}function y(){var e=W();if(h(e))return g(e);a=setTimeout(y,function(e){var t=n-(e-c);return s?$(t,i-(e-f)):t}(e))}function g(e){return a=void 0,d&&r?v(e):(r=u=void 0,o)}function m(){var e=W(),t=h(e);if(r=arguments,u=this,c=e,t){if(void 0===a)return p(c);if(s)return clearTimeout(a),a=setTimeout(y,n),v(c)}return void 0===a&&(a=setTimeout(y,n)),o}return n=U(n)||0,F(t)&&(l=!!t.leading,i=(s="maxWait"in t)?V(U(t.maxWait)||0,n):i,d="trailing"in t?!!t.trailing:d),m.cancel=function(){void 0!==a&&clearTimeout(a),f=0,r=c=u=a=void 0},m.flush=function(){return void 0===a?o:g(W())},m},B=q,K=l;var Y=function(e,n,t){var r=!0,u=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return K(t)&&(r="leading"in t?!!t.leading:r,u="trailing"in t?!!t.trailing:u),B(e,n,{leading:r,maxWait:n,trailing:u})};function G(e){var t=n.useRef(e);t.current=e;var r=n.useCallback((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];var r=t.current;return null==r?void 0:r.apply(void 0,c([],a(e),!1))}),[t]);return r}var J=function(e,t){var r=n.useRef(!1);n.useEffect((function(){if(r.current)return e();r.current=!0}),t)};function Q(){return"undefined"==typeof document||void 0===document.visibilityState||"hidden"!==document.visibilityState}var X={},Z=function(e){var n=X[e];if(n){var t=n.startTime,r=n.cacheTime,u=n.data;if(!((new Date).getTime()-t>=r))return u;n.timer&&(clearTimeout(n.timer),n.timer=null,delete X[e])}},ee=function(e,n,t){void 0===t&&(t=3e5),X[e]&&clearTimeout(X[e].timer);var r=setTimeout((function(){delete X[e]}),t);X[e]={data:n,timer:r,cacheTime:t,startTime:(new Date).getTime()}};var ne=[];var te=!1;if("undefined"!=typeof window&&window.addEventListener&&!te){var re=function(){if(Q()&&("undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine))for(var e=0;e<ne.length;e++){(0,ne[e])()}};window.addEventListener("visibilitychange",re,!1),window.addEventListener("focus",re,!1),te=!0}var ue=[];var ie=!1;if("undefined"!=typeof window&&window.addEventListener&&!ie){window.addEventListener("visibilitychange",(function(){if(Q())for(var e=0;e<ue.length;e++){(0,ue[e])()}}),!1),ie=!0}var oe=function(){};function ae(e,t){var r=t||{},i=r.autoRun,o=void 0===i||i,f=r.refreshDeps,l=void 0===f?[]:f,s=r.defaultParams,d=void 0===s?[]:s,v=r.defaultLoading,p=void 0!==v&&v,h=r.initialData,y=r.cacheKey,g=void 0===y?"":y,m=r.cacheTime,b=void 0===m?3e5:m,w=r.persisted,E=void 0!==w&&w,R=r.onSuccess,T=void 0===R?oe:R,S=r.onError,O=void 0===S?oe:S,C=r.__INTERNAL_FORMAT__,j=r.pollingInterval,k=void 0===j?0:j,L=r.pollingWhenHidden,x=void 0===L||L,P=r.refreshOnWindowFocus,A=void 0!==P&&P,M=r.focusTimespan,N=void 0===M?5e3:M,_=r.loadingDelay,z=r.debounceInterval,D=r.throttleInterval,H=a(n.useState({params:Array.isArray(d)?d:[d],loading:p,error:null,data:g&&Z(g)||h}),2),I=H[0],F=H[1],W=n.useRef(0),U=n.useRef(null),V=n.useRef(!1),$=n.useRef(null),B=n.useRef(!1),K=n.useRef([]),X=G(e),te=G(T),re=G(O),ie=n.useRef(C);ie.current=C;var ae=n.useCallback((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];U.current&&clearTimeout(U.current),$.current&&clearTimeout($.current);var t=W.current,r=g?Z(g):void 0;r&&E||(F((function(n){return u(u({},n),{loading:!_,params:e})})),$.current=_?setTimeout((function(){F((function(e){return u(u({},e),{loading:!0})}))}),_):null);var i=function(){return new Promise((function(n,i){r&&E?B.current||t!==W.current||(te(r,e),F((function(e){return u(u({},e),{data:r,error:null,loading:!1})})),n(r)):X.apply(void 0,c([],a(e),!1)).then((function(r){if(!B.current&&t===W.current){$.current&&clearTimeout($.current);var i="function"==typeof ie.current?ie.current(r,e):r;F((function(e){return u(u({},e),{data:i,error:null,loading:!1})})),g&&ee(g,i,b),te(i,e),n(i)}})).catch((function(n){B.current||t!==W.current||($.current&&clearTimeout($.current),F((function(e){return u(u({},e),{error:n,loading:!1})})),re(n,e),i(n))}))}))};return i().finally((function(){if(!B.current&&t===W.current&&k){if(!Q()&&!x)return void(V.current=!0);U.current=setTimeout((function(){le.apply(void 0,c([],a(e),!1))}),k)}}))}),[g,b,_,E,k,x]),ce=n.useRef(z?q(ae,z):void 0),fe=n.useRef(D?Y(ae,D):void 0),le=n.useCallback((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return ce.current?(ce.current.apply(ce,c([],a(e),!1)),Promise.resolve(null)):fe.current?(fe.current.apply(fe,c([],a(e),!1)),Promise.resolve(null)):(W.current+=1,ae.apply(void 0,c([],a(e),!1)))}),[ae]),se=n.useCallback((function(){return le.apply(void 0,c([],a(I.params),!1))}),[le,I.params]),de=n.useCallback((function(){V.current&&(V.current=!1,se())}),[se]),ve=n.useCallback((function(){ce.current&&ce.current.cancel(),fe.current&&fe.current.cancel(),U.current&&clearTimeout(U.current),$.current&&clearTimeout($.current),V.current=!1,W.current+=1,F((function(e){return u(u({},e),{loading:!1})}))}),[]);J((function(){o&&Array.isArray(l)&&l.length>0&&se()}),l);return n.useEffect((function(){B.current=!1,o&&le.apply(void 0,c([],a(I.params),!1));var e,n,t,r,u=K.current;if(k&&u.push((e=de,ue.push(e),function(){var n=ue.indexOf(e);ue.splice(n,1)})),A){var i=(n=se,t=N,r=!1,function(){for(var e=[],u=0;u<arguments.length;u++)e[u]=arguments[u];r||(r=!0,n.apply(void 0,c([],a(e),!1)),setTimeout((function(){r=!1}),t))});u.push(function(e){return ne.push(e),function(){var n=ne.indexOf(e);ne.splice(n,1)}}(i))}return function(){B.current=!0,ve(),u.forEach((function(e){return e()}))}}),[]),u(u({},I),{run:le,cancel:ve,mutate:function(e){F("function"==typeof e?function(n){return u(u({},n),{data:e(I.data)})}:function(n){return u(u({},n),{data:e})})},refresh:se})}var ce=function(e){return null!=e&&e===(null==e?void 0:e.window)};function fe(e){return"function"==typeof e?e():e}var le=function(e){var t=void 0===e?{}:e,r=t.target,u=t.threshold,i=void 0===u?100:u,o=t.onScrollLower,a=G(void 0===o?function(){}:o),c=n.useCallback((function(){if(r){var e,n=fe(r);if(n)void 0===(e=n)&&(e=window),("undefined"==typeof window?0:ce(e)?document.documentElement.scrollHeight:e.scrollHeight)-function(e){return void 0===e&&(e=window),"undefined"==typeof window?0:ce(e)?window.scrollY:(null==e?void 0:e.scrollTop)||0}(n)<=function(e){return void 0===e&&(e=window),"undefined"==typeof window?0:ce(e)?document.documentElement.clientHeight:e.clientHeight}(n)+i&&a()}}),[a,r,i]);n.useEffect((function(){if(r){var e=fe(r);if(e)return e.addEventListener("scroll",c),function(){e.removeEventListener("scroll",c)}}}),[r,c])};var se=function(e){var t=n.useRef(e);t.current=e,n.useEffect((function(){return function(){return t.current()}}),[])};function de(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var u=n.useRef(e);u.current=e;var i=n.useRef(q((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return u.current.apply(u,c([],a(e),!1))}),t,r));return se((function(){i.current.cancel()})),{run:i.current,cancel:i.current.cancel,flush:i.current.flush}}function ve(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var u=n.useRef(e);u.current=e;var i=n.useRef(Y((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return u.current.apply(u,c([],a(e),!1))}),t,r));return se((function(){i.current.cancel()})),{run:i.current,cancel:i.current.cancel,flush:i.current.flush}}var pe=function(){var e=r.useRef(!1);return r.useEffect((function(){return e.current=!1,function(){e.current=!0}}),[]),e};function he(e){return"function"==typeof e?e():e&&"current"in e?e.current:e}var ye="undefined"!=typeof window&&"undefined"!=typeof document&&window.document===document,ge=["top","right","bottom","left","width","height","size","weight"],me={characterData:!0,childList:!0,attributes:!0,subtree:!0},be=function(e){var n=this;this.refresh=function(){n.targetNode&&n.callback([{target:n.targetNode}],{})},this.onTransitionEnd_=function(e){var t=e.propertyName,r=void 0===t?"":t;ge.some((function(e){return r.indexOf(e)>-1}))&&n.throttleRefresh()},this.observe=function(e,t){ye&&(n.targetNode=e,document.addEventListener("transitionend",n.onTransitionEnd_),window.addEventListener("resize",n.throttleRefresh),n.observer.observe(document,u(u({},me),t)))},this.disconnect=function(){ye&&(n.throttleRefresh.cancel(),n.targetNode=null,document.removeEventListener("transitionend",n.onTransitionEnd_),window.removeEventListener("resize",n.throttleRefresh),n.observer.disconnect())},this.throttleRefresh=Y(this.refresh,50),this.targetNode=null,this.callback=e,this.observer=new MutationObserver(this.throttleRefresh)};e.useAsync=ae,e.useClickAway=function(e,n,t){void 0===t&&(t="click");var u=r.useRef(n);u.current=n,r.useEffect((function(){var n,r,i=function(n){var t;(Array.isArray(e)?e:[e]).some((function(e){var t=he(e);return!t||(null==t?void 0:t.contains(n.target))}))||null===(t=u.current)||void 0===t||t.call(u,n)},a=Array.isArray(t)?t:[t];try{for(var c=o(a),f=c.next();!f.done;f=c.next()){var l=f.value;document.addEventListener(l,i)}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}return function(){var e,n;try{for(var t=o(a),r=t.next();!r.done;r=t.next()){var u=r.value;document.removeEventListener(u,i)}}catch(n){e={error:n}}finally{try{r&&!r.done&&(n=t.return)&&n.call(t)}finally{if(e)throw e.error}}}}),[e,t])},e.useClientRect=function(){var e=n.useRef(null),t=a(n.useState(),2),r=t[0],u=t[1];return n.useEffect((function(){var n;e.current&&u(null===(n=e.current)||void 0===n?void 0:n.getBoundingClientRect())}),[e]),[r,e]},e.useControllableValue=function(e,t){void 0===e&&(e={}),void 0===t&&(t={});var r=t.defaultValue,u=t.defaultValuePropName,i=void 0===u?"defaultValue":u,o=t.valuePropName,f=void 0===o?"value":o,l=t.trigger,s=void 0===l?"onChange":l,d=f in e,v=e[f],p=a(n.useState((function(){return d?v:i in e?e[i]:r})),2),h=p[0],y=p[1];J((function(){d&&y(v)}),[v,d]);var g=n.useCallback((function(n){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];d||y(n),e[s]&&e[s].apply(e,c([n],a(t),!1))}),[d,e,s]);return[d?v:h,g]},e.useDebounce=function(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var u=a(n.useState(e),2),i=u[0],o=de(u[1],t,r).run;return n.useEffect((function(){o(e)}),[o,e]),i},e.useDebounceFn=de,e.useIsMounted=function(){var e=n.useRef(!1);return n.useEffect((function(){return e.current=!0,function(){e.current=!1}}),[]),e},e.useLimitList=function(e,t){void 0===t&&(t={});var r=t||{},u=r.count,i=void 0===u?3:u,o=r.defaultLimited,c=void 0===o||o,f=n.useRef(e);f.current=Array.isArray(e)?e:[];var l=n.useMemo((function(){return i<0?0:Math.ceil(i)}),[i]),s=f.current.length>l,d=a(n.useState((function(){return s&&c?f.current.slice(0,l):f.current})),2),v=d[0],p=d[1],h=s&&v.length!==f.current.length,y=n.useCallback((function(){p(h?f.current:f.current.slice(0,l))}),[l,h]);return n.useEffect((function(){p(h?f.current.slice(0,l):f.current)}),[l,e]),{canLimit:s,limited:h,data:v,toggle:y}},e.useLoadMore=function(e,n){var t=n||{},o=t.threshold,f=void 0===o?100:o,l=t.target,s=t.isNoMore,d=void 0===s?function(){return!1}:s,v=t.refreshDeps,p=void 0===v?[]:v,h=i(t,["threshold","target","isNoMore","refreshDeps"]),y=r.useRef([]),g=r.useRef(1),m=ae(e,u(u({defaultParams:[{current:g.current}]},h),{onError:function(e,n){var t;g.current>1&&(g.current-=1),null===(t=null==h?void 0:h.onError)||void 0===t||t.call(h,e,n)},__INTERNAL_FORMAT__:function(e){return y.current=1===g.current?e.list:y.current.concat(e.list),u(u({},e),{list:y.current})}})),b=m.run,w=m.data,E=m.loading,R=m.cancel,T=m.params,S=m.mutate,O=i(m,["run","data","loading","cancel","params","mutate"]),C=!!d&&(!E&&d(w)),j=r.useCallback((function(){var e=a(T).slice(1);return b.apply(void 0,c([{current:g.current}],a(e),!1))}),[T,b]),k=r.useCallback((function(){E&&g.current>1&&(g.current-=1),R()}),[R,E]),L=r.useCallback((function(){E||C||(g.current+=1,j())}),[E,C,j]),x=r.useCallback((function(e){var n="function"==typeof e?e(w):e;y.current=(null==n?void 0:n.list)||[],S(n)}),[w,S]),P=r.useCallback((function(){return k(),g.current=1,x((function(e){return u(u({},e),{list:[]})})),j()}),[k,j,x]),A=r.useCallback((function(){if(!E&&l)return L()}),[L,l,E]);return le({target:l,threshold:f,onScrollLower:A}),J((function(){(void 0===(null==n?void 0:n.autoRun)||(null==n?void 0:n.autoRun))&&Array.isArray(p)&&p.length>0&&P()}),p),u(u({},O),{loading:E,data:w,run:b,refresh:P,cancel:k,mutate:x,params:T,loadMore:L,loadingMore:E&&g.current>1,noMore:C})},e.useMount=function(e){n.useEffect((function(){e()}),[])},e.useMountedRef=function(){var e=n.useRef(!1);return n.useEffect((function(){return e.current=!0,function(){e.current=!1}}),[]),e},e.usePagination=function(e,n){var t=n||{},o=t.defaultPageSize,f=void 0===o?10:o,l=t.refreshDeps,s=void 0===l?[]:l,d=i(t,["defaultPageSize","refreshDeps"]),v=ae(e,u({defaultParams:[{current:1,pageSize:f}]},d)),p=v.run,h=v.data,y=v.params,g=v.loading,m=i(v,["run","data","params","loading"]),b=y&&y[0]?y[0]:{},w=b.current,E=b.pageSize,R=(null==h?void 0:h.total)||0,T=Math.ceil(R/E),S=r.useCallback((function(e){var n=a(y),t=n[0],r=n.slice(1);p.apply(void 0,c([u(u({},t),e)],a(r),!1))}),[y,p]),O=r.useCallback((function(e,n){var t=e<=0?1:e,r=n<=0?1:n,u=Math.ceil(R/r);t>u&&u>0&&(t=u),S({current:t,pageSize:r})}),[S,R]),C=r.useCallback((function(e){O(e,E)}),[O,E]),j=r.useCallback((function(e){O(w,e)}),[w,O]),k=r.useCallback((function(e,n,t,r){S({current:null==e?void 0:e.current,pageSize:null==e?void 0:e.pageSize,filters:n,sorter:t,extra:r})}),[S]);return J((function(){(void 0===(null==n?void 0:n.autoRun)||(null==n?void 0:n.autoRun))&&Array.isArray(s)&&s.length>0&&C(1)}),s),u(u({},m),{data:h,run:p,loading:g,params:y,pagination:{current:w,pageSize:E,total:R,totalPage:T,onChange:O,changeCurrent:C,changePageSize:j},tableProps:{dataSource:(null==h?void 0:h.list)||[],loading:g,onChange:k,pagination:{total:R,current:w,pageSize:E}}})},e.usePersistFn=G,e.usePrevious=function(e){var t=n.useRef();return n.useEffect((function(){t.current=e})),t.current},e.useSafeState=function(e){var n=pe(),t=a(r.useState(e),2),u=t[0],i=t[1];return[u,r.useCallback((function(e){n.current||i(e)}),[n])]},e.useSize=function(e){var t=a(n.useState((function(){var n=he(e);return{width:(n||{}).clientWidth,height:(n||{}).clientHeight}})),2),r=t[0],u=t[1];return n.useEffect((function(){var n=he(e);function t(e){e&&u({width:e.clientWidth,height:e.clientHeight})}if(!n)return function(){};t(n);var r=new be((function(e){var n,r;try{for(var u=o(e),i=u.next();!i.done;i=u.next()){t(i.value.target)}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}));return r.observe(n),function(){r.disconnect()}}),[e]),r},e.useThrottle=function(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var u=a(n.useState(e),2),i=u[0],o=ve(u[1],t,r).run;return n.useEffect((function(){o(e)}),[o,e]),i},e.useThrottleFn=ve,e.useUnmount=se,e.useUnmountedRef=pe,e.useUpdate=function(){var e=a(n.useState(0),2)[1];return n.useCallback((function(){return e((function(e){return e+1}))}),[])},e.useUpdateEffect=J,e.useUpdateLayoutEffect=function(e,t){var r=n.useRef(!1);n.useLayoutEffect((function(){if(r.current)return e();r.current=!0}),t)},Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).rcHooks={},e.React)}(this,(function(e,n){"use strict";function t(e){if(e&&e.__esModule)return e;var n=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}})),n.default=e,Object.freeze(n)}var r=t(n),i=function(){return i=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var i in n=arguments[t])Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i]);return e},i.apply(this,arguments)};function o(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(t[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)n.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(t[r[i]]=e[r[i]])}return t}function u(e){var n="function"==typeof Symbol&&Symbol.iterator,t=n&&e[n],r=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function a(e,n){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var r,i,o=t.call(e),u=[];try{for(;(void 0===n||n-- >0)&&!(r=o.next()).done;)u.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(t=o.return)&&t.call(o)}finally{if(i)throw i.error}}return u}function c(e,n,t){if(t||2===arguments.length)for(var r,i=0,o=n.length;i<o;i++)!r&&i in n||(r||(r=Array.prototype.slice.call(n,0,i)),r[i]=n[i]);return e.concat(r||Array.prototype.slice.call(n))}function l(e){var t=n.useRef(e);t.current=e;var r=n.useCallback((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];var r=t.current;return null==r?void 0:r.apply(void 0,c([],a(e),!1))}),[t]);return r}var f=function(e,t){var r=n.useRef(!1);n.useEffect((function(){if(r.current)return e();r.current=!0}),t)},s={},d=function(e){var n=s[e];if(n){var t=n.startTime,r=n.cacheTime,i=n.data;return(new Date).getTime()-t>=r?(n.timer&&clearTimeout(n.timer),void delete s[e]):i}},v=function(e,n,t){void 0===t&&(t=3e5),s[e]&&clearTimeout(s[e].timer);var r=setTimeout((function(){delete s[e]}),t);s[e]={data:n,timer:r,cacheTime:t,startTime:(new Date).getTime()}},h="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var p=function(e){var n=typeof e;return null!=e&&("object"==n||"function"==n)},y="object"==typeof h&&h&&h.Object===Object&&h,g="object"==typeof self&&self&&self.Object===Object&&self,m=y||g||Function("return this")(),b=m,w=function(){return b.Date.now()},T=/\s/;var E=function(e){for(var n=e.length;n--&&T.test(e.charAt(n)););return n},O=/^\s+/;var S=function(e){return e?e.slice(0,E(e)+1).replace(O,""):e},R=m.Symbol,C=R,j=Object.prototype,k=j.hasOwnProperty,L=j.toString,P=C?C.toStringTag:void 0;var A=function(e){var n=k.call(e,P),t=e[P];try{e[P]=void 0;var r=!0}catch(e){}var i=L.call(e);return r&&(n?e[P]=t:delete e[P]),i},x=Object.prototype.toString;var I=A,_=function(e){return x.call(e)},M=R?R.toStringTag:void 0;var F=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":M&&M in Object(e)?I(e):_(e)},N=function(e){return null!=e&&"object"==typeof e};var W=S,D=p,z=function(e){return"symbol"==typeof e||N(e)&&"[object Symbol]"==F(e)},H=/^[-+]0x[0-9a-f]+$/i,U=/^0b[01]+$/i,V=/^0o[0-7]+$/i,B=parseInt;var K=p,$=w,q=function(e){if("number"==typeof e)return e;if(z(e))return NaN;if(D(e)){var n="function"==typeof e.valueOf?e.valueOf():e;e=D(n)?n+"":n}if("string"!=typeof e)return 0===e?e:+e;e=W(e);var t=U.test(e);return t||V.test(e)?B(e.slice(2),t?2:8):H.test(e)?NaN:+e},Y=Math.max,G=Math.min;var J=function(e,n,t){var r,i,o,u,a,c,l=0,f=!1,s=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function v(n){var t=r,o=i;return r=i=void 0,l=n,u=e.apply(o,t)}function h(e){return l=e,a=setTimeout(y,n),f?v(e):u}function p(e){var t=e-c;return void 0===c||t>=n||t<0||s&&e-l>=o}function y(){var e=$();if(p(e))return g(e);a=setTimeout(y,function(e){var t=n-(e-c);return s?G(t,o-(e-l)):t}(e))}function g(e){return a=void 0,d&&r?v(e):(r=i=void 0,u)}function m(){var e=$(),t=p(e);if(r=arguments,i=this,c=e,t){if(void 0===a)return h(c);if(s)return clearTimeout(a),a=setTimeout(y,n),v(c)}return void 0===a&&(a=setTimeout(y,n)),u}return n=q(n)||0,K(t)&&(f=!!t.leading,o=(s="maxWait"in t)?Y(q(t.maxWait)||0,n):o,d="trailing"in t?!!t.trailing:d),m.cancel=function(){void 0!==a&&clearTimeout(a),l=0,r=c=i=a=void 0},m.flush=function(){return void 0===a?u:g($())},m},Q=J,X=p;var Z=function(e,n,t){var r=!0,i=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return X(t)&&(r="leading"in t?!!t.leading:r,i="trailing"in t?!!t.trailing:i),Q(e,n,{leading:r,maxWait:n,trailing:i})};function ee(){return"undefined"==typeof document||void 0===document.visibilityState||"hidden"!==document.visibilityState}var ne=[];var te=!1;if("undefined"!=typeof window&&window.addEventListener&&!te){window.addEventListener("visibilitychange",(function(){if(ee())for(var e=0;e<ne.length;e++){(0,ne[e])()}}),!1),te=!0}var re=[];var ie=!1;if("undefined"!=typeof window&&window.addEventListener&&!ie){var oe=function(){if(ee()&&("undefined"==typeof navigator||void 0===navigator.onLine||navigator.onLine))for(var e=0;e<re.length;e++){(0,re[e])()}};window.addEventListener("visibilitychange",oe,!1),window.addEventListener("focus",oe,!1),ie=!0}var ue={},ae=function(e,n){return n&&ue[n]?ue[n]:n?(ue[n]=e().then((function(e){return delete ue[n],e})).catch((function(e){return delete ue[n],Promise.reject(e)})),ue[n]):e()},ce=function(){function e(e,n){this.params=[],this.pollingWhenVisibleFlag=!1,this.pollingTimer=null,this.counter=1,this.destroyed=!1,this.async=e,this.options=i({cacheTime:3e5,persisted:!1,pollingWhenHidden:!0,refreshOnWindowFocus:!1,focusTimespan:5e3},n),this.unsubscribes=[],this.init()}return e.prototype.init=function(){var e,n,t,r,i=this.options,o=i.pollingInterval,u=i.refreshOnWindowFocus,l=i.focusTimespan;if(this.updateDebounce(),o&&this.unsubscribes.push((e=this.rePolling.bind(this),ne.push(e),function(){var n=ne.indexOf(e);ne.splice(n,1)})),u){var f=(n=this.refresh.bind(this),t=l,r=!1,function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];r||(r=!0,n.apply(void 0,c([],a(e),!1)),setTimeout((function(){r=!1}),t))});this.unsubscribes.push(function(e){return re.push(e),function(){var n=re.indexOf(e);re.splice(n,1)}}(f))}},e.prototype.updateDebounce=function(){var e=this.options,n=e.debounceInterval,t=e.throttleInterval;this.debounce="number"==typeof n&&n>0?J(this._run,n):void 0,this.throttle="number"==typeof t&&t>0?Z(this._run,t):void 0},e.prototype.rePolling=function(){this.pollingWhenVisibleFlag&&(this.pollingWhenVisibleFlag=!1,this.refresh())},e.prototype.afterUpdateOptions=function(e,n){void 0===n&&(n={}),("debounceInterval"in n&&n.debounceInterval!==e.debounceInterval||"throttleInterval"in n&&n.throttleInterval!==e.throttleInterval)&&this.updateDebounce()},e.prototype.updateOptions=function(e){var n=this.options,t=i(i({},this.options),e);this.options=t,this.afterUpdateOptions(n,t)},e.prototype._run=function(){for(var e=this,n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];this.pollingTimer&&clearTimeout(this.pollingTimer);var r=this.counter;this.params=n;var i=this.options,o=i.cacheKey,u=i.cacheTime,l=i.persisted,f=i.formatResult,s=i.onSuccess,h=i.onError,p=i.onFinally,y=i.onBefore,g=i.pollingWhenHidden,m=i.pollingInterval;return null==y||y(n),new Promise((function(t,i){var y;if(o&&l){var b=d(o);if(b&&r===e.counter)return null==s||s(b,n),void t(b)}null===(y=ae((function(){return e.async.apply(e,c([],a(n),!1))}),o))||void 0===y||y.then((function(i){if(r===e.counter){var a="function"==typeof f?f(i,n):i;o&&v(o,a,u),null==s||s(a,n),t(a)}})).catch((function(t){r===e.counter&&(null==h||h(t,n),i(t))})).finally((function(){if(r===e.counter&&(null==p||p(),m)){if(!ee()&&!g)return void(e.pollingWhenVisibleFlag=!0);e.pollingTimer=setTimeout((function(){e.run.apply(e,c([],a(n),!1))}),m)}}))}))},e.prototype.run=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return this.debounce?(this.debounce.apply(this,c([],a(e),!1)),Promise.resolve(null)):this.throttle?(this.throttle.apply(this,c([],a(e),!1)),Promise.resolve(null)):(this.counter+=1,this._run.apply(this,c([],a(e),!1)))},e.prototype.refresh=function(){return this.run.apply(this,c([],a(this.params),!1))},e.prototype.cancel=function(){this.debounce&&this.debounce.cancel(),this.throttle&&this.throttle.cancel(),this.pollingTimer&&(clearTimeout(this.pollingTimer),this.pollingTimer=null),this.counter+=1},e.prototype.destroy=function(e){void 0===e&&(e=!0),e&&this.cancel(),this.destroyed||(this.destroyed=!0,this.unsubscribes.forEach((function(e){return e()})),this.unsubscribes=[])},e.prototype.resume=function(){this.destroyed&&(this.destroyed=!1,this.init())},e}(),le=function(){};function fe(e,t){var r=t||{},o=r.autoRun,u=void 0===o||o,s=r.refreshDeps,v=void 0===s?[]:s,h=r.defaultParams,p=r.loadingDelay,y=r.__INTERNAL_FORMAT__,g=r.defaultLoading,m=void 0!==g&&g,b=r.initialData,w=r.cacheKey,T=void 0===w?"":w,E=r.cacheTime,O=void 0===E?3e5:E,S=r.persisted,R=void 0!==S&&S,C=r.onSuccess,j=void 0===C?le:C,k=r.onError,L=void 0===k?le:k,P=r.onFinally,A=void 0===P?le:P,x=r.onBefore,I=void 0===x?le:x,_=r.pollingInterval,M=void 0===_?0:_,F=r.pollingWhenHidden,N=void 0===F||F,W=r.refreshOnWindowFocus,D=void 0!==W&&W,z=r.focusTimespan,H=void 0===z?5e3:z,U=r.debounceInterval,V=r.throttleInterval,B=a(n.useState({params:[],loading:m,error:null,data:T?d(T):b}),2),K=B[0],$=B[1],q=n.useRef(null),Y=l(e),G=l(j),J=l(L),Q=l(A),X=l(I),Z=n.useRef(y);Z.current!==y&&(Z.current=y);var ee=n.useCallback((function(e){X(e),q.current&&clearTimeout(q.current),(T?d(T):void 0)&&R||($((function(n){return i(i({},n),{loading:!p,params:e})})),p&&(q.current=setTimeout((function(){$((function(e){return i(i({},e),{loading:!0})}))}),p)))}),[T,p,X,R]),ne=n.useCallback((function(e,n){q.current&&clearTimeout(q.current),$((function(n){return i(i({},n),{data:e,error:null,loading:!1})})),G(e,n)}),[G]),te=n.useCallback((function(e,n){q.current&&clearTimeout(q.current),$((function(n){return i(i({},n),{error:e,loading:!1})})),J(e,n)}),[J]),re=n.useRef();re.current||(re.current=new ce(Y,{cacheKey:T,cacheTime:O,persisted:R,formatResult:Z.current,onSuccess:ne,onError:te,onFinally:Q,onBefore:ee,debounceInterval:U,throttleInterval:V,pollingInterval:M,pollingWhenHidden:N,refreshOnWindowFocus:D,focusTimespan:H})),f((function(){var e;null===(e=re.current)||void 0===e||e.updateOptions({cacheKey:T,cacheTime:O,persisted:R,formatResult:Z.current,onSuccess:ne,onError:te,onFinally:Q,onBefore:ee,debounceInterval:U,throttleInterval:V,pollingInterval:M,pollingWhenHidden:N,refreshOnWindowFocus:D,focusTimespan:H})}),[G,J,T,O,R,U,V,Q,X,M,N,D,H,ne,te,ee]);var ie=n.useCallback((function(){for(var e,n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return null===(e=re.current)||void 0===e?void 0:e.run.apply(e,c([],a(n),!1))}),[]),oe=n.useCallback((function(){var e;return null===(e=re.current)||void 0===e?void 0:e.refresh()}),[]),ue=n.useCallback((function(){var e;null===(e=re.current)||void 0===e||e.cancel(),q.current&&clearTimeout(q.current),$((function(e){return i(i({},e),{loading:!1})}))}),[]);return f((function(){u&&Array.isArray(v)&&v.length>0&&oe()}),c([u],a(v),!1)),n.useEffect((function(){var e;if(u){var n=Array.isArray(h)?h:void 0!==h?[h]:[];ie.apply(void 0,c([],a(n),!1))}return null===(e=re.current)||void 0===e||e.resume(),function(){var e;ue(),null===(e=re.current)||void 0===e||e.destroy(!1)}}),[]),i(i({},K),{run:ie,cancel:ue,mutate:function(e){$("function"==typeof e?function(n){return i(i({},n),{data:e(K.data)})}:function(n){return i(i({},n),{data:e})})},refresh:oe})}var se=function(e){return null!=e&&e===(null==e?void 0:e.window)};function de(e){return"function"==typeof e?e():e}var ve=function(e){var t=void 0===e?{}:e,r=t.target,i=t.threshold,o=void 0===i?100:i,u=t.onScrollLower,a=l(void 0===u?function(){}:u),c=n.useCallback((function(){if(r){var e,n=de(r);if(n)void 0===(e=n)&&(e=window),("undefined"==typeof window?0:se(e)?document.documentElement.scrollHeight:e.scrollHeight)-function(e){return void 0===e&&(e=window),"undefined"==typeof window?0:se(e)?window.scrollY:(null==e?void 0:e.scrollTop)||0}(n)<=function(e){return void 0===e&&(e=window),"undefined"==typeof window?0:se(e)?document.documentElement.clientHeight:e.clientHeight}(n)+o&&a()}}),[a,r,o]);n.useEffect((function(){if(r){var e=de(r);if(e)return e.addEventListener("scroll",c),function(){e.removeEventListener("scroll",c)}}}),[r,c])};var he=function(e){var t=n.useRef(e);t.current=e,n.useEffect((function(){return function(){return t.current()}}),[])};function pe(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var i=n.useRef(e);i.current=e;var o=n.useRef(J((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return i.current.apply(i,c([],a(e),!1))}),t,r));return he((function(){o.current.cancel()})),{run:o.current,cancel:o.current.cancel,flush:o.current.flush}}function ye(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var i=n.useRef(e);i.current=e;var o=n.useRef(Z((function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return i.current.apply(i,c([],a(e),!1))}),t,r));return he((function(){o.current.cancel()})),{run:o.current,cancel:o.current.cancel,flush:o.current.flush}}var ge=function(){var e=r.useRef(!1);return r.useEffect((function(){return e.current=!1,function(){e.current=!0}}),[]),e};function me(e){return"function"==typeof e?e():e&&"current"in e?e.current:e}var be="undefined"!=typeof window&&"undefined"!=typeof document&&window.document===document,we=["top","right","bottom","left","width","height","size","weight"],Te={characterData:!0,childList:!0,attributes:!0,subtree:!0},Ee=function(e){var n=this;this.refresh=function(){n.targetNode&&n.callback([{target:n.targetNode}],{})},this.onTransitionEnd_=function(e){var t=e.propertyName,r=void 0===t?"":t;we.some((function(e){return r.indexOf(e)>-1}))&&n.throttleRefresh()},this.observe=function(e,t){be&&(n.targetNode=e,document.addEventListener("transitionend",n.onTransitionEnd_),window.addEventListener("resize",n.throttleRefresh),n.observer.observe(document,i(i({},Te),t)))},this.disconnect=function(){be&&(n.throttleRefresh.cancel(),n.targetNode=null,document.removeEventListener("transitionend",n.onTransitionEnd_),window.removeEventListener("resize",n.throttleRefresh),n.observer.disconnect())},this.throttleRefresh=Z(this.refresh,50),this.targetNode=null,this.callback=e,this.observer=new MutationObserver(this.throttleRefresh)};e.clearCache=function(e){(void 0===e?Object.keys(s):Array.isArray(e)?e:[e]).forEach((function(e){s[e]&&(s[e].timer&&clearTimeout(s[e].timer),delete s[e])}))},e.useAsync=fe,e.useClickAway=function(e,n,t){void 0===t&&(t="click");var i=r.useRef(n);i.current=n,r.useEffect((function(){var n,r,o=function(n){var t;(Array.isArray(e)?e:[e]).some((function(e){var t=me(e);return!t||(null==t?void 0:t.contains(n.target))}))||null===(t=i.current)||void 0===t||t.call(i,n)},a=Array.isArray(t)?t:[t];try{for(var c=u(a),l=c.next();!l.done;l=c.next()){var f=l.value;document.addEventListener(f,o)}}catch(e){n={error:e}}finally{try{l&&!l.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}return function(){var e,n;try{for(var t=u(a),r=t.next();!r.done;r=t.next()){var i=r.value;document.removeEventListener(i,o)}}catch(n){e={error:n}}finally{try{r&&!r.done&&(n=t.return)&&n.call(t)}finally{if(e)throw e.error}}}}),[e,t])},e.useClientRect=function(){var e=n.useRef(null),t=a(n.useState(),2),r=t[0],i=t[1];return n.useEffect((function(){var n;e.current&&i(null===(n=e.current)||void 0===n?void 0:n.getBoundingClientRect())}),[e]),[r,e]},e.useControllableValue=function(e,t){void 0===e&&(e={}),void 0===t&&(t={});var r=t.defaultValue,i=t.defaultValuePropName,o=void 0===i?"defaultValue":i,u=t.valuePropName,l=void 0===u?"value":u,s=t.trigger,d=void 0===s?"onChange":s,v=l in e,h=e[l],p=a(n.useState((function(){return v?h:o in e?e[o]:r})),2),y=p[0],g=p[1];f((function(){v&&g(h)}),[h,v]);var m=n.useCallback((function(n){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];v||g(n),e[d]&&e[d].apply(e,c([n],a(t),!1))}),[v,e,d]);return[v?h:y,m]},e.useDebounce=function(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var i=a(n.useState(e),2),o=i[0],u=pe(i[1],t,r).run;return n.useEffect((function(){u(e)}),[u,e]),o},e.useDebounceFn=pe,e.useIsMounted=function(){var e=n.useRef(!1);return n.useEffect((function(){return e.current=!0,function(){e.current=!1}}),[]),e},e.useLimitList=function(e,t){void 0===t&&(t={});var r=t||{},i=r.count,o=void 0===i?3:i,u=r.defaultLimited,c=void 0===u||u,l=n.useRef(e);l.current=Array.isArray(e)?e:[];var f=n.useMemo((function(){return o<0?0:Math.ceil(o)}),[o]),s=l.current.length>f,d=a(n.useState((function(){return s&&c?l.current.slice(0,f):l.current})),2),v=d[0],h=d[1],p=s&&v.length!==l.current.length,y=n.useCallback((function(){h(p?l.current:l.current.slice(0,f))}),[f,p]);return n.useEffect((function(){h(p?l.current.slice(0,f):l.current)}),[f,e]),{canLimit:s,limited:p,data:v,toggle:y}},e.useLoadMore=function(e,n){var t=n||{},u=t.threshold,l=void 0===u?100:u,s=t.target,d=t.isNoMore,v=void 0===d?function(){return!1}:d,h=t.refreshDeps,p=void 0===h?[]:h,y=o(t,["threshold","target","isNoMore","refreshDeps"]),g=r.useRef([]),m=r.useRef(1),b=fe(e,i(i({defaultParams:[{current:m.current}]},y),{onError:function(e,n){var t;m.current>1&&(m.current-=1),null===(t=null==y?void 0:y.onError)||void 0===t||t.call(y,e,n)},__INTERNAL_FORMAT__:function(e){return g.current=1===m.current?e.list:g.current.concat(e.list),i(i({},e),{list:g.current})}})),w=b.run,T=b.data,E=b.loading,O=b.cancel,S=b.params,R=b.mutate,C=o(b,["run","data","loading","cancel","params","mutate"]),j=!!v&&(!E&&v(T)),k=r.useCallback((function(){var e=a(S).slice(1);return w.apply(void 0,c([{current:m.current}],a(e),!1))}),[S,w]),L=r.useCallback((function(){E&&m.current>1&&(m.current-=1),O()}),[O,E]),P=r.useCallback((function(){E||j||(m.current+=1,k())}),[E,j,k]),A=r.useCallback((function(e){var n="function"==typeof e?e(T):e;g.current=(null==n?void 0:n.list)||[],R(n)}),[T,R]),x=r.useCallback((function(){return L(),m.current=1,A((function(e){return i(i({},e),{list:[]})})),k()}),[L,k,A]),I=r.useCallback((function(){if(!E&&s)return P()}),[P,s,E]);return ve({target:s,threshold:l,onScrollLower:I}),f((function(){(void 0===(null==n?void 0:n.autoRun)||(null==n?void 0:n.autoRun))&&Array.isArray(p)&&p.length>0&&x()}),p),i(i({},C),{loading:E,data:T,run:w,refresh:x,cancel:L,mutate:A,params:S,loadMore:P,loadingMore:E&&m.current>1,noMore:j})},e.useMount=function(e){n.useEffect((function(){e()}),[])},e.useMountedRef=function(){var e=n.useRef(!1);return n.useEffect((function(){return e.current=!0,function(){e.current=!1}}),[]),e},e.usePagination=function(e,n){var t=n||{},u=t.defaultPageSize,l=void 0===u?10:u,s=t.refreshDeps,d=void 0===s?[]:s,v=t.defaultParams,h=o(t,["defaultPageSize","refreshDeps","defaultParams"]),p=r.useMemo((function(){return v||[{current:1,pageSize:l}]}),[l,v]),y=fe(e,i({defaultParams:p},h)),g=y.run,m=y.data,b=y.params,w=y.loading,T=o(y,["run","data","params","loading"]),E=b&&b[0]?b[0]:p[0],O=E.current,S=E.pageSize,R=(null==m?void 0:m.total)||0,C=r.useCallback((function(e){var n=a(b),t=n[0],r=n.slice(1);g.apply(void 0,c([i(i({},t),e)],a(r),!1))}),[b,g]),j=r.useCallback((function(e,n){var t=e<=0?1:e,r=n<=0?1:n,i=Math.ceil(R/r);t>i&&i>0&&(t=i),C({current:t,pageSize:r})}),[C,R]),k=r.useCallback((function(e){j(e,S)}),[j,S]),L=r.useCallback((function(e){j(O,e)}),[O,j]),P=r.useCallback((function(e,n,t,r){C({current:null==e?void 0:e.current,pageSize:null==e?void 0:e.pageSize,filters:n,sorter:t,extra:r})}),[C]);return f((function(){(void 0===(null==n?void 0:n.autoRun)||(null==n?void 0:n.autoRun))&&Array.isArray(d)&&d.length>0&&k(1)}),d),i(i({},T),{data:m,run:g,loading:w,params:b,pagination:{current:O,pageSize:S,total:R,onChange:j,changeCurrent:k,changePageSize:L},tableProps:{dataSource:(null==m?void 0:m.list)||[],loading:w,onChange:P,pagination:{total:R,current:O,pageSize:S}}})},e.usePersistFn=l,e.usePrevious=function(e){var t=n.useRef();return n.useEffect((function(){t.current=e})),t.current},e.useSafeState=function(e){var n=ge(),t=a(r.useState(e),2),i=t[0],o=t[1];return[i,r.useCallback((function(e){n.current||o(e)}),[n])]},e.useSize=function(e){var t=a(n.useState((function(){var n=me(e);return{width:(n||{}).clientWidth,height:(n||{}).clientHeight}})),2),r=t[0],i=t[1];return n.useEffect((function(){var n=me(e);function t(e){e&&i({width:e.clientWidth,height:e.clientHeight})}if(!n)return function(){};t(n);var r=new Ee((function(e){var n,r;try{for(var i=u(e),o=i.next();!o.done;o=i.next()){t(o.value.target)}}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}));return r.observe(n),function(){r.disconnect()}}),[e]),r},e.useThrottle=function(e,t,r){void 0===t&&(t=0),void 0===r&&(r={});var i=a(n.useState(e),2),o=i[0],u=ye(i[1],t,r).run;return n.useEffect((function(){u(e)}),[u,e]),o},e.useThrottleFn=ye,e.useUnmount=he,e.useUnmountedRef=ge,e.useUpdate=function(){var e=a(n.useState(0),2)[1];return n.useCallback((function(){return e((function(e){return e+1}))}),[])},e.useUpdateEffect=f,e.useUpdateLayoutEffect=function(e,t){var r=n.useRef(!1);n.useLayoutEffect((function(){if(r.current)return e();r.current=!0}),t)},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=rcHooks.min.js.map

@@ -0,3 +1,7 @@

export { default as useAsync } from './useAsync';
export * from './useAsync';
export { clearCache } from './utils/cache';
export { default as useLoadMore } from './useAsync/useLoadMore';
export * from './useAsync/useLoadMore';
export { default as usePagination } from './useAsync/usePagination';
export * from './useAsync/usePagination';

@@ -4,0 +8,0 @@ export { default as useDebounceFn } from './useDebounceFn';

// async
export { default as useAsync } from './useAsync';
export * from './useAsync';
export { clearCache } from './utils/cache';
export { default as useLoadMore } from './useAsync/useLoadMore';
export * from './useAsync/useLoadMore';
export { default as usePagination } from './useAsync/usePagination';
export * from './useAsync/usePagination';

@@ -5,0 +9,0 @@ // side effect

@@ -1,8 +0,7 @@

declare type VoidFunctionType = () => void;
export declare type AsyncFunction<R = any, P extends any[] = any> = (...args: P) => Promise<R>;
export declare type AsyncOptions<R = any, P extends any[] = any> = Partial<{
import { Options, AsyncFunction } from './Async';
export declare type AsyncOptions<R = any, P extends any[] = any[]> = Partial<{
autoRun: boolean;
refreshDeps: any[];
defaultParams: P;
defaultLoading: boolean;
loadingDelay: number;
/**

@@ -12,31 +11,13 @@ * @private 该API仅用于内部传递,请不要使用。

__INTERNAL_FORMAT__: (res: R, params: P) => R;
/** @deprecated */
defaultLoading: boolean;
/** @deprecated */
initialData: R;
cacheKey: string;
cacheTime: number;
persisted: boolean;
onSuccess: (data: R, params: P) => void;
onError: (error: Error, params: P) => void;
pollingInterval: number;
pollingWhenHidden: boolean;
refreshOnWindowFocus: boolean;
focusTimespan: number;
loadingDelay: number;
debounceInterval: number;
throttleInterval: number;
}>;
export declare type AsyncResult<R = any, P extends any[] = any> = {
run: (...args: P) => Promise<R | null>;
cancel: VoidFunctionType;
mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<R | null>;
params: P;
loading: boolean;
error: null | Error;
data?: R;
};
export declare function useAsync<R = any, P extends any[] = any>(asyncFn: AsyncFunction<R, P>, options?: AsyncOptions<R, P>): {
run: (...args: P) => Promise<R> | Promise<null>;
} & Omit<Options<R, P>, 'formatResult'>>;
export type { AsyncFunction };
declare function useAsync<R = any, P extends any[] = any[]>(asyncFn: AsyncFunction<R, P>, options?: AsyncOptions<R, P>): {
run: (...args: P) => any;
cancel: () => void;
mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<R> | Promise<null>;
refresh: () => any;
params: P;

@@ -43,0 +24,0 @@ loading: boolean;

import { __assign, __read, __spreadArray } from "tslib";
import { useState, useEffect, useCallback, useRef } from 'react';
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';
import usePersistFn from '../usePersistFn';
import useUpdateEffect from '../useUpdateEffect';
import { isDocumentVisible } from '../utils';
import { getCache, setCache } from '../utils/cache';
import limit from '../utils/limit';
import subscribeFocus from '../utils/windowFocus';
import subscribeVisible from '../utils/windowVisible';
import { getCache } from '../utils/cache';
import AsyncCalss from './Async';
// 空函数
var noop = function () { };
// 异步方法hooks
export function useAsync(asyncFn, options) {
var _a = (options || {}), _b = _a.autoRun, autoRun = _b === void 0 ? true : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, _d = _a.defaultParams, defaultParams = _d === void 0 ? [] : _d, _e = _a.defaultLoading, defaultLoading = _e === void 0 ? false : _e, initialData = _a.initialData, _f = _a.cacheKey, cacheKey = _f === void 0 ? '' : _f, _g = _a.cacheTime, cacheTime = _g === void 0 ? 5 * 60 * 1000 : _g, _h = _a.persisted, persisted = _h === void 0 ? false : _h, _j = _a.onSuccess, onSuccess = _j === void 0 ? noop : _j, _k = _a.onError, onError = _k === void 0 ? noop : _k, __INTERNAL_FORMAT__ = _a.__INTERNAL_FORMAT__, _l = _a.pollingInterval, pollingInterval = _l === void 0 ? 0 : _l, _m = _a.pollingWhenHidden, pollingWhenHidden = _m === void 0 ? true : _m, _o = _a.refreshOnWindowFocus, refreshOnWindowFocus = _o === void 0 ? false : _o, _p = _a.focusTimespan, focusTimespan = _p === void 0 ? 5000 : _p, loadingDelay = _a.loadingDelay, debounceInterval = _a.debounceInterval, throttleInterval = _a.throttleInterval;
var _q = __read(useState({
function useAsync(asyncFn, options) {
var _a = options || {}, _b = _a.autoRun, autoRun = _b === void 0 ? true : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, defaultParams = _a.defaultParams, loadingDelay = _a.loadingDelay, __INTERNAL_FORMAT__ = _a.__INTERNAL_FORMAT__, _d = _a.defaultLoading, defaultLoading = _d === void 0 ? false : _d, initialData = _a.initialData, _e = _a.cacheKey, cacheKey = _e === void 0 ? '' : _e, _f = _a.cacheTime, cacheTime = _f === void 0 ? 5 * 60 * 1000 : _f, _g = _a.persisted, persisted = _g === void 0 ? false : _g, _h = _a.onSuccess, onSuccess = _h === void 0 ? noop : _h, _j = _a.onError, onError = _j === void 0 ? noop : _j, _k = _a.onFinally, onFinally = _k === void 0 ? noop : _k, _l = _a.onBefore, onBefore = _l === void 0 ? noop : _l, _m = _a.pollingInterval, pollingInterval = _m === void 0 ? 0 : _m, _o = _a.pollingWhenHidden, pollingWhenHidden = _o === void 0 ? true : _o, _p = _a.refreshOnWindowFocus, refreshOnWindowFocus = _p === void 0 ? false : _p, _q = _a.focusTimespan, focusTimespan = _q === void 0 ? 5000 : _q, debounceInterval = _a.debounceInterval, throttleInterval = _a.throttleInterval;
var _r = __read(useState({
// 参数兼容非array的情况
params: (Array.isArray(defaultParams) ? defaultParams : [defaultParams]),
params: [],
loading: defaultLoading,
error: null,
data: (cacheKey && getCache(cacheKey)) || initialData
}), 2), state = _q[0], set = _q[1];
var counterRef = useRef(0); // 计数器用于判定,或多次执行,只取最后一次结果
var pollingTimerRef = useRef(null); // 轮询定时器
var pollingWhenVisibleFlagRef = useRef(false); // 视窗获取焦点标识
data: cacheKey ? getCache(cacheKey) : initialData
}), 2), state = _r[0], set = _r[1];
var loadingDelayTimerRef = useRef(null); // 延迟loading
var unmountFlagRef = useRef(false); // 卸载标识
var unsubscribeRef = useRef([]); // 取消订阅集合
// 持久化一些函数

@@ -34,13 +24,11 @@ var asyncFnPersist = usePersistFn(asyncFn);

var onErrorPersist = usePersistFn(onError);
var onFinallyPersist = usePersistFn(onFinally);
var onBeforePersist = usePersistFn(onBefore);
var internalFormatRef = useRef(__INTERNAL_FORMAT__);
internalFormatRef.current = __INTERNAL_FORMAT__;
var _run = useCallback(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// 取消轮询定时器
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
}
if (internalFormatRef.current !== __INTERNAL_FORMAT__) {
internalFormatRef.current = __INTERNAL_FORMAT__;
}
// 异步执行前
var handleBefore = useCallback(function (p) {
onBeforePersist(p);
// 取消延迟loading

@@ -50,4 +38,2 @@ if (loadingDelayTimerRef.current) {

}
// 确保返回最后结果,并且不会返回取消的结果
var currentCount = counterRef.current;
// 缓存数据

@@ -57,3 +43,3 @@ var cacheData = cacheKey ? getCache(cacheKey) : undefined;

if (!cacheData || !persisted) {
set(function (s) { return (__assign(__assign({}, s), { loading: !loadingDelay, params: args })); });
set(function (s) { return (__assign(__assign({}, s), { loading: !loadingDelay, params: p })); });
// 设置延迟loading定时器

@@ -65,66 +51,78 @@ if (loadingDelay) {

}
else {
loadingDelayTimerRef.current = null;
}
}
var wrapperAsyncFn = function () {
// fix: 同时多次调用run,并通过then处理时,前面调用的会返回undefined导致异常的问题
return new Promise(function (resolve, reject) {
// 有缓存数据,且开启持久缓存,不需要再次请求
if (cacheData && persisted) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
onSuccessPersist(cacheData, args);
set(function (s) { return (__assign(__assign({}, s), { data: cacheData, error: null, loading: false })); });
resolve(cacheData);
}
}
else {
asyncFnPersist.apply(void 0, __spreadArray([], __read(args), false)).then(function (data) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
var fmtData_1 = typeof internalFormatRef.current === 'function'
? internalFormatRef.current(data, args)
: data;
set(function (s) { return (__assign(__assign({}, s), { data: fmtData_1, error: null, loading: false })); });
if (cacheKey) {
setCache(cacheKey, fmtData_1, cacheTime);
}
onSuccessPersist(fmtData_1, args);
resolve(fmtData_1);
}
})
.catch(function (error) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (__assign(__assign({}, s), { error: error, loading: false })); });
onErrorPersist(error, args);
reject(error);
}
});
}
});
};
return wrapperAsyncFn().finally(function () {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
// 轮询
if (pollingInterval) {
if (!isDocumentVisible() && !pollingWhenHidden) {
pollingWhenVisibleFlagRef.current = true;
return;
}
pollingTimerRef.current = setTimeout(function () {
run.apply(void 0, __spreadArray([], __read(args), false));
}, pollingInterval);
}
}
}, [cacheKey, loadingDelay, onBeforePersist, persisted]);
// 异步执行成功后
var handleSuccess = useCallback(function (res, args) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (__assign(__assign({}, s), { data: res, error: null, loading: false })); });
onSuccessPersist(res, args);
}, [onSuccessPersist]);
// 异步执行失败后
var handleError = useCallback(function (err, args) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (__assign(__assign({}, s), { error: err, loading: false })); });
onErrorPersist(err, args);
}, [onErrorPersist]);
var asyncInstanceRef = useRef();
if (!asyncInstanceRef.current) {
asyncInstanceRef.current = new AsyncCalss(asyncFnPersist, {
cacheKey: cacheKey,
cacheTime: cacheTime,
persisted: persisted,
formatResult: internalFormatRef.current,
onSuccess: handleSuccess,
onError: handleError,
onFinally: onFinallyPersist,
onBefore: handleBefore,
debounceInterval: debounceInterval,
throttleInterval: throttleInterval,
pollingInterval: pollingInterval,
pollingWhenHidden: pollingWhenHidden,
refreshOnWindowFocus: refreshOnWindowFocus,
focusTimespan: focusTimespan
});
}, [cacheKey, cacheTime, loadingDelay, persisted, pollingInterval, pollingWhenHidden] // eslint-disable-line react-hooks/exhaustive-deps
);
var debounceRunRef = useRef(debounceInterval ? debounce(_run, debounceInterval) : undefined);
var throttleRunRef = useRef(throttleInterval ? throttle(_run, throttleInterval) : undefined);
}
useUpdateEffect(function () {
var _a;
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.updateOptions({
cacheKey: cacheKey,
cacheTime: cacheTime,
persisted: persisted,
formatResult: internalFormatRef.current,
onSuccess: handleSuccess,
onError: handleError,
onFinally: onFinallyPersist,
onBefore: handleBefore,
debounceInterval: debounceInterval,
throttleInterval: throttleInterval,
pollingInterval: pollingInterval,
pollingWhenHidden: pollingWhenHidden,
refreshOnWindowFocus: refreshOnWindowFocus,
focusTimespan: focusTimespan
});
}, [
onSuccessPersist,
onErrorPersist,
cacheKey,
cacheTime,
persisted,
debounceInterval,
throttleInterval,
onFinallyPersist,
onBeforePersist,
pollingInterval,
pollingWhenHidden,
refreshOnWindowFocus,
focusTimespan,
handleSuccess,
handleError,
handleBefore
]);
// 执行异步
var run = useCallback(function () {
var _a;
var args = [];

@@ -134,33 +132,12 @@ for (var _i = 0; _i < arguments.length; _i++) {

}
if (debounceRunRef.current) {
debounceRunRef.current.apply(debounceRunRef, __spreadArray([], __read(args), false));
return Promise.resolve(null);
}
if (throttleRunRef.current) {
throttleRunRef.current.apply(throttleRunRef, __spreadArray([], __read(args), false));
return Promise.resolve(null);
}
counterRef.current += 1;
return _run.apply(void 0, __spreadArray([], __read(args), false));
}, [_run]);
return (_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.run.apply(_a, __spreadArray([], __read(args), false));
}, []);
// 使用上一次执行异步的参数,重新执行
var refresh = useCallback(function () {
return run.apply(void 0, __spreadArray([], __read(state.params), false));
}, [run, state.params]);
var rePolling = useCallback(function () {
if (pollingWhenVisibleFlagRef.current) {
pollingWhenVisibleFlagRef.current = false;
refresh();
}
}, [refresh]);
var _a;
return (_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.refresh();
}, []);
var cancel = useCallback(function () {
if (debounceRunRef.current) {
debounceRunRef.current.cancel();
}
if (throttleRunRef.current) {
throttleRunRef.current.cancel();
}
// 取消轮询定时器
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
}
var _a;
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
// 取消延迟loading

@@ -170,13 +147,4 @@ if (loadingDelayTimerRef.current) {

}
pollingWhenVisibleFlagRef.current = false;
counterRef.current += 1;
set(function (s) { return (__assign(__assign({}, s), { loading: false })); });
}, []);
// autoRun=true 时,refreshDeps 变化,将重新执行
useUpdateEffect(function () {
// 区分 React.StrictMode 下触发
if (autoRun && Array.isArray(refreshDeps) && refreshDeps.length > 0) {
refresh();
}
}, refreshDeps);
// 突变

@@ -192,24 +160,25 @@ var mutate = function (newData) {

};
// autoRun=true 时,refreshDeps 变化,将重新执行
useUpdateEffect(function () {
// 区分 React.StrictMode 下触发
if (autoRun && Array.isArray(refreshDeps) && refreshDeps.length > 0) {
refresh();
}
}, __spreadArray([autoRun], __read(refreshDeps), false));
useEffect(function () {
unmountFlagRef.current = false;
var _a;
// 默认自动执行
if (autoRun) {
// 支持默认参数
run.apply(void 0, __spreadArray([], __read(state.params), false));
var fmtDefaultParams = Array.isArray(defaultParams)
? defaultParams
: (typeof defaultParams !== 'undefined' ? [defaultParams] : []);
run.apply(void 0, __spreadArray([], __read(fmtDefaultParams), false));
}
var unsubscribeArr = unsubscribeRef.current;
// 订阅页面显示时轮询
if (pollingInterval) {
unsubscribeArr.push(subscribeVisible(rePolling));
}
// 订阅屏幕聚焦时请求
if (refreshOnWindowFocus) {
var limitRefresh = limit(refresh, focusTimespan);
unsubscribeArr.push(subscribeFocus(limitRefresh));
}
// 如果销毁过,可以重新恢复异步实例
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.resume();
return function () {
unmountFlagRef.current = true;
var _a;
cancel();
// 取消订阅
unsubscribeArr.forEach(function (s) { return s(); });
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy(false);
};

@@ -216,0 +185,0 @@ // eslint-disable-next-line react-hooks/exhaustive-deps

@@ -1,4 +0,4 @@

import type { AsyncOptions, AsyncResult } from '.';
import type { AsyncOptions } from '.';
import { TargetType } from './useScrollToLower';
export interface LoadMoreAsyncReturn<DataItem = any> {
export interface LoadMoreResult<DataItem = any> {
list: DataItem[];

@@ -13,3 +13,3 @@ [key: string]: any;

];
export interface LoadMoreAsyncOption<R extends LoadMoreAsyncReturn = any> extends Omit<AsyncOptions<R, LoadMoreParams>, 'cacheKey' | 'cacheTime' | 'persisted' | 'pollingInterval' | 'pollingWhenHidden'> {
export interface LoadMoreOptions<R extends LoadMoreResult = any> extends Omit<AsyncOptions<R, LoadMoreParams>, 'cacheKey' | 'cacheTime' | 'persisted' | 'pollingInterval' | 'pollingWhenHidden'> {
threshold?: number;

@@ -19,8 +19,3 @@ target?: TargetType;

}
export interface LoadMoreResult<R extends LoadMoreAsyncReturn = any, P extends any[] = any> extends AsyncResult<R, P> {
loadMore: () => void;
loadingMore: boolean;
noMore: boolean;
}
export declare function useLoadMore<R extends LoadMoreAsyncReturn = any>(asyncFn: (...args: LoadMoreParams) => Promise<R>, options?: LoadMoreAsyncOption<R>): {
declare function useLoadMore<R extends LoadMoreResult = any>(asyncFn: (...args: LoadMoreParams) => Promise<R>, options?: LoadMoreOptions<R>): {
loading: boolean;

@@ -30,4 +25,4 @@ data: R | undefined;

current: number;
}, ...args: any[]) => Promise<null> | Promise<R>;
refresh: () => Promise<null> | Promise<R>;
}, ...args: any[]) => any;
refresh: () => any;
cancel: () => void;

@@ -34,0 +29,0 @@ mutate: (newData: R | ((oldData: R) => R) | undefined) => void;

@@ -6,3 +6,3 @@ import { __assign, __read, __rest, __spreadArray } from "tslib";

import useUpdateEffect from '../useUpdateEffect';
export function useLoadMore(asyncFn, options) {
function useLoadMore(asyncFn, options) {
var _a = (options || {}), _b = _a.threshold, threshold = _b === void 0 ? 100 : _b, target = _a.target, _c = _a.isNoMore, isNoMore = _c === void 0 ? function () { return false; } : _c, _d = _a.refreshDeps, refreshDeps = _d === void 0 ? [] : _d, restOptions = __rest(_a, ["threshold", "target", "isNoMore", "refreshDeps"]);

@@ -9,0 +9,0 @@ var dataGroup = React.useRef([]); // 缓存之前请求的列表数据

@@ -1,3 +0,3 @@

import type { AsyncOptions, AsyncResult } from '.';
export interface PaginationAsyncReturn<DataItem = any> {
import type { AsyncOptions } from '.';
export interface PaginationResult<DataItem = any> {
list: DataItem[];

@@ -15,27 +15,6 @@ total: number;

];
export interface PaginationAsyncBaseOption<R extends PaginationAsyncReturn = any> extends AsyncOptions<R, PaginationParams> {
export interface PaginationOptions<R extends PaginationResult = any> extends AsyncOptions<R, PaginationParams> {
defaultPageSize?: number;
}
export interface PaginationResult<R extends PaginationAsyncReturn = any, P extends any[] = any> extends AsyncResult<R, P> {
pagination: {
current: number;
pageSize: number;
total: number;
totalPage: number;
onChange: (current: number, pageSize: number) => void;
changeCurrent: (current: number) => void;
changePageSize: (pageSize: number) => void;
};
tableProps: {
dataSource: R['list'];
loading: boolean;
onChange: (pagination: any, sorter?: any, filters?: any, extra?: any) => void;
pagination: {
current: number;
pageSize: number;
total: number;
};
};
}
export declare function usePagination<R extends PaginationAsyncReturn = any>(asyncFn: (...args: PaginationParams) => Promise<R>, options?: PaginationAsyncBaseOption<R>): {
export declare function usePagination<R extends PaginationResult = any>(asyncFn: (...args: PaginationParams) => Promise<R>, options?: PaginationOptions<R>): {
data: R | undefined;

@@ -46,3 +25,3 @@ run: (param1: {

pageSize: number;
}, ...args: any[]) => Promise<null> | Promise<R>;
}, ...args: any[]) => any;
loading: boolean;

@@ -54,3 +33,2 @@ params: PaginationParams;

total: number;
totalPage: number;
onChange: (c: number, p: number) => void;

@@ -75,5 +53,5 @@ changeCurrent: (c: number) => void;

mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<null> | Promise<R>;
refresh: () => any;
error: Error | null;
};
export default usePagination;

@@ -6,12 +6,7 @@ import { __assign, __read, __rest, __spreadArray } from "tslib";

export function usePagination(asyncFn, options) {
var _a = options || {}, _b = _a.defaultPageSize, defaultPageSize = _b === void 0 ? 10 : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, restOptions = __rest(_a, ["defaultPageSize", "refreshDeps"]);
var _d = useAsync(asyncFn, __assign({ defaultParams: [
{
current: 1,
pageSize: defaultPageSize
}
] }, restOptions)), run = _d.run, data = _d.data, params = _d.params, loading = _d.loading, restAsyncReturn = __rest(_d, ["run", "data", "params", "loading"]);
var _e = params && params[0] ? params[0] : {}, current = _e.current, pageSize = _e.pageSize;
var _a = options || {}, _b = _a.defaultPageSize, defaultPageSize = _b === void 0 ? 10 : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, defaultParamsProp = _a.defaultParams, restOptions = __rest(_a, ["defaultPageSize", "refreshDeps", "defaultParams"]);
var defaultParams = React.useMemo(function () { return (defaultParamsProp || [{ current: 1, pageSize: defaultPageSize }]); }, [defaultPageSize, defaultParamsProp]);
var _d = useAsync(asyncFn, __assign({ defaultParams: defaultParams }, restOptions)), run = _d.run, data = _d.data, params = _d.params, loading = _d.loading, restAsyncReturn = __rest(_d, ["run", "data", "params", "loading"]);
var _e = params && params[0] ? params[0] : defaultParams[0], current = _e.current, pageSize = _e.pageSize;
var total = (data === null || data === void 0 ? void 0 : data.total) || 0;
var totalPage = Math.ceil(total / pageSize);
var changePagination = React.useCallback(function (pagination) {

@@ -58,3 +53,2 @@ var _a = __read(params), oldParams = _a[0], restParams = _a.slice(1);

total: total,
totalPage: totalPage,
onChange: onChange,

@@ -61,0 +55,0 @@ changeCurrent: changeCurrent,

@@ -1,4 +0,4 @@

declare type CacheKey = string | number;
declare const getCache: <T = any>(key: CacheKey) => T | undefined;
declare const setCache: <T = any>(key: CacheKey, data: T, cacheTime?: number) => void;
export { getCache, setCache };
declare const getCache: <T = any>(key: string) => T | undefined;
declare const setCache: <T = any>(key: string, data: T, cacheTime?: number) => void;
declare const clearCache: (key?: string | string[]) => void;
export { getCache, setCache, clearCache };

@@ -13,6 +13,4 @@ var cache = {};

clearTimeout(currentCache.timer);
// @ts-ignore
currentCache.timer = null;
delete cache[key];
}
delete cache[key];
return;

@@ -37,2 +35,19 @@ }

};
export { getCache, setCache };
var clearCache = function (key) {
var keys = [];
if (typeof key === 'undefined') {
keys = Object.keys(cache);
}
else {
keys = Array.isArray(key) ? key : [key];
}
keys.forEach(function (k) {
if (cache[k]) {
if (cache[k].timer) {
clearTimeout(cache[k].timer);
}
delete cache[k];
}
});
};
export { getCache, setCache, clearCache };

@@ -0,3 +1,7 @@

export { default as useAsync } from './useAsync';
export * from './useAsync';
export { clearCache } from './utils/cache';
export { default as useLoadMore } from './useAsync/useLoadMore';
export * from './useAsync/useLoadMore';
export { default as usePagination } from './useAsync/usePagination';
export * from './useAsync/usePagination';

@@ -4,0 +8,0 @@ export { default as useDebounceFn } from './useDebounceFn';

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLimitList = exports.useSafeState = exports.usePersistFn = exports.usePrevious = exports.useControllableValue = exports.useSize = exports.useClickAway = exports.useClientRect = exports.useUpdateLayoutEffect = exports.useUpdateEffect = exports.useUpdate = exports.useUnmountedRef = exports.useUnmount = exports.useMountedRef = exports.useIsMounted = exports.useMount = exports.useThrottle = exports.useThrottleFn = exports.useDebounce = exports.useDebounceFn = void 0;
exports.useLimitList = exports.useSafeState = exports.usePersistFn = exports.usePrevious = exports.useControllableValue = exports.useSize = exports.useClickAway = exports.useClientRect = exports.useUpdateLayoutEffect = exports.useUpdateEffect = exports.useUpdate = exports.useUnmountedRef = exports.useUnmount = exports.useMountedRef = exports.useIsMounted = exports.useMount = exports.useThrottle = exports.useThrottleFn = exports.useDebounce = exports.useDebounceFn = exports.usePagination = exports.useLoadMore = exports.clearCache = exports.useAsync = void 0;
var tslib_1 = require("tslib");
// async
var useAsync_1 = require("./useAsync");
Object.defineProperty(exports, "useAsync", { enumerable: true, get: function () { return tslib_1.__importDefault(useAsync_1).default; } });
tslib_1.__exportStar(require("./useAsync"), exports);
var cache_1 = require("./utils/cache");
Object.defineProperty(exports, "clearCache", { enumerable: true, get: function () { return cache_1.clearCache; } });
var useLoadMore_1 = require("./useAsync/useLoadMore");
Object.defineProperty(exports, "useLoadMore", { enumerable: true, get: function () { return tslib_1.__importDefault(useLoadMore_1).default; } });
tslib_1.__exportStar(require("./useAsync/useLoadMore"), exports);
var usePagination_1 = require("./useAsync/usePagination");
Object.defineProperty(exports, "usePagination", { enumerable: true, get: function () { return tslib_1.__importDefault(usePagination_1).default; } });
tslib_1.__exportStar(require("./useAsync/usePagination"), exports);

@@ -9,0 +17,0 @@ // side effect

@@ -1,8 +0,7 @@

declare type VoidFunctionType = () => void;
export declare type AsyncFunction<R = any, P extends any[] = any> = (...args: P) => Promise<R>;
export declare type AsyncOptions<R = any, P extends any[] = any> = Partial<{
import { Options, AsyncFunction } from './Async';
export declare type AsyncOptions<R = any, P extends any[] = any[]> = Partial<{
autoRun: boolean;
refreshDeps: any[];
defaultParams: P;
defaultLoading: boolean;
loadingDelay: number;
/**

@@ -12,31 +11,13 @@ * @private 该API仅用于内部传递,请不要使用。

__INTERNAL_FORMAT__: (res: R, params: P) => R;
/** @deprecated */
defaultLoading: boolean;
/** @deprecated */
initialData: R;
cacheKey: string;
cacheTime: number;
persisted: boolean;
onSuccess: (data: R, params: P) => void;
onError: (error: Error, params: P) => void;
pollingInterval: number;
pollingWhenHidden: boolean;
refreshOnWindowFocus: boolean;
focusTimespan: number;
loadingDelay: number;
debounceInterval: number;
throttleInterval: number;
}>;
export declare type AsyncResult<R = any, P extends any[] = any> = {
run: (...args: P) => Promise<R | null>;
cancel: VoidFunctionType;
mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<R | null>;
params: P;
loading: boolean;
error: null | Error;
data?: R;
};
export declare function useAsync<R = any, P extends any[] = any>(asyncFn: AsyncFunction<R, P>, options?: AsyncOptions<R, P>): {
run: (...args: P) => Promise<R> | Promise<null>;
} & Omit<Options<R, P>, 'formatResult'>>;
export type { AsyncFunction };
declare function useAsync<R = any, P extends any[] = any[]>(asyncFn: AsyncFunction<R, P>, options?: AsyncOptions<R, P>): {
run: (...args: P) => any;
cancel: () => void;
mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<R> | Promise<null>;
refresh: () => any;
params: P;

@@ -43,0 +24,0 @@ loading: boolean;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAsync = void 0;
var tslib_1 = require("tslib");
var react_1 = require("react");
var debounce_1 = tslib_1.__importDefault(require("lodash/debounce"));
var throttle_1 = tslib_1.__importDefault(require("lodash/throttle"));
var usePersistFn_1 = tslib_1.__importDefault(require("../usePersistFn"));
var useUpdateEffect_1 = tslib_1.__importDefault(require("../useUpdateEffect"));
var utils_1 = require("../utils");
var cache_1 = require("../utils/cache");
var limit_1 = tslib_1.__importDefault(require("../utils/limit"));
var windowFocus_1 = tslib_1.__importDefault(require("../utils/windowFocus"));
var windowVisible_1 = tslib_1.__importDefault(require("../utils/windowVisible"));
var Async_1 = tslib_1.__importDefault(require("./Async"));
// 空函数

@@ -19,16 +13,11 @@ var noop = function () { };

function useAsync(asyncFn, options) {
var _a = (options || {}), _b = _a.autoRun, autoRun = _b === void 0 ? true : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, _d = _a.defaultParams, defaultParams = _d === void 0 ? [] : _d, _e = _a.defaultLoading, defaultLoading = _e === void 0 ? false : _e, initialData = _a.initialData, _f = _a.cacheKey, cacheKey = _f === void 0 ? '' : _f, _g = _a.cacheTime, cacheTime = _g === void 0 ? 5 * 60 * 1000 : _g, _h = _a.persisted, persisted = _h === void 0 ? false : _h, _j = _a.onSuccess, onSuccess = _j === void 0 ? noop : _j, _k = _a.onError, onError = _k === void 0 ? noop : _k, __INTERNAL_FORMAT__ = _a.__INTERNAL_FORMAT__, _l = _a.pollingInterval, pollingInterval = _l === void 0 ? 0 : _l, _m = _a.pollingWhenHidden, pollingWhenHidden = _m === void 0 ? true : _m, _o = _a.refreshOnWindowFocus, refreshOnWindowFocus = _o === void 0 ? false : _o, _p = _a.focusTimespan, focusTimespan = _p === void 0 ? 5000 : _p, loadingDelay = _a.loadingDelay, debounceInterval = _a.debounceInterval, throttleInterval = _a.throttleInterval;
var _q = tslib_1.__read((0, react_1.useState)({
var _a = options || {}, _b = _a.autoRun, autoRun = _b === void 0 ? true : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, defaultParams = _a.defaultParams, loadingDelay = _a.loadingDelay, __INTERNAL_FORMAT__ = _a.__INTERNAL_FORMAT__, _d = _a.defaultLoading, defaultLoading = _d === void 0 ? false : _d, initialData = _a.initialData, _e = _a.cacheKey, cacheKey = _e === void 0 ? '' : _e, _f = _a.cacheTime, cacheTime = _f === void 0 ? 5 * 60 * 1000 : _f, _g = _a.persisted, persisted = _g === void 0 ? false : _g, _h = _a.onSuccess, onSuccess = _h === void 0 ? noop : _h, _j = _a.onError, onError = _j === void 0 ? noop : _j, _k = _a.onFinally, onFinally = _k === void 0 ? noop : _k, _l = _a.onBefore, onBefore = _l === void 0 ? noop : _l, _m = _a.pollingInterval, pollingInterval = _m === void 0 ? 0 : _m, _o = _a.pollingWhenHidden, pollingWhenHidden = _o === void 0 ? true : _o, _p = _a.refreshOnWindowFocus, refreshOnWindowFocus = _p === void 0 ? false : _p, _q = _a.focusTimespan, focusTimespan = _q === void 0 ? 5000 : _q, debounceInterval = _a.debounceInterval, throttleInterval = _a.throttleInterval;
var _r = tslib_1.__read((0, react_1.useState)({
// 参数兼容非array的情况
params: (Array.isArray(defaultParams) ? defaultParams : [defaultParams]),
params: [],
loading: defaultLoading,
error: null,
data: (cacheKey && (0, cache_1.getCache)(cacheKey)) || initialData
}), 2), state = _q[0], set = _q[1];
var counterRef = (0, react_1.useRef)(0); // 计数器用于判定,或多次执行,只取最后一次结果
var pollingTimerRef = (0, react_1.useRef)(null); // 轮询定时器
var pollingWhenVisibleFlagRef = (0, react_1.useRef)(false); // 视窗获取焦点标识
data: cacheKey ? (0, cache_1.getCache)(cacheKey) : initialData
}), 2), state = _r[0], set = _r[1];
var loadingDelayTimerRef = (0, react_1.useRef)(null); // 延迟loading
var unmountFlagRef = (0, react_1.useRef)(false); // 卸载标识
var unsubscribeRef = (0, react_1.useRef)([]); // 取消订阅集合
// 持久化一些函数

@@ -38,13 +27,11 @@ var asyncFnPersist = (0, usePersistFn_1.default)(asyncFn);

var onErrorPersist = (0, usePersistFn_1.default)(onError);
var onFinallyPersist = (0, usePersistFn_1.default)(onFinally);
var onBeforePersist = (0, usePersistFn_1.default)(onBefore);
var internalFormatRef = (0, react_1.useRef)(__INTERNAL_FORMAT__);
internalFormatRef.current = __INTERNAL_FORMAT__;
var _run = (0, react_1.useCallback)(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// 取消轮询定时器
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
}
if (internalFormatRef.current !== __INTERNAL_FORMAT__) {
internalFormatRef.current = __INTERNAL_FORMAT__;
}
// 异步执行前
var handleBefore = (0, react_1.useCallback)(function (p) {
onBeforePersist(p);
// 取消延迟loading

@@ -54,4 +41,2 @@ if (loadingDelayTimerRef.current) {

}
// 确保返回最后结果,并且不会返回取消的结果
var currentCount = counterRef.current;
// 缓存数据

@@ -61,3 +46,3 @@ var cacheData = cacheKey ? (0, cache_1.getCache)(cacheKey) : undefined;

if (!cacheData || !persisted) {
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { loading: !loadingDelay, params: args })); });
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { loading: !loadingDelay, params: p })); });
// 设置延迟loading定时器

@@ -69,66 +54,78 @@ if (loadingDelay) {

}
else {
loadingDelayTimerRef.current = null;
}
}
var wrapperAsyncFn = function () {
// fix: 同时多次调用run,并通过then处理时,前面调用的会返回undefined导致异常的问题
return new Promise(function (resolve, reject) {
// 有缓存数据,且开启持久缓存,不需要再次请求
if (cacheData && persisted) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
onSuccessPersist(cacheData, args);
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { data: cacheData, error: null, loading: false })); });
resolve(cacheData);
}
}
else {
asyncFnPersist.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(args), false)).then(function (data) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
var fmtData_1 = typeof internalFormatRef.current === 'function'
? internalFormatRef.current(data, args)
: data;
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { data: fmtData_1, error: null, loading: false })); });
if (cacheKey) {
(0, cache_1.setCache)(cacheKey, fmtData_1, cacheTime);
}
onSuccessPersist(fmtData_1, args);
resolve(fmtData_1);
}
})
.catch(function (error) {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { error: error, loading: false })); });
onErrorPersist(error, args);
reject(error);
}
});
}
});
};
return wrapperAsyncFn().finally(function () {
if (!unmountFlagRef.current && currentCount === counterRef.current) {
// 轮询
if (pollingInterval) {
if (!(0, utils_1.isDocumentVisible)() && !pollingWhenHidden) {
pollingWhenVisibleFlagRef.current = true;
return;
}
pollingTimerRef.current = setTimeout(function () {
run.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(args), false));
}, pollingInterval);
}
}
}, [cacheKey, loadingDelay, onBeforePersist, persisted]);
// 异步执行成功后
var handleSuccess = (0, react_1.useCallback)(function (res, args) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { data: res, error: null, loading: false })); });
onSuccessPersist(res, args);
}, [onSuccessPersist]);
// 异步执行失败后
var handleError = (0, react_1.useCallback)(function (err, args) {
if (loadingDelayTimerRef.current) {
clearTimeout(loadingDelayTimerRef.current);
}
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { error: err, loading: false })); });
onErrorPersist(err, args);
}, [onErrorPersist]);
var asyncInstanceRef = (0, react_1.useRef)();
if (!asyncInstanceRef.current) {
asyncInstanceRef.current = new Async_1.default(asyncFnPersist, {
cacheKey: cacheKey,
cacheTime: cacheTime,
persisted: persisted,
formatResult: internalFormatRef.current,
onSuccess: handleSuccess,
onError: handleError,
onFinally: onFinallyPersist,
onBefore: handleBefore,
debounceInterval: debounceInterval,
throttleInterval: throttleInterval,
pollingInterval: pollingInterval,
pollingWhenHidden: pollingWhenHidden,
refreshOnWindowFocus: refreshOnWindowFocus,
focusTimespan: focusTimespan
});
}, [cacheKey, cacheTime, loadingDelay, persisted, pollingInterval, pollingWhenHidden] // eslint-disable-line react-hooks/exhaustive-deps
);
var debounceRunRef = (0, react_1.useRef)(debounceInterval ? (0, debounce_1.default)(_run, debounceInterval) : undefined);
var throttleRunRef = (0, react_1.useRef)(throttleInterval ? (0, throttle_1.default)(_run, throttleInterval) : undefined);
}
(0, useUpdateEffect_1.default)(function () {
var _a;
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.updateOptions({
cacheKey: cacheKey,
cacheTime: cacheTime,
persisted: persisted,
formatResult: internalFormatRef.current,
onSuccess: handleSuccess,
onError: handleError,
onFinally: onFinallyPersist,
onBefore: handleBefore,
debounceInterval: debounceInterval,
throttleInterval: throttleInterval,
pollingInterval: pollingInterval,
pollingWhenHidden: pollingWhenHidden,
refreshOnWindowFocus: refreshOnWindowFocus,
focusTimespan: focusTimespan
});
}, [
onSuccessPersist,
onErrorPersist,
cacheKey,
cacheTime,
persisted,
debounceInterval,
throttleInterval,
onFinallyPersist,
onBeforePersist,
pollingInterval,
pollingWhenHidden,
refreshOnWindowFocus,
focusTimespan,
handleSuccess,
handleError,
handleBefore
]);
// 执行异步
var run = (0, react_1.useCallback)(function () {
var _a;
var args = [];

@@ -138,33 +135,12 @@ for (var _i = 0; _i < arguments.length; _i++) {

}
if (debounceRunRef.current) {
debounceRunRef.current.apply(debounceRunRef, tslib_1.__spreadArray([], tslib_1.__read(args), false));
return Promise.resolve(null);
}
if (throttleRunRef.current) {
throttleRunRef.current.apply(throttleRunRef, tslib_1.__spreadArray([], tslib_1.__read(args), false));
return Promise.resolve(null);
}
counterRef.current += 1;
return _run.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(args), false));
}, [_run]);
return (_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.run.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(args), false));
}, []);
// 使用上一次执行异步的参数,重新执行
var refresh = (0, react_1.useCallback)(function () {
return run.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(state.params), false));
}, [run, state.params]);
var rePolling = (0, react_1.useCallback)(function () {
if (pollingWhenVisibleFlagRef.current) {
pollingWhenVisibleFlagRef.current = false;
refresh();
}
}, [refresh]);
var _a;
return (_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.refresh();
}, []);
var cancel = (0, react_1.useCallback)(function () {
if (debounceRunRef.current) {
debounceRunRef.current.cancel();
}
if (throttleRunRef.current) {
throttleRunRef.current.cancel();
}
// 取消轮询定时器
if (pollingTimerRef.current) {
clearTimeout(pollingTimerRef.current);
}
var _a;
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.cancel();
// 取消延迟loading

@@ -174,13 +150,4 @@ if (loadingDelayTimerRef.current) {

}
pollingWhenVisibleFlagRef.current = false;
counterRef.current += 1;
set(function (s) { return (tslib_1.__assign(tslib_1.__assign({}, s), { loading: false })); });
}, []);
// autoRun=true 时,refreshDeps 变化,将重新执行
(0, useUpdateEffect_1.default)(function () {
// 区分 React.StrictMode 下触发
if (autoRun && Array.isArray(refreshDeps) && refreshDeps.length > 0) {
refresh();
}
}, refreshDeps);
// 突变

@@ -196,24 +163,25 @@ var mutate = function (newData) {

};
// autoRun=true 时,refreshDeps 变化,将重新执行
(0, useUpdateEffect_1.default)(function () {
// 区分 React.StrictMode 下触发
if (autoRun && Array.isArray(refreshDeps) && refreshDeps.length > 0) {
refresh();
}
}, tslib_1.__spreadArray([autoRun], tslib_1.__read(refreshDeps), false));
(0, react_1.useEffect)(function () {
unmountFlagRef.current = false;
var _a;
// 默认自动执行
if (autoRun) {
// 支持默认参数
run.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(state.params), false));
var fmtDefaultParams = Array.isArray(defaultParams)
? defaultParams
: (typeof defaultParams !== 'undefined' ? [defaultParams] : []);
run.apply(void 0, tslib_1.__spreadArray([], tslib_1.__read(fmtDefaultParams), false));
}
var unsubscribeArr = unsubscribeRef.current;
// 订阅页面显示时轮询
if (pollingInterval) {
unsubscribeArr.push((0, windowVisible_1.default)(rePolling));
}
// 订阅屏幕聚焦时请求
if (refreshOnWindowFocus) {
var limitRefresh = (0, limit_1.default)(refresh, focusTimespan);
unsubscribeArr.push((0, windowFocus_1.default)(limitRefresh));
}
// 如果销毁过,可以重新恢复异步实例
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.resume();
return function () {
unmountFlagRef.current = true;
var _a;
cancel();
// 取消订阅
unsubscribeArr.forEach(function (s) { return s(); });
(_a = asyncInstanceRef.current) === null || _a === void 0 ? void 0 : _a.destroy(false);
};

@@ -224,3 +192,2 @@ // eslint-disable-next-line react-hooks/exhaustive-deps

}
exports.useAsync = useAsync;
exports.default = useAsync;

@@ -1,4 +0,4 @@

import type { AsyncOptions, AsyncResult } from '.';
import type { AsyncOptions } from '.';
import { TargetType } from './useScrollToLower';
export interface LoadMoreAsyncReturn<DataItem = any> {
export interface LoadMoreResult<DataItem = any> {
list: DataItem[];

@@ -13,3 +13,3 @@ [key: string]: any;

];
export interface LoadMoreAsyncOption<R extends LoadMoreAsyncReturn = any> extends Omit<AsyncOptions<R, LoadMoreParams>, 'cacheKey' | 'cacheTime' | 'persisted' | 'pollingInterval' | 'pollingWhenHidden'> {
export interface LoadMoreOptions<R extends LoadMoreResult = any> extends Omit<AsyncOptions<R, LoadMoreParams>, 'cacheKey' | 'cacheTime' | 'persisted' | 'pollingInterval' | 'pollingWhenHidden'> {
threshold?: number;

@@ -19,8 +19,3 @@ target?: TargetType;

}
export interface LoadMoreResult<R extends LoadMoreAsyncReturn = any, P extends any[] = any> extends AsyncResult<R, P> {
loadMore: () => void;
loadingMore: boolean;
noMore: boolean;
}
export declare function useLoadMore<R extends LoadMoreAsyncReturn = any>(asyncFn: (...args: LoadMoreParams) => Promise<R>, options?: LoadMoreAsyncOption<R>): {
declare function useLoadMore<R extends LoadMoreResult = any>(asyncFn: (...args: LoadMoreParams) => Promise<R>, options?: LoadMoreOptions<R>): {
loading: boolean;

@@ -30,4 +25,4 @@ data: R | undefined;

current: number;
}, ...args: any[]) => Promise<null> | Promise<R>;
refresh: () => Promise<null> | Promise<R>;
}, ...args: any[]) => any;
refresh: () => any;
cancel: () => void;

@@ -34,0 +29,0 @@ mutate: (newData: R | ((oldData: R) => R) | undefined) => void;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLoadMore = void 0;
var tslib_1 = require("tslib");

@@ -80,3 +79,2 @@ var React = tslib_1.__importStar(require("react"));

}
exports.useLoadMore = useLoadMore;
exports.default = useLoadMore;

@@ -1,3 +0,3 @@

import type { AsyncOptions, AsyncResult } from '.';
export interface PaginationAsyncReturn<DataItem = any> {
import type { AsyncOptions } from '.';
export interface PaginationResult<DataItem = any> {
list: DataItem[];

@@ -15,27 +15,6 @@ total: number;

];
export interface PaginationAsyncBaseOption<R extends PaginationAsyncReturn = any> extends AsyncOptions<R, PaginationParams> {
export interface PaginationOptions<R extends PaginationResult = any> extends AsyncOptions<R, PaginationParams> {
defaultPageSize?: number;
}
export interface PaginationResult<R extends PaginationAsyncReturn = any, P extends any[] = any> extends AsyncResult<R, P> {
pagination: {
current: number;
pageSize: number;
total: number;
totalPage: number;
onChange: (current: number, pageSize: number) => void;
changeCurrent: (current: number) => void;
changePageSize: (pageSize: number) => void;
};
tableProps: {
dataSource: R['list'];
loading: boolean;
onChange: (pagination: any, sorter?: any, filters?: any, extra?: any) => void;
pagination: {
current: number;
pageSize: number;
total: number;
};
};
}
export declare function usePagination<R extends PaginationAsyncReturn = any>(asyncFn: (...args: PaginationParams) => Promise<R>, options?: PaginationAsyncBaseOption<R>): {
export declare function usePagination<R extends PaginationResult = any>(asyncFn: (...args: PaginationParams) => Promise<R>, options?: PaginationOptions<R>): {
data: R | undefined;

@@ -46,3 +25,3 @@ run: (param1: {

pageSize: number;
}, ...args: any[]) => Promise<null> | Promise<R>;
}, ...args: any[]) => any;
loading: boolean;

@@ -54,3 +33,2 @@ params: PaginationParams;

total: number;
totalPage: number;
onChange: (c: number, p: number) => void;

@@ -75,5 +53,5 @@ changeCurrent: (c: number) => void;

mutate: (newData: R | ((oldData: R) => R) | undefined) => void;
refresh: () => Promise<null> | Promise<R>;
refresh: () => any;
error: Error | null;
};
export default usePagination;

@@ -9,12 +9,7 @@ "use strict";

function usePagination(asyncFn, options) {
var _a = options || {}, _b = _a.defaultPageSize, defaultPageSize = _b === void 0 ? 10 : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, restOptions = tslib_1.__rest(_a, ["defaultPageSize", "refreshDeps"]);
var _d = (0, _1.default)(asyncFn, tslib_1.__assign({ defaultParams: [
{
current: 1,
pageSize: defaultPageSize
}
] }, restOptions)), run = _d.run, data = _d.data, params = _d.params, loading = _d.loading, restAsyncReturn = tslib_1.__rest(_d, ["run", "data", "params", "loading"]);
var _e = params && params[0] ? params[0] : {}, current = _e.current, pageSize = _e.pageSize;
var _a = options || {}, _b = _a.defaultPageSize, defaultPageSize = _b === void 0 ? 10 : _b, _c = _a.refreshDeps, refreshDeps = _c === void 0 ? [] : _c, defaultParamsProp = _a.defaultParams, restOptions = tslib_1.__rest(_a, ["defaultPageSize", "refreshDeps", "defaultParams"]);
var defaultParams = React.useMemo(function () { return (defaultParamsProp || [{ current: 1, pageSize: defaultPageSize }]); }, [defaultPageSize, defaultParamsProp]);
var _d = (0, _1.default)(asyncFn, tslib_1.__assign({ defaultParams: defaultParams }, restOptions)), run = _d.run, data = _d.data, params = _d.params, loading = _d.loading, restAsyncReturn = tslib_1.__rest(_d, ["run", "data", "params", "loading"]);
var _e = params && params[0] ? params[0] : defaultParams[0], current = _e.current, pageSize = _e.pageSize;
var total = (data === null || data === void 0 ? void 0 : data.total) || 0;
var totalPage = Math.ceil(total / pageSize);
var changePagination = React.useCallback(function (pagination) {

@@ -61,3 +56,2 @@ var _a = tslib_1.__read(params), oldParams = _a[0], restParams = _a.slice(1);

total: total,
totalPage: totalPage,
onChange: onChange,

@@ -64,0 +58,0 @@ changeCurrent: changeCurrent,

@@ -1,4 +0,4 @@

declare type CacheKey = string | number;
declare const getCache: <T = any>(key: CacheKey) => T | undefined;
declare const setCache: <T = any>(key: CacheKey, data: T, cacheTime?: number) => void;
export { getCache, setCache };
declare const getCache: <T = any>(key: string) => T | undefined;
declare const setCache: <T = any>(key: string, data: T, cacheTime?: number) => void;
declare const clearCache: (key?: string | string[]) => void;
export { getCache, setCache, clearCache };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setCache = exports.getCache = void 0;
exports.clearCache = exports.setCache = exports.getCache = void 0;
var cache = {};

@@ -16,6 +16,4 @@ var defaultCacheTime = 5 * 60 * 1000; // 默认缓存5分钟

clearTimeout(currentCache.timer);
// @ts-ignore
currentCache.timer = null;
delete cache[key];
}
delete cache[key];
return;

@@ -42,1 +40,19 @@ }

exports.setCache = setCache;
var clearCache = function (key) {
var keys = [];
if (typeof key === 'undefined') {
keys = Object.keys(cache);
}
else {
keys = Array.isArray(key) ? key : [key];
}
keys.forEach(function (k) {
if (cache[k]) {
if (cache[k].timer) {
clearTimeout(cache[k].timer);
}
delete cache[k];
}
});
};
exports.clearCache = clearCache;
{
"name": "rc-hooks",
"version": "2.0.8",
"version": "2.1.0",
"description": "React Hooks Library.",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc