hookery 1.0.0 → 1.0.1

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.
Files changed (98) hide show
  1. package/README.md +28 -26
  2. package/dist/index.d.ts +147 -1
  3. package/dist/index.js +10 -4304
  4. package/dist/index.mjs +10 -4164
  5. package/package.json +10 -81
  6. package/dist/bridges/auth0.d.mts +0 -16
  7. package/dist/bridges/auth0.d.ts +0 -16
  8. package/dist/bridges/auth0.js +0 -3015
  9. package/dist/bridges/auth0.js.map +0 -1
  10. package/dist/bridges/auth0.mjs +0 -2977
  11. package/dist/bridges/auth0.mjs.map +0 -1
  12. package/dist/bridges/axios.d.mts +0 -17
  13. package/dist/bridges/axios.d.ts +0 -17
  14. package/dist/bridges/axios.js +0 -15351
  15. package/dist/bridges/axios.js.map +0 -1
  16. package/dist/bridges/axios.mjs +0 -15347
  17. package/dist/bridges/axios.mjs.map +0 -1
  18. package/dist/bridges/clerk.d.mts +0 -1
  19. package/dist/bridges/clerk.d.ts +0 -1
  20. package/dist/bridges/clerk.js +0 -5991
  21. package/dist/bridges/clerk.js.map +0 -1
  22. package/dist/bridges/clerk.mjs +0 -5985
  23. package/dist/bridges/clerk.mjs.map +0 -1
  24. package/dist/bridges/firebase.d.mts +0 -14
  25. package/dist/bridges/firebase.d.ts +0 -14
  26. package/dist/bridges/firebase.js +0 -52
  27. package/dist/bridges/firebase.js.map +0 -1
  28. package/dist/bridges/firebase.mjs +0 -25
  29. package/dist/bridges/firebase.mjs.map +0 -1
  30. package/dist/bridges/jotai.d.mts +0 -11
  31. package/dist/bridges/jotai.d.ts +0 -11
  32. package/dist/bridges/jotai.js +0 -870
  33. package/dist/bridges/jotai.js.map +0 -1
  34. package/dist/bridges/jotai.mjs +0 -827
  35. package/dist/bridges/jotai.mjs.map +0 -1
  36. package/dist/bridges/motion.d.mts +0 -6
  37. package/dist/bridges/motion.d.ts +0 -6
  38. package/dist/bridges/motion.js +0 -3752
  39. package/dist/bridges/motion.js.map +0 -1
  40. package/dist/bridges/motion.mjs +0 -3721
  41. package/dist/bridges/motion.mjs.map +0 -1
  42. package/dist/bridges/next.d.mts +0 -10
  43. package/dist/bridges/next.d.ts +0 -10
  44. package/dist/bridges/next.js +0 -2588
  45. package/dist/bridges/next.js.map +0 -1
  46. package/dist/bridges/next.mjs +0 -2582
  47. package/dist/bridges/next.mjs.map +0 -1
  48. package/dist/bridges/redux.d.mts +0 -15
  49. package/dist/bridges/redux.d.ts +0 -15
  50. package/dist/bridges/redux.js +0 -410
  51. package/dist/bridges/redux.js.map +0 -1
  52. package/dist/bridges/redux.mjs +0 -402
  53. package/dist/bridges/redux.mjs.map +0 -1
  54. package/dist/bridges/remix.d.mts +0 -1
  55. package/dist/bridges/remix.d.ts +0 -1
  56. package/dist/bridges/remix.js +0 -2215
  57. package/dist/bridges/remix.js.map +0 -1
  58. package/dist/bridges/remix.mjs +0 -2174
  59. package/dist/bridges/remix.mjs.map +0 -1
  60. package/dist/bridges/stripe.d.mts +0 -15
  61. package/dist/bridges/stripe.d.ts +0 -15
  62. package/dist/bridges/stripe.js +0 -1572
  63. package/dist/bridges/stripe.js.map +0 -1
  64. package/dist/bridges/stripe.mjs +0 -1556
  65. package/dist/bridges/stripe.mjs.map +0 -1
  66. package/dist/bridges/supabase.d.mts +0 -13
  67. package/dist/bridges/supabase.d.ts +0 -13
  68. package/dist/bridges/supabase.js +0 -51
  69. package/dist/bridges/supabase.js.map +0 -1
  70. package/dist/bridges/supabase.mjs +0 -24
  71. package/dist/bridges/supabase.mjs.map +0 -1
  72. package/dist/bridges/tanstack.d.mts +0 -3
  73. package/dist/bridges/tanstack.d.ts +0 -3
  74. package/dist/bridges/tanstack.js +0 -1319
  75. package/dist/bridges/tanstack.js.map +0 -1
  76. package/dist/bridges/tanstack.mjs +0 -1281
  77. package/dist/bridges/tanstack.mjs.map +0 -1
  78. package/dist/bridges/yup.d.mts +0 -16
  79. package/dist/bridges/yup.d.ts +0 -16
  80. package/dist/bridges/yup.js +0 -80
  81. package/dist/bridges/yup.js.map +0 -1
  82. package/dist/bridges/yup.mjs +0 -43
  83. package/dist/bridges/yup.mjs.map +0 -1
  84. package/dist/bridges/zod.d.mts +0 -19
  85. package/dist/bridges/zod.d.ts +0 -19
  86. package/dist/bridges/zod.js +0 -66
  87. package/dist/bridges/zod.js.map +0 -1
  88. package/dist/bridges/zod.mjs +0 -39
  89. package/dist/bridges/zod.mjs.map +0 -1
  90. package/dist/bridges/zustand.d.mts +0 -14
  91. package/dist/bridges/zustand.d.ts +0 -14
  92. package/dist/bridges/zustand.js +0 -58
  93. package/dist/bridges/zustand.js.map +0 -1
  94. package/dist/bridges/zustand.mjs +0 -21
  95. package/dist/bridges/zustand.mjs.map +0 -1
  96. package/dist/index.d.mts +0 -3130
  97. package/dist/index.js.map +0 -1
  98. package/dist/index.mjs.map +0 -1
package/dist/index.d.mts DELETED
@@ -1,3130 +0,0 @@
1
- import * as react from 'react';
2
- import { useEffect, EffectCallback, DependencyList, RefObject, UIEvent, MutableRefObject, FormEvent } from 'react';
3
- import { AnimationConfig, AnimationItem } from 'lottie-web';
4
- import * as THREE from 'three';
5
-
6
- /**
7
- * useIsomorphicLayoutEffect
8
- *
9
- * SSR-safe version of useLayoutEffect.
10
- * Uses useEffect on the server and useLayoutEffect in the browser.
11
- *
12
- * @example
13
- * ```tsx
14
- * useIsomorphicLayoutEffect(() => {
15
- * // DOM measurements or mutations
16
- * }, [dependency]);
17
- * ```
18
- */
19
- declare const useIsomorphicLayoutEffect: typeof useEffect;
20
-
21
- interface UseToggleOptions {
22
- /** Initial value for the toggle (default: false) */
23
- initialValue?: boolean;
24
- }
25
- interface UseToggleReturn {
26
- /** Current toggle value */
27
- value: boolean;
28
- /** Toggle the value */
29
- toggle: () => void;
30
- /** Set value to true */
31
- setTrue: () => void;
32
- /** Set value to false */
33
- setFalse: () => void;
34
- /** Set to specific value */
35
- setValue: (value: boolean) => void;
36
- }
37
- /**
38
- * useToggle
39
- *
40
- * A simple hook for managing boolean state with stable action handlers.
41
- *
42
- * @param options - Configuration options
43
- * @returns Object with value and control functions
44
- *
45
- * @example
46
- * ```tsx
47
- * const { value, toggle, setTrue, setFalse } = useToggle();
48
- *
49
- * return (
50
- * <div>
51
- * <p>Value: {value ? 'ON' : 'OFF'}</p>
52
- * <button onClick={toggle}>Toggle</button>
53
- * <button onClick={setTrue}>Set ON</button>
54
- * <button onClick={setFalse}>Set OFF</button>
55
- * </div>
56
- * );
57
- * ```
58
- */
59
- declare function useToggle(options?: UseToggleOptions): UseToggleReturn;
60
-
61
- interface UseCounterOptions {
62
- /** Initial value (default: 0) */
63
- initialValue?: number;
64
- /** Minimum value (optional) */
65
- min?: number;
66
- /** Maximum value (optional) */
67
- max?: number;
68
- /** Step value for increment/decrement (default: 1) */
69
- step?: number;
70
- }
71
- interface UseCounterReturn {
72
- /** Current count value */
73
- count: number;
74
- /** Increment by step */
75
- increment: () => void;
76
- /** Decrement by step */
77
- decrement: () => void;
78
- /** Reset to initial value */
79
- reset: () => void;
80
- /** Set to specific value */
81
- set: (value: number) => void;
82
- }
83
- /**
84
- * useCounter
85
- *
86
- * A hook for managing numeric state with increment, decrement, and bounds.
87
- *
88
- * @param options - Configuration options
89
- * @returns Object with count value and control functions
90
- *
91
- * @example
92
- * ```tsx
93
- * const { count, increment, decrement, reset } = useCounter({
94
- * initialValue: 0,
95
- * min: 0,
96
- * max: 10,
97
- * step: 1,
98
- * });
99
- *
100
- * return (
101
- * <div>
102
- * <p>Count: {count}</p>
103
- * <button onClick={decrement}>-</button>
104
- * <button onClick={increment}>+</button>
105
- * <button onClick={reset}>Reset</button>
106
- * </div>
107
- * );
108
- * ```
109
- */
110
- declare function useCounter(options?: UseCounterOptions): UseCounterReturn;
111
-
112
- /**
113
- * usePrevious
114
- *
115
- * A hook that returns the previous value of a state or prop.
116
- *
117
- * @param value - The value to track
118
- * @returns The previous value (undefined on first render)
119
- *
120
- * @example
121
- * ```tsx
122
- * const [count, setCount] = useState(0);
123
- * const previousCount = usePrevious(count);
124
- *
125
- * console.log(`Current: ${count}, Previous: ${previousCount}`);
126
- * ```
127
- */
128
- declare function usePrevious<T>(value: T): T | undefined;
129
-
130
- /**
131
- * useMount
132
- *
133
- * A hook that runs a callback once when the component mounts.
134
- * Works correctly with React Strict Mode.
135
- *
136
- * @param callback - Function to run on mount
137
- *
138
- * @example
139
- * ```tsx
140
- * useMount(() => {
141
- * console.log('Component mounted!');
142
- * // Initialize analytics, fetch initial data, etc.
143
- * });
144
- * ```
145
- */
146
- declare function useMount(callback: () => void | (() => void)): void;
147
-
148
- /**
149
- * useUnmount
150
- *
151
- * A hook that runs a callback when the component unmounts.
152
- * Always uses the latest callback reference.
153
- *
154
- * @param callback - Function to run on unmount
155
- *
156
- * @example
157
- * ```tsx
158
- * useUnmount(() => {
159
- * console.log('Component unmounted!');
160
- * // Cleanup subscriptions, cancel requests, etc.
161
- * });
162
- * ```
163
- */
164
- declare function useUnmount(callback: () => void): void;
165
-
166
- interface UseDebounceOptions {
167
- /** Delay in milliseconds (default: 500) */
168
- delay?: number;
169
- /** Maximum wait time in milliseconds (optional) */
170
- maxWait?: number;
171
- /** Leading edge execution (default: false) */
172
- leading?: boolean;
173
- /** Trailing edge execution (default: true) */
174
- trailing?: boolean;
175
- }
176
- interface UseDebounceReturn<T> {
177
- /** The debounced value */
178
- debouncedValue: T;
179
- /** Whether currently in debounce period */
180
- isPending: boolean;
181
- /** Cancel pending debounce */
182
- cancel: () => void;
183
- /** Flush debounced value immediately */
184
- flush: () => void;
185
- }
186
- /**
187
- * useDebounce
188
- *
189
- * A hook that debounces a value, delaying updates until after a specified delay.
190
- *
191
- * @param value - The value to debounce
192
- * @param options - Configuration options
193
- * @returns Object with debounced value and control functions
194
- *
195
- * @example
196
- * ```tsx
197
- * const [searchTerm, setSearchTerm] = useState('');
198
- * const { debouncedValue } = useDebounce(searchTerm, { delay: 300 });
199
- *
200
- * useEffect(() => {
201
- * // API call with debounced value
202
- * fetchResults(debouncedValue);
203
- * }, [debouncedValue]);
204
- * ```
205
- */
206
- declare function useDebounce<T>(value: T, options?: UseDebounceOptions): UseDebounceReturn<T>;
207
-
208
- interface UseThrottleOptions {
209
- /** Throttle interval in milliseconds (default: 500) */
210
- interval?: number;
211
- /** Execute on leading edge (default: true) */
212
- leading?: boolean;
213
- /** Execute on trailing edge (default: true) */
214
- trailing?: boolean;
215
- }
216
- interface UseThrottleReturn<T> {
217
- /** The throttled value */
218
- throttledValue: T;
219
- /** Whether currently in throttle period */
220
- isPending: boolean;
221
- }
222
- /**
223
- * useThrottle
224
- *
225
- * A hook that throttles a value, limiting how often it can update.
226
- *
227
- * @param value - The value to throttle
228
- * @param options - Configuration options
229
- * @returns Object with throttled value and pending state
230
- *
231
- * @example
232
- * ```tsx
233
- * const [scrollY, setScrollY] = useState(0);
234
- * const { throttledValue } = useThrottle(scrollY, { interval: 100 });
235
- *
236
- * useEffect(() => {
237
- * // Update UI with throttled scroll position
238
- * updateScrollIndicator(throttledValue);
239
- * }, [throttledValue]);
240
- * ```
241
- */
242
- declare function useThrottle<T>(value: T, options?: UseThrottleOptions): UseThrottleReturn<T>;
243
-
244
- interface UseLocalStorageOptions<T> {
245
- /** Serializer function (default: JSON.stringify) */
246
- serializer?: (value: T) => string;
247
- /** Deserializer function (default: JSON.parse) */
248
- deserializer?: (value: string) => T;
249
- /** Sync across tabs (default: true) */
250
- syncAcrossTabs?: boolean;
251
- }
252
- interface UseLocalStorageReturn<T> {
253
- /** Current stored value */
254
- value: T;
255
- /** Set the value */
256
- setValue: (value: T | ((prev: T) => T)) => void;
257
- /** Remove the value from storage */
258
- remove: () => void;
259
- /** Check if value exists in storage */
260
- exists: boolean;
261
- }
262
- /**
263
- * useLocalStorage
264
- *
265
- * A hook for persisting state in localStorage with SSR support and cross-tab sync.
266
- *
267
- * @param key - Storage key
268
- * @param initialValue - Default value if key doesn't exist
269
- * @param options - Configuration options
270
- * @returns Object with value and control functions
271
- *
272
- * @example
273
- * ```tsx
274
- * interface AppSettings {
275
- * theme: 'dark' | 'light';
276
- * notifications: boolean;
277
- * }
278
- *
279
- * // Default settings
280
- * const defaults: AppSettings = { theme: 'light', notifications: true };
281
- *
282
- * export function SettingsPanel() {
283
- * const {
284
- * value: settings,
285
- * setValue: setSettings,
286
- * remove,
287
- * exists
288
- * } = useLocalStorage<AppSettings>('app-settings', defaults);
289
- *
290
- * const toggleTheme = () => {
291
- * setSettings(prev => ({
292
- * ...prev,
293
- * theme: prev.theme === 'dark' ? 'light' : 'dark'
294
- * }));
295
- * };
296
- *
297
- * return (
298
- * <div className={`panel ${settings.theme}`}>
299
- * <h2>Settings {exists ? '(Saved)' : '(Default)'}</h2>
300
- *
301
- * <div className="option">
302
- * <label>Theme: {settings.theme}</label>
303
- * <button onClick={toggleTheme}>Toggle Theme</button>
304
- * </div>
305
- *
306
- * <div className="option">
307
- * <label>
308
- * <input
309
- * type="checkbox"
310
- * checked={settings.notifications}
311
- * onChange={e => setSettings(p => ({ ...p, notifications: e.target.checked }))}
312
- * />
313
- * Enable Notifications
314
- * </label>
315
- * </div>
316
- *
317
- * <button onClick={remove} className="danger">
318
- * Reset to Defaults
319
- * </button>
320
- * </div>
321
- * );
322
- * }
323
- * ```
324
- */
325
- declare function useLocalStorage<T>(key: string, initialValue: T, options?: UseLocalStorageOptions<T>): UseLocalStorageReturn<T>;
326
-
327
- interface UseSessionStorageOptions<T> {
328
- /** Serializer function (default: JSON.stringify) */
329
- serializer?: (value: T) => string;
330
- /** Deserializer function (default: JSON.parse) */
331
- deserializer?: (value: string) => T;
332
- /** Initialize even if key exists (default: false) */
333
- initializeWithValue?: boolean;
334
- }
335
- /**
336
- * useSessionStorage
337
- *
338
- * A hook for managing state in sessionStorage.
339
- * Clears when the page session ends (tab close).
340
- *
341
- * @param key - Storage key
342
- * @param initialValue - Initial value
343
- * @param options - Configuration options
344
- * @returns [value, setValue, removeValue]
345
- *
346
- * @example
347
- * ```tsx
348
- * interface FormData {
349
- * step: number;
350
- * data: Record<string, any>;
351
- * }
352
- *
353
- * const initialForm: FormData = { step: 1, data: {} };
354
- *
355
- * export function MultiStepForm() {
356
- * // Persist form state even if user refreshes, but clear on close
357
- * const [formState, setFormState, clearSession] = useSessionStorage<FormData>(
358
- * 'registration_form',
359
- * initialForm
360
- * );
361
- *
362
- * const nextStep = (newData: any) => {
363
- * setFormState(prev => ({
364
- * step: prev.step + 1,
365
- * data: { ...prev.data, ...newData }
366
- * }));
367
- * };
368
- *
369
- * return (
370
- * <div>
371
- * <h1>Step {formState.step}</h1>
372
- * <FormStep
373
- * step={formState.step}
374
- * onSubmit={nextStep}
375
- * />
376
- *
377
- * <button onClick={clearSession}>
378
- * Cancel & Clear Session
379
- * </button>
380
- * </div>
381
- * );
382
- * }
383
- * ```
384
- */
385
- declare function useSessionStorage<T>(key: string, initialValue: T | (() => T), options?: UseSessionStorageOptions<T>): [T, (value: T | ((val: T) => T)) => void, () => void];
386
-
387
- interface UseTimeoutOptions {
388
- /** Delay in milliseconds */
389
- delay: number;
390
- /** Auto-start the timeout (default: true) */
391
- autoStart?: boolean;
392
- }
393
- interface UseTimeoutReturn {
394
- /** Whether the timeout is currently running */
395
- isRunning: boolean;
396
- /** Whether the timeout has completed */
397
- isComplete: boolean;
398
- /** Start or restart the timeout */
399
- start: () => void;
400
- /** Stop/cancel the timeout */
401
- stop: () => void;
402
- /** Reset the timeout to initial state */
403
- reset: () => void;
404
- }
405
- /**
406
- * useTimeout
407
- *
408
- * A declarative hook for managing timeouts.
409
- *
410
- * @param callback - Function to call when timeout completes
411
- * @param options - Configuration options
412
- * @returns Object with timeout state and control functions
413
- *
414
- * @example
415
- * ```tsx
416
- * const { isRunning, start, stop } = useTimeout(
417
- * () => console.log('Timeout completed!'),
418
- * { delay: 3000 }
419
- * );
420
- *
421
- * return (
422
- * <div>
423
- * <p>Status: {isRunning ? 'Running' : 'Stopped'}</p>
424
- * <button onClick={start}>Start</button>
425
- * <button onClick={stop}>Stop</button>
426
- * </div>
427
- * );
428
- * ```
429
- */
430
- declare function useTimeout(callback: () => void, options: UseTimeoutOptions): UseTimeoutReturn;
431
-
432
- interface UseIntervalOptions {
433
- /** Interval delay in milliseconds */
434
- delay: number;
435
- /** Auto-start the interval (default: true) */
436
- autoStart?: boolean;
437
- /** Execute callback immediately on start (default: false) */
438
- immediate?: boolean;
439
- }
440
- interface UseIntervalReturn {
441
- /** Whether the interval is currently running */
442
- isRunning: boolean;
443
- /** Number of times the callback has been called */
444
- count: number;
445
- /** Start the interval */
446
- start: () => void;
447
- /** Stop/pause the interval */
448
- stop: () => void;
449
- /** Reset count to 0 */
450
- reset: () => void;
451
- }
452
- /**
453
- * useInterval
454
- *
455
- * A declarative hook for managing intervals.
456
- *
457
- * @param callback - Function to call on each interval tick
458
- * @param options - Configuration options
459
- * @returns Object with interval state and control functions
460
- *
461
- * @example
462
- * ```tsx
463
- * const { count, isRunning, start, stop } = useInterval(
464
- * () => console.log('Tick!'),
465
- * { delay: 1000 }
466
- * );
467
- *
468
- * return (
469
- * <div>
470
- * <p>Count: {count}</p>
471
- * <button onClick={isRunning ? stop : start}>
472
- * {isRunning ? 'Stop' : 'Start'}
473
- * </button>
474
- * </div>
475
- * );
476
- * ```
477
- */
478
- declare function useInterval(callback: () => void, options: UseIntervalOptions): UseIntervalReturn;
479
-
480
- /**
481
- * useUpdateEffect
482
- *
483
- * A hook that works like useEffect but skips the first render.
484
- * Useful when you only want to run an effect on updates, not on mount.
485
- *
486
- * @param effect - Effect callback (same as useEffect)
487
- * @param deps - Dependency array (same as useEffect)
488
- *
489
- * @example
490
- * ```tsx
491
- * const [count, setCount] = useState(0);
492
- *
493
- * useUpdateEffect(() => {
494
- * console.log('Count updated to:', count);
495
- * // This won't run on initial mount, only on updates
496
- * }, [count]);
497
- * ```
498
- */
499
- declare function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
500
-
501
- /**
502
- * useIsMounted
503
- *
504
- * A hook that returns a function to check if the component is still mounted.
505
- * Useful for preventing state updates on unmounted components in async operations.
506
- *
507
- * @returns Function that returns true if component is mounted
508
- *
509
- * @example
510
- * ```tsx
511
- * const isMounted = useIsMounted();
512
- *
513
- * useEffect(() => {
514
- * fetchData().then((data) => {
515
- * if (isMounted()) {
516
- * setData(data); // Safe - only updates if mounted
517
- * }
518
- * });
519
- * }, []);
520
- * ```
521
- */
522
- declare function useIsMounted(): () => boolean;
523
-
524
- /**
525
- * useStableCallback
526
- *
527
- * Creates a callback function that maintains a stable reference identity
528
- * while accessing the latest props/state. Useful for avoiding
529
- * unnecessary effect re-executions.
530
- *
531
- * @param callback - The function to stabilize
532
- * @returns A stable callback function
533
- *
534
- * @example
535
- * ```tsx
536
- * const stableLog = useStableCallback(() => {
537
- * console.log(count); // Alway access latest count
538
- * });
539
- *
540
- * // stableLog identity never changes, safe to use in useEffect deps
541
- * useEffect(() => {
542
- * stableLog();
543
- * }, [stableLog]);
544
- * ```
545
- */
546
- declare function useStableCallback<T extends (...args: any[]) => any>(callback: T): T;
547
-
548
- interface UseMediaQueryOptions {
549
- /** Default value for SSR (default: false) */
550
- defaultValue?: boolean;
551
- /** Initialize on mount only (default: false) */
552
- initializeOnMount?: boolean;
553
- }
554
- /**
555
- * useMediaQuery
556
- *
557
- * A hook that tracks the state of a CSS media query.
558
- * Supports SSR with default values and hydration mismatch prevention.
559
- *
560
- * @param query - CSS media query string
561
- * @param options - Configuration options
562
- * @returns Whether the media query matches
563
- *
564
- * @example
565
- * ```tsx
566
- * // Basic Mobile Detection
567
- * const isMobile = useMediaQuery('(max-width: 768px)');
568
- *
569
- * // Advanced Usage with SSR support
570
- * const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)', {
571
- * defaultValue: false, // Default value during server rendering
572
- * initializeOnMount: true // Prevent hydration mismatch by initializing on mount
573
- * });
574
- *
575
- * return (
576
- * <div style={{ background: isDarkMode ? '#333' : '#FFF' }}>
577
- * <h1>{isMobile ? 'Mobile View' : 'Desktop View'}</h1>
578
- * <p>Current Theme: {isDarkMode ? 'Dark' : 'Light'}</p>
579
- * </div>
580
- * );
581
- * ```
582
- */
583
- declare function useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean;
584
-
585
- interface WindowSize {
586
- /** Window inner width */
587
- width: number;
588
- /** Window inner height */
589
- height: number;
590
- }
591
- interface UseWindowSizeOptions {
592
- /** Debounce delay in ms (default: 0) */
593
- debounce?: number;
594
- /** Initial width for SSR (default: 0) */
595
- initialWidth?: number;
596
- /** Initial height for SSR (default: 0) */
597
- initialHeight?: number;
598
- }
599
- /**
600
- * useWindowSize
601
- *
602
- * A hook that tracks the browser window dimensions.
603
- * Handles debouncing to avoid performance issues during resize.
604
- *
605
- * @param options - Configuration options
606
- * @returns Object with width and height
607
- *
608
- * @example
609
- * ```tsx
610
- * const { width, height } = useWindowSize({
611
- * debounce: 100, // Wait 100ms after resize stops
612
- * initialWidth: 1920, // Predictable server-side width
613
- * initialHeight: 1080
614
- * });
615
- *
616
- * const isLandscape = width > height;
617
- *
618
- * return (
619
- * <div>
620
- * <h2>Viewport Info</h2>
621
- * <p>Dimensions: {width}px x {height}px</p>
622
- * <p>Orientation: {isLandscape ? 'Landscape' : 'Portrait'}</p>
623
- *
624
- * {width < 768 && (
625
- * <div className="mobile-warning">
626
- * Optimized for Desktop
627
- * </div>
628
- * )}
629
- * </div>
630
- * );
631
- * ```
632
- */
633
- declare function useWindowSize(options?: UseWindowSizeOptions): WindowSize;
634
-
635
- interface UseClickOutsideOptions {
636
- /** Events to listen for (default: ['mousedown', 'touchstart']) */
637
- events?: Array<'mousedown' | 'mouseup' | 'touchstart' | 'touchend'>;
638
- /** Whether the listener is active (default: true) */
639
- enabled?: boolean;
640
- }
641
- /**
642
- * useClickOutside
643
- *
644
- * A hook that detects clicks outside of a referenced element.
645
- * Useful for closing modals, dropdowns, or popovers.
646
- *
647
- * @param ref - React ref to the element to monitor
648
- * @param callback - Function to call when clicking outside
649
- * @param options - Configuration options
650
- *
651
- * @example
652
- * ```tsx
653
- * const [isOpen, setIsOpen] = useState(false);
654
- * const menuRef = useRef<HTMLDivElement>(null);
655
- *
656
- * useClickOutside(menuRef, () => {
657
- * console.log('Clicked outside menu, closing...');
658
- * setIsOpen(false);
659
- * }, {
660
- * enabled: isOpen, // Only listen when menu is open (performance)
661
- * events: ['mousedown', 'touchstart'] // Handle touch devices too
662
- * });
663
- *
664
- * return (
665
- * <div className="relative">
666
- * <button onClick={() => setIsOpen(!isOpen)}>Toggle Menu</button>
667
- *
668
- * {isOpen && (
669
- * <div ref={menuRef} className="dropdown-menu">
670
- * <p>Menu Item 1</p>
671
- * <p>Menu Item 2</p>
672
- * </div>
673
- * )}
674
- * </div>
675
- * );
676
- * ```
677
- */
678
- declare function useClickOutside<T extends HTMLElement = HTMLElement>(ref: RefObject<T | null>, callback: (event: MouseEvent | TouchEvent) => void, options?: UseClickOutsideOptions): void;
679
-
680
- interface UseHoverReturn<T extends HTMLElement = HTMLElement> {
681
- /** Whether the element is being hovered */
682
- isHovered: boolean;
683
- /** Ref to attach to the target element */
684
- ref: React.RefCallback<T>;
685
- /** Props to spread on the target element */
686
- hoverProps: {
687
- onMouseEnter: () => void;
688
- onMouseLeave: () => void;
689
- };
690
- }
691
- /**
692
- * useHover
693
- *
694
- * A hook that tracks hover state of an element.
695
- * Provides both a ref-based and prop-based API for flexibility.
696
- *
697
- * @returns Object with hover state, ref, and event handlers
698
- *
699
- * @example
700
- * ```tsx
701
- * // pattern 1: Using Ref (Recommended for access to DOM)
702
- * const { isHovered: isCardHovered, ref: cardRef } = useHover<HTMLDivElement>();
703
- *
704
- * // pattern 2: Using Spread Props (Easier for simpler components)
705
- * const { isHovered: isBtnHovered, hoverProps } = useHover();
706
- *
707
- * return (
708
- * <div>
709
- * <div
710
- * ref={cardRef}
711
- * style={{
712
- * padding: 20,
713
- * background: isCardHovered ? '#eee' : '#fff'
714
- * }}
715
- * >
716
- * {isCardHovered ? 'Card Active!' : 'Hover Card'}
717
- * </div>
718
- *
719
- * <button
720
- * {...hoverProps}
721
- * style={{ opacity: isBtnHovered ? 1 : 0.7 }}
722
- * >
723
- * {isBtnHovered ? 'Click Me!' : 'Button'}
724
- * </button>
725
- * </div>
726
- * );
727
- * ```
728
- */
729
- declare function useHover<T extends HTMLElement = HTMLElement>(): UseHoverReturn<T>;
730
-
731
- interface UseKeyPressOptions {
732
- /** Target element (default: window) */
733
- target?: 'window' | 'document';
734
- /** Event type (default: 'keydown') */
735
- event?: 'keydown' | 'keyup' | 'keypress';
736
- /** Whether to prevent default behavior */
737
- preventDefault?: boolean;
738
- /** Whether the listener is active (default: true) */
739
- enabled?: boolean;
740
- }
741
- /**
742
- * useKeyPress
743
- *
744
- * A hook that tracks whether a specific key is pressed.
745
- *
746
- * @param targetKey - The key to track (e.g., 'Enter', 'Escape', 'a')
747
- * @param callback - Optional callback when key is pressed
748
- * @param options - Configuration options
749
- * @returns Whether the key is currently pressed
750
- *
751
- * @example
752
- * ```tsx
753
- * // Simple usage
754
- * const isEnterPressed = useKeyPress('Enter');
755
- *
756
- * // With callback
757
- * useKeyPress('Escape', () => {
758
- * closeModal();
759
- * });
760
- *
761
- * // With modifiers (check inside callback)
762
- * useKeyPress('s', (event) => {
763
- * if (event.ctrlKey) {
764
- * event.preventDefault();
765
- * saveDocument();
766
- * }
767
- * });
768
- * ```
769
- */
770
- declare function useKeyPress(targetKey: string, callback?: (event: KeyboardEvent) => void, options?: UseKeyPressOptions): boolean;
771
-
772
- interface ScrollPosition {
773
- /** Horizontal scroll position */
774
- x: number;
775
- /** Vertical scroll position */
776
- y: number;
777
- }
778
- interface UseScrollOptions {
779
- /** Throttle delay in ms (default: 0) */
780
- throttle?: number;
781
- }
782
- interface UseScrollReturn extends ScrollPosition {
783
- /** Whether scroll is at the top */
784
- isAtTop: boolean;
785
- /** Whether scroll is at the bottom */
786
- isAtBottom: boolean;
787
- /** Whether scroll is at the left */
788
- isAtLeft: boolean;
789
- /** Whether scroll is at the right */
790
- isAtRight: boolean;
791
- /** Scroll direction */
792
- direction: 'up' | 'down' | 'left' | 'right' | null;
793
- }
794
- /**
795
- * useScroll
796
- *
797
- * A hook that tracks scroll position of window or an element.
798
- * Provides coordinates, direction, and boundary detection (top/bottom/left/right).
799
- *
800
- * @param ref - Optional ref to track element scroll (defaults to window)
801
- * @param options - Configuration options
802
- * @returns Object with scroll position and state
803
- *
804
- * @example
805
- * ```tsx
806
- * // Track window scroll with progress bar
807
- * const { y, direction, isAtTop, isAtBottom } = useScroll();
808
- *
809
- * // Track specific element
810
- * const containerRef = useRef<HTMLDivElement>(null);
811
- * const { x } = useScroll(containerRef, { throttle: 100 });
812
- *
813
- * return (
814
- * <>
815
- * <div className="fixed-header" style={{ opacity: isAtTop ? 1 : 0.8 }}>
816
- * Scrolling: {direction}
817
- * {isAtBottom && <span> (Reached Bottom!)</span>}
818
- * </div>
819
- *
820
- * <div
821
- * ref={containerRef}
822
- * style={{ width: 300, overflowX: 'scroll', whiteSpace: 'nowrap' }}
823
- * >
824
- * {items.map(item => <Item key={item.id} {...item} />)}
825
- * </div>
826
- * </>
827
- * );
828
- * ```
829
- */
830
- declare function useScroll<T extends HTMLElement = HTMLElement>(ref?: RefObject<T | null>, options?: UseScrollOptions): UseScrollReturn;
831
-
832
- interface UseIntersectionOptions {
833
- /** Root element for intersection (default: viewport) */
834
- root?: Element | null;
835
- /** Root margin (default: '0px') */
836
- rootMargin?: string;
837
- /** Threshold(s) for intersection (default: 0) */
838
- threshold?: number | number[];
839
- /** Trigger only once (default: false) */
840
- triggerOnce?: boolean;
841
- /** Whether the observer is active (default: true) */
842
- enabled?: boolean;
843
- }
844
- interface UseIntersectionReturn {
845
- /** Whether the element is intersecting */
846
- isIntersecting: boolean;
847
- /** The intersection entry */
848
- entry: IntersectionObserverEntry | null;
849
- /** Ref to attach to the target element */
850
- ref: RefObject<HTMLElement | null>;
851
- }
852
- /**
853
- * useIntersection
854
- *
855
- * A hook that uses IntersectionObserver to detect element visibility.
856
- * Perfect for lazy loading images, infinite scrolling, or animations.
857
- *
858
- * @param options - Configuration options
859
- * @returns Object with intersection state and ref
860
- *
861
- * @example
862
- * ```tsx
863
- * const { ref, isIntersecting, entry } = useIntersection({
864
- * threshold: 0.5, // Trigger when 50% visible
865
- * triggerOnce: true, // Only trigger once (good for animations)
866
- * rootMargin: '100px' // Pre-load before appearing on screen
867
- * });
868
- *
869
- * return (
870
- * <div
871
- * ref={ref}
872
- * className={`transition-opacity duration-500 ${
873
- * isIntersecting ? 'opacity-100' : 'opacity-0'
874
- * }`}
875
- * >
876
- * {isIntersecting ? (
877
- * <img src="heavy-image.jpg" alt="Lazy loaded" />
878
- * ) : (
879
- * <div className="placeholder" />
880
- * )}
881
- * </div>
882
- * );
883
- * ```
884
- */
885
- declare function useIntersection(options?: UseIntersectionOptions): UseIntersectionReturn;
886
-
887
- interface UseCopyToClipboardReturn {
888
- /** The last copied value */
889
- copiedValue: string | null;
890
- /** Whether the copy was successful */
891
- isSuccess: boolean;
892
- /** Any error that occurred */
893
- error: Error | null;
894
- /** Function to copy text to clipboard */
895
- copy: (text: string) => Promise<boolean>;
896
- /** Reset state */
897
- reset: () => void;
898
- }
899
- /**
900
- * useCopyToClipboard
901
- *
902
- * A hook for copying text to the clipboard.
903
- * Uses modern Clipboard API with fallback for legacy browsers.
904
- *
905
- * @returns Object with copy function and state
906
- *
907
- * @example
908
- * ```tsx
909
- * const { copy, copiedValue, isSuccess, error } = useCopyToClipboard();
910
- *
911
- * const handleCopy = async () => {
912
- * const success = await copy('API_KEY_12345');
913
- * if (success) {
914
- * toast.success('Copied to clipboard!');
915
- * }
916
- * };
917
- *
918
- * return (
919
- * <div className="api-key-box">
920
- * <code>API_KEY_12345</code>
921
- *
922
- * <button onClick={handleCopy} disabled={isSuccess}>
923
- * {isSuccess ? 'Copied!' : 'Copy Key'}
924
- * </button>
925
- *
926
- * {error && <p className="error">Failed to copy: {error.message}</p>}
927
- *
928
- * {isSuccess && (
929
- * <p className="hint">
930
- * Last copied: {copiedValue}
931
- * </p>
932
- * )}
933
- * </div>
934
- * );
935
- * ```
936
- */
937
- declare function useCopyToClipboard(): UseCopyToClipboardReturn;
938
-
939
- interface UseDocumentTitleOptions {
940
- /** Restore previous title on unmount (default: true) */
941
- restoreOnUnmount?: boolean;
942
- }
943
- /**
944
- * useDocumentTitle
945
- *
946
- * A hook that sets the document title.
947
- *
948
- * @param title - The title to set
949
- * @param options - Configuration options
950
- *
951
- * @example
952
- * ```tsx
953
- * useDocumentTitle('Dashboard - My App');
954
- *
955
- * // With dynamic title
956
- * useDocumentTitle(`${unreadCount} new messages`);
957
- *
958
- * // Don't restore on unmount
959
- * useDocumentTitle('Settings', { restoreOnUnmount: false });
960
- * ```
961
- */
962
- declare function useDocumentTitle(title: string, options?: UseDocumentTitleOptions): void;
963
-
964
- /**
965
- * useLockBodyScroll
966
- *
967
- * A hook that locks body scroll when active (useful for modals).
968
- *
969
- * @param lock - Whether to lock scroll (default: true)
970
- *
971
- * @example
972
- * ```tsx
973
- * const [isModalOpen, setIsModalOpen] = useState(false);
974
- *
975
- * useLockBodyScroll(isModalOpen);
976
- *
977
- * return (
978
- * <>
979
- * <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
980
- * {isModalOpen && <Modal onClose={() => setIsModalOpen(false)} />}
981
- * </>
982
- * );
983
- * ```
984
- */
985
- declare function useLockBodyScroll(lock?: boolean): void;
986
-
987
- type Theme = 'light' | 'dark' | 'system';
988
- interface UseThemeOptions {
989
- /** Key to store theme in localStorage (default: 'theme') */
990
- storageKey?: string;
991
- /** Attribute to apply to HTML element (default: 'data-theme') */
992
- attribute?: string;
993
- /** Default theme if storage is empty (default: 'system') */
994
- defaultTheme?: Theme;
995
- /** Disable transition on theme switch to prevent flicker (default: true) */
996
- disableTransitionOnChange?: boolean;
997
- }
998
- interface UseThemeReturn {
999
- /** Active theme (light/dark/system) */
1000
- theme: Theme;
1001
- /** Resolved theme (light/dark) */
1002
- resolvedTheme: 'light' | 'dark';
1003
- /** Set theme */
1004
- setTheme: (theme: Theme) => void;
1005
- /** Toggle between light and dark */
1006
- toggleTheme: () => void;
1007
- }
1008
- /**
1009
- * useTheme
1010
- *
1011
- * A hook for managing light/dark mode with system preference support
1012
- * and no-flash-of-unstyled-content (FOUC).
1013
- *
1014
- * @param options - Configuration options
1015
- * @returns Theme state and controls
1016
- *
1017
- * @example
1018
- * ```tsx
1019
- * const { theme, toggleTheme } = useTheme();
1020
- *
1021
- * return (
1022
- * <button onClick={toggleTheme}>
1023
- * Current: {theme}
1024
- * </button>
1025
- * );
1026
- * ```
1027
- */
1028
- declare function useTheme(options?: UseThemeOptions): UseThemeReturn;
1029
-
1030
- interface UseEventOptions {
1031
- /** Capture phase (default: false) */
1032
- capture?: boolean;
1033
- /** Passive listener (default: false) */
1034
- passive?: boolean;
1035
- /** Once listener (default: false) */
1036
- once?: boolean;
1037
- }
1038
- /**
1039
- * useEvent
1040
- *
1041
- * A hook that attaches an event listener to a target element.
1042
- * Handles adding/removing listeners automatically on cleanup.
1043
- *
1044
- * @param name - Event name
1045
- * @param handler - Event handler function
1046
- * @param target - Target element (default: window)
1047
- * @param options - Event options
1048
- *
1049
- * @example
1050
- * ```tsx
1051
- * useEvent('click', handleClick);
1052
- * useEvent('scroll', handleScroll, window, { passive: true });
1053
- * ```
1054
- */
1055
- declare function useEvent<KD extends keyof DocumentEventMap>(name: KD, handler: (this: Document, ev: DocumentEventMap[KD]) => any, target?: Document | null, options?: UseEventOptions): void;
1056
- declare function useEvent<KH extends keyof HTMLElementEventMap>(name: KH, handler: (this: HTMLElement, ev: HTMLElementEventMap[KH]) => any, target?: HTMLElement | null, options?: UseEventOptions): void;
1057
- declare function useEvent<KW extends keyof WindowEventMap>(name: KW, handler: (this: Window, ev: WindowEventMap[KW]) => any, target?: Window | null, options?: UseEventOptions): void;
1058
-
1059
- interface UseLongPressOptions {
1060
- /** Time in ms to trigger long press (default: 500) */
1061
- threshold?: number;
1062
- /** Cancel on movement (default: true) */
1063
- cancelOnMove?: boolean;
1064
- /** Triggered when long press starts */
1065
- onStart?: (event: AnyEvent) => void;
1066
- /** Triggered when long press finishes successfully */
1067
- onFinish?: (event: AnyEvent) => void;
1068
- /** Triggered when long press is cancelled */
1069
- onCancel?: (event: AnyEvent) => void;
1070
- }
1071
- type AnyEvent = MouseEvent | TouchEvent | React.MouseEvent | React.TouchEvent;
1072
- interface UseLongPressReturn {
1073
- onMouseDown: (e: any) => void;
1074
- onTouchStart: (e: any) => void;
1075
- onMouseUp: (e: any) => void;
1076
- onMouseLeave: (e: any) => void;
1077
- onTouchEnd: (e: any) => void;
1078
- }
1079
- /**
1080
- * useLongPress
1081
- *
1082
- * A hook for detecting long press gestures.
1083
- *
1084
- * @param onLongPress - Callback fired when long press threshold is reached
1085
- * @param options - Configuration options
1086
- * @returns Event handlers to spread onto element
1087
- *
1088
- * @example
1089
- * ```tsx
1090
- * const onLongPress = () => {
1091
- * console.log('Long pressed!');
1092
- * };
1093
- *
1094
- * const bind = useLongPress(onLongPress);
1095
- *
1096
- * return <button {...bind}>Press me</button>;
1097
- * ```
1098
- */
1099
- declare function useLongPress(onLongPress: (event: AnyEvent) => void, options?: UseLongPressOptions): UseLongPressReturn;
1100
-
1101
- /**
1102
- * useWindowFocus
1103
- *
1104
- * A hook that detects if the window currently has focus.
1105
- *
1106
- * @returns boolean - true if window is focused, false if blurred
1107
- *
1108
- * @example
1109
- * ```tsx
1110
- * const isFocused = useWindowFocus();
1111
- *
1112
- * useEffect(() => {
1113
- * if (isFocused) {
1114
- * // Resume polling
1115
- * } else {
1116
- * // Pause polling
1117
- * }
1118
- * }, [isFocused]);
1119
- * ```
1120
- */
1121
- declare function useWindowFocus(): boolean;
1122
-
1123
- interface UseResizeObserverOptions {
1124
- /** Output only contentRect (default: true) */
1125
- contentRect?: boolean;
1126
- /** Throttling delay in ms (default: 0) */
1127
- throttle?: number;
1128
- }
1129
- /**
1130
- * useResizeObserver
1131
- *
1132
- * A hook that tracks element size changes using ResizeObserver.
1133
- *
1134
- * @param ref - Ref to the element to observe
1135
- * @param options - Configuration options
1136
- * @returns The resize observer entry's contentRect
1137
- *
1138
- * @example
1139
- * ```tsx
1140
- * const ref = useRef<HTMLDivElement>(null);
1141
- * const rect = useResizeObserver(ref);
1142
- *
1143
- * return (
1144
- * <div ref={ref}>
1145
- * Width: {rect?.width}, Height: {rect?.height}
1146
- * </div>
1147
- * );
1148
- * ```
1149
- */
1150
- declare function useResizeObserver<T extends HTMLElement = HTMLElement>(ref: RefObject<T | null>, options?: UseResizeObserverOptions): DOMRectReadOnly | undefined;
1151
-
1152
- interface UseMutationObserverOptions extends MutationObserverInit {
1153
- }
1154
- /**
1155
- * useMutationObserver
1156
- *
1157
- * A hook that tracks mutations in the DOM using MutationObserver.
1158
- *
1159
- * @param ref - Ref to the element to observe
1160
- * @param callback - Function to call on mutation
1161
- * @param options - MutationObserver options
1162
- *
1163
- * @example
1164
- * ```tsx
1165
- * const ref = useRef(null);
1166
- * useMutationObserver(ref, (mutations) => {
1167
- * console.log('DOM changed!', mutations);
1168
- * }, { childList: true });
1169
- * ```
1170
- */
1171
- declare function useMutationObserver<T extends HTMLElement>(ref: RefObject<T | null>, callback: MutationCallback, options?: UseMutationObserverOptions): void;
1172
-
1173
- /**
1174
- * usePageLeave
1175
- *
1176
- * It triggers a callback when the mouse leaves the page (e.g. intent to close tab).
1177
- *
1178
- * @param onPageLeave - Callback function
1179
- *
1180
- * @example
1181
- * ```tsx
1182
- * usePageLeave(() => {
1183
- * console.log('User is leaving!');
1184
- * });
1185
- * ```
1186
- */
1187
- declare function usePageLeave(onPageLeave: () => void): void;
1188
-
1189
- interface EyeDropperOpenOptions {
1190
- signal?: AbortSignal;
1191
- }
1192
- interface UseEyeDropperReturn {
1193
- isSupported: boolean;
1194
- open: (options?: EyeDropperOpenOptions) => Promise<{
1195
- sRGBHex: string;
1196
- } | undefined>;
1197
- }
1198
- /**
1199
- * useEyeDropper
1200
- *
1201
- * A hook for using the EyeDropper API to sample colors from the screen.
1202
- *
1203
- * @returns Object with support status and open function
1204
- *
1205
- * @example
1206
- * ```tsx
1207
- * const { open, isSupported } = useEyeDropper();
1208
- *
1209
- * const pickColor = async () => {
1210
- * try {
1211
- * const color = await open();
1212
- * console.log(color?.sRGBHex);
1213
- * } catch (e) {
1214
- * console.error(e);
1215
- * }
1216
- * };
1217
- * ```
1218
- */
1219
- declare function useEyeDropper(): UseEyeDropperReturn;
1220
-
1221
- interface UseOnlineReturn {
1222
- /** Whether the browser is online */
1223
- isOnline: boolean;
1224
- /** Whether the browser is offline */
1225
- isOffline: boolean;
1226
- /** Time since last status change (in ms) */
1227
- since: number | null;
1228
- }
1229
- /**
1230
- * useOnline
1231
- *
1232
- * A hook that tracks the browser's online/offline status.
1233
- *
1234
- * @returns Object with online status
1235
- *
1236
- * @example
1237
- * ```tsx
1238
- * const { isOnline, isOffline } = useOnline();
1239
- *
1240
- * return (
1241
- * <div>
1242
- * {isOnline ? '🟢 Online' : '🔴 Offline'}
1243
- * </div>
1244
- * );
1245
- * ```
1246
- */
1247
- declare function useOnline(): UseOnlineReturn;
1248
-
1249
- interface NetworkState {
1250
- online: boolean;
1251
- downlink?: number;
1252
- downlinkMax?: number;
1253
- effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';
1254
- rtt?: number;
1255
- saveData?: boolean;
1256
- type?: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';
1257
- }
1258
- /**
1259
- * useNetworkState
1260
- *
1261
- * A hook that tracks detailed network connection information.
1262
- * Note: Browser support varies for Navigator.connection.
1263
- */
1264
- declare function useNetworkState(): NetworkState;
1265
-
1266
- interface UseFullscreenReturn {
1267
- /** Whether fullscreen is active */
1268
- isFullscreen: boolean;
1269
- /** Whether fullscreen is supported */
1270
- isSupported: boolean;
1271
- /** Enter fullscreen mode */
1272
- enter: () => Promise<void>;
1273
- /** Exit fullscreen mode */
1274
- exit: () => Promise<void>;
1275
- /** Toggle fullscreen mode */
1276
- toggle: () => Promise<void>;
1277
- }
1278
- /**
1279
- * useFullscreen
1280
- *
1281
- * A hook for controlling the Fullscreen API.
1282
- *
1283
- * @param ref - Optional ref to element to make fullscreen (defaults to document.documentElement)
1284
- * @returns Object with fullscreen state and controls
1285
- *
1286
- * @example
1287
- * ```tsx
1288
- * // Fullscreen the whole document
1289
- * const { isFullscreen, toggle, isSupported } = useFullscreen();
1290
- *
1291
- * // Fullscreen a specific element
1292
- * const videoRef = useRef<HTMLVideoElement>(null);
1293
- * const { isFullscreen, enter, exit } = useFullscreen(videoRef);
1294
- *
1295
- * return (
1296
- * <div>
1297
- * <video ref={videoRef} />
1298
- * <button onClick={toggle} disabled={!isSupported}>
1299
- * {isFullscreen ? 'Exit' : 'Enter'} Fullscreen
1300
- * </button>
1301
- * </div>
1302
- * );
1303
- * ```
1304
- */
1305
- declare function useFullscreen<T extends HTMLElement = HTMLElement>(ref?: RefObject<T | null>): UseFullscreenReturn;
1306
-
1307
- interface ShareData {
1308
- /** Title of the shared content */
1309
- title?: string;
1310
- /** Text/description of the shared content */
1311
- text?: string;
1312
- /** URL to share */
1313
- url?: string;
1314
- }
1315
- interface UseShareReturn {
1316
- /** Whether Web Share API is supported */
1317
- isSupported: boolean;
1318
- /** Whether a share is currently in progress */
1319
- isSharing: boolean;
1320
- /** Whether share was successful */
1321
- isSuccess: boolean;
1322
- /** Any error that occurred */
1323
- error: Error | null;
1324
- /** Share data */
1325
- share: (data: ShareData) => Promise<boolean>;
1326
- /** Check if specific data can be shared */
1327
- canShare: (data?: ShareData) => boolean;
1328
- }
1329
- /**
1330
- * useShare
1331
- *
1332
- * A hook for using the Web Share API.
1333
- *
1334
- * @returns Object with share function and state
1335
- *
1336
- * @example
1337
- * ```tsx
1338
- * const { share, isSupported, isSharing } = useShare();
1339
- *
1340
- * const handleShare = async () => {
1341
- * const success = await share({
1342
- * title: 'Check this out!',
1343
- * text: 'A very interesting article',
1344
- * url: window.location.href,
1345
- * });
1346
- *
1347
- * if (success) {
1348
- * console.log('Shared successfully!');
1349
- * }
1350
- * };
1351
- *
1352
- * if (!isSupported) {
1353
- * return <CopyLinkButton />;
1354
- * }
1355
- *
1356
- * return (
1357
- * <button onClick={handleShare} disabled={isSharing}>
1358
- * {isSharing ? 'Sharing...' : 'Share'}
1359
- * </button>
1360
- * );
1361
- * ```
1362
- */
1363
- declare function useShare(): UseShareReturn;
1364
-
1365
- type PermissionName = 'geolocation' | 'notifications' | 'push' | 'midi' | 'camera' | 'microphone' | 'speaker-selection' | 'device-info' | 'background-fetch' | 'background-sync' | 'bluetooth' | 'persistent-storage' | 'ambient-light-sensor' | 'accelerometer' | 'gyroscope' | 'magnetometer' | 'clipboard-read' | 'clipboard-write' | 'display-capture' | 'nfc';
1366
- type PermissionState = 'granted' | 'denied' | 'prompt' | 'unknown';
1367
- /**
1368
- * usePermissions
1369
- *
1370
- * A hook to query and track permission status for browser APIs.
1371
- *
1372
- * @param name - The name of the permission to query
1373
- * @returns The current state of the permission
1374
- *
1375
- * @example
1376
- * ```tsx
1377
- * const status = usePermissions('geolocation');
1378
- *
1379
- * return <div>Location permission: {status}</div>;
1380
- * ```
1381
- */
1382
- declare function usePermissions(name: PermissionName | string): PermissionState;
1383
-
1384
- interface UseWakeLockReturn {
1385
- isSupported: boolean;
1386
- released: boolean;
1387
- request: () => Promise<void>;
1388
- release: () => Promise<void>;
1389
- }
1390
- /**
1391
- * useWakeLock
1392
- *
1393
- * A hook to prevent the device screen from dimming/sleeping.
1394
- *
1395
- * @param onRequest - Callback when lock is acquired
1396
- * @param onRelease - Callback when lock is released
1397
- * @returns Object with lock status and controls
1398
- */
1399
- declare function useWakeLock({ onRequest, onRelease, onError, }?: {
1400
- onRequest?: () => void;
1401
- onRelease?: () => void;
1402
- onError?: (err: Error) => void;
1403
- }): UseWakeLockReturn;
1404
-
1405
- interface UseMediaDevicesReturn {
1406
- devices: MediaDeviceInfo[];
1407
- isLoading: boolean;
1408
- error: Error | null;
1409
- isSupported: boolean;
1410
- }
1411
- /**
1412
- * useMediaDevices
1413
- *
1414
- * A hook to list and track connected hardware (cameras, microphones, speakers).
1415
- * Automatically updates when devices are plugged in or removed.
1416
- *
1417
- * @returns Object with devices list, loading state, and support status
1418
- *
1419
- * @example
1420
- * ```tsx
1421
- * const { devices, isLoading, error, isSupported } = useMediaDevices();
1422
- *
1423
- * if (!isSupported) return <p>Media Devices API not supported</p>;
1424
- * if (isLoading) return <p>Scanning hardware...</p>;
1425
- *
1426
- * const cameras = devices.filter(d => d.kind === 'videoinput');
1427
- * const mics = devices.filter(d => d.kind === 'audioinput');
1428
- *
1429
- * return (
1430
- * <div className="device-manager">
1431
- * <h3>Cameras ({cameras.length})</h3>
1432
- * <ul>
1433
- * {cameras.map(c => <li key={c.deviceId}>{c.label || 'Unknown Camera'}</li>)}
1434
- * </ul>
1435
- *
1436
- * <h3>Microphones ({mics.length})</h3>
1437
- * <ul>
1438
- * {mics.map(m => <li key={m.deviceId}>{m.label || 'Unknown Mic'}</li>)}
1439
- * </ul>
1440
- *
1441
- * {error && <p className="error">{error.message}</p>}
1442
- * </div>
1443
- * );
1444
- * ```
1445
- */
1446
- declare function useMediaDevices(): UseMediaDevicesReturn;
1447
-
1448
- type RecorderStatus = 'idle' | 'recording' | 'paused' | 'stopped';
1449
- interface UseMediaRecorderReturn {
1450
- status: RecorderStatus;
1451
- start: (timeSlice?: number) => void;
1452
- stop: () => void;
1453
- pause: () => void;
1454
- resume: () => void;
1455
- isRecording: boolean;
1456
- mediaBlob: Blob | undefined;
1457
- mediaUrl: string | undefined;
1458
- clear: () => void;
1459
- error: Error | null;
1460
- }
1461
- /**
1462
- * useMediaRecorder
1463
- *
1464
- * A hook to record media (audio/video) from a MediaStream.
1465
- * Returns a Blob and URL for the recording.
1466
- *
1467
- * @param stream - The MediaStream to record (from useMediaDevices)
1468
- * @param options - MediaRecorder options (mimeType, bitsPerSecond)
1469
- * @returns Object with recording controls and data
1470
- *
1471
- * @example
1472
- * ```tsx
1473
- * const [stream, setStream] = useState<MediaStream | null>(null);
1474
- * const {
1475
- * status,
1476
- * start,
1477
- * stop,
1478
- * mediaUrl,
1479
- * clear
1480
- * } = useMediaRecorder(stream);
1481
- *
1482
- * // Setup camera (simplified)
1483
- * useEffect(() => {
1484
- * navigator.mediaDevices.getUserMedia({ video: true, audio: true })
1485
- * .then(setStream);
1486
- * }, []);
1487
- *
1488
- * return (
1489
- * <div>
1490
- * <video
1491
- * ref={v => v && (v.srcObject = stream)}
1492
- * autoPlay muted
1493
- * width={300}
1494
- * />
1495
- *
1496
- * <div className="controls">
1497
- * <button onClick={() => start()}>Record</button>
1498
- * <button onClick={stop} disabled={status !== 'recording'}>Stop</button>
1499
- * </div>
1500
- *
1501
- * {mediaUrl && (
1502
- * <div className="preview">
1503
- * <h3>Recorded Video</h3>
1504
- * <video src={mediaUrl} controls width={300} />
1505
- * <a href={mediaUrl} download="recording.webm">Download</a>
1506
- * <button onClick={clear}>Clear</button>
1507
- * </div>
1508
- * )}
1509
- * </div>
1510
- * );
1511
- * ```
1512
- */
1513
- declare function useMediaRecorder(stream: MediaStream | null, options?: MediaRecorderOptions): UseMediaRecorderReturn;
1514
-
1515
- interface BatteryState {
1516
- supported: boolean;
1517
- loading: boolean;
1518
- level: number;
1519
- charging: boolean;
1520
- chargingTime: number;
1521
- dischargingTime: number;
1522
- }
1523
- /**
1524
- * useBattery
1525
- *
1526
- * A hook that tracks battery status.
1527
- *
1528
- * @returns Battery state object
1529
- */
1530
- declare function useBattery(): BatteryState;
1531
-
1532
- interface UseBluetoothReturn {
1533
- isSupported: boolean;
1534
- isConnected: boolean;
1535
- isConnecting: boolean;
1536
- device: BluetoothDevice | null;
1537
- server: BluetoothRemoteGATTServer | null;
1538
- error: Error | null;
1539
- requestDevice: (options?: RequestDeviceOptions) => Promise<void>;
1540
- disconnect: () => void;
1541
- }
1542
- /**
1543
- * useBluetooth
1544
- *
1545
- * A hook for connecting to Bluetooth Low Energy (BLE) devices.
1546
- */
1547
- declare function useBluetooth(): UseBluetoothReturn;
1548
-
1549
- interface UseGamepadOptions {
1550
- /** Enable polling loop (default: true) */
1551
- enabled?: boolean;
1552
- }
1553
- /**
1554
- * useGamepad
1555
- *
1556
- * A hook that tracks connected gamepads and their state.
1557
- * Uses requestAnimationFrame for polling input state.
1558
- */
1559
- declare function useGamepad(options?: UseGamepadOptions): {
1560
- gamepads: (Gamepad | null)[];
1561
- };
1562
-
1563
- interface UseFileSystemReturn {
1564
- isSupported: boolean;
1565
- file: File | null;
1566
- fileHandle: FileSystemFileHandle | null;
1567
- openFile: (options?: OpenFilePickerOptions) => Promise<void>;
1568
- saveFile: (data: BlobPart, options?: SaveFilePickerOptions) => Promise<void>;
1569
- error: Error | null;
1570
- }
1571
- /**
1572
- * useFileSystem
1573
- *
1574
- * A hook for the File System Access API.
1575
- */
1576
- declare function useFileSystem(): UseFileSystemReturn;
1577
-
1578
- interface StorageEstimateState {
1579
- quota: number | undefined;
1580
- usage: number | undefined;
1581
- supported: boolean;
1582
- loading: boolean;
1583
- }
1584
- /**
1585
- * useStorageEstimate
1586
- *
1587
- * A hook to estimate storage quota and usage.
1588
- */
1589
- declare function useStorageEstimate(): StorageEstimateState;
1590
-
1591
- type AsyncStatus = 'idle' | 'pending' | 'success' | 'error';
1592
- interface UseAsyncOptions<T> {
1593
- /** Execute immediately on mount (default: false) */
1594
- immediate?: boolean;
1595
- /** Initial data value */
1596
- initialData?: T;
1597
- /** Callback on success */
1598
- onSuccess?: (data: T) => void;
1599
- /** Callback on error */
1600
- onError?: (error: Error) => void;
1601
- }
1602
- interface UseAsyncReturn<T, Args extends unknown[]> {
1603
- /** The async function execution result */
1604
- data: T | undefined;
1605
- /** Any error that occurred */
1606
- error: Error | null;
1607
- /** Current status */
1608
- status: AsyncStatus;
1609
- /** Whether currently loading */
1610
- isLoading: boolean;
1611
- /** Whether request was successful */
1612
- isSuccess: boolean;
1613
- /** Whether request errored */
1614
- isError: boolean;
1615
- /** Execute the async function */
1616
- execute: (...args: Args) => Promise<T | undefined>;
1617
- /** Reset to initial state */
1618
- reset: () => void;
1619
- }
1620
- /**
1621
- * useAsync
1622
- *
1623
- * A hook for managing async function state.
1624
- *
1625
- * @param asyncFunction - The async function to execute
1626
- * @param options - Configuration options
1627
- * @returns Object with async state and execute function
1628
- *
1629
- * @example
1630
- * ```tsx
1631
- * const fetchUser = async (id: number) => {
1632
- * const response = await fetch(`/api/users/${id}`);
1633
- * return response.json();
1634
- * };
1635
- *
1636
- * const { data, isLoading, execute } = useAsync(fetchUser);
1637
- *
1638
- * return (
1639
- * <div>
1640
- * <button onClick={() => execute(1)}>Load User</button>
1641
- * {isLoading && <Spinner />}
1642
- * {data && <UserCard user={data} />}
1643
- * </div>
1644
- * );
1645
- * ```
1646
- */
1647
- declare function useAsync<T, Args extends unknown[] = []>(asyncFunction: (...args: Args) => Promise<T>, options?: UseAsyncOptions<T>): UseAsyncReturn<T, Args>;
1648
-
1649
- type FetchStatus = 'idle' | 'loading' | 'success' | 'error';
1650
- interface UseFetchOptions<T> extends Omit<RequestInit, 'signal'> {
1651
- /** Execute immediately (default: true) */
1652
- immediate?: boolean;
1653
- /** Initial data value */
1654
- initialData?: T;
1655
- /** Transform response before setting data */
1656
- transform?: (response: Response) => Promise<T>;
1657
- /** Number of retry attempts (default: 0) */
1658
- retries?: number;
1659
- /** Retry delay in ms (default: 1000) */
1660
- retryDelay?: number;
1661
- /** Callback on success */
1662
- onSuccess?: (data: T) => void;
1663
- /** Callback on error */
1664
- onError?: (error: Error) => void;
1665
- /** Abort previous request (default: true) */
1666
- abortPrevious?: boolean;
1667
- }
1668
- interface UseFetchReturn<T> {
1669
- /** Fetched data */
1670
- data: T | undefined;
1671
- /** Error if any */
1672
- error: Error | null;
1673
- /** Current status */
1674
- status: FetchStatus;
1675
- /** Loading state */
1676
- isLoading: boolean;
1677
- /** Success state */
1678
- isSuccess: boolean;
1679
- /** Error state */
1680
- isError: boolean;
1681
- /** Refetch data */
1682
- refetch: () => Promise<void>;
1683
- /** Abort current request */
1684
- abort: () => void;
1685
- }
1686
- /**
1687
- * useFetch
1688
- *
1689
- * A powerful hook for data fetching with abort, retry, and race condition handling.
1690
- *
1691
- * @param url - URL to fetch
1692
- * @param options - Fetch and hook options
1693
- * @returns Object with data, status, and control functions
1694
- *
1695
- * @example
1696
- * ```tsx
1697
- * interface User { id: number; name: string; }
1698
- *
1699
- * const {
1700
- * data,
1701
- * isLoading,
1702
- * error,
1703
- * refetch,
1704
- * abort
1705
- * } = useFetch<User[]>('/api/users', {
1706
- * retries: 3,
1707
- * retryDelay: 2000,
1708
- * immediate: true,
1709
- * transform: async (res) => {
1710
- * const json = await res.json();
1711
- * return json.users; // Transform response structure
1712
- * },
1713
- * onSuccess: (data) => console.log('Fetched:', data.length),
1714
- * onError: (err) => console.error('Failed:', err)
1715
- * });
1716
- *
1717
- * if (isLoading) return <div>Loading... <button onClick={abort}>Cancel</button></div>;
1718
- * if (error) return <ErrorDisplay message={error.message} onRetry={refetch} />;
1719
- *
1720
- * return (
1721
- * <ul>
1722
- * {data?.map(user => (
1723
- * <li key={user.id}>{user.name}</li>
1724
- * ))}
1725
- * </ul>
1726
- * );
1727
- * ```
1728
- */
1729
- declare function useFetch<T = unknown>(url: string | null, options?: UseFetchOptions<T>): UseFetchReturn<T>;
1730
-
1731
- type ScriptStatus = 'idle' | 'loading' | 'ready' | 'error';
1732
- interface UseScriptOptions {
1733
- /** Load script immediately (default: true) */
1734
- immediate?: boolean;
1735
- /** Remove script on unmount (default: false) */
1736
- removeOnUnmount?: boolean;
1737
- /** Script attributes */
1738
- attributes?: Record<string, string>;
1739
- }
1740
- interface UseScriptReturn {
1741
- /** Script loading status */
1742
- status: ScriptStatus;
1743
- /** Whether script is loading */
1744
- isLoading: boolean;
1745
- /** Whether script is ready */
1746
- isReady: boolean;
1747
- /** Whether script failed to load */
1748
- isError: boolean;
1749
- /** Load the script manually */
1750
- load: () => void;
1751
- }
1752
- /**
1753
- * useScript
1754
- *
1755
- * A hook for dynamically loading external scripts.
1756
- *
1757
- * @param src - Script source URL
1758
- * @param options - Configuration options
1759
- * @returns Object with script status and controls
1760
- *
1761
- * @example
1762
- * ```tsx
1763
- * const { isReady, isLoading, isError } = useScript(
1764
- * 'https://maps.googleapis.com/maps/api/js?key=YOUR_KEY'
1765
- * );
1766
- *
1767
- * if (isLoading) return <LoadingSpinner />;
1768
- * if (isError) return <ErrorMessage />;
1769
- * if (isReady) return <GoogleMap />;
1770
- * ```
1771
- */
1772
- declare function useScript(src: string, options?: UseScriptOptions): UseScriptReturn;
1773
-
1774
- type WorkerFunction<T, R> = (input: T) => R;
1775
- type WorkerStatus = 'idle' | 'running' | 'error' | 'success';
1776
- interface UseWorkerReturn<T, R> {
1777
- result: R | undefined;
1778
- error: Error | null;
1779
- status: WorkerStatus;
1780
- run: (input: T) => void;
1781
- terminate: () => void;
1782
- }
1783
- /**
1784
- * useWorker
1785
- *
1786
- * A hook to offload heavy computation to a Web Worker.
1787
- *
1788
- * @param workerScript - URL string or Function code to run in worker
1789
- */
1790
- declare function useWorker<T = any, R = any>(workerScript: string | WorkerFunction<T, R>): UseWorkerReturn<T, R>;
1791
-
1792
- interface UseIndexedDBReturn<T> {
1793
- value: T | undefined;
1794
- set: (value: T) => Promise<void>;
1795
- remove: () => Promise<void>;
1796
- error: Error | null;
1797
- isLoading: boolean;
1798
- }
1799
- /**
1800
- * useIndexedDB
1801
- *
1802
- * A simple hook to persist data in IndexedDB.
1803
- * Suitable for storing large objects/blobs that LocalStorage can't handle.
1804
- */
1805
- declare function useIndexedDB<T = any>(dbName: string, storeName: string, key: string): UseIndexedDBReturn<T>;
1806
-
1807
- interface UseHistoryOptions {
1808
- /** Maximum history size (default: 100) */
1809
- maxSize?: number;
1810
- }
1811
- interface UseHistoryReturn<T> {
1812
- /** Current value */
1813
- value: T;
1814
- /** Set new value (adds to history) */
1815
- set: (value: T | ((prev: T) => T)) => void;
1816
- /** Undo to previous value */
1817
- undo: () => void;
1818
- /** Redo to next value */
1819
- redo: () => void;
1820
- /** Clear history and set new value */
1821
- reset: (value: T) => void;
1822
- /** Whether undo is available */
1823
- canUndo: boolean;
1824
- /** Whether redo is available */
1825
- canRedo: boolean;
1826
- /** History array (past values) */
1827
- history: T[];
1828
- /** Current position in history */
1829
- position: number;
1830
- /** Go to specific position in history */
1831
- go: (position: number) => void;
1832
- }
1833
- /**
1834
- * useHistory
1835
- *
1836
- * A hook for managing state with undo/redo functionality.
1837
- *
1838
- * @param initialValue - Initial state value
1839
- * @param options - Configuration options
1840
- * @returns Object with value, history controls, and state
1841
- *
1842
- * @example
1843
- * ```tsx
1844
- * const { value, set, undo, redo, canUndo, canRedo } = useHistory('');
1845
- *
1846
- * return (
1847
- * <div>
1848
- * <input value={value} onChange={(e) => set(e.target.value)} />
1849
- * <button onClick={undo} disabled={!canUndo}>Undo</button>
1850
- * <button onClick={redo} disabled={!canRedo}>Redo</button>
1851
- * </div>
1852
- * );
1853
- * ```
1854
- */
1855
- declare function useHistory<T>(initialValue: T, options?: UseHistoryOptions): UseHistoryReturn<T>;
1856
-
1857
- interface UseStepOptions {
1858
- /** Initial step (default: 0) */
1859
- initialStep?: number;
1860
- /** Total number of steps */
1861
- maxStep: number;
1862
- }
1863
- interface UseStepReturn {
1864
- /** Current step (0-indexed) */
1865
- currentStep: number;
1866
- /** Current step (1-indexed for display) */
1867
- step: number;
1868
- /** Go to next step */
1869
- next: () => void;
1870
- /** Go to previous step */
1871
- prev: () => void;
1872
- /** Go to specific step */
1873
- goTo: (step: number) => void;
1874
- /** Reset to initial step */
1875
- reset: () => void;
1876
- /** Whether at first step */
1877
- isFirst: boolean;
1878
- /** Whether at last step */
1879
- isLast: boolean;
1880
- /** Progress percentage (0-100) */
1881
- progress: number;
1882
- /** Total number of steps */
1883
- totalSteps: number;
1884
- /** Whether a specific step is completed */
1885
- isStepComplete: (step: number) => boolean;
1886
- }
1887
- /**
1888
- * useStep
1889
- *
1890
- * A hook for managing wizard/stepper flow.
1891
- *
1892
- * @param options - Configuration options
1893
- * @returns Object with step state and control functions
1894
- *
1895
- * @example
1896
- * ```tsx
1897
- * const steps = ['Personal Info', 'Address', 'Payment', 'Confirm'];
1898
- *
1899
- * const { currentStep, step, next, prev, isFirst, isLast, progress } = useStep({
1900
- * maxStep: steps.length,
1901
- * });
1902
- *
1903
- * return (
1904
- * <div>
1905
- * <ProgressBar value={progress} />
1906
- * <h2>Step {step}: {steps[currentStep]}</h2>
1907
- * {currentStep === 0 && <PersonalInfoForm />}
1908
- * {currentStep === 1 && <AddressForm />}
1909
- * {currentStep === 2 && <PaymentForm />}
1910
- * {currentStep === 3 && <ConfirmForm />}
1911
- * <div>
1912
- * <button onClick={prev} disabled={isFirst}>Back</button>
1913
- * <button onClick={next} disabled={isLast}>Next</button>
1914
- * </div>
1915
- * </div>
1916
- * );
1917
- * ```
1918
- */
1919
- declare function useStep(options: UseStepOptions): UseStepReturn;
1920
-
1921
- interface UsePaginationOptions {
1922
- /** Total number of items */
1923
- totalItems: number;
1924
- /** Items per page (default: 10) */
1925
- pageSize?: number;
1926
- /** Initial page (1-indexed, default: 1) */
1927
- initialPage?: number;
1928
- /** Number of sibling pages to show (default: 1) */
1929
- siblings?: number;
1930
- }
1931
- interface UsePaginationReturn {
1932
- /** Current page (1-indexed) */
1933
- page: number;
1934
- /** Total number of pages */
1935
- totalPages: number;
1936
- /** Items per page */
1937
- pageSize: number;
1938
- /** Go to next page */
1939
- next: () => void;
1940
- /** Go to previous page */
1941
- prev: () => void;
1942
- /** Go to specific page */
1943
- goTo: (page: number) => void;
1944
- /** Go to first page */
1945
- first: () => void;
1946
- /** Go to last page */
1947
- last: () => void;
1948
- /** Whether at first page */
1949
- isFirst: boolean;
1950
- /** Whether at last page */
1951
- isLast: boolean;
1952
- /** Start index for current page (0-indexed) */
1953
- startIndex: number;
1954
- /** End index for current page (0-indexed, exclusive) */
1955
- endIndex: number;
1956
- /** Page range for pagination UI */
1957
- range: (number | 'dots')[];
1958
- /** Set page size */
1959
- setPageSize: (size: number) => void;
1960
- }
1961
- /**
1962
- * usePagination
1963
- *
1964
- * A hook for managing pagination state and logic.
1965
- *
1966
- * @param options - Configuration options
1967
- * @returns Object with pagination state and controls
1968
- *
1969
- * @example
1970
- * ```tsx
1971
- * const { page, totalPages, next, prev, range, isFirst, isLast } = usePagination({
1972
- * totalItems: 100,
1973
- * pageSize: 10,
1974
- * });
1975
- *
1976
- * return (
1977
- * <div>
1978
- * <button onClick={prev} disabled={isFirst}>Previous</button>
1979
- *
1980
- * {range.map((item, index) =>
1981
- * item === 'dots' ? (
1982
- * <span key={index}>...</span>
1983
- * ) : (
1984
- * <button
1985
- * key={index}
1986
- * onClick={() => goTo(item)}
1987
- * className={item === page ? 'active' : ''}
1988
- * >
1989
- * {item}
1990
- * </button>
1991
- * )
1992
- * )}
1993
- *
1994
- * <button onClick={next} disabled={isLast}>Next</button>
1995
- * </div>
1996
- * );
1997
- * ```
1998
- */
1999
- declare function usePagination(options: UsePaginationOptions): UsePaginationReturn;
2000
-
2001
- interface MachineState<S> {
2002
- value: S;
2003
- context?: any;
2004
- }
2005
- interface MachineConfig<S extends string, E extends string> {
2006
- initial: S;
2007
- states: {
2008
- [key in S]: {
2009
- on?: {
2010
- [key in E]?: S | {
2011
- target: S;
2012
- action?: () => void;
2013
- };
2014
- };
2015
- effect?: () => (() => void) | void;
2016
- };
2017
- };
2018
- }
2019
- /**
2020
- * useMachine
2021
- *
2022
- * A lightweight state machine hook.
2023
- */
2024
- declare function useMachine<S extends string, E extends string>(config: MachineConfig<S, E>): [S, (event: E) => void];
2025
-
2026
- interface UseVirtualListOptions {
2027
- /** Height of individual item */
2028
- itemHeight: number;
2029
- /** Total number of items */
2030
- itemCount: number;
2031
- /** Height of scrollable container (viewport) */
2032
- containerHeight: number;
2033
- /** Number of items to render outside viewport (buffer) */
2034
- overscan?: number;
2035
- }
2036
- interface VirtualItem {
2037
- index: number;
2038
- style: {
2039
- position: 'absolute';
2040
- top: number;
2041
- height: number;
2042
- width: '100%';
2043
- };
2044
- }
2045
- interface UseVirtualListReturn {
2046
- items: VirtualItem[];
2047
- totalHeight: number;
2048
- onScroll: (event: UIEvent<HTMLElement>) => void;
2049
- }
2050
- /**
2051
- * useVirtualList
2052
- *
2053
- * A hook for efficiently rendering large lists by only rendering visible items.
2054
- * Assumes fixed height items.
2055
- */
2056
- declare function useVirtualList(options: UseVirtualListOptions): UseVirtualListReturn;
2057
-
2058
- interface UseInfiniteScrollOptions {
2059
- /** Threshold for intersection (0.0 - 1.0) */
2060
- threshold?: number;
2061
- /** Root margin for intersection */
2062
- rootMargin?: string;
2063
- /** Whether loading is currently in progress */
2064
- isLoading?: boolean;
2065
- /** Whether there is more data to load */
2066
- hasMore?: boolean;
2067
- /** Disable the observer */
2068
- disabled?: boolean;
2069
- }
2070
- /**
2071
- * useInfiniteScroll
2072
- *
2073
- * A hook that triggers a callback when an element (target) becomes visible.
2074
- * Useful for infinite scrolling.
2075
- *
2076
- * @param onLoadMore - Function to call when target is visible
2077
- * @param options - Configuration options
2078
- * @returns A ref to attach to the sentinel element (bottom of list)
2079
- */
2080
- declare function useInfiniteScroll(onLoadMore: () => void, options?: UseInfiniteScrollOptions): MutableRefObject<HTMLDivElement | null>;
2081
-
2082
- interface AnthropicMessage {
2083
- role: 'user' | 'assistant';
2084
- content: string;
2085
- }
2086
- interface UseAnthropicOptions {
2087
- apiKey?: string;
2088
- model?: string;
2089
- maxTokens?: number;
2090
- temperature?: number;
2091
- }
2092
- declare function useAnthropic(options?: UseAnthropicOptions): {
2093
- chat: (messages: AnthropicMessage[]) => Promise<any>;
2094
- response: string | null;
2095
- loading: boolean;
2096
- error: any;
2097
- };
2098
-
2099
- interface UseEmbeddingsReturn {
2100
- embeddings: number[][] | null;
2101
- loading: boolean;
2102
- error: any;
2103
- generate: (texts: string[]) => Promise<number[][]>;
2104
- }
2105
- /**
2106
- * useEmbeddings
2107
- *
2108
- * Generic hook to manage embedding generation.
2109
- * The actual provider logic is passed via the `fetcher` callback.
2110
- */
2111
- declare function useEmbeddings(fetcher: (texts: string[]) => Promise<number[][]>): UseEmbeddingsReturn;
2112
-
2113
- interface GeminiPart {
2114
- text: string;
2115
- }
2116
- interface GeminiContent {
2117
- role: 'user' | 'model';
2118
- parts: GeminiPart[];
2119
- }
2120
- interface UseGeminiOptions {
2121
- apiKey?: string;
2122
- model?: string;
2123
- }
2124
- declare function useGemini(options?: UseGeminiOptions): {
2125
- chat: (contents: GeminiContent[]) => Promise<any>;
2126
- response: string | null;
2127
- loading: boolean;
2128
- error: any;
2129
- };
2130
-
2131
- interface UseLLMStreamOptions {
2132
- onToken?: (token: string, fullText: string) => void;
2133
- onComplete?: (fullText: string) => void;
2134
- onError?: (error: any) => void;
2135
- }
2136
- interface UseLLMStreamReturn {
2137
- stream: (url: string, fetchOptions?: RequestInit) => Promise<void>;
2138
- cancel: () => void;
2139
- data: string;
2140
- loading: boolean;
2141
- error: any;
2142
- }
2143
- /**
2144
- * useLLMStream
2145
- *
2146
- * A hook for handling streaming responses (Server-Sent Events) from LLM APIs.
2147
- * Simplifies the process of reading chunks and updating UI in real-time.
2148
- *
2149
- * @param options - Callbacks for token updates, completion, and errors
2150
- * @returns Object with stream initiator, canceler, and current data
2151
- *
2152
- * @example
2153
- * ```tsx
2154
- * const { stream, data, loading, error } = useLLMStream({
2155
- * onToken: (token) => console.log('Received token:', token),
2156
- * onComplete: (fullText) => console.log('Stream finished:', fullText)
2157
- * });
2158
- *
2159
- * const handleAsk = async (prompt: string) => {
2160
- * await stream('/api/chat', {
2161
- * method: 'POST',
2162
- * body: JSON.stringify({ prompt }),
2163
- * headers: { 'Content-Type': 'application/json' }
2164
- * });
2165
- * };
2166
- *
2167
- * return (
2168
- * <div className="chat-box">
2169
- * <div className="response">
2170
- * {data || (loading ? 'Generating...' : 'Waiting for prompt...')}
2171
- * </div>
2172
- *
2173
- * <button onClick={() => handleAsk('Write a React hook')}>
2174
- * Ask AI
2175
- * </button>
2176
- *
2177
- * {error && <div className="error">{error.message}</div>}
2178
- * </div>
2179
- * );
2180
- * ```
2181
- */
2182
- declare function useLLMStream(options?: UseLLMStreamOptions): UseLLMStreamReturn;
2183
-
2184
- interface Message {
2185
- role: 'system' | 'user' | 'assistant';
2186
- content: string;
2187
- }
2188
- interface UseOpenAIOptions {
2189
- apiKey?: string;
2190
- apiBase?: string;
2191
- model?: string;
2192
- temperature?: number;
2193
- stream?: boolean;
2194
- }
2195
- declare function useOpenAI(options?: UseOpenAIOptions): {
2196
- chat: (messages: Message[]) => Promise<any>;
2197
- response: string | null;
2198
- loading: boolean;
2199
- error: any;
2200
- };
2201
-
2202
- interface RAGDocument {
2203
- id: string;
2204
- content: string;
2205
- metadata?: Record<string, any>;
2206
- }
2207
- interface UseRAGOptions {
2208
- retrieve: (query: string) => Promise<RAGDocument[]>;
2209
- generate: (prompt: string, context: RAGDocument[]) => Promise<string>;
2210
- }
2211
- declare function useRAG(options: UseRAGOptions): {
2212
- ask: (query: string) => Promise<string>;
2213
- answer: string | null;
2214
- retrievedDocs: RAGDocument[];
2215
- loading: boolean;
2216
- error: any;
2217
- };
2218
-
2219
- interface UseSearchHighlightOptions {
2220
- highlightTag?: string;
2221
- highlightClass?: string;
2222
- caseSensitive?: boolean;
2223
- }
2224
- interface HighlightPart {
2225
- text: string;
2226
- isMatch: boolean;
2227
- }
2228
- /**
2229
- * useSearchHighlight
2230
- *
2231
- * Splits text into parts based on a search query.
2232
- */
2233
- declare function useSearchHighlight(text: string, query: string, options?: UseSearchHighlightOptions): HighlightPart[];
2234
-
2235
- type Vector = number[];
2236
- interface SemanticResult<T> {
2237
- item: T;
2238
- score: number;
2239
- }
2240
- /**
2241
- * useSemanticSearch
2242
- *
2243
- * Performs client-side vector similarity search (Cosine Similarity).
2244
- * Assumes embeddings are already generated.
2245
- */
2246
- declare function useSemanticSearch<T>(queryEmbedding: Vector | null, items: T[], getItemEmbedding: (item: T) => Vector, topK?: number): SemanticResult<T>[];
2247
-
2248
- interface UseSTTOptions {
2249
- continuous?: boolean;
2250
- interimResults?: boolean;
2251
- lang?: string;
2252
- onResult?: (transcript: string) => void;
2253
- onError?: (error: any) => void;
2254
- onEnd?: () => void;
2255
- }
2256
- interface UseSTTReturn {
2257
- listen: () => void;
2258
- stop: () => void;
2259
- abort: () => void;
2260
- listening: boolean;
2261
- transcript: string;
2262
- supported: boolean;
2263
- }
2264
- /**
2265
- * useSTT
2266
- *
2267
- * A hook for Speech-to-Text (Recognition) integration.
2268
- * Provides real-time transcription with controls for continuous or one-shot listening.
2269
- *
2270
- * @param options - Configuration options (lang, continuous, interimResults, etc.)
2271
- * @returns Object with recognition controls and transcription state
2272
- *
2273
- * @example
2274
- * ```tsx
2275
- * const { listen, stop, transcript, listening, supported } = useSTT({
2276
- * lang: 'en-US',
2277
- * continuous: true,
2278
- * interimResults: true
2279
- * });
2280
- *
2281
- * if (!supported) return <p>Speech Recognition not supported in this browser</p>;
2282
- *
2283
- * return (
2284
- * <div className="stt-container">
2285
- * <div className="controls">
2286
- * <button onClick={listen} disabled={listening}>Start Listening</button>
2287
- * <button onClick={stop} disabled={!listening}>Stop</button>
2288
- * </div>
2289
- *
2290
- * <div className={`status ${listening ? 'active' : ''}`}>
2291
- * {listening ? '🎤 Listening...' : 'Mic Off'}
2292
- * </div>
2293
- *
2294
- * <div className="transcript">
2295
- * <h3>Transcript:</h3>
2296
- * <p>{transcript || 'Start speaking to see transcription...'}</p>
2297
- * </div>
2298
- * </div>
2299
- * );
2300
- * ```
2301
- */
2302
- declare function useSTT(options?: UseSTTOptions): UseSTTReturn;
2303
-
2304
- interface UseTTSOptions {
2305
- volume?: number;
2306
- rate?: number;
2307
- pitch?: number;
2308
- voiceURI?: string;
2309
- onStart?: () => void;
2310
- onEnd?: () => void;
2311
- onError?: (event: SpeechSynthesisErrorEvent) => void;
2312
- }
2313
- /**
2314
- * useTTS
2315
- *
2316
- * A hook for Text-to-Speech (Synthesis) integration.
2317
- * Wraps the Web Speech API with a React-friendly interface.
2318
- *
2319
- * @param options - Configuration options (volume, rate, voice, etc.)
2320
- * @returns Object with speech controls and state
2321
- *
2322
- * @example
2323
- * ```tsx
2324
- * const { speak, cancel, speaking, supported, voices } = useTTS({
2325
- * volume: 1,
2326
- * rate: 1,
2327
- * });
2328
- *
2329
- * if (!supported) return <p>Text-to-Speech not supported</p>;
2330
- *
2331
- * return (
2332
- * <div>
2333
- * <textarea id="text-input" defaultValue="Hello world" />
2334
- *
2335
- * <div className="controls">
2336
- * <button onClick={() => speak(document.querySelector('textarea')?.value || '')}>
2337
- * Speak
2338
- * </button>
2339
- * <button onClick={cancel} disabled={!speaking}>
2340
- * Stop
2341
- * </button>
2342
- * </div>
2343
- *
2344
- * <div className="status">
2345
- * {speaking ? '🔊 Speaking...' : 'Idle'}
2346
- * </div>
2347
- *
2348
- * <div className="voices">
2349
- * <p>Available Voices: {voices.length}</p>
2350
- * </div>
2351
- * </div>
2352
- * );
2353
- * ```
2354
- */
2355
- declare function useTTS(options?: UseTTSOptions): {
2356
- speak: (text: string, overrideOptions?: UseTTSOptions) => void;
2357
- cancel: () => void;
2358
- speaking: boolean;
2359
- supported: boolean;
2360
- voices: SpeechSynthesisVoice[];
2361
- };
2362
-
2363
- type AnimationCallback = (time: number, deltaTime: number) => void;
2364
- declare function useAnimate(callback: AnimationCallback, running?: boolean): void;
2365
-
2366
- interface UseMediaRefReturn<T extends HTMLMediaElement> {
2367
- ref: React.RefObject<T>;
2368
- controls: {
2369
- play: () => Promise<void>;
2370
- pause: () => void;
2371
- toggle: () => void;
2372
- seek: (time: number) => void;
2373
- mute: () => void;
2374
- unmute: () => void;
2375
- setVolume: (val: number) => void;
2376
- };
2377
- state: {
2378
- playing: boolean;
2379
- paused: boolean;
2380
- muted: boolean;
2381
- volume: number;
2382
- time: number;
2383
- duration: number;
2384
- buffered: number;
2385
- waiting: boolean;
2386
- ended: boolean;
2387
- };
2388
- }
2389
- /**
2390
- * useVideoRef
2391
- *
2392
- * A hook providing a declarative interface for HTML5 Video elements.
2393
- * Returns a ref, easy-to-use controls, and real-time playback state.
2394
- *
2395
- * @returns Object with ref, controls (play, pause, volume), and state (time, duration, etc.)
2396
- *
2397
- * @example
2398
- * ```tsx
2399
- * const { ref, controls, state } = useVideoRef();
2400
- *
2401
- * return (
2402
- * <div className="player">
2403
- * <video ref={ref} src="movie.mp4" width="600" />
2404
- *
2405
- * <div className="ui">
2406
- * <button onClick={controls.toggle}>
2407
- * {state.paused ? '▶️ Play' : '⏸️ Pause'}
2408
- * </button>
2409
- *
2410
- * <input
2411
- * type="range"
2412
- * min="0"
2413
- * max={state.duration}
2414
- * value={state.time}
2415
- * onChange={(e) => controls.seek(Number(e.target.value))}
2416
- * />
2417
- *
2418
- * <span>{Math.round(state.time)}s / {Math.round(state.duration)}s</span>
2419
- *
2420
- * <button onClick={controls.mute}>
2421
- * {state.muted ? '🔈' : '🔊'}
2422
- * </button>
2423
- * </div>
2424
- * </div>
2425
- * );
2426
- * ```
2427
- */
2428
- declare function useVideoRef(): UseMediaRefReturn<HTMLVideoElement>;
2429
-
2430
- /**
2431
- * useAudioRef
2432
- *
2433
- * Helper for audio elements.
2434
- * Provides controls (play, pause, seek, volume) and state (time, duration, buffered).
2435
- *
2436
- * @returns Object with ref, controls, and state
2437
- *
2438
- * @example
2439
- * ```tsx
2440
- * const { ref, controls, state } = useAudioRef();
2441
- *
2442
- * return (
2443
- * <div>
2444
- * <audio ref={ref} src="song.mp3" />
2445
- * <button onClick={controls.toggle}>
2446
- * {state.paused ? 'Play' : 'Pause'}
2447
- * </button>
2448
- * </div>
2449
- * );
2450
- * ```
2451
- */
2452
- declare function useAudioRef(): UseMediaRefReturn<HTMLAudioElement>;
2453
-
2454
- interface UseCanvasOptions {
2455
- width?: number;
2456
- height?: number;
2457
- animate?: (context: CanvasRenderingContext2D, frameCount: number) => void;
2458
- }
2459
- declare function useCanvas(options?: UseCanvasOptions): react.RefObject<HTMLCanvasElement>;
2460
-
2461
- declare function useFrameRate(running?: boolean): number;
2462
-
2463
- interface UseLottieOptions extends Omit<AnimationConfig, 'container'> {
2464
- path?: string;
2465
- animationData?: any;
2466
- speed?: number;
2467
- direction?: 1 | -1;
2468
- isPlaying?: boolean;
2469
- }
2470
- declare function useLottie(containerRef: React.RefObject<HTMLElement>, options: UseLottieOptions): AnimationItem | undefined;
2471
-
2472
- interface UseParallaxOptions {
2473
- speed?: number;
2474
- axis?: 'y' | 'x';
2475
- }
2476
- /**
2477
- * useParallax
2478
- *
2479
- * Returns a style object with transform to create a parallax effect.
2480
- * Needs to be attached to the element style.
2481
- */
2482
- declare function useParallax(options?: UseParallaxOptions): {
2483
- ref: react.RefObject<HTMLElement>;
2484
- style: {
2485
- transform: string;
2486
- willChange: string;
2487
- };
2488
- };
2489
-
2490
- interface SpringConfig {
2491
- stiffness?: number;
2492
- damping?: number;
2493
- mass?: number;
2494
- }
2495
- interface UseSpringCoreOptions extends SpringConfig {
2496
- initialValue?: number;
2497
- }
2498
- /**
2499
- * useSpringCore
2500
- *
2501
- * A simplified spring physics implementation using a semi-implicit Euler integration
2502
- * or basic RK4 (simplified here for performant React state updates).
2503
- *
2504
- * Note: For high frequency animation, use useAnimate directly with refs.
2505
- * This hook is for state-based spring values.
2506
- */
2507
- declare function useSpringCore(targetValue: number, options?: UseSpringCoreOptions): number;
2508
-
2509
- interface UseSVGAnimationOptions {
2510
- duration?: number;
2511
- delay?: number;
2512
- easing?: (t: number) => number;
2513
- }
2514
- declare function useSVGAnimation(length: number, options?: UseSVGAnimationOptions): {
2515
- strokeDasharray: number;
2516
- strokeDashoffset: number;
2517
- };
2518
-
2519
- interface UseThreeJSOptions {
2520
- init?: (scene: THREE.Scene, camera: THREE.PerspectiveCamera, renderer: THREE.WebGLRenderer) => void;
2521
- animate?: (time: number, scene: THREE.Scene, camera: THREE.PerspectiveCamera) => void;
2522
- resize?: boolean;
2523
- }
2524
- declare function useThreeJS(containerRef: React.RefObject<HTMLElement>, options?: UseThreeJSOptions): {
2525
- scene: THREE.Scene<THREE.Object3DEventMap> | undefined;
2526
- camera: THREE.PerspectiveCamera | undefined;
2527
- renderer: THREE.WebGLRenderer | undefined;
2528
- };
2529
-
2530
- declare function useBroadcastChannel<T>(channelName: string): {
2531
- postMessage: (message: T) => void;
2532
- lastMessage: T | null;
2533
- };
2534
-
2535
- interface UseCalendarOptions {
2536
- initialDate?: Date;
2537
- }
2538
- declare function useCalendar(options?: UseCalendarOptions): {
2539
- date: Date;
2540
- daysInMonth: number;
2541
- firstDayOfMonth: number;
2542
- nextMonth: () => void;
2543
- prevMonth: () => void;
2544
- setHeader: react.Dispatch<react.SetStateAction<Date>>;
2545
- };
2546
-
2547
- interface UseDragAndDropOptions {
2548
- onDrop?: (files: File[]) => void;
2549
- accept?: string[];
2550
- }
2551
- declare function useDragAndDrop(options?: UseDragAndDropOptions): {
2552
- ref: react.RefObject<HTMLElement>;
2553
- isDragging: boolean;
2554
- };
2555
-
2556
- interface UseFileProcessingOptions {
2557
- limit?: number;
2558
- accept?: string[];
2559
- }
2560
- declare function useFileProcessing(options?: UseFileProcessingOptions): {
2561
- process: (file: File) => Promise<string>;
2562
- processing: boolean;
2563
- error: string | null;
2564
- };
2565
-
2566
- interface UseFormOptions<T> {
2567
- /** Initial values for the form fields */
2568
- initialValues: T;
2569
- /** Callback function when form is submitted successfully */
2570
- onSubmit: (values: T) => void | Promise<void>;
2571
- /** Validation function that returns an object of error messages */
2572
- validate?: (values: T) => Record<keyof T, string> | Promise<Record<keyof T, string>>;
2573
- }
2574
- interface UseFormReturn<T> {
2575
- /** Current form values */
2576
- values: T;
2577
- /** Current validation errors */
2578
- errors: Record<keyof T, string>;
2579
- /** Touched fields status */
2580
- touched: Record<keyof T, boolean>;
2581
- /** Whether the form is currently submitting */
2582
- isSubmitting: boolean;
2583
- /** Handle input change events */
2584
- handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
2585
- /** Handle input blur events */
2586
- handleBlur: (e: React.FocusEvent<any>) => void;
2587
- /** Handle form submission */
2588
- handleSubmit: (e?: FormEvent) => Promise<void>;
2589
- /** Manually set a field value */
2590
- setFieldValue: (name: keyof T, value: any) => void;
2591
- /** Manually set all form values */
2592
- setValues: React.Dispatch<React.SetStateAction<T>>;
2593
- }
2594
- /**
2595
- * useForm
2596
- *
2597
- * A simple yet powerful hook for managing form state, validation, and submission.
2598
- * It handles values, errors, touched states, and provides handlers for inputs and forms.
2599
- *
2600
- * @param options - Configuration options for the form
2601
- * @returns Object with form state and handlers
2602
- *
2603
- * @example
2604
- * ```tsx
2605
- * interface LoginForm {
2606
- * email: string;
2607
- * password: string;
2608
- * }
2609
- *
2610
- * const {
2611
- * values,
2612
- * errors,
2613
- * handleChange,
2614
- * handleSubmit,
2615
- * isSubmitting
2616
- * } = useForm<LoginForm>({
2617
- * initialValues: { email: '', password: '' },
2618
- *
2619
- * validate: (values) => {
2620
- * const errors: Partial<Record<keyof LoginForm, string>> = {};
2621
- * if (!values.email) errors.email = 'Email required';
2622
- * if (!values.password) errors.password = 'Password required';
2623
- * return errors as Record<keyof LoginForm, string>;
2624
- * },
2625
- *
2626
- * onSubmit: async (values) => {
2627
- * console.log('Logging in...', values);
2628
- * await new Promise(r => setTimeout(r, 1000));
2629
- * }
2630
- * });
2631
- *
2632
- * return (
2633
- * <form onSubmit={handleSubmit} className="login-form">
2634
- * <div className="field">
2635
- * <label>Email</label>
2636
- * <input
2637
- * name="email"
2638
- * value={values.email}
2639
- * onChange={handleChange}
2640
- * className={errors.email ? 'invalid' : ''}
2641
- * />
2642
- * {errors.email && <span className="error">{errors.email}</span>}
2643
- * </div>
2644
- *
2645
- * <div className="field">
2646
- * <label>Password</label>
2647
- * <input
2648
- * name="password"
2649
- * type="password"
2650
- * value={values.password}
2651
- * onChange={handleChange}
2652
- * />
2653
- * {errors.password && <span className="error">{errors.password}</span>}
2654
- * </div>
2655
- *
2656
- * <button type="submit" disabled={isSubmitting}>
2657
- * {isSubmitting ? 'Verifying...' : 'Login'}
2658
- * </button>
2659
- * </form>
2660
- * );
2661
- * ```
2662
- */
2663
- declare function useForm<T extends Record<string, any>>(options: UseFormOptions<T>): UseFormReturn<T>;
2664
-
2665
- /**
2666
- * useMarkdown
2667
- *
2668
- * Simple parser or wrapper typically.
2669
- * Here we return a simple compilation function.
2670
- */
2671
- declare function useMarkdown(): {
2672
- compile: (markdown: string) => string;
2673
- };
2674
-
2675
- declare function usePDF(): {
2676
- generate: (content: string, filename?: string) => Promise<boolean>;
2677
- generating: boolean;
2678
- };
2679
-
2680
- /**
2681
- * usePresence
2682
- *
2683
- * Tracks basic user presence (online/idle) or remote presence list logic.
2684
- */
2685
- declare function usePresence(heartbeatInterval?: number): {
2686
- isIdle: boolean;
2687
- lastActive: number;
2688
- };
2689
-
2690
- interface CollabEvent {
2691
- type: string;
2692
- payload: any;
2693
- timestamp: number;
2694
- userId: string;
2695
- }
2696
- /**
2697
- * useRealtimeCollab
2698
- *
2699
- * Logic stub for Operational Transformation or CRDTs.
2700
- * Simple event log for now.
2701
- */
2702
- declare function useRealtimeCollab(userId: string): {
2703
- events: CollabEvent[];
2704
- emit: (type: string, payload: any) => void;
2705
- applyRemote: (event: CollabEvent) => void;
2706
- };
2707
-
2708
- type ShortcutHandler = (event: KeyboardEvent) => void;
2709
- interface ShortcutMap {
2710
- [key: string]: ShortcutHandler;
2711
- }
2712
- /**
2713
- * useShortcuts
2714
- *
2715
- * Defines keyboard shortcuts.
2716
- * key combo format: 'Control+Shift+K', 'Enter', 'a'
2717
- */
2718
- declare function useShortcuts(shortcuts: ShortcutMap): void;
2719
-
2720
- interface UseSortableOptions<T> {
2721
- items: T[];
2722
- onReorder: (newItems: T[]) => void;
2723
- }
2724
- declare function useSortable<T>(options: UseSortableOptions<T>): {
2725
- draggedIndex: number | null;
2726
- setDraggedIndex: react.Dispatch<react.SetStateAction<number | null>>;
2727
- move: (fromIndex: number, toIndex: number) => void;
2728
- };
2729
-
2730
- type CellValue = string | number | null;
2731
- type GridData = CellValue[][];
2732
- interface UseSpreadsheetOptions {
2733
- rows: number;
2734
- cols: number;
2735
- initialData?: GridData;
2736
- }
2737
- declare function useSpreadsheet(options: UseSpreadsheetOptions): {
2738
- data: GridData;
2739
- setCell: (r: number, c: number, value: CellValue) => void;
2740
- selectedCell: {
2741
- r: number;
2742
- c: number;
2743
- } | null;
2744
- setSelectedCell: react.Dispatch<react.SetStateAction<{
2745
- r: number;
2746
- c: number;
2747
- } | null>>;
2748
- };
2749
-
2750
- type SortDirection = 'asc' | 'desc';
2751
- interface Column<T> {
2752
- /** Property key of the data item */
2753
- key: keyof T;
2754
- /** Header label for the column */
2755
- label: string;
2756
- /** Whether the column is sortable */
2757
- sortable?: boolean;
2758
- }
2759
- interface UseTableOptions<T> {
2760
- /** Array of data items to display */
2761
- data: T[];
2762
- /** Array of column definitions */
2763
- columns: Column<T>[];
2764
- /** Initial sorting configuration */
2765
- initialSort?: {
2766
- key: keyof T;
2767
- direction: SortDirection;
2768
- };
2769
- }
2770
- interface UseTableReturn<T> {
2771
- /** Sorted and filtered items */
2772
- items: T[];
2773
- /** Function to request sorting by a key */
2774
- requestSort: (key: keyof T) => void;
2775
- /** Current sort configuration */
2776
- sortConfig: {
2777
- key: keyof T;
2778
- direction: SortDirection;
2779
- } | null;
2780
- /** Column definitions (passed through) */
2781
- columns: Column<T>[];
2782
- }
2783
- /**
2784
- * useTable
2785
- *
2786
- * A headless hook for managing table state, including sorting and column definitions.
2787
- *
2788
- * @param options - Table configuration options
2789
- * @returns Object with sorted items and sort controls
2790
- *
2791
- * @example
2792
- * ```tsx
2793
- * interface User { id: number; name: string; age: number; email: string; }
2794
- *
2795
- * const data: User[] = [
2796
- * { id: 1, name: 'Alice', age: 28, email: 'alice@example.com' },
2797
- * { id: 2, name: 'Bob', age: 34, email: 'bob@example.com' },
2798
- * ];
2799
- *
2800
- * const columns: Column<User>[] = [
2801
- * { key: 'name', label: 'Full Name', sortable: true },
2802
- * { key: 'age', label: 'Age', sortable: true },
2803
- * { key: 'email', label: 'Email' },
2804
- * ];
2805
- *
2806
- * export function DataTable() {
2807
- * const { items, requestSort, sortConfig, columns: cols } = useTable({ data, columns });
2808
- *
2809
- * return (
2810
- * <table className="data-table">
2811
- * <thead>
2812
- * <tr>
2813
- * {cols.map(col => (
2814
- * <th
2815
- * key={col.key.toString()}
2816
- * onClick={() => col.sortable && requestSort(col.key)}
2817
- * className={col.sortable ? 'sortable' : ''}
2818
- * >
2819
- * {col.label}
2820
- * {sortConfig?.key === col.key && (
2821
- * <span>{sortConfig.direction === 'asc' ? ' ↑' : ' ↓'}</span>
2822
- * )}
2823
- * </th>
2824
- * ))}
2825
- * </tr>
2826
- * </thead>
2827
- * <tbody>
2828
- * {items.map(user => (
2829
- * <tr key={user.id}>
2830
- * <td>{user.name}</td>
2831
- * <td>{user.age}</td>
2832
- * <td>{user.email}</td>
2833
- * </tr>
2834
- * ))}
2835
- * </tbody>
2836
- * </table>
2837
- * );
2838
- * }
2839
- * ```
2840
- */
2841
- declare function useTable<T>(options: UseTableOptions<T>): UseTableReturn<T>;
2842
-
2843
- interface UseWebRTCOptions {
2844
- iceServers?: RTCIceServer[];
2845
- }
2846
- /**
2847
- * useWebRTC
2848
- *
2849
- * Basic wrapper for RTCPeerConnection.
2850
- */
2851
- declare function useWebRTC(options?: UseWebRTCOptions): {
2852
- pc: RTCPeerConnection | null;
2853
- connectionState: RTCPeerConnectionState;
2854
- signalingState: RTCSignalingState;
2855
- };
2856
-
2857
- interface UseWebSocketOptions {
2858
- onOpen?: (event: Event) => void;
2859
- onClose?: (event: CloseEvent) => void;
2860
- onMessage?: (event: MessageEvent) => void;
2861
- onError?: (event: Event) => void;
2862
- reconnect?: boolean;
2863
- reconnectAttempts?: number;
2864
- reconnectInterval?: number;
2865
- }
2866
- declare function useWebSocket(url: string, options?: UseWebSocketOptions): {
2867
- send: (data: string | ArrayBuffer | Blob | ArrayBufferView) => void;
2868
- lastMessage: MessageEvent<any> | null;
2869
- isConnected: boolean;
2870
- ws: WebSocket | null;
2871
- };
2872
-
2873
- declare function useClickAnywhere(handler: (event: MouseEvent) => void): void;
2874
-
2875
- interface UseCountdownOptions {
2876
- countStart: number;
2877
- intervalMs?: number;
2878
- isIncrement?: boolean;
2879
- countStop?: number;
2880
- }
2881
- interface UseCountdownReturn {
2882
- count: number;
2883
- startCountdown: () => void;
2884
- stopCountdown: () => void;
2885
- resetCountdown: () => void;
2886
- }
2887
- declare function useCountdown({ countStart, intervalMs, isIncrement, countStop, }: UseCountdownOptions): UseCountdownReturn;
2888
-
2889
- interface DebounceOptions {
2890
- leading?: boolean;
2891
- trailing?: boolean;
2892
- maxWait?: number;
2893
- }
2894
- interface ControlFunctions {
2895
- cancel: () => void;
2896
- flush: () => void;
2897
- }
2898
- declare function useDebounceCallback<T extends (...args: any[]) => any>(func: T, wait?: number, options?: DebounceOptions): ((...args: Parameters<T>) => void) & ControlFunctions;
2899
-
2900
- declare function useIsClient(): boolean;
2901
-
2902
- interface UseListActions<T> {
2903
- set: (list: T[]) => void;
2904
- push: (element: T) => void;
2905
- updateAt: (index: number, element: T) => void;
2906
- insertAt: (index: number, element: T) => void;
2907
- update: (predicate: (a: T, b: T) => boolean, newElement: T) => void;
2908
- removeAt: (index: number) => void;
2909
- clear: () => void;
2910
- reset: () => void;
2911
- }
2912
- type UseListReturn<T> = [T[], UseListActions<T>];
2913
- declare function useList<T>(initialList?: T[]): UseListReturn<T>;
2914
-
2915
- type MapOrEntries<K, V> = Map<K, V> | [K, V][];
2916
- interface UseMapActions<K, V> {
2917
- set: (key: K, value: V) => void;
2918
- setAll: (entries: MapOrEntries<K, V>) => void;
2919
- remove: (key: K) => void;
2920
- reset: () => void;
2921
- }
2922
- type UseMapReturn<K, V> = [Map<K, V>, UseMapActions<K, V>];
2923
- /**
2924
- * useMap
2925
- *
2926
- * A specific hook for managing `Map` state in React.
2927
- * Simplifies adding, removing, and updating Map entries while ensuring immutability.
2928
- *
2929
- * @param initialState - Initial Map entries
2930
- * @returns [map, actions]
2931
- *
2932
- * @example
2933
- * ```tsx
2934
- * const initialData = [['key1', 'value1'], ['key2', 'value2']] as const;
2935
- * const [map, mapActions] = useMap<string, string>(initialData);
2936
- *
2937
- * return (
2938
- * <div>
2939
- * <h3>Map Size: {map.size}</h3>
2940
- *
2941
- * <button onClick={() => mapActions.set('newKey', 'newValue')}>
2942
- * Add/Update Key
2943
- * </button>
2944
- * <button onClick={() => mapActions.setAll([['fresh', 'start']])}>
2945
- * Replace All
2946
- * </button>
2947
- * <button onClick={() => mapActions.reset()}>
2948
- * Reset to Initial
2949
- * </button>
2950
- *
2951
- * <ul>
2952
- * {Array.from(map.entries()).map(([key, value]) => (
2953
- * <li key={key}>
2954
- * <strong>{key}:</strong> {value}
2955
- * <button onClick={() => mapActions.remove(key)}>X</button>
2956
- * </li>
2957
- * ))}
2958
- * </ul>
2959
- * </div>
2960
- * );
2961
- * ```
2962
- */
2963
- declare function useMap<K, V>(initialState?: MapOrEntries<K, V>): UseMapReturn<K, V>;
2964
-
2965
- interface UseQueueActions<T> {
2966
- add: (element: T) => void;
2967
- remove: () => T | undefined;
2968
- clear: () => void;
2969
- }
2970
- type UseQueueReturn<T> = {
2971
- queue: T[];
2972
- first: T;
2973
- last: T;
2974
- size: number;
2975
- } & UseQueueActions<T>;
2976
- /**
2977
- * useQueue
2978
- *
2979
- * A hook for managing a queue data structure (FIFO - First In First Out).
2980
- *
2981
- * @param initialValue - Initial elements in the queue
2982
- * @returns Object with queue state and operations
2983
- *
2984
- * @example
2985
- * ```tsx
2986
- * const {
2987
- * add,
2988
- * remove,
2989
- * clear,
2990
- * first,
2991
- * last,
2992
- * size,
2993
- * queue
2994
- * } = useQueue<string>(['Task 1']);
2995
- *
2996
- * return (
2997
- * <div>
2998
- * <h2>Task Queue ({size})</h2>
2999
- *
3000
- * <div className="controls">
3001
- * <button onClick={() => add(`Task ${Date.now()}`)}>Add Task</button>
3002
- * <button onClick={() => remove()} disabled={size === 0}>Process Next</button>
3003
- * <button onClick={clear}>Clear All</button>
3004
- * </div>
3005
- *
3006
- * <div className="status">
3007
- * <p>Next: {first || 'None'}</p>
3008
- * <p>Newest: {last || 'None'}</p>
3009
- * </div>
3010
- *
3011
- * <ul>
3012
- * {queue.map((task, index) => (
3013
- * <li key={index}>{task}</li>
3014
- * ))}
3015
- * </ul>
3016
- * </div>
3017
- * );
3018
- * ```
3019
- */
3020
- /**
3021
- * useQueue
3022
- *
3023
- * A hook for managing a queue data structure (FIFO - First In First Out).
3024
- *
3025
- * @param initialValue - Initial elements in the queue
3026
- * @returns Object with queue state and operations
3027
- *
3028
- * @example
3029
- * ```tsx
3030
- * const {
3031
- * add,
3032
- * remove,
3033
- * clear,
3034
- * first,
3035
- * last,
3036
- * size,
3037
- * queue
3038
- * } = useQueue<string>(['Task 1']);
3039
- *
3040
- * return (
3041
- * <div>
3042
- * <h2>Task Queue ({size})</h2>
3043
- *
3044
- * <div className="controls">
3045
- * <button onClick={() => add(`Task ${Date.now()}`)}>Add Task</button>
3046
- * <button onClick={() => remove()} disabled={size === 0}>Process Next</button>
3047
- * <button onClick={clear}>Clear All</button>
3048
- * </div>
3049
- *
3050
- * <div className="status">
3051
- * <p>Next: {first || 'None'}</p>
3052
- * <p>Newest: {last || 'None'}</p>
3053
- * </div>
3054
- *
3055
- * <ul>
3056
- * {queue.map((task, index) => (
3057
- * <li key={index}>{task}</li>
3058
- * ))}
3059
- * </ul>
3060
- * </div>
3061
- * );
3062
- * ```
3063
- */
3064
- declare function useQueue<T>(initialValue?: T[]): UseQueueReturn<T>;
3065
-
3066
- declare function useScreen(): Screen | undefined;
3067
-
3068
- interface UseSetActions<K> {
3069
- add: (key: K) => void;
3070
- remove: (key: K) => void;
3071
- toggle: (key: K) => void;
3072
- reset: () => void;
3073
- clear: () => void;
3074
- }
3075
- type UseSetReturn<K> = [Set<K>, UseSetActions<K>];
3076
- /**
3077
- * useSet
3078
- *
3079
- * A specific hook for managing `Set` state in React.
3080
- * Useful for tracking selections, tags, or active filters.
3081
- *
3082
- * @param initialSet - Initial Set entries
3083
- * @returns [set, actions]
3084
- *
3085
- * @example
3086
- * ```tsx
3087
- * const availableTags = ['React', 'Vue', 'Angular', 'Svelte'];
3088
- * const [selectedTags, { toggle, has, clear }] = useSet<string>(new Set(['React']));
3089
- *
3090
- * return (
3091
- * <div>
3092
- * <h2>Select Frameworks ({selectedTags.size})</h2>
3093
- *
3094
- * <div className="tags">
3095
- * {availableTags.map(tag => (
3096
- * <button
3097
- * key={tag}
3098
- * onClick={() => toggle(tag)}
3099
- * className={selectedTags.has(tag) ? 'active' : ''}
3100
- * >
3101
- * {tag} {selectedTags.has(tag) ? '✓' : ''}
3102
- * </button>
3103
- * ))}
3104
- * </div>
3105
- *
3106
- * <button onClick={clear}>Clear Selection</button>
3107
- *
3108
- * <pre>
3109
- * Selection: {JSON.stringify(Array.from(selectedTags))}
3110
- * </pre>
3111
- * </div>
3112
- * );
3113
- * ```
3114
- */
3115
- declare function useSet<K>(initialSet?: Set<K>): UseSetReturn<K>;
3116
-
3117
- /**
3118
- * Check if code is running on the server (SSR)
3119
- */
3120
- declare const isServer: boolean;
3121
- /**
3122
- * Check if code is running in the browser
3123
- */
3124
- declare const isBrowser: boolean;
3125
- /**
3126
- * No-operation function
3127
- */
3128
- declare const noop: () => void;
3129
-
3130
- export { type AnimationCallback, type AnthropicMessage, type AnyEvent, type AsyncStatus, type BatteryState, type CellValue, type CollabEvent, type Column, type EyeDropperOpenOptions, type FetchStatus, type GeminiContent, type GeminiPart, type GridData, type HighlightPart, type MachineConfig, type MachineState, type Message, type NetworkState, type PermissionName, type PermissionState, type RAGDocument, type RecorderStatus, type ScriptStatus, type ScrollPosition, type SemanticResult, type ShareData, type ShortcutHandler, type ShortcutMap, type SortDirection, type SpringConfig, type StorageEstimateState, type Theme, type UseAnthropicOptions, type UseAsyncOptions, type UseAsyncReturn, type UseBluetoothReturn, type UseCalendarOptions, type UseCanvasOptions, type UseClickOutsideOptions, type UseCopyToClipboardReturn, type UseCountdownOptions, type UseCountdownReturn, type UseCounterOptions, type UseCounterReturn, type UseDebounceOptions, type UseDebounceReturn, type UseDocumentTitleOptions, type UseDragAndDropOptions, type UseEmbeddingsReturn, type UseEventOptions, type UseEyeDropperReturn, type UseFetchOptions, type UseFetchReturn, type UseFileProcessingOptions, type UseFileSystemReturn, type UseFormOptions, type UseFormReturn, type UseFullscreenReturn, type UseGamepadOptions, type UseGeminiOptions, type UseHistoryOptions, type UseHistoryReturn, type UseHoverReturn, type UseIndexedDBReturn, type UseInfiniteScrollOptions, type UseIntersectionOptions, type UseIntersectionReturn, type UseIntervalOptions, type UseIntervalReturn, type UseKeyPressOptions, type UseLLMStreamOptions, type UseLLMStreamReturn, type UseListActions, type UseListReturn, type UseLocalStorageOptions, type UseLocalStorageReturn, type UseLongPressOptions, type UseLongPressReturn, type UseLottieOptions, type UseMapActions, type UseMapReturn, type UseMediaQueryOptions, type UseMediaRecorderReturn, type UseMediaRefReturn, type UseMutationObserverOptions, type UseOnlineReturn, type UseOpenAIOptions, type UsePaginationOptions, type UsePaginationReturn, type UseParallaxOptions, type UseQueueActions, type UseQueueReturn, type UseRAGOptions, type UseResizeObserverOptions, type UseSTTOptions, type UseSTTReturn, type UseSVGAnimationOptions, type UseScriptOptions, type UseScriptReturn, type UseScrollOptions, type UseScrollReturn, type UseSearchHighlightOptions, type UseSessionStorageOptions, type UseSetActions, type UseSetReturn, type UseShareReturn, type UseSortableOptions, type UseSpreadsheetOptions, type UseSpringCoreOptions, type UseStepOptions, type UseStepReturn, type UseTTSOptions, type UseTableOptions, type UseTableReturn, type UseThemeOptions, type UseThemeReturn, type UseThreeJSOptions, type UseThrottleOptions, type UseThrottleReturn, type UseTimeoutOptions, type UseTimeoutReturn, type UseToggleOptions, type UseToggleReturn, type UseVirtualListOptions, type UseVirtualListReturn, type UseWakeLockReturn, type UseWebRTCOptions, type UseWebSocketOptions, type UseWindowSizeOptions, type UseWorkerReturn, type Vector, type VirtualItem, type WindowSize, type WorkerStatus, isBrowser, isServer, noop, useAnimate, useAnthropic, useAsync, useAudioRef, useBattery, useBluetooth, useBroadcastChannel, useCalendar, useCanvas, useClickAnywhere, useClickOutside, useCopyToClipboard, useCountdown, useCounter, useDebounce, useDebounceCallback, useDocumentTitle, useDragAndDrop, useEmbeddings, useEvent, useEyeDropper, useFetch, useFileProcessing, useFileSystem, useForm, useFrameRate, useFullscreen, useGamepad, useGemini, useHistory, useHover, useIndexedDB, useInfiniteScroll, useIntersection, useInterval, useIsClient, useIsMounted, useIsomorphicLayoutEffect, useKeyPress, useLLMStream, useList, useLocalStorage, useLockBodyScroll, useLongPress, useLottie, useMachine, useMap, useMarkdown, useMediaDevices, useMediaQuery, useMediaRecorder, useMount, useMutationObserver, useNetworkState, useOnline, useOpenAI, usePDF, usePageLeave, usePagination, useParallax, usePermissions, usePresence, usePrevious, useQueue, useRAG, useRealtimeCollab, useResizeObserver, useSTT, useSVGAnimation, useScreen, useScript, useScroll, useSearchHighlight, useSemanticSearch, useSessionStorage, useSet, useShare, useShortcuts, useSortable, useSpreadsheet, useSpringCore, useStableCallback, useStep, useStorageEstimate, useTTS, useTable, useTheme, useThreeJS, useThrottle, useTimeout, useToggle, useUnmount, useUpdateEffect, useVideoRef, useVirtualList, useWakeLock, useWebRTC, useWebSocket, useWindowFocus, useWindowSize, useWorker };