react-hook-toolkit 1.0.13 → 1.0.14

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.
@@ -0,0 +1,267 @@
1
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
2
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
3
+ if (ar || !(i in from)) {
4
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
5
+ ar[i] = from[i];
6
+ }
7
+ }
8
+ return to.concat(ar || Array.prototype.slice.call(from));
9
+ };
10
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react";
11
+ import { throttle } from '../utils';
12
+ function historyReducer(state, action) {
13
+ switch (action.type) {
14
+ case 'UNDO':
15
+ if (state.past.length === 0)
16
+ return state;
17
+ var _a = state.past, newPresent = _a[0], newPast = _a.slice(1);
18
+ return {
19
+ past: newPast,
20
+ present: newPresent,
21
+ future: __spreadArray([state.present], state.future, true),
22
+ };
23
+ case 'REDO':
24
+ if (state.future.length === 0)
25
+ return state;
26
+ var _b = state.future, nextPresent = _b[0], newFuture = _b.slice(1);
27
+ return {
28
+ past: __spreadArray([state.present], state.past, true),
29
+ present: nextPresent,
30
+ future: newFuture,
31
+ };
32
+ case 'SET':
33
+ if (action.newPresent === state.present)
34
+ return state;
35
+ return {
36
+ past: __spreadArray([state.present], state.past, true),
37
+ present: action.newPresent,
38
+ future: [],
39
+ };
40
+ case 'RESET':
41
+ return {
42
+ past: [],
43
+ present: action.newPresent,
44
+ future: [],
45
+ };
46
+ case 'CLEAR':
47
+ return {
48
+ past: [],
49
+ present: state.present,
50
+ future: [],
51
+ };
52
+ default:
53
+ return state;
54
+ }
55
+ }
56
+ export function useHistoryState(initialPresent) {
57
+ var _a = useReducer((historyReducer), {
58
+ past: [],
59
+ present: initialPresent,
60
+ future: [],
61
+ }), state = _a[0], dispatch = _a[1];
62
+ var canUndo = state.past.length > 0;
63
+ var canRedo = state.future.length > 0;
64
+ var undo = useCallback(function () {
65
+ if (canUndo) {
66
+ dispatch({ type: 'UNDO' });
67
+ }
68
+ }, [canUndo]);
69
+ var redo = useCallback(function () {
70
+ if (canRedo) {
71
+ dispatch({ type: 'REDO' });
72
+ }
73
+ }, [canRedo]);
74
+ var set = useCallback(function (newPresent) {
75
+ dispatch({ type: 'SET', newPresent: newPresent });
76
+ }, []);
77
+ var reset = useCallback(function (newPresent) {
78
+ dispatch({ type: 'RESET', newPresent: newPresent });
79
+ }, []);
80
+ var clear = useCallback(function () {
81
+ dispatch({ type: 'CLEAR' });
82
+ }, []);
83
+ return {
84
+ state: state.present,
85
+ set: set,
86
+ undo: undo,
87
+ redo: redo,
88
+ reset: reset,
89
+ clear: clear,
90
+ canUndo: canUndo,
91
+ canRedo: canRedo,
92
+ past: state.past,
93
+ future: state.future,
94
+ };
95
+ }
96
+ export function useIdle(ms) {
97
+ if (ms === void 0) { ms = 1000 * 60; }
98
+ var _a = useState(false), idle = _a[0], setIdle = _a[1];
99
+ var timeoutIdRef = useRef(null);
100
+ useEffect(function () {
101
+ var handleTimeout = function () {
102
+ setIdle(true);
103
+ };
104
+ var handleEvent = throttle(function () {
105
+ setIdle(false);
106
+ if (timeoutIdRef.current) {
107
+ clearTimeout(timeoutIdRef.current);
108
+ }
109
+ timeoutIdRef.current = setTimeout(handleTimeout, ms);
110
+ }, 500);
111
+ var handleVisibilityChange = function () {
112
+ if (!document.hidden) {
113
+ handleEvent();
114
+ }
115
+ };
116
+ // Initialize
117
+ timeoutIdRef.current = setTimeout(handleTimeout, ms);
118
+ // Events to listen for activity
119
+ var events = [
120
+ 'mousemove',
121
+ 'mousedown',
122
+ 'resize',
123
+ 'keydown',
124
+ 'touchstart',
125
+ 'wheel',
126
+ 'scroll',
127
+ ];
128
+ events.forEach(function (event) { return window.addEventListener(event, handleEvent); });
129
+ document.addEventListener('visibilitychange', handleVisibilityChange);
130
+ return function () {
131
+ events.forEach(function (event) { return window.removeEventListener(event, handleEvent); });
132
+ document.removeEventListener('visibilitychange', handleVisibilityChange);
133
+ if (timeoutIdRef.current) {
134
+ clearTimeout(timeoutIdRef.current);
135
+ }
136
+ };
137
+ }, [ms]);
138
+ return idle;
139
+ }
140
+ export function useIsFirstRender() {
141
+ var isFirstRender = useRef(true);
142
+ useEffect(function () {
143
+ isFirstRender.current = false;
144
+ }, []);
145
+ return isFirstRender.current;
146
+ }
147
+ export function useList(initialList) {
148
+ if (initialList === void 0) { initialList = []; }
149
+ var _a = useState(initialList), list = _a[0], setList = _a[1];
150
+ var set = useCallback(function (newList) {
151
+ setList(newList);
152
+ }, []);
153
+ var push = useCallback(function (element) {
154
+ setList(function (current) { return __spreadArray(__spreadArray([], current, true), [element], false); });
155
+ }, []);
156
+ var removeAt = useCallback(function (index) {
157
+ setList(function (current) { return current.filter(function (_, i) { return i !== index; }); });
158
+ }, []);
159
+ var insertAt = useCallback(function (index, element) {
160
+ setList(function (current) { return __spreadArray(__spreadArray(__spreadArray([], current.slice(0, index), true), [
161
+ element
162
+ ], false), current.slice(index), true); });
163
+ }, []);
164
+ var updateAt = useCallback(function (index, element) {
165
+ setList(function (current) {
166
+ return current.map(function (item, i) { return (i === index ? element : item); });
167
+ });
168
+ }, []);
169
+ var clear = useCallback(function () {
170
+ setList([]);
171
+ }, []);
172
+ return {
173
+ list: list,
174
+ actions: {
175
+ set: set,
176
+ push: push,
177
+ removeAt: removeAt,
178
+ insertAt: insertAt,
179
+ updateAt: updateAt,
180
+ clear: clear,
181
+ },
182
+ };
183
+ }
184
+ export function useLockBodyScroll(lock) {
185
+ if (lock === void 0) { lock = true; }
186
+ useLayoutEffect(function () {
187
+ if (!lock)
188
+ return;
189
+ // Get current body overflow value
190
+ var originalOverflow = document.body.style.overflow;
191
+ var originalPaddingRight = document.body.style.paddingRight;
192
+ // Calculate scrollbar width to prevent layout shift
193
+ var scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
194
+ // Lock body scroll
195
+ document.body.style.overflow = 'hidden';
196
+ // Compensate for scrollbar width if needed
197
+ if (scrollbarWidth > 0) {
198
+ document.body.style.paddingRight = "".concat(scrollbarWidth, "px");
199
+ }
200
+ return function () {
201
+ // Restore original styles
202
+ document.body.style.overflow = originalOverflow;
203
+ document.body.style.paddingRight = originalPaddingRight;
204
+ };
205
+ }, [lock]);
206
+ }
207
+ function isMouseEvent(event) {
208
+ return 'clientX' in event && 'clientY' in event;
209
+ }
210
+ function isTouchEvent(event) {
211
+ return 'touches' in event;
212
+ }
213
+ export function useLongPress(callback, options) {
214
+ if (options === void 0) { options = {}; }
215
+ var _a = options.threshold, threshold = _a === void 0 ? 400 : _a, onStart = options.onStart, onFinish = options.onFinish, onCancel = options.onCancel;
216
+ var isLongPressActive = useRef(false);
217
+ var isPressed = useRef(false);
218
+ var timerId = useRef();
219
+ var start = useCallback(function (event) {
220
+ if (!isMouseEvent(event) && !isTouchEvent(event))
221
+ return;
222
+ if (onStart) {
223
+ onStart(event);
224
+ }
225
+ isPressed.current = true;
226
+ timerId.current = setTimeout(function () {
227
+ if (isPressed.current) {
228
+ callback(event);
229
+ isLongPressActive.current = true;
230
+ }
231
+ }, threshold);
232
+ }, [callback, threshold, onStart]);
233
+ var cancel = useCallback(function (event) {
234
+ if (!isMouseEvent(event) && !isTouchEvent(event))
235
+ return;
236
+ if (isLongPressActive.current) {
237
+ if (onFinish) {
238
+ onFinish(event);
239
+ }
240
+ }
241
+ else if (isPressed.current) {
242
+ if (onCancel) {
243
+ onCancel(event);
244
+ }
245
+ }
246
+ isLongPressActive.current = false;
247
+ isPressed.current = false;
248
+ if (timerId.current) {
249
+ clearTimeout(timerId.current);
250
+ }
251
+ }, [onFinish, onCancel]);
252
+ // Clean up on unmount
253
+ useEffect(function () {
254
+ return function () {
255
+ if (timerId.current) {
256
+ clearTimeout(timerId.current);
257
+ }
258
+ };
259
+ }, []);
260
+ return useMemo(function () { return ({
261
+ onMouseDown: start,
262
+ onMouseUp: cancel,
263
+ onMouseLeave: cancel,
264
+ onTouchStart: start,
265
+ onTouchEnd: cancel,
266
+ }); }, [start, cancel]);
267
+ }
@@ -0,0 +1,265 @@
1
+ import { RefObject } from 'react';
2
+ import { AxiosRequestConfig } from 'axios';
3
+ interface UseAxiosResponse<T> {
4
+ data: T | null;
5
+ loading: boolean;
6
+ error: string | null;
7
+ makeRequest: (url: string, method?: string, requestData?: any) => void;
8
+ cancelRequest: () => void;
9
+ }
10
+ interface UseAxiosConfig extends AxiosRequestConfig {
11
+ baseURL?: string;
12
+ headers?: {
13
+ [key: string]: string;
14
+ };
15
+ }
16
+ export declare const useAxios: <T>(config?: UseAxiosConfig) => UseAxiosResponse<T>;
17
+ export declare const useDrawer: () => import("../contexts/chunk158261").DrawerContextValue;
18
+ export declare const useAdvReducer: <State, Action extends {
19
+ type: string;
20
+ }>(initialState: State, actions: Record<string, (state: State, action: Action) => State>) => (state: State | undefined, action: Action) => State;
21
+ interface FetchState<T> {
22
+ data: T | null;
23
+ loading: boolean;
24
+ error: string | null;
25
+ }
26
+ export declare function useFetch<T>(url: string): FetchState<T>;
27
+ export declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void];
28
+ export declare function useToggle(initialValue?: boolean): [boolean, () => void];
29
+ export declare function useDebounce<T>(value: T, delay: number): T;
30
+ export declare function useThrottle<T>(value: T, limit: number): T;
31
+ export declare function usePrevious<T>(value: T): T | undefined;
32
+ export declare function useMediaQuery(query: string): boolean;
33
+ export declare function useClipboard(): [boolean, (text: string) => Promise<void>];
34
+ export declare function useInterval(callback: () => void, delay: number | null): void;
35
+ interface WindowSize {
36
+ width: number;
37
+ height: number;
38
+ }
39
+ export declare function useWindowSize(): WindowSize;
40
+ export declare function useKeyPress(targetKey: string): boolean;
41
+ export declare function useOnlineStatus(): boolean;
42
+ interface ScrollPosition {
43
+ x: number;
44
+ y: number;
45
+ }
46
+ export declare function useScrollPosition(): ScrollPosition;
47
+ export declare function useTimeout(callback: () => void, delay: number | null): void;
48
+ export declare function useDarkMode(): [boolean, () => void];
49
+ export declare function useForm<T extends Record<string, any>>(initialValues: T): {
50
+ values: T;
51
+ errors: Partial<Record<keyof T, string>>;
52
+ handleChange: (name: keyof T, value: any) => void;
53
+ validate: (validators: Partial<Record<keyof T, (value: any) => string | null>>) => boolean;
54
+ };
55
+ export declare function useArray<T>(initialArray: T[]): {
56
+ array: T[];
57
+ set: import("react").Dispatch<import("react").SetStateAction<T[]>>;
58
+ push: (item: T) => void;
59
+ removeByIndex: (index: number) => void;
60
+ clear: () => void;
61
+ };
62
+ export declare const useStepper: (totalSteps: number) => {
63
+ activeStep: number;
64
+ handleNext: () => void;
65
+ handleBack: () => void;
66
+ handleReset: () => void;
67
+ totalSteps: number;
68
+ isFirstStep: boolean;
69
+ isLastStep: boolean;
70
+ isProccesing: boolean;
71
+ setIsProccesing: import("react").Dispatch<import("react").SetStateAction<boolean>>;
72
+ };
73
+ export declare function useTimeoutFn(callback: () => void, delay: number | null): {
74
+ reset: () => void;
75
+ clear: () => void;
76
+ };
77
+ export declare function useDebouncedCallback(callback: () => void, delay: number): () => void;
78
+ export declare function useScrollLock(lock: boolean): void;
79
+ export declare function useResizeObserver<T extends HTMLElement>(ref: RefObject<T>): WindowSize | null;
80
+ interface MousePosition {
81
+ x: number;
82
+ y: number;
83
+ }
84
+ export declare function useMousePosition(): MousePosition;
85
+ type ScrollDirection = 'up' | 'down';
86
+ export declare function useScrollDirection(): ScrollDirection;
87
+ export declare function useImageLoader(src: string): {
88
+ loaded: boolean;
89
+ error: boolean;
90
+ };
91
+ export declare function usePersistedState<T>(key: string, initialValue: T): [T, React.Dispatch<React.SetStateAction<T>>];
92
+ export declare function useReducedMotion(): boolean;
93
+ export declare function useCookie(key: string): [string | null, (value: string, options?: any) => void, () => void];
94
+ export declare function useFetchRetry<T>(url: string, options: RequestInit, retries?: number): {
95
+ data: T | null;
96
+ error: string | null;
97
+ loading: boolean;
98
+ };
99
+ export declare function useDelay<T>(value: T, delay: number): T;
100
+ export declare function useVisibilityChange(): boolean;
101
+ export declare function useDebouncedValue<T>(value: T, delay: number): T;
102
+ export type Status = 'idle' | 'pending' | 'success' | 'error';
103
+ export type AsyncFunction<T> = () => Promise<T>;
104
+ export interface UseAsyncReturn<T> {
105
+ execute: () => void;
106
+ status: Status;
107
+ value: T | null;
108
+ error: Error | null;
109
+ }
110
+ export declare function useAsync<T>(asyncFunction: AsyncFunction<T>, immediate?: boolean): UseAsyncReturn<T>;
111
+ export type ScriptStatus = 'loading' | 'ready' | 'error' | 'unknown';
112
+ export declare function useScript(src: string, removeOnUnmount?: boolean): ScriptStatus;
113
+ export declare function useIndexedDB<T>(dbName: string, storeName: string): {
114
+ data: T | null;
115
+ error: Error | null;
116
+ };
117
+ export declare function useGeoLocation(): {
118
+ position: GeolocationPosition | null;
119
+ error: Error | null;
120
+ };
121
+ export declare function useTimer(initialTime: number): {
122
+ time: number;
123
+ error: Error | null;
124
+ };
125
+ export declare function useIsMounted(): boolean;
126
+ export declare function useCss(css: string): {
127
+ error: Error | null;
128
+ };
129
+ export declare function useSpeak(text: string): {
130
+ speak: () => void;
131
+ error: Error | null;
132
+ };
133
+ export declare function useCountUp(target: number, duration: number): {
134
+ count: number;
135
+ error: Error | null;
136
+ };
137
+ export declare function useCountDown(start: number): {
138
+ count: number;
139
+ error: Error | null;
140
+ };
141
+ interface BatteryState {
142
+ supported: boolean;
143
+ loading: boolean;
144
+ level: number | null;
145
+ charging: boolean | null;
146
+ chargingTime: number | null;
147
+ dischargingTime: number | null;
148
+ }
149
+ export declare const useBattery: () => BatteryState;
150
+ export declare const useEventListener: (eventName: string, handler: (event: Event) => void, elementRef?: React.RefObject<HTMLElement>, options?: boolean | AddEventListenerOptions) => void;
151
+ interface HistoryState {
152
+ [key: string]: any;
153
+ }
154
+ interface UseHistory {
155
+ history: History;
156
+ state: HistoryState | null;
157
+ push: (path: string, state?: HistoryState) => void;
158
+ replace: (path: string, state?: HistoryState) => void;
159
+ goBack: () => void;
160
+ goForward: () => void;
161
+ }
162
+ export declare const useHistory: () => UseHistory;
163
+ interface UsePreferredLanguage {
164
+ language: string;
165
+ languages: Array<string>;
166
+ isSupported: boolean;
167
+ }
168
+ export declare const usePreferredLanguage: () => UsePreferredLanguage;
169
+ interface UseSessionStorage<T> {
170
+ (key: string, initialValue: T): [T, (value: T) => void];
171
+ }
172
+ export declare const useSessionStorage: UseSessionStorage<any>;
173
+ interface UseSound {
174
+ play: () => void;
175
+ pause: () => void;
176
+ stop: () => void;
177
+ setVolume: (volume: number) => void;
178
+ isPlaying: boolean;
179
+ error: Error | null;
180
+ }
181
+ export declare const useSound: (url: string) => UseSound;
182
+ interface TouchPosition {
183
+ x: number | null;
184
+ y: number | null;
185
+ }
186
+ interface UseTouch {
187
+ (elementRef: React.RefObject<HTMLElement>): {
188
+ touchStart: TouchPosition;
189
+ touchMove: TouchPosition;
190
+ touchEnd: TouchPosition;
191
+ };
192
+ }
193
+ export declare const useTouch: UseTouch;
194
+ export declare const useUpdateEffect: (effect: React.EffectCallback, deps: React.DependencyList) => void;
195
+ export declare const usePersistedForm: <T>(key: string, initialValue: T) => [T, (value: T) => void];
196
+ export declare const useCrossFieldValidation: <T extends Record<string, any>>(validate: (values: T) => Record<keyof T, string | null>) => {
197
+ errors: Record<keyof T, string | null>;
198
+ validateFields: (values: T) => boolean;
199
+ };
200
+ export declare const useFieldArray: <T>(initialValue: T[]) => {
201
+ fields: T[];
202
+ append: (item: T) => void;
203
+ remove: (index: number) => void;
204
+ update: (index: number, item: T) => void;
205
+ };
206
+ type SubmitHandler<T> = (data: T) => Promise<void>;
207
+ export declare const useFormSubmit: <T>(handler: SubmitHandler<T>) => {
208
+ handleSubmit: (data: T) => Promise<void>;
209
+ isSubmitting: boolean;
210
+ submitError: string | null;
211
+ };
212
+ export declare const useSmartForm: <T extends Record<string, any>>(initialValues: T, storageKey?: string) => {
213
+ values: T;
214
+ handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
215
+ setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
216
+ dirty: boolean;
217
+ };
218
+ export declare const useUndo: <T>(initialState: T) => {
219
+ state: T;
220
+ setState: (newState: T) => void;
221
+ undo: () => false | void;
222
+ redo: () => false | void;
223
+ canUndo: boolean;
224
+ canRedo: boolean;
225
+ };
226
+ export declare const useFormWizard: <T extends Record<string, any>>(steps: {
227
+ validate?: (values: T) => Record<string, string>;
228
+ component: React.FC<{
229
+ values: T;
230
+ setValues: (v: T) => void;
231
+ }>;
232
+ }[], initialValues: T) => {
233
+ currentStep: number;
234
+ CurrentStep: import("react").FC<{
235
+ values: T;
236
+ setValues: (v: T) => void;
237
+ }>;
238
+ values: T;
239
+ setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
240
+ next: () => void;
241
+ prev: () => void;
242
+ errors: Record<string, string>;
243
+ isFirstStep: boolean;
244
+ isLastStep: boolean;
245
+ };
246
+ export declare const createOptimizedContext: <T>() => readonly [import("react").Provider<T | undefined>, <U>(selector: (value: T) => U) => U];
247
+ export declare const useWebSocket: <T>(url: string, onMessage?: (data: T) => void) => {
248
+ data: T | null;
249
+ send: (message: any) => void;
250
+ isConnected: boolean;
251
+ };
252
+ export declare const useDragReorder: <T>(initialItems: T[]) => {
253
+ items: T[];
254
+ handleDragStart: (index: number) => void;
255
+ handleDragEnter: (index: number) => void;
256
+ handleDrop: () => void;
257
+ };
258
+ export declare const useInfiniteScroll: <T>(fetchData: (page: number) => Promise<T[]>, initialData?: T[]) => {
259
+ data: T[];
260
+ loading: boolean;
261
+ hasMore: boolean;
262
+ lastElementRef: (node: HTMLElement | null) => void;
263
+ };
264
+ export declare const useEventListeners: (eventType: string, handler: (event: Event) => void, element?: HTMLElement | Window, options?: AddEventListenerOptions) => void;
265
+ export {};