@alessiofrittoli/react-hooks 3.3.0-alpha.1 → 3.3.0-alpha.3
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 +1358 -216
- package/dist/eslint.js +1 -1
- package/dist/eslint.mjs +1 -1
- package/dist/index.d.mts +43 -18
- package/dist/index.d.ts +43 -18
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
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
|
|
|
@@ -242,31 +243,31 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
242
243
|
*/
|
|
243
244
|
listener: DocumentEventListener<K>;
|
|
244
245
|
}
|
|
245
|
-
interface
|
|
246
|
+
interface ElementListenerOptions<T extends HTMLElement, K extends keyof HTMLElementEventMap> extends CommonListenerOptions {
|
|
246
247
|
/**
|
|
247
|
-
* The
|
|
248
|
+
* The React RefObject of the target where the listener get attached to.
|
|
248
249
|
*
|
|
249
250
|
*/
|
|
250
|
-
|
|
251
|
+
target: T | React.RefObject<T | null>;
|
|
251
252
|
/**
|
|
252
|
-
* The
|
|
253
|
+
* The HTMLElement Event listener.
|
|
253
254
|
*
|
|
254
|
-
* @param event The [`
|
|
255
|
+
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
255
256
|
*/
|
|
256
|
-
listener:
|
|
257
|
+
listener: ElementEventListener<K>;
|
|
257
258
|
}
|
|
258
|
-
interface
|
|
259
|
+
interface MediaQueryListenerOptions extends CommonListenerOptions {
|
|
259
260
|
/**
|
|
260
|
-
* The
|
|
261
|
+
* The Media Query string to check.
|
|
261
262
|
*
|
|
262
263
|
*/
|
|
263
|
-
|
|
264
|
+
query: string;
|
|
264
265
|
/**
|
|
265
|
-
* The
|
|
266
|
+
* The MediaQueryList Event listener.
|
|
266
267
|
*
|
|
267
|
-
* @param event The
|
|
268
|
+
* @param event The [`MediaQueryListEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListEvent) object.
|
|
268
269
|
*/
|
|
269
|
-
listener:
|
|
270
|
+
listener: MediaQueryChangeListener;
|
|
270
271
|
}
|
|
271
272
|
interface CustomEventListenerOptions<T extends Record<string, Event>, K extends keyof T = keyof T> extends CommonListenerOptions {
|
|
272
273
|
/**
|
|
@@ -409,7 +410,7 @@ declare function useEventListener<T extends HTMLElement, K extends keyof HTMLEle
|
|
|
409
410
|
/**
|
|
410
411
|
* Listen MediaQuery changes.
|
|
411
412
|
*
|
|
412
|
-
* @param type The `MediaQueryList` event name
|
|
413
|
+
* @param type The `MediaQueryList` event name.
|
|
413
414
|
* @param options An object defining init options. See {@link MediaQueryListenerOptions} for more info.
|
|
414
415
|
*
|
|
415
416
|
* @example
|
|
@@ -885,7 +886,7 @@ interface UseInputOutput<I = unknown, O = I> extends InputState<I, O> {
|
|
|
885
886
|
*/
|
|
886
887
|
reset: () => void;
|
|
887
888
|
/**
|
|
888
|
-
* Call `focus` method to focus the Input Element.
|
|
889
|
+
* Call `focus` method to focus the Input Element. `inputRef` must be provided in the input options.
|
|
889
890
|
*
|
|
890
891
|
*/
|
|
891
892
|
focus: () => void;
|
|
@@ -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
|
*
|
|
@@ -934,8 +955,10 @@ declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_mat
|
|
|
934
955
|
* @template V The `entry` type.
|
|
935
956
|
*
|
|
936
957
|
* @param value The `entry` to check.
|
|
958
|
+
*
|
|
959
|
+
* @return `true` if the given `entry` is in `selection`, `false` otherwise.
|
|
937
960
|
*/
|
|
938
|
-
type IsSelectedHandler<V> = (entry: V) =>
|
|
961
|
+
type IsSelectedHandler<V> = (entry: V) => boolean;
|
|
939
962
|
/**
|
|
940
963
|
* A React Dispatch SetStateAction that allows custom selection update.
|
|
941
964
|
*
|
|
@@ -986,6 +1009,8 @@ interface UseSelectionReturnType<V> {
|
|
|
986
1009
|
* @template V The `entry` type.
|
|
987
1010
|
*
|
|
988
1011
|
* @param value The `entry` to check.
|
|
1012
|
+
*
|
|
1013
|
+
* @return `true` if the given `entry` is in `selection`, `false` otherwise.
|
|
989
1014
|
*/
|
|
990
1015
|
isSelected: IsSelectedHandler<V>;
|
|
991
1016
|
/**
|
|
@@ -1029,7 +1054,7 @@ interface UseSelectionReturnType<V> {
|
|
|
1029
1054
|
*
|
|
1030
1055
|
* Provides functionality for single and group selection, as well as resetting the selection.
|
|
1031
1056
|
*
|
|
1032
|
-
* @template V The type of the values in the `array
|
|
1057
|
+
* @template V The type of the values in the `array`.
|
|
1033
1058
|
*
|
|
1034
1059
|
* @param array The array of items to manage selection for.
|
|
1035
1060
|
* @param initial The initial selection state (defaults to an empty array).
|
|
@@ -1191,7 +1216,7 @@ declare function useInterval<T extends readonly unknown[]>(callback: TimerHandle
|
|
|
1191
1216
|
/**
|
|
1192
1217
|
* Schedules repeated execution of `callback` every `delay` milliseconds.
|
|
1193
1218
|
*
|
|
1194
|
-
* This is a lighter version of [`useInterval`](./useInterval.ts)
|
|
1219
|
+
* This is a lighter version of [`useInterval`](./useInterval.ts) and is suggested to use when
|
|
1195
1220
|
* a basic functionality is enough (no manual start/stop or state updates).
|
|
1196
1221
|
*
|
|
1197
1222
|
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
|
|
@@ -1334,4 +1359,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1334
1359
|
*/
|
|
1335
1360
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1336
1361
|
|
|
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 };
|
|
1362
|
+
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
|
|
|
@@ -242,31 +243,31 @@ interface DocumentListenerOptions<K extends keyof DocumentEventMap> extends Comm
|
|
|
242
243
|
*/
|
|
243
244
|
listener: DocumentEventListener<K>;
|
|
244
245
|
}
|
|
245
|
-
interface
|
|
246
|
+
interface ElementListenerOptions<T extends HTMLElement, K extends keyof HTMLElementEventMap> extends CommonListenerOptions {
|
|
246
247
|
/**
|
|
247
|
-
* The
|
|
248
|
+
* The React RefObject of the target where the listener get attached to.
|
|
248
249
|
*
|
|
249
250
|
*/
|
|
250
|
-
|
|
251
|
+
target: T | React.RefObject<T | null>;
|
|
251
252
|
/**
|
|
252
|
-
* The
|
|
253
|
+
* The HTMLElement Event listener.
|
|
253
254
|
*
|
|
254
|
-
* @param event The [`
|
|
255
|
+
* @param event The event object that implements the [`Event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface.
|
|
255
256
|
*/
|
|
256
|
-
listener:
|
|
257
|
+
listener: ElementEventListener<K>;
|
|
257
258
|
}
|
|
258
|
-
interface
|
|
259
|
+
interface MediaQueryListenerOptions extends CommonListenerOptions {
|
|
259
260
|
/**
|
|
260
|
-
* The
|
|
261
|
+
* The Media Query string to check.
|
|
261
262
|
*
|
|
262
263
|
*/
|
|
263
|
-
|
|
264
|
+
query: string;
|
|
264
265
|
/**
|
|
265
|
-
* The
|
|
266
|
+
* The MediaQueryList Event listener.
|
|
266
267
|
*
|
|
267
|
-
* @param event The
|
|
268
|
+
* @param event The [`MediaQueryListEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListEvent) object.
|
|
268
269
|
*/
|
|
269
|
-
listener:
|
|
270
|
+
listener: MediaQueryChangeListener;
|
|
270
271
|
}
|
|
271
272
|
interface CustomEventListenerOptions<T extends Record<string, Event>, K extends keyof T = keyof T> extends CommonListenerOptions {
|
|
272
273
|
/**
|
|
@@ -409,7 +410,7 @@ declare function useEventListener<T extends HTMLElement, K extends keyof HTMLEle
|
|
|
409
410
|
/**
|
|
410
411
|
* Listen MediaQuery changes.
|
|
411
412
|
*
|
|
412
|
-
* @param type The `MediaQueryList` event name
|
|
413
|
+
* @param type The `MediaQueryList` event name.
|
|
413
414
|
* @param options An object defining init options. See {@link MediaQueryListenerOptions} for more info.
|
|
414
415
|
*
|
|
415
416
|
* @example
|
|
@@ -885,7 +886,7 @@ interface UseInputOutput<I = unknown, O = I> extends InputState<I, O> {
|
|
|
885
886
|
*/
|
|
886
887
|
reset: () => void;
|
|
887
888
|
/**
|
|
888
|
-
* Call `focus` method to focus the Input Element.
|
|
889
|
+
* Call `focus` method to focus the Input Element. `inputRef` must be provided in the input options.
|
|
889
890
|
*
|
|
890
891
|
*/
|
|
891
892
|
focus: () => void;
|
|
@@ -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
|
*
|
|
@@ -934,8 +955,10 @@ declare const usePagination: (options?: PaginateOptions) => _alessiofrittoli_mat
|
|
|
934
955
|
* @template V The `entry` type.
|
|
935
956
|
*
|
|
936
957
|
* @param value The `entry` to check.
|
|
958
|
+
*
|
|
959
|
+
* @return `true` if the given `entry` is in `selection`, `false` otherwise.
|
|
937
960
|
*/
|
|
938
|
-
type IsSelectedHandler<V> = (entry: V) =>
|
|
961
|
+
type IsSelectedHandler<V> = (entry: V) => boolean;
|
|
939
962
|
/**
|
|
940
963
|
* A React Dispatch SetStateAction that allows custom selection update.
|
|
941
964
|
*
|
|
@@ -986,6 +1009,8 @@ interface UseSelectionReturnType<V> {
|
|
|
986
1009
|
* @template V The `entry` type.
|
|
987
1010
|
*
|
|
988
1011
|
* @param value The `entry` to check.
|
|
1012
|
+
*
|
|
1013
|
+
* @return `true` if the given `entry` is in `selection`, `false` otherwise.
|
|
989
1014
|
*/
|
|
990
1015
|
isSelected: IsSelectedHandler<V>;
|
|
991
1016
|
/**
|
|
@@ -1029,7 +1054,7 @@ interface UseSelectionReturnType<V> {
|
|
|
1029
1054
|
*
|
|
1030
1055
|
* Provides functionality for single and group selection, as well as resetting the selection.
|
|
1031
1056
|
*
|
|
1032
|
-
* @template V The type of the values in the `array
|
|
1057
|
+
* @template V The type of the values in the `array`.
|
|
1033
1058
|
*
|
|
1034
1059
|
* @param array The array of items to manage selection for.
|
|
1035
1060
|
* @param initial The initial selection state (defaults to an empty array).
|
|
@@ -1191,7 +1216,7 @@ declare function useInterval<T extends readonly unknown[]>(callback: TimerHandle
|
|
|
1191
1216
|
/**
|
|
1192
1217
|
* Schedules repeated execution of `callback` every `delay` milliseconds.
|
|
1193
1218
|
*
|
|
1194
|
-
* This is a lighter version of [`useInterval`](./useInterval.ts)
|
|
1219
|
+
* This is a lighter version of [`useInterval`](./useInterval.ts) and is suggested to use when
|
|
1195
1220
|
* a basic functionality is enough (no manual start/stop or state updates).
|
|
1196
1221
|
*
|
|
1197
1222
|
* When `delay` is larger than `2147483647` or less than `1` or `NaN`, the `delay`
|
|
@@ -1334,4 +1359,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1334
1359
|
*/
|
|
1335
1360
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1336
1361
|
|
|
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 };
|
|
1362
|
+
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,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 Xe=(e,n)=>H(e,n,"session");var j=e=>e?"online":"offline",tt= 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 vt=(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=_react.useMemo.call(void 0, ()=>u?u(o.value):o.value,[o.value,u]),a=_react.useMemo.call(void 0, ()=>typeof i=="function"?i(l):!0,[l,i]),{isTouched:p}=o,d=R(l),f=!a&&p||!!t&&!a;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:p,isValid:a,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:O,focus:g,reset:V}};var gt=(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 G=()=>{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 Ut=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var Qt=(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(p=>{let d=new Set(p);return d.has(a)?d.delete(a):d.add(a),Array.from(d.values())}),[]),o=_react.useCallback.call(void 0, a=>{r(p=>{if(p.length===0)return[a];let d=[...e],f=d.indexOf(p.at(0)),y=d.indexOf(a);if(f>y){let S=[...d].reverse(),O=S.indexOf(p.at(0)),E=S.indexOf(a);return S.slice(O,E+1)}return d.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 Xt=(e={})=>{let n=G(),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(p=>{let d=p.getAttribute("media"),f=p.getAttribute("content");if(f){if(!d||d==="(prefers-color-scheme: light)"){a.current.light=f;return}a.current.dark=f}})},[]),I(()=>{let p=a.current.dark,d=a.current.light;u&&!p||!u&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",u?p:d)})},[u]),{isDarkMode:n?o:!1,isDarkOS:n?t:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(p=>!p),[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 on=()=>k(_device.portraitMediaQuery);var Ie=["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]),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(Ie)),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 mn=(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,p=_react.useRef.call(void 0, !0),[d,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,!p.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(p.current=!0,!(!y||!e.current||!g))return g.observe(e.current),()=>{p.current=!1,g.disconnect()}},[e,g,y]),{inView:d,enabled:y,observer:g,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var En=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 Z=(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 Hn=(e,n=500)=>{let[t,r]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return Z(r,{delay:n,args:i}),t};function _(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,[]),p=_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]),d=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return p(),d},[i,p,d]),s?{isActive:c,start:p,stop:d}:{start:p,stop:d}}var Dn=(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 Wn(e,n={}){let{autoplay:t=!0}=n,r=_(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 jn(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,[]),p=_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]),d=_react.useCallback.call(void 0, ()=>{a()&&s&&l(!1)},[s,a]);return _react.useEffect.call(void 0, ()=>{if(i)return p(),d},[i,p,d]),s?{isActive:c,start:p,stop:d}:{start:p,stop:d}}exports.getState = j; exports.useConnection = tt; exports.useDarkMode = Xt; exports.useDebounce = Hn; exports.useDeferCallback = gt; exports.useEffectOnce = ht; exports.useEventListener = P; exports.useFocusTrap = cn; exports.useInView = mn; exports.useInput = vt; exports.useInterval = _; exports.useIntervalWhenVisible = Wn; exports.useIsClient = G; exports.useIsFirstRender = h; exports.useIsPortrait = on; exports.useLightInterval = Dn; exports.useLightTimeout = Z; exports.useLocalStorage = $; exports.useMediaQuery = k; exports.usePagination = Ut; exports.useScrollBlock = En; exports.useSelection = Qt; exports.useSessionStorage = Xe; exports.useStorage = H; exports.useTimeout = jn; exports.useUpdateEffect = I;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as Q,useEffect as
|
|
1
|
+
import{useCallback as Q,useEffect as te,useState as ne}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,u]=ne(n),s=Q(o=>{u(c=>{let l=o instanceof Function?o(c):o;return(typeof window<"u"&&t==="local"?F:$).set(e,l),l})},[t,e]);return te(()=>{u(r())},[r]),[i,s]};var j=(e,n)=>h(e,n,"local");var Ye=(e,n)=>h(e,n,"session");import{useCallback as re,useState as oe}from"react";var P=e=>e?"online":"offline",nt=()=>{let[e,n]=oe(P(!0)),t=e==="online",r=e==="offline",i=re(()=>n(P(navigator.onLine)),[]);return B(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:t,isOffline:r}};import{useCallback as w,useEffect as J,useRef as Se}from"react";import{useCallback as I,useMemo as G,useReducer as ue}from"react";import{useEffect as ie}from"react";import{useRef as se}from"react";var R=()=>{let e=se(!0);return e.current?(e.current=!1,!0):e.current};var H=(e,n)=>{let t=R();ie(()=>{if(!t)return e()},n)};import{isEmpty as ae}from"@alessiofrittoli/web-utils";var L=e=>typeof e=="string"?ae(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 Et=(e={})=>{let{inputRef:n}=e,{initialValue:t}=e,{touchTimeout:r=600}=e,{validate:i,parse:u}=e,{onChange:s}=e,[o,c]=ue(N,{...D,value:t}),l=G(()=>u?u(o.value):o.value,[o.value,u]),a=G(()=>typeof i=="function"?i(l):!0,[l,i]),{isTouched:p}=o,d=L(l),T=!a&&p||!!t&&!a;H(()=>{let y=setTimeout(()=>{L(l)||c({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;c({type:"CHANGE",value:b}),s?.(u?u(b):b)},[s,u]),O=I(()=>{c({type:"BLUR"})},[]),g=I(()=>{c({type:"TOUCHED"})},[]),x=I(y=>{c({type:"CHANGE",value:y})},[]),M=I(()=>{n?.current?.focus()},[n]),C=I(()=>{c({type:"RESET"})},[]);return{value:l,isTouched:p,isValid:a,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 le}from"@alessiofrittoli/web-utils";var Mt=(e,n)=>ce(le(e),n);import{useEffect as pe}from"react";var Rt=e=>{let n=R();pe(()=>{if(n)return e()},[])};import{useEffect as de,useState as me}from"react";var q=()=>{let[e,n]=me(!1);return de(()=>n(!0),[]),e};import{useMemo as fe}from"react";import{paginate as Te}from"@alessiofrittoli/math-utils/helpers";var Kt=(e={})=>fe(()=>Te(e),[e]);import{useCallback as k,useState as ye}from"react";var Ft=(e,n=[])=>{let[t,r]=ye(n),i=t.length>0,u=a=>t.includes(a),s=k(a=>r(p=>{let d=new Set(p);return d.has(a)?d.delete(a):d.add(a),Array.from(d.values())}),[]),o=k(a=>{r(p=>{if(p.length===0)return[a];let d=[...e],T=d.indexOf(p.at(0)),v=d.indexOf(a);if(T>v){let O=[...d].reverse(),g=O.indexOf(p.at(0)),x=O.indexOf(a);return O.slice(g,x+1)}return d.slice(T,v+1)})},[e]),c=k(()=>{r(e)},[e]),l=k(a=>r(a?n:[]),[n]);return{selection:t,hasSelection:i,isSelected:u,setSelection:r,select:s,groupSelect:o,selectAll:c,resetSelection:l}};import{useCallback as ve,useEffect as Ee,useState as xe}from"react";import{getMediaMatches as z}from"@alessiofrittoli/web-utils/browser-api";function V(e,n={}){let{updateState:t=!0,onChange:r}=n,[i,u]=xe(z(e)),s=ve(()=>{let o=z(e);t&&u(o),r?.(o)},[e,t,r]);if(Ee(()=>{let o=window.matchMedia(e),{matches:c}=o;return t&&u(c),r?.(c),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,t,r,s]),!!t)return i}var Yt=(e={})=>{let n=q(),t=V("(prefers-color-scheme: dark)"),{initial:r=t,docClassNames:i=[]}=e,[u,s]=j("dark-mode",r),o=u??t,[c,l]=i,a=Se({light:"",dark:""});return H(()=>{s(t)},[t,s]),J(()=>{c&&document.documentElement.classList.toggle(c,o),l&&document.documentElement.classList.toggle(l,!o)},[o,c,l]),J(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(p=>{let d=p.getAttribute("media"),T=p.getAttribute("content");if(T){if(!d||d==="(prefers-color-scheme: light)"){a.current.light=T;return}a.current.dark=T}})},[]),H(()=>{let p=a.current.dark,d=a.current.light;u&&!p||!u&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",u?p:d)})},[u]),{isDarkMode:n?o:!1,isDarkOS:n?t:!1,toggleDarkMode:w(()=>s(p=>!p),[s]),enableDarkMode:w(()=>s(!0),[s]),disableDarkMode:w(()=>s(!1),[s])}};import{useEffect as Oe}from"react";function B(e,n){let{target:t,query:r,options:i,listener:u,onLoad:s,onCleanUp:o}=n;Oe(()=>{let c=Array.isArray(e)?e:[e],l=(r?window.matchMedia(r):t&&"current"in t?t.current:t)??window;if(l.addEventListener)return s?.(),c.map(a=>{l.addEventListener(a,u,i)}),()=>{c.map(a=>{l.removeEventListener(a,u,i)}),o?.()}},[e,t,r,i,u,s,o])}import{portraitMediaQuery as ge}from"@alessiofrittoli/web-utils/device";var sn=()=>V(ge);import{useCallback as X,useEffect as Me,useRef as be,useState as Ie}from"react";var He=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),ln=e=>{let[n,t]=Ie(!1),r=be(null),i=X(s=>{r.current=document.activeElement;let o=s||e?.current||!1;if(o)return t(o)},[e]),u=X(()=>{r.current?.focus(),t(!1)},[]);return Me(()=>{if(!n)return;let s=o=>{if(o.key!=="Tab")return;let c=Array.from(n.querySelectorAll(He)),l=c.at(0),a=c.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,u]};import{useEffect as he,useMemo as Re,useRef as U,useState as Y}from"react";var fn=(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,p=U(!0),[d,T]=Y(t),[v,O]=Y(o),g=U(null),x=U(!1),M=Re(()=>{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&&c&&await c({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,!p.current)return;T(E)}catch(b){console.error(b)}E&&r&&S.disconnect()},{root:s||void 0,rootMargin:u,threshold:C})}catch(y){console.error(y)}},[s,u,i,r,v,c,l,a]);return he(()=>{if(p.current=!0,!(!v||!e.current||!M))return M.observe(e.current),()=>{p.current=!1,M.disconnect()}},[e,M,v]),{inView:d,enabled:v,observer:M,isExiting:x.current,setInView:T,setEnabled:O}};import{useCallback as Z}from"react";import{blockScroll as Le,restoreScroll as ke}from"@alessiofrittoli/web-utils/dom";var xn=e=>{let n=Z(()=>Le(e?.current||void 0),[e]),t=Z(()=>ke(e?.current||void 0),[e]);return[n,t]};import{useMemo as Ce,useState as De}from"react";import{useEffect as Ve}from"react";var _=(e,n={})=>{let{delay:t=1,args:r}=n;Ve(()=>{let i=setTimeout(e,t,...r||[]);return()=>clearTimeout(i)},[t,r,e])};var hn=(e,n=500)=>{let[t,r]=De(e),i=Ce(()=>[e],[e]);return _(r,{delay:n,args:i}),t};import{useCallback as K,useEffect as we,useRef as Ue,useState as Ke}from"react";function ee(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:u=!1,updateState:s=!1}=n,o=Ue(void 0),[c,l]=Ke(i),a=K(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),p=K(()=>{let T=a();return u&&(r?e(...r):e()),o.current=setInterval(e,t,...r||[]),!T&&s&&l(!0),o.current},[t,r,s,u,e,a]),d=K(()=>{a()&&s&&l(!1)},[s,a]);return we(()=>{if(i)return p(),d},[i,p,d]),s?{isActive:c,start:p,stop:d}:{start:p,stop:d}}import{useEffect as Ae}from"react";var wn=(e,n={})=>{let{delay:t=1,args:r}=n;Ae(()=>{let i=setInterval(e,t,...r||[]);return()=>clearInterval(i)},[t,r,e])};import{useCallback as A,useEffect as We}from"react";function Qn(e,n={}){let{autoplay:t=!0}=n,r=ee(e,{autoplay:!1,...n}),{start:i,stop:u}=r,s=A(()=>document.hidden?u():i(),[i,u]),o=A(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=A(()=>{u(),document.removeEventListener("visibilitychange",s)},[u,s]);return We(()=>{if(t)return o(),c},[t,o,c]),{...r,start:o,stop:c}}import{useCallback as W,useEffect as Qe,useRef as Fe,useState as $e}from"react";function Pn(e,n={}){let{delay:t=1,args:r,autoplay:i=!0,runOnStart:u=!1,updateState:s=!1}=n,o=Fe(void 0),[c,l]=$e(i),a=W(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),p=W(()=>{let T=a();return u&&(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,u,e,a]),d=W(()=>{a()&&s&&l(!1)},[s,a]);return Qe(()=>{if(i)return p(),d},[i,p,d]),s?{isActive:c,start:p,stop:d}:{start:p,stop:d}}export{P as getState,nt as useConnection,Yt as useDarkMode,hn as useDebounce,Mt as useDeferCallback,Rt as useEffectOnce,B as useEventListener,ln as useFocusTrap,fn as useInView,Et as useInput,ee as useInterval,Qn as useIntervalWhenVisible,q as useIsClient,R as useIsFirstRender,sn as useIsPortrait,wn as useLightInterval,_ as useLightTimeout,j as useLocalStorage,V as useMediaQuery,Kt as usePagination,xn as useScrollBlock,Ft as useSelection,Ye as useSessionStorage,h as useStorage,Pn 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.3",
|
|
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",
|