@alessiofrittoli/react-hooks 3.3.0-alpha.1 → 3.3.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -0
- package/dist/eslint.js +1 -1
- package/dist/eslint.mjs +1 -1
- package/dist/index.d.mts +22 -1
- package/dist/index.d.ts +22 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
- [Getting started](#getting-started)
|
|
25
25
|
- [ESLint Configuration](#eslint-configuration)
|
|
26
|
+
- [What's Changed](#whats-changed)
|
|
26
27
|
- [API Reference](#api-reference)
|
|
27
28
|
- [Browser API](#browser-api)
|
|
28
29
|
- [`useStorage`](#usestorage)
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
- [`useFocusTrap`](#usefocustrap)
|
|
37
38
|
- [`useInView`](#useinview)
|
|
38
39
|
- [Miscellaneous](#miscellaneous)
|
|
40
|
+
- [`useDeferCallback`](#usedefercallback)
|
|
39
41
|
- [`useIsClient`](#useisclient)
|
|
40
42
|
- [`useIsFirstRender`](#useisfirstrender)
|
|
41
43
|
- [`useUpdateEffect`](#useupdateeffect)
|
|
@@ -88,6 +90,14 @@ export default config
|
|
|
88
90
|
|
|
89
91
|
---
|
|
90
92
|
|
|
93
|
+
### What's Changed
|
|
94
|
+
|
|
95
|
+
#### Updates in the latest release 🎉
|
|
96
|
+
|
|
97
|
+
- Add `useDeferCallback`. See [API Reference](#usedefercallback) for more info.
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
91
101
|
### API Reference
|
|
92
102
|
|
|
93
103
|
#### Browser API
|
|
@@ -956,6 +966,74 @@ Docs coming soon
|
|
|
956
966
|
|
|
957
967
|
---
|
|
958
968
|
|
|
969
|
+
##### `useDeferCallback`
|
|
970
|
+
|
|
971
|
+
`useDeferCallback` will return a memoized and deferred version of the callback that only changes if one of the `inputs` in the dependency list has changed.
|
|
972
|
+
|
|
973
|
+
Since [`deferCallback`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferCallback) returns a new function when called, it may cause your child components to uselessly re-validate when a state update occurs in the main component.
|
|
974
|
+
To avoid these pitfalls you can memoize and defer your task with `useDeferCallback`.
|
|
975
|
+
|
|
976
|
+
Take a look at [`deferTask`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferTask) to defer single tasks in a function handler.
|
|
977
|
+
|
|
978
|
+
<details>
|
|
979
|
+
|
|
980
|
+
<summary style="cursor:pointer">Type Parameters</summary>
|
|
981
|
+
|
|
982
|
+
| Parameter | Description |
|
|
983
|
+
|-----------|------------------------------|
|
|
984
|
+
| `T` | The task function definition. `unknown` types will be inherited by your function type definition. |
|
|
985
|
+
| `U` | The task function arguments. `unknown` types will be inherited by your function type. |
|
|
986
|
+
|
|
987
|
+
</details>
|
|
988
|
+
|
|
989
|
+
---
|
|
990
|
+
|
|
991
|
+
<details>
|
|
992
|
+
|
|
993
|
+
<summary style="cursor:pointer">Parameters</summary>
|
|
994
|
+
|
|
995
|
+
| Parameter | Type | Description |
|
|
996
|
+
|-----------|----------|-----------------------------|
|
|
997
|
+
| `task` | `T` | The task callable function. |
|
|
998
|
+
|
|
999
|
+
</details>
|
|
1000
|
+
|
|
1001
|
+
---
|
|
1002
|
+
|
|
1003
|
+
<details>
|
|
1004
|
+
|
|
1005
|
+
<summary style="cursor:pointer">Returns</summary>
|
|
1006
|
+
|
|
1007
|
+
Type: `( ...args: U ) => Promise<Awaited<ReturnType<T>>>`
|
|
1008
|
+
|
|
1009
|
+
A new memoized handler which returns a new Promise that returns the `task` result once fulfilled.
|
|
1010
|
+
|
|
1011
|
+
</details>
|
|
1012
|
+
|
|
1013
|
+
---
|
|
1014
|
+
|
|
1015
|
+
<details>
|
|
1016
|
+
|
|
1017
|
+
<summary style="cursor:pointer">Usage</summary>
|
|
1018
|
+
|
|
1019
|
+
```tsx
|
|
1020
|
+
const MyComponent: React.FC = () => {
|
|
1021
|
+
|
|
1022
|
+
const clickHandler = useDeferCallback<React.MouseEventHandler>(
|
|
1023
|
+
event => { ... }, []
|
|
1024
|
+
)
|
|
1025
|
+
|
|
1026
|
+
return (
|
|
1027
|
+
<button onClick={ clickHandler }>Button</button>
|
|
1028
|
+
)
|
|
1029
|
+
|
|
1030
|
+
}
|
|
1031
|
+
```
|
|
1032
|
+
|
|
1033
|
+
</details>
|
|
1034
|
+
|
|
1035
|
+
---
|
|
1036
|
+
|
|
959
1037
|
##### `useEffectOnce`
|
|
960
1038
|
|
|
961
1039
|
Docs coming soon
|
package/dist/eslint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var e=["useUpdateEffect","useDeferCallback"],n= exports.config ={recommended:[{rules:{"react-hooks/exhaustive-deps":["warn",{additionalHooks:e.join("|")}]}}]};exports.config = n;
|
package/dist/eslint.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var e=["useUpdateEffect","useDeferCallback"],i={recommended:[{rules:{"react-hooks/exhaustive-deps":["warn",{additionalHooks:e.join("|")}]}}]};export{i as config};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
+
import { DeferredTask } from '@alessiofrittoli/web-utils';
|
|
2
3
|
import * as _alessiofrittoli_math_utils_helpers from '@alessiofrittoli/math-utils/helpers';
|
|
3
4
|
import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
|
|
4
5
|
|
|
@@ -898,6 +899,26 @@ interface UseInputOutput<I = unknown, O = I> extends InputState<I, O> {
|
|
|
898
899
|
*/
|
|
899
900
|
declare const useInput: <I = unknown, O = I>(options?: UseInputOptions<I, O>) => UseInputOutput<I, O>;
|
|
900
901
|
|
|
902
|
+
/**
|
|
903
|
+
* `useDeferCallback` will return a memoized and deferred version of the callback
|
|
904
|
+
* that only changes if one of the `inputs` in the dependency list has changed.
|
|
905
|
+
*
|
|
906
|
+
* Since [`deferCallback`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferCallback) returns a new function when called,
|
|
907
|
+
* it may cause your child components to uselessly re-validate when a state update occurs in the main component.
|
|
908
|
+
* To avoid these pitfalls you can memoize and defer your task with `useDeferCallback`.
|
|
909
|
+
*
|
|
910
|
+
* Take a look at [`deferTask`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferTask) to defer single tasks in a function handler.
|
|
911
|
+
*
|
|
912
|
+
* @example
|
|
913
|
+
*
|
|
914
|
+
* ```ts
|
|
915
|
+
* const onKeyDown = useDeferCallback<React.KeyboardEventHandler>(
|
|
916
|
+
* event => { ... }, []
|
|
917
|
+
* )
|
|
918
|
+
* ```
|
|
919
|
+
*/
|
|
920
|
+
declare const useDeferCallback: <T extends DeferredTask<U>, U extends any[] = any[]>(task: T, deps: React.DependencyList) => (...args: U) => Promise<Awaited<ReturnType<T>>>;
|
|
921
|
+
|
|
901
922
|
/**
|
|
902
923
|
* Modified version of `useEffect` that only run once on intial load.
|
|
903
924
|
*
|
|
@@ -1334,4 +1355,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1334
1355
|
*/
|
|
1335
1356
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1336
1357
|
|
|
1337
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
|
1358
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
+
import { DeferredTask } from '@alessiofrittoli/web-utils';
|
|
2
3
|
import * as _alessiofrittoli_math_utils_helpers from '@alessiofrittoli/math-utils/helpers';
|
|
3
4
|
import { PaginateOptions } from '@alessiofrittoli/math-utils/helpers';
|
|
4
5
|
|
|
@@ -898,6 +899,26 @@ interface UseInputOutput<I = unknown, O = I> extends InputState<I, O> {
|
|
|
898
899
|
*/
|
|
899
900
|
declare const useInput: <I = unknown, O = I>(options?: UseInputOptions<I, O>) => UseInputOutput<I, O>;
|
|
900
901
|
|
|
902
|
+
/**
|
|
903
|
+
* `useDeferCallback` will return a memoized and deferred version of the callback
|
|
904
|
+
* that only changes if one of the `inputs` in the dependency list has changed.
|
|
905
|
+
*
|
|
906
|
+
* Since [`deferCallback`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferCallback) returns a new function when called,
|
|
907
|
+
* it may cause your child components to uselessly re-validate when a state update occurs in the main component.
|
|
908
|
+
* To avoid these pitfalls you can memoize and defer your task with `useDeferCallback`.
|
|
909
|
+
*
|
|
910
|
+
* Take a look at [`deferTask`](https://npmjs.com/package/@alessiofrittoli/web-utils?activeTab=readme#deferTask) to defer single tasks in a function handler.
|
|
911
|
+
*
|
|
912
|
+
* @example
|
|
913
|
+
*
|
|
914
|
+
* ```ts
|
|
915
|
+
* const onKeyDown = useDeferCallback<React.KeyboardEventHandler>(
|
|
916
|
+
* event => { ... }, []
|
|
917
|
+
* )
|
|
918
|
+
* ```
|
|
919
|
+
*/
|
|
920
|
+
declare const useDeferCallback: <T extends DeferredTask<U>, U extends any[] = any[]>(task: T, deps: React.DependencyList) => (...args: U) => Promise<Awaited<ReturnType<T>>>;
|
|
921
|
+
|
|
901
922
|
/**
|
|
902
923
|
* Modified version of `useEffect` that only run once on intial load.
|
|
903
924
|
*
|
|
@@ -1334,4 +1355,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1334
1355
|
*/
|
|
1335
1356
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1336
1357
|
|
|
1337
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
|
1358
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _LocalStorage = require('@alessiofrittoli/web-utils/storage/LocalStorage');var _SessionStorage = require('@alessiofrittoli/web-utils/storage/SessionStorage');var H=(e,n,t="local")=>{let r=_react.useCallback.call(void 0, ()=>_nullishCoalesce((t==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).get(e), () => (n)),[t,e,n]),[i,u]=_react.useState.call(void 0, n),s=_react.useCallback.call(void 0, o=>{u(c=>{let l=o instanceof Function?o(c):o;return(typeof window<"u"&&t==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).set(e,l),l})},[t,e]);return _react.useEffect.call(void 0, ()=>{u(r())},[r]),[i,s]};var $=(e,n)=>H(e,n,"local");var qe=(e,n)=>H(e,n,"session");var j=e=>e?"online":"offline",Ze= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, j(!0)),t=e==="online",r=e==="offline",i=_react.useCallback.call(void 0, ()=>n(j(navigator.onLine)),[]);return P(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:t,isOffline:r}};var h=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var I=(e,n)=>{let t=h();_react.useEffect.call(void 0, ()=>{if(!t)return e()},n)};var _webutils = require('@alessiofrittoli/web-utils');var R=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,C={value:"",isTouched:!1,isValid:!0},B=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!R(_nullishCoalesce(e.value, () => ("")))};case"RESET":return C}};var ft=(e={})=>{let{inputRef:n}=e,{initialValue:t}=e,{touchTimeout:r=600}=e,{validate:i,parse:u}=e,{onChange:s}=e,[o,c]=_react.useReducer.call(void 0, B,{...C,value:t}),l=u?u(o.value):o.value,{isTouched:a}=o,d=R(l),p=typeof i=="function"?i(l):!0,f=!p&&a||!!t&&!p;I(()=>{let T=setTimeout(()=>{R(l)||c({type:"TOUCHED"})},r);return()=>clearTimeout(T)},[l,r]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,M=v==="checkbox"?x.checked:x.value;c({type:"CHANGE",value:M}),_optionalChain([s, 'optionalCall', _2 => _2(u?u(M):M)])},[s,u]),S=_react.useCallback.call(void 0, ()=>{c({type:"BLUR"})},[]),O=_react.useCallback.call(void 0, ()=>{c({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{c({type:"CHANGE",value:T})},[]),g=_react.useCallback.call(void 0, ()=>{_optionalChain([n, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[n]),V=_react.useCallback.call(void 0, ()=>{c({type:"RESET"})},[]);return{value:l,isTouched:a,isValid:p,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:O,focus:g,reset:V}};var xt=e=>{let n=h();_react.useEffect.call(void 0, ()=>{if(n)return e()},[])};var N=()=>{let[e,n]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>n(!0),[]),e};var _helpers = require('@alessiofrittoli/math-utils/helpers');var ht=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var Vt=(e,n=[])=>{let[t,r]=_react.useState.call(void 0, n),i=t.length>0,u=a=>t.includes(a),s=_react.useCallback.call(void 0, a=>r(d=>{let p=new Set(d);return p.has(a)?p.delete(a):p.add(a),Array.from(p.values())}),[]),o=_react.useCallback.call(void 0, a=>{r(d=>{if(d.length===0)return[a];let p=[...e],f=p.indexOf(d.at(0)),y=p.indexOf(a);if(f>y){let S=[...p].reverse(),O=S.indexOf(d.at(0)),E=S.indexOf(a);return S.slice(O,E+1).reverse()}return p.slice(f,y+1)})},[e]),c=_react.useCallback.call(void 0, ()=>{r(e)},[e]),l=_react.useCallback.call(void 0, a=>r(a?n:[]),[n]);return{selection:t,hasSelection:i,isSelected:u,setSelection:r,select:s,groupSelect:o,selectAll:c,resetSelection:l}};var _browserapi = require('@alessiofrittoli/web-utils/browser-api');function k(e,n={}){let{updateState:t=!0,onChange:r}=n,[i,u]=_react.useState.call(void 0, _browserapi.getMediaMatches.call(void 0, e)),s=_react.useCallback.call(void 0, ()=>{let o=_browserapi.getMediaMatches.call(void 0, e);t&&u(o),_optionalChain([r, 'optionalCall', _6 => _6(o)])},[e,t,r]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:c}=o;return t&&u(c),_optionalChain([r, 'optionalCall', _7 => _7(c)]),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,t,r,s]),!!t)return i}var jt=(e={})=>{let n=N(),t=k("(prefers-color-scheme: dark)"),{initial:r=t,docClassNames:i=[]}=e,[u,s]=$("dark-mode",r),o=_nullishCoalesce(u, () => (t)),[c,l]=i,a=_react.useRef.call(void 0, {light:"",dark:""});return I(()=>{s(t)},[t,s]),_react.useEffect.call(void 0, ()=>{c&&document.documentElement.classList.toggle(c,o),l&&document.documentElement.classList.toggle(l,!o)},[o,c,l]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(d=>{let p=d.getAttribute("media"),f=d.getAttribute("content");if(f){if(!p||p==="(prefers-color-scheme: light)"){a.current.light=f;return}a.current.dark=f}})},[]),I(()=>{let d=a.current.dark,p=a.current.light;u&&!d||!u&&!p||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",u?d:p)})},[u]),{isDarkMode:n?o:!1,isDarkOS:n?t:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(d=>!d),[s]),enableDarkMode:_react.useCallback.call(void 0, ()=>s(!0),[s]),disableDarkMode:_react.useCallback.call(void 0, ()=>s(!1),[s])}};function P(e,n){let{target:t,query:r,options:i,listener:u,onLoad:s,onCleanUp:o}=n;_react.useEffect.call(void 0, ()=>{let c=Array.isArray(e)?e:[e],l=_nullishCoalesce((r?window.matchMedia(r):t&&"current"in t?t.current:t), () => (window));if(l.addEventListener)return _optionalChain([s, 'optionalCall', _8 => _8()]),c.map(a=>{l.addEventListener(a,u,i)}),()=>{c.map(a=>{l.removeEventListener(a,u,i)}),_optionalChain([o, 'optionalCall', _9 => _9()])}},[e,t,r,i,u,s,o])}var _device = require('@alessiofrittoli/web-utils/device');var Xt=()=>k(_device.portraitMediaQuery);var ge=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),en= exports.useFocusTrap =e=>{let[n,t]=_react.useState.call(void 0, !1),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, s=>{r.current=document.activeElement;let o=s||_optionalChain([e, 'optionalAccess', _10 => _10.current])||!1;if(o)return t(o)},[e]),u=_react.useCallback.call(void 0, ()=>{_optionalChain([r, 'access', _11 => _11.current, 'optionalAccess', _12 => _12.focus, 'call', _13 => _13()]),t(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!n)return;let s=o=>{if(o.key!=="Tab")return;let c=Array.from(n.querySelectorAll(ge)),l=c.at(0),a=c.at(-1);if(!o.shiftKey){document.activeElement===a&&(o.preventDefault(),_optionalChain([l, 'optionalAccess', _14 => _14.focus, 'call', _15 => _15()]));return}document.activeElement===l&&(o.preventDefault(),_optionalChain([a, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]))};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s)}},[n]),[i,u]};var on=(e,n={})=>{let{initial:t=!1,once:r,amount:i,margin:u,root:s,enable:o=!0}=n,{onEnter:c,onExit:l,onIntersect:a}=n,d=_react.useRef.call(void 0, !0),[p,f]=_react.useState.call(void 0, t),[y,S]=_react.useState.call(void 0, o),O=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),g=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let V=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!O.current,v&&c&&await c({entry:T,observer:x}),E.current&&l&&await l({entry:T,observer:x}),a&&(v||!v&&O.current!=null)){let M={isEntering:v,isExiting:E.current};await a({entry:T,observer:x,...M})}if(O.current=v,!d.current)return;f(v)}catch(M){console.error(M)}v&&r&&x.disconnect()},{root:s||void 0,rootMargin:u,threshold:V})}catch(T){console.error(T)}},[s,u,i,r,y,c,l,a]);return _react.useEffect.call(void 0, ()=>{if(d.current=!0,!(!y||!e.current||!g))return g.observe(e.current),()=>{d.current=!1,g.disconnect()}},[e,g,y]),{inView:p,enabled:y,observer:g,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var ln=e=>{let n=_react.useCallback.call(void 0, ()=>_dom.blockScroll.call(void 0, _optionalChain([e, 'optionalAccess', _18 => _18.current])||void 0),[e]),t=_react.useCallback.call(void 0, ()=>_dom.restoreScroll.call(void 0, _optionalChain([e, 'optionalAccess', _19 => _19.current])||void 0),[e]);return[n,t]};var Y=(e,n={})=>{let{delay:t=1,args:r}=n;_react.useEffect.call(void 0, ()=>{let i=setTimeout(e,t,...r||[]);return()=>clearTimeout(i)},[t,r,e])};var En=(e,n=500)=>{let[t,r]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return Y(r,{delay:n,args:i}),t};function Z(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:u=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,l]=_react.useState.call(void 0, i),a=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),d=_react.useCallback.call(void 0, ()=>{let f=a();return u&&(r?e(...r):e()),o.current=setInterval(e,t,...r||[]),!f&&s&&l(!0),o.current},[t,r,s,u,e,a]),p=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return d(),p},[i,d,p]),s?{isActive:c,start:d,stop:p}:{start:d,stop:p}}var In=(e,n={})=>{let{delay:t=1,args:r}=n;_react.useEffect.call(void 0, ()=>{let i=setInterval(e,t,...r||[]);return()=>clearInterval(i)},[t,r,e])};function kn(e,n={}){let{autoplay:t=!0}=n,r=Z(e,{autoplay:!1,...n}),{start:i,stop:u}=r,s=_react.useCallback.call(void 0, ()=>document.hidden?u():i(),[i,u]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=_react.useCallback.call(void 0, ()=>{u(),document.removeEventListener("visibilitychange",s)},[u,s]);return _react.useEffect.call(void 0, ()=>{if(t)return o(),c},[t,o,c]),{...r,start:o,stop:c}}function Dn(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:u=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,l]=_react.useState.call(void 0, i),a=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),d=_react.useCallback.call(void 0, ()=>{let f=a();return u&&(r?e(...r):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&l(!1),r)return e(...r);e()},t),!f&&s&&l(!0),o.current},[t,r,s,u,e,a]),p=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return d(),p},[i,d,p]),s?{isActive:c,start:d,stop:p}:{start:d,stop:p}}exports.getState = j; exports.useConnection = Ze; exports.useDarkMode = jt; exports.useDebounce = En; exports.useEffectOnce = xt; exports.useEventListener = P; exports.useFocusTrap = en; exports.useInView = on; exports.useInput = ft; exports.useInterval = Z; exports.useIntervalWhenVisible = kn; exports.useIsClient = N; exports.useIsFirstRender = h; exports.useIsPortrait = Xt; exports.useLightInterval = In; exports.useLightTimeout = Y; exports.useLocalStorage = $; exports.useMediaQuery = k; exports.usePagination = ht; exports.useScrollBlock = ln; exports.useSelection = Vt; exports.useSessionStorage = qe; exports.useStorage = H; exports.useTimeout = Dn; exports.useUpdateEffect = I;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _LocalStorage = require('@alessiofrittoli/web-utils/storage/LocalStorage');var _SessionStorage = require('@alessiofrittoli/web-utils/storage/SessionStorage');var H=(e,n,t="local")=>{let r=_react.useCallback.call(void 0, ()=>_nullishCoalesce((t==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).get(e), () => (n)),[t,e,n]),[i,c]=_react.useState.call(void 0, n),s=_react.useCallback.call(void 0, o=>{c(u=>{let l=o instanceof Function?o(u):o;return(typeof window<"u"&&t==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).set(e,l),l})},[t,e]);return _react.useEffect.call(void 0, ()=>{c(r())},[r]),[i,s]};var $=(e,n)=>H(e,n,"local");var Je=(e,n)=>H(e,n,"session");var j=e=>e?"online":"offline",et= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, j(!0)),t=e==="online",r=e==="offline",i=_react.useCallback.call(void 0, ()=>n(j(navigator.onLine)),[]);return P(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:t,isOffline:r}};var h=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var I=(e,n)=>{let t=h();_react.useEffect.call(void 0, ()=>{if(!t)return e()},n)};var _webutils = require('@alessiofrittoli/web-utils');var R=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,C={value:"",isTouched:!1,isValid:!0},B=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!R(_nullishCoalesce(e.value, () => ("")))};case"RESET":return C}};var yt=(e={})=>{let{inputRef:n}=e,{initialValue:t}=e,{touchTimeout:r=600}=e,{validate:i,parse:c}=e,{onChange:s}=e,[o,u]=_react.useReducer.call(void 0, B,{...C,value:t}),l=c?c(o.value):o.value,{isTouched:a}=o,d=R(l),p=typeof i=="function"?i(l):!0,f=!p&&a||!!t&&!p;I(()=>{let T=setTimeout(()=>{R(l)||u({type:"TOUCHED"})},r);return()=>clearTimeout(T)},[l,r]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,M=v==="checkbox"?x.checked:x.value;u({type:"CHANGE",value:M}),_optionalChain([s, 'optionalCall', _2 => _2(c?c(M):M)])},[s,c]),S=_react.useCallback.call(void 0, ()=>{u({type:"BLUR"})},[]),O=_react.useCallback.call(void 0, ()=>{u({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{u({type:"CHANGE",value:T})},[]),g=_react.useCallback.call(void 0, ()=>{_optionalChain([n, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[n]),V=_react.useCallback.call(void 0, ()=>{u({type:"RESET"})},[]);return{value:l,isTouched:a,isValid:p,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:O,focus:g,reset:V}};var Ot=(e,n)=>_react.useCallback.call(void 0, _webutils.deferCallback.call(void 0, e),n);var Ht=e=>{let n=h();_react.useEffect.call(void 0, ()=>{if(n)return e()},[])};var N=()=>{let[e,n]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>n(!0),[]),e};var _helpers = require('@alessiofrittoli/math-utils/helpers');var wt=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var Wt=(e,n=[])=>{let[t,r]=_react.useState.call(void 0, n),i=t.length>0,c=a=>t.includes(a),s=_react.useCallback.call(void 0, a=>r(d=>{let p=new Set(d);return p.has(a)?p.delete(a):p.add(a),Array.from(p.values())}),[]),o=_react.useCallback.call(void 0, a=>{r(d=>{if(d.length===0)return[a];let p=[...e],f=p.indexOf(d.at(0)),y=p.indexOf(a);if(f>y){let S=[...p].reverse(),O=S.indexOf(d.at(0)),E=S.indexOf(a);return S.slice(O,E+1).reverse()}return p.slice(f,y+1)})},[e]),u=_react.useCallback.call(void 0, ()=>{r(e)},[e]),l=_react.useCallback.call(void 0, a=>r(a?n:[]),[n]);return{selection:t,hasSelection:i,isSelected:c,setSelection:r,select:s,groupSelect:o,selectAll:u,resetSelection:l}};var _browserapi = require('@alessiofrittoli/web-utils/browser-api');function k(e,n={}){let{updateState:t=!0,onChange:r}=n,[i,c]=_react.useState.call(void 0, _browserapi.getMediaMatches.call(void 0, e)),s=_react.useCallback.call(void 0, ()=>{let o=_browserapi.getMediaMatches.call(void 0, e);t&&c(o),_optionalChain([r, 'optionalCall', _6 => _6(o)])},[e,t,r]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:u}=o;return t&&c(u),_optionalChain([r, 'optionalCall', _7 => _7(u)]),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,t,r,s]),!!t)return i}var Jt=(e={})=>{let n=N(),t=k("(prefers-color-scheme: dark)"),{initial:r=t,docClassNames:i=[]}=e,[c,s]=$("dark-mode",r),o=_nullishCoalesce(c, () => (t)),[u,l]=i,a=_react.useRef.call(void 0, {light:"",dark:""});return I(()=>{s(t)},[t,s]),_react.useEffect.call(void 0, ()=>{u&&document.documentElement.classList.toggle(u,o),l&&document.documentElement.classList.toggle(l,!o)},[o,u,l]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(d=>{let p=d.getAttribute("media"),f=d.getAttribute("content");if(f){if(!p||p==="(prefers-color-scheme: light)"){a.current.light=f;return}a.current.dark=f}})},[]),I(()=>{let d=a.current.dark,p=a.current.light;c&&!d||!c&&!p||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",c?d:p)})},[c]),{isDarkMode:n?o:!1,isDarkOS:n?t:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(d=>!d),[s]),enableDarkMode:_react.useCallback.call(void 0, ()=>s(!0),[s]),disableDarkMode:_react.useCallback.call(void 0, ()=>s(!1),[s])}};function P(e,n){let{target:t,query:r,options:i,listener:c,onLoad:s,onCleanUp:o}=n;_react.useEffect.call(void 0, ()=>{let u=Array.isArray(e)?e:[e],l=_nullishCoalesce((r?window.matchMedia(r):t&&"current"in t?t.current:t), () => (window));if(l.addEventListener)return _optionalChain([s, 'optionalCall', _8 => _8()]),u.map(a=>{l.addEventListener(a,c,i)}),()=>{u.map(a=>{l.removeEventListener(a,c,i)}),_optionalChain([o, 'optionalCall', _9 => _9()])}},[e,t,r,i,c,s,o])}var _device = require('@alessiofrittoli/web-utils/device');var rn=()=>k(_device.portraitMediaQuery);var be=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),cn= exports.useFocusTrap =e=>{let[n,t]=_react.useState.call(void 0, !1),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, s=>{r.current=document.activeElement;let o=s||_optionalChain([e, 'optionalAccess', _10 => _10.current])||!1;if(o)return t(o)},[e]),c=_react.useCallback.call(void 0, ()=>{_optionalChain([r, 'access', _11 => _11.current, 'optionalAccess', _12 => _12.focus, 'call', _13 => _13()]),t(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!n)return;let s=o=>{if(o.key!=="Tab")return;let u=Array.from(n.querySelectorAll(be)),l=u.at(0),a=u.at(-1);if(!o.shiftKey){document.activeElement===a&&(o.preventDefault(),_optionalChain([l, 'optionalAccess', _14 => _14.focus, 'call', _15 => _15()]));return}document.activeElement===l&&(o.preventDefault(),_optionalChain([a, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]))};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s)}},[n]),[i,c]};var dn=(e,n={})=>{let{initial:t=!1,once:r,amount:i,margin:c,root:s,enable:o=!0}=n,{onEnter:u,onExit:l,onIntersect:a}=n,d=_react.useRef.call(void 0, !0),[p,f]=_react.useState.call(void 0, t),[y,S]=_react.useState.call(void 0, o),O=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),g=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let V=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!O.current,v&&u&&await u({entry:T,observer:x}),E.current&&l&&await l({entry:T,observer:x}),a&&(v||!v&&O.current!=null)){let M={isEntering:v,isExiting:E.current};await a({entry:T,observer:x,...M})}if(O.current=v,!d.current)return;f(v)}catch(M){console.error(M)}v&&r&&x.disconnect()},{root:s||void 0,rootMargin:c,threshold:V})}catch(T){console.error(T)}},[s,c,i,r,y,u,l,a]);return _react.useEffect.call(void 0, ()=>{if(d.current=!0,!(!y||!e.current||!g))return g.observe(e.current),()=>{d.current=!1,g.disconnect()}},[e,g,y]),{inView:p,enabled:y,observer:g,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var vn=e=>{let n=_react.useCallback.call(void 0, ()=>_dom.blockScroll.call(void 0, _optionalChain([e, 'optionalAccess', _18 => _18.current])||void 0),[e]),t=_react.useCallback.call(void 0, ()=>_dom.restoreScroll.call(void 0, _optionalChain([e, 'optionalAccess', _19 => _19.current])||void 0),[e]);return[n,t]};var Y=(e,n={})=>{let{delay:t=1,args:r}=n;_react.useEffect.call(void 0, ()=>{let i=setTimeout(e,t,...r||[]);return()=>clearTimeout(i)},[t,r,e])};var In=(e,n=500)=>{let[t,r]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return Y(r,{delay:n,args:i}),t};function Z(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:c=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[u,l]=_react.useState.call(void 0, i),a=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),d=_react.useCallback.call(void 0, ()=>{let f=a();return c&&(r?e(...r):e()),o.current=setInterval(e,t,...r||[]),!f&&s&&l(!0),o.current},[t,r,s,c,e,a]),p=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return d(),p},[i,d,p]),s?{isActive:u,start:d,stop:p}:{start:d,stop:p}}var Cn=(e,n={})=>{let{delay:t=1,args:r}=n;_react.useEffect.call(void 0, ()=>{let i=setInterval(e,t,...r||[]);return()=>clearInterval(i)},[t,r,e])};function An(e,n={}){let{autoplay:t=!0}=n,r=Z(e,{autoplay:!1,...n}),{start:i,stop:c}=r,s=_react.useCallback.call(void 0, ()=>document.hidden?c():i(),[i,c]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),u=_react.useCallback.call(void 0, ()=>{c(),document.removeEventListener("visibilitychange",s)},[c,s]);return _react.useEffect.call(void 0, ()=>{if(t)return o(),u},[t,o,u]),{...r,start:o,stop:u}}function $n(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:c=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[u,l]=_react.useState.call(void 0, i),a=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),d=_react.useCallback.call(void 0, ()=>{let f=a();return c&&(r?e(...r):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&l(!1),r)return e(...r);e()},t),!f&&s&&l(!0),o.current},[t,r,s,c,e,a]),p=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return d(),p},[i,d,p]),s?{isActive:u,start:d,stop:p}:{start:d,stop:p}}exports.getState = j; exports.useConnection = et; exports.useDarkMode = Jt; exports.useDebounce = In; exports.useDeferCallback = Ot; exports.useEffectOnce = Ht; exports.useEventListener = P; exports.useFocusTrap = cn; exports.useInView = dn; exports.useInput = yt; exports.useInterval = Z; exports.useIntervalWhenVisible = An; exports.useIsClient = N; exports.useIsFirstRender = h; exports.useIsPortrait = rn; exports.useLightInterval = Cn; exports.useLightTimeout = Y; exports.useLocalStorage = $; exports.useMediaQuery = k; exports.usePagination = wt; exports.useScrollBlock = vn; exports.useSelection = Wt; exports.useSessionStorage = Je; exports.useStorage = H; exports.useTimeout = $n; exports.useUpdateEffect = I;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as Q,useEffect as ee,useState as te}from"react";import{LocalStorage as F}from"@alessiofrittoli/web-utils/storage/LocalStorage";import{SessionStorage as $}from"@alessiofrittoli/web-utils/storage/SessionStorage";var h=(e,n,t="local")=>{let r=Q(()=>(t==="local"?F:$).get(e)??n,[t,e,n]),[i,
|
|
1
|
+
import{useCallback as Q,useEffect as ee,useState as te}from"react";import{LocalStorage as F}from"@alessiofrittoli/web-utils/storage/LocalStorage";import{SessionStorage as $}from"@alessiofrittoli/web-utils/storage/SessionStorage";var h=(e,n,t="local")=>{let r=Q(()=>(t==="local"?F:$).get(e)??n,[t,e,n]),[i,c]=te(n),s=Q(o=>{c(u=>{let l=o instanceof Function?o(u):o;return(typeof window<"u"&&t==="local"?F:$).set(e,l),l})},[t,e]);return ee(()=>{c(r())},[r]),[i,s]};var j=(e,n)=>h(e,n,"local");var Xe=(e,n)=>h(e,n,"session");import{useCallback as ne,useState as re}from"react";var P=e=>e?"online":"offline",tt=()=>{let[e,n]=re(P(!0)),t=e==="online",r=e==="offline",i=ne(()=>n(P(navigator.onLine)),[]);return B(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:t,isOffline:r}};import{useCallback as w,useEffect as z,useRef as xe}from"react";import{useCallback as I,useReducer as ae}from"react";import{useEffect as se}from"react";import{useRef as oe}from"react";var R=()=>{let e=oe(!0);return e.current?(e.current=!1,!0):e.current};var H=(e,n)=>{let t=R();se(()=>{if(!t)return e()},n)};import{isEmpty as ie}from"@alessiofrittoli/web-utils";var L=e=>typeof e=="string"?ie(e):!e,D={value:"",isTouched:!1,isValid:!0},N=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!L(e.value??"")};case"RESET":return D}};var vt=(e={})=>{let{inputRef:n}=e,{initialValue:t}=e,{touchTimeout:r=600}=e,{validate:i,parse:c}=e,{onChange:s}=e,[o,u]=ae(N,{...D,value:t}),l=c?c(o.value):o.value,{isTouched:a}=o,d=L(l),p=typeof i=="function"?i(l):!0,T=!p&&a||!!t&&!p;H(()=>{let y=setTimeout(()=>{L(l)||u({type:"TOUCHED"})},r);return()=>clearTimeout(y)},[l,r]);let v=I(y=>{let{target:S}=y,{type:E}=S,b=E==="checkbox"?S.checked:S.value;u({type:"CHANGE",value:b}),s?.(c?c(b):b)},[s,c]),O=I(()=>{u({type:"BLUR"})},[]),g=I(()=>{u({type:"TOUCHED"})},[]),x=I(y=>{u({type:"CHANGE",value:y})},[]),M=I(()=>{n?.current?.focus()},[n]),C=I(()=>{u({type:"RESET"})},[]);return{value:l,isTouched:a,isValid:p,isEmpty:d,hasError:T,changeHandler:v,blurHandler:O,setValue:x,submit:g,focus:M,reset:C}};import{useCallback as ce}from"react";import{deferCallback as ue}from"@alessiofrittoli/web-utils";var gt=(e,n)=>ce(ue(e),n);import{useEffect as le}from"react";var ht=e=>{let n=R();le(()=>{if(n)return e()},[])};import{useEffect as pe,useState as de}from"react";var G=()=>{let[e,n]=de(!1);return pe(()=>n(!0),[]),e};import{useMemo as me}from"react";import{paginate as fe}from"@alessiofrittoli/math-utils/helpers";var Ut=(e={})=>me(()=>fe(e),[e]);import{useCallback as k,useState as Te}from"react";var Qt=(e,n=[])=>{let[t,r]=Te(n),i=t.length>0,c=a=>t.includes(a),s=k(a=>r(d=>{let p=new Set(d);return p.has(a)?p.delete(a):p.add(a),Array.from(p.values())}),[]),o=k(a=>{r(d=>{if(d.length===0)return[a];let p=[...e],T=p.indexOf(d.at(0)),v=p.indexOf(a);if(T>v){let O=[...p].reverse(),g=O.indexOf(d.at(0)),x=O.indexOf(a);return O.slice(g,x+1).reverse()}return p.slice(T,v+1)})},[e]),u=k(()=>{r(e)},[e]),l=k(a=>r(a?n:[]),[n]);return{selection:t,hasSelection:i,isSelected:c,setSelection:r,select:s,groupSelect:o,selectAll:u,resetSelection:l}};import{useCallback as ye,useEffect as ve,useState as Ee}from"react";import{getMediaMatches as q}from"@alessiofrittoli/web-utils/browser-api";function V(e,n={}){let{updateState:t=!0,onChange:r}=n,[i,c]=Ee(q(e)),s=ye(()=>{let o=q(e);t&&c(o),r?.(o)},[e,t,r]);if(ve(()=>{let o=window.matchMedia(e),{matches:u}=o;return t&&c(u),r?.(u),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,t,r,s]),!!t)return i}var Xt=(e={})=>{let n=G(),t=V("(prefers-color-scheme: dark)"),{initial:r=t,docClassNames:i=[]}=e,[c,s]=j("dark-mode",r),o=c??t,[u,l]=i,a=xe({light:"",dark:""});return H(()=>{s(t)},[t,s]),z(()=>{u&&document.documentElement.classList.toggle(u,o),l&&document.documentElement.classList.toggle(l,!o)},[o,u,l]),z(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(d=>{let p=d.getAttribute("media"),T=d.getAttribute("content");if(T){if(!p||p==="(prefers-color-scheme: light)"){a.current.light=T;return}a.current.dark=T}})},[]),H(()=>{let d=a.current.dark,p=a.current.light;c&&!d||!c&&!p||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",c?d:p)})},[c]),{isDarkMode:n?o:!1,isDarkOS:n?t:!1,toggleDarkMode:w(()=>s(d=>!d),[s]),enableDarkMode:w(()=>s(!0),[s]),disableDarkMode:w(()=>s(!1),[s])}};import{useEffect as Se}from"react";function B(e,n){let{target:t,query:r,options:i,listener:c,onLoad:s,onCleanUp:o}=n;Se(()=>{let u=Array.isArray(e)?e:[e],l=(r?window.matchMedia(r):t&&"current"in t?t.current:t)??window;if(l.addEventListener)return s?.(),u.map(a=>{l.addEventListener(a,c,i)}),()=>{u.map(a=>{l.removeEventListener(a,c,i)}),o?.()}},[e,t,r,i,c,s,o])}import{portraitMediaQuery as Oe}from"@alessiofrittoli/web-utils/device";var on=()=>V(Oe);import{useCallback as J,useEffect as ge,useRef as Me,useState as be}from"react";var Ie=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),un=e=>{let[n,t]=be(!1),r=Me(null),i=J(s=>{r.current=document.activeElement;let o=s||e?.current||!1;if(o)return t(o)},[e]),c=J(()=>{r.current?.focus(),t(!1)},[]);return ge(()=>{if(!n)return;let s=o=>{if(o.key!=="Tab")return;let u=Array.from(n.querySelectorAll(Ie)),l=u.at(0),a=u.at(-1);if(!o.shiftKey){document.activeElement===a&&(o.preventDefault(),l?.focus());return}document.activeElement===l&&(o.preventDefault(),a?.focus())};return document.addEventListener("keydown",s),()=>{document.removeEventListener("keydown",s)}},[n]),[i,c]};import{useEffect as He,useMemo as he,useRef as U,useState as X}from"react";var mn=(e,n={})=>{let{initial:t=!1,once:r,amount:i,margin:c,root:s,enable:o=!0}=n,{onEnter:u,onExit:l,onIntersect:a}=n,d=U(!0),[p,T]=X(t),[v,O]=X(o),g=U(null),x=U(!1),M=he(()=>{if(!v||typeof IntersectionObserver>"u")return;let C=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([y],S)=>{if(!y)return;let E=y.isIntersecting;try{if(x.current=!E&&!!g.current,E&&u&&await u({entry:y,observer:S}),x.current&&l&&await l({entry:y,observer:S}),a&&(E||!E&&g.current!=null)){let b={isEntering:E,isExiting:x.current};await a({entry:y,observer:S,...b})}if(g.current=E,!d.current)return;T(E)}catch(b){console.error(b)}E&&r&&S.disconnect()},{root:s||void 0,rootMargin:c,threshold:C})}catch(y){console.error(y)}},[s,c,i,r,v,u,l,a]);return He(()=>{if(d.current=!0,!(!v||!e.current||!M))return M.observe(e.current),()=>{d.current=!1,M.disconnect()}},[e,M,v]),{inView:p,enabled:v,observer:M,isExiting:x.current,setInView:T,setEnabled:O}};import{useCallback as Y}from"react";import{blockScroll as Re,restoreScroll as Le}from"@alessiofrittoli/web-utils/dom";var En=e=>{let n=Y(()=>Re(e?.current||void 0),[e]),t=Y(()=>Le(e?.current||void 0),[e]);return[n,t]};import{useMemo as Ve,useState as Ce}from"react";import{useEffect as ke}from"react";var Z=(e,n={})=>{let{delay:t=1,args:r}=n;ke(()=>{let i=setTimeout(e,t,...r||[]);return()=>clearTimeout(i)},[t,r,e])};var Hn=(e,n=500)=>{let[t,r]=Ce(e),i=Ve(()=>[e],[e]);return Z(r,{delay:n,args:i}),t};import{useCallback as K,useEffect as De,useRef as we,useState as Ue}from"react";function _(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:c=!1,updateState:s=!1}=n,o=we(void 0),[u,l]=Ue(i),a=K(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),d=K(()=>{let T=a();return c&&(r?e(...r):e()),o.current=setInterval(e,t,...r||[]),!T&&s&&l(!0),o.current},[t,r,s,c,e,a]),p=K(()=>{a()&&s&&l(!1)},[s,a]);return De(()=>{if(i)return d(),p},[i,d,p]),s?{isActive:u,start:d,stop:p}:{start:d,stop:p}}import{useEffect as Ke}from"react";var Dn=(e,n={})=>{let{delay:t=1,args:r}=n;Ke(()=>{let i=setInterval(e,t,...r||[]);return()=>clearInterval(i)},[t,r,e])};import{useCallback as A,useEffect as Ae}from"react";function Wn(e,n={}){let{autoplay:t=!0}=n,r=_(e,{autoplay:!1,...n}),{start:i,stop:c}=r,s=A(()=>document.hidden?c():i(),[i,c]),o=A(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),u=A(()=>{c(),document.removeEventListener("visibilitychange",s)},[c,s]);return Ae(()=>{if(t)return o(),u},[t,o,u]),{...r,start:o,stop:u}}import{useCallback as W,useEffect as We,useRef as Qe,useState as Fe}from"react";function jn(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:c=!1,updateState:s=!1}=n,o=Qe(void 0),[u,l]=Fe(i),a=W(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),d=W(()=>{let T=a();return c&&(r?e(...r):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&l(!1),r)return e(...r);e()},t),!T&&s&&l(!0),o.current},[t,r,s,c,e,a]),p=W(()=>{a()&&s&&l(!1)},[s,a]);return We(()=>{if(i)return d(),p},[i,d,p]),s?{isActive:u,start:d,stop:p}:{start:d,stop:p}}export{P as getState,tt as useConnection,Xt as useDarkMode,Hn as useDebounce,gt as useDeferCallback,ht as useEffectOnce,B as useEventListener,un as useFocusTrap,mn as useInView,vt as useInput,_ as useInterval,Wn as useIntervalWhenVisible,G as useIsClient,R as useIsFirstRender,on as useIsPortrait,Dn as useLightInterval,Z as useLightTimeout,j as useLocalStorage,V as useMediaQuery,Ut as usePagination,En as useScrollBlock,Qt as useSelection,Xe as useSessionStorage,h as useStorage,jn as useTimeout,H as useUpdateEffect};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alessiofrittoli/react-hooks",
|
|
3
|
-
"version": "3.3.0-alpha.
|
|
3
|
+
"version": "3.3.0-alpha.2",
|
|
4
4
|
"description": "TypeScript React utility Hooks",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Alessio Frittoli",
|
|
@@ -99,7 +99,7 @@
|
|
|
99
99
|
"@testing-library/react": "^16.3.0",
|
|
100
100
|
"@testing-library/user-event": "^14.6.1",
|
|
101
101
|
"@types/jest": "^30.0.0",
|
|
102
|
-
"@types/node": "^24.0.
|
|
102
|
+
"@types/node": "^24.0.15",
|
|
103
103
|
"@types/react": "^19.1.8",
|
|
104
104
|
"@types/react-dom": "^19.1.6",
|
|
105
105
|
"concurrently": "^9.2.0",
|
|
@@ -123,7 +123,7 @@
|
|
|
123
123
|
"dependencies": {
|
|
124
124
|
"@alessiofrittoli/math-utils": "^1.14.0",
|
|
125
125
|
"@alessiofrittoli/type-utils": "^1.8.0",
|
|
126
|
-
"@alessiofrittoli/web-utils": "^1.
|
|
126
|
+
"@alessiofrittoli/web-utils": "^1.16.1"
|
|
127
127
|
},
|
|
128
128
|
"peerDependencies": {
|
|
129
129
|
"@types/react": "^19",
|