sse-hooks 1.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts DELETED
@@ -1,2429 +0,0 @@
1
- import React$1, { Dispatch, SetStateAction, RefObject, useEffect } from 'react';
2
-
3
- declare enum EffectFlags {
4
- ACTIVE = 1,
5
- RUNNING = 2,
6
- TRACKING = 4,
7
- NOTIFIED = 8,
8
- DIRTY = 16,
9
- ALLOW_RECURSE = 32,
10
- PAUSED = 64
11
- }
12
- declare enum TrackOpTypes {
13
- GET = "get",
14
- HAS = "has",
15
- ITERATE = "iterate"
16
- }
17
- declare enum TriggerOpTypes {
18
- SET = "set",
19
- ADD = "add",
20
- DELETE = "delete",
21
- CLEAR = "clear"
22
- }
23
- declare const ReactiveFlags: {
24
- readonly IS_REF: "__v_isRef";
25
- readonly IS_READONLY: "__v_isReadonly";
26
- readonly SKIP: "__v_skip";
27
- };
28
-
29
- declare let globalVersion: number;
30
- declare class Link {
31
- sub: Subscriber;
32
- dep: Dep;
33
- version: number;
34
- nextDep?: Link;
35
- prevDep?: Link;
36
- nextSub?: Link;
37
- prevSub?: Link;
38
- prevActiveLink?: Link;
39
- constructor(sub: Subscriber, dep: Dep);
40
- }
41
- declare class Dep {
42
- computed?: ComputedRefImpl | undefined;
43
- version: number;
44
- activeLink?: Link;
45
- subs?: Link;
46
- subsHead?: Link;
47
- map?: Map<any, Dep>;
48
- key?: unknown;
49
- sc: number;
50
- constructor(computed?: ComputedRefImpl | undefined);
51
- track(debugInfo?: DebuggerEventExtraInfo): Link | undefined;
52
- trigger(debugInfo?: DebuggerEventExtraInfo): void;
53
- notify(debugInfo?: DebuggerEventExtraInfo): void;
54
- }
55
- type KeyToDepMap = Map<any, Dep>;
56
- declare const targetMap: WeakMap<object, KeyToDepMap>;
57
- declare function track(target: object, type: TrackOpTypes, key: unknown): void;
58
-
59
- interface Subscriber {
60
- deps?: Link;
61
- depsTail?: Link;
62
- flags: EffectFlags;
63
- next?: Subscriber;
64
- notify(): true | void;
65
- onTrack?: (event: DebuggerEvent) => void;
66
- onTrigger?: (event: DebuggerEvent) => void;
67
- }
68
- type DebuggerEvent = {
69
- effect: Subscriber;
70
- } & DebuggerEventExtraInfo;
71
- type DebuggerEventExtraInfo = {
72
- target: object;
73
- type: TrackOpTypes | TriggerOpTypes;
74
- key: any;
75
- newValue?: any;
76
- oldValue?: any;
77
- oldTarget?: Map<any, any> | Set<any>;
78
- };
79
- interface DebuggerOptions {
80
- onTrack?: (event: DebuggerEvent) => void;
81
- onTrigger?: (event: DebuggerEvent) => void;
82
- }
83
- declare let shouldTrack: boolean;
84
- declare function getActiveSub(): Subscriber | undefined;
85
- declare function setActiveSub(sub: Subscriber | undefined): void;
86
- declare function startBatch(): void;
87
- declare function endBatch(): void;
88
- declare function batch(sub: Subscriber, isComputed?: boolean): void;
89
-
90
- interface Ref<T = any> {
91
- value: T;
92
- }
93
- declare class RefImpl<T> implements Ref<T> {
94
- private _value;
95
- dep: Dep;
96
- __v_isRef: boolean;
97
- constructor(value: T);
98
- get value(): T;
99
- set value(newVal: T);
100
- }
101
- declare function ref<T>(value: T): Ref<T>;
102
-
103
- declare const ComputedRefSymbol: unique symbol;
104
- type BaseComputedRef<T> = Ref<T> & {
105
- [ComputedRefSymbol]: true;
106
- effect: Subscriber;
107
- };
108
- type ComputedRef<T = any> = BaseComputedRef<T> & {
109
- readonly value: T;
110
- };
111
- type ComputedGetter<T> = (oldValue?: T) => T;
112
- type ComputedSetter<T> = (newValue: T) => void;
113
- interface WritableComputedOptions<T> {
114
- get: ComputedGetter<T>;
115
- set: ComputedSetter<T>;
116
- }
117
- declare function refreshComputed(computed: ComputedRefImpl): void;
118
- declare class ComputedRefImpl<T = any> implements Subscriber {
119
- fn: ComputedGetter<T>;
120
- private readonly setter;
121
- _value: any;
122
- readonly dep: Dep;
123
- readonly __v_isRef = true;
124
- deps?: Link;
125
- depsTail?: Link;
126
- flags: EffectFlags;
127
- globalVersion: number;
128
- isSSR: boolean;
129
- effect: this;
130
- onTrack?: (event: DebuggerEvent) => void;
131
- onTrigger?: (event: DebuggerEvent) => void;
132
- constructor(fn: ComputedGetter<T>, setter: ComputedSetter<T> | undefined, isSSR: boolean);
133
- notify(): true | void;
134
- get value(): T;
135
- set value(newValue: T);
136
- }
137
- declare function computed<T>(getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T>, debugOptions?: DebuggerOptions, isSSR?: boolean): any;
138
-
139
- declare function useReactive<T>(refObj: Ref<T>): T;
140
- declare function useComputed<T>(getter: () => T, deps?: any[]): T;
141
-
142
- declare const extend: {
143
- <T extends {}, U>(target: T, source: U): T & U;
144
- <T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
145
- <T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
146
- (target: object, ...sources: any[]): any;
147
- };
148
- declare const isArray: (arg: any) => arg is any[];
149
- declare const isMap: (val: unknown) => val is Map<any, any>;
150
- declare const isFunction: (val: unknown) => val is Function;
151
- declare const isSymbol: (val: unknown) => val is symbol;
152
- declare const isObject: (val: unknown) => val is Record<any, any>;
153
- declare const isIntegerKey: (key: any) => boolean;
154
- declare const __DEV__: boolean;
155
-
156
- /** Supported audio MIME types for recording. */
157
- type AudioMimeType = "audio/webm" | "audio/webm;codecs=opus" | "audio/webm;codecs=vorbis" | "audio/ogg" | "audio/ogg;codecs=opus" | "audio/ogg;codecs=vorbis" | "application/ogg" | "audio/mp4" | "audio/mp4;codecs=mp4a.40.2" | "audio/aac" | "audio/x-m4a" | "audio/mpeg" | "audio/mp3" | "audio/wav" | "audio/x-wav" | "audio/wave" | "audio/flac" | "audio/3gpp" | "audio/3gpp2";
158
- /** Options for configuring the useAudioRecorder hook. */
159
- interface UseAudioRecorderOptions {
160
- /**
161
- * Audio bitrate in bits per second.
162
- * @default 128000
163
- */
164
- audioBitsPerSecond?: number;
165
- /**
166
- * MIME type for the recorded audio.
167
- * @default "audio/webm"
168
- */
169
- mimeType?: AudioMimeType;
170
- /**
171
- * Timeslice (ms) for MediaRecorder data chunks.
172
- */
173
- timeslice?: number;
174
- /**
175
- * If set, enables real-time audio analysis during recording.
176
- */
177
- enableAnalysis?: boolean;
178
- /**
179
- * FFT size for audio analysis.
180
- * @default 2048
181
- */
182
- fftSize?: number;
183
- }
184
- /** Audio analysis data returned when `enableAnalysis` is true. */
185
- interface AudioAnalysisData {
186
- /** Frequency domain data (FFT). */
187
- frequencyData: Uint8Array;
188
- /** Time domain waveform data. */
189
- timeData: Uint8Array;
190
- /** Calculated RMS volume level. */
191
- volume: number;
192
- }
193
- /** The useAudioRecorder return type. */
194
- interface UseAudioRecorderReturn {
195
- /** Whether audio recording is supported in the current browser. */
196
- isSupported: boolean;
197
- /** Whether recording is currently active. */
198
- isRecording: boolean;
199
- /** Whether recording is currently paused. */
200
- isPaused: boolean;
201
- /** Active media stream. */
202
- stream: MediaStream | null;
203
- /** MediaRecorder instance. */
204
- mediaRecorder: MediaRecorder | null;
205
- /** Final recorded audio blob. */
206
- audioBlob: Blob | null;
207
- /** Object URL for the recorded audio. */
208
- audioUrl: string | null;
209
- /** Duration of the recording in seconds. */
210
- duration: number;
211
- /** Error message if recording fails. */
212
- error: string | null;
213
- /** Live audio analysis data. */
214
- analysisData: AudioAnalysisData | null;
215
- /** Starts audio recording. */
216
- startRecording: () => Promise<void>;
217
- /** Stops audio recording. */
218
- stopRecording: () => void;
219
- /** Pauses the recording. */
220
- pauseRecording: () => void;
221
- /** Resumes a paused recording. */
222
- resumeRecording: () => void;
223
- /** Clears the current recording state. */
224
- clearRecording: () => void;
225
- /** Downloads the recording as a file. */
226
- downloadRecording: (filename?: string) => void;
227
- }
228
-
229
- /**
230
- * A comprehensive hook for audio recording with real-time analysis using getUserMedia, MediaRecorder, and Web Audio APIs
231
- *
232
- * @category sensors
233
- * @param {UseAudioRecorderOptions} [options] - Configuration options for audio recording.
234
- * @returns {UseAudioRecorderReturn} Object containing recording state, audio data, and control methods.
235
- * @throws Will set an error if audio recording is not supported or permission is denied.
236
- * @public
237
- * @example
238
- * ```tsx
239
- * const {
240
- * isRecording,
241
- * startRecording,
242
- * stopRecording,
243
- * audioUrl,
244
- * } = useAudioRecorder({ enableAnalysis: true });
245
- * ```
246
- */
247
- declare const useAudioRecorder: (options?: UseAudioRecorderOptions) => UseAudioRecorderReturn;
248
-
249
- /**
250
- * Represents the state of the battery.
251
- */
252
- interface BatteryState {
253
- /**
254
- * A boolean value indicating whether the battery is currently being charged.
255
- */
256
- charging: boolean;
257
- /**
258
- * A number representing the remaining time in seconds until the battery is fully charged,
259
- * or 0 if the battery is already fully charged.
260
- */
261
- chargingTime: number;
262
- /**
263
- * A number representing the remaining time in seconds until the battery is completely discharged
264
- * and the system will suspend.
265
- */
266
- dischargingTime: number;
267
- /**
268
- * A number representing the system's battery charge level scaled to a value between 0.0 and 1.0.
269
- */
270
- level: number;
271
- }
272
- /**
273
- * Return type for the `useBattery` hook.
274
- * It is a discriminated union based on the `isSupported` and `fetched` states.
275
- */
276
- type UseBatteryState = {
277
- isSupported: false;
278
- } | {
279
- isSupported: true;
280
- fetched: false;
281
- } | (BatteryState & {
282
- isSupported: true;
283
- fetched: true;
284
- });
285
- /**
286
- * Custom hook that tracks the state of the device's battery using the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API).
287
- *
288
- * It returns the battery level, charging status, charging time, and discharging time.
289
- * If the API is not supported, `isSupported` will be false.
290
- *
291
- * @returns {UseBatteryState} The current state of the battery, including support and fetch status.
292
- * @public
293
- * @example
294
- * ```tsx
295
- * const battery = useBattery();
296
- *
297
- * if (!battery.isSupported) {
298
- * return <p>Battery API is not supported on this device.</p>;
299
- * }
300
- *
301
- * if (!battery.fetched) {
302
- * return <p>Fetching battery status...</p>;
303
- * }
304
- *
305
- * return (
306
- * <div>
307
- * <p>Battery Level: {(battery.level * 100).toFixed(0)}%</p>
308
- * <p>Charging: {battery.charging ? 'Yes' : 'No'}</p>
309
- * </div>
310
- * );
311
- * ```
312
- */
313
- declare function useBattery(): UseBatteryState;
314
- /**
315
- * Custom hook that tracks the state of the device's battery using the [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API).
316
- *
317
- * It returns the battery level, charging status, charging time, and discharging time.
318
- * If the API is not supported, `isSupported` will be false.
319
- *
320
- * @returns {UseBatteryState} The current state of the battery, including support and fetch status.
321
- * @public
322
- * @example
323
- * ```tsx
324
- * const battery = useBattery();
325
- *
326
- * if (!battery.isSupported) {
327
- * return <p>Battery API is not supported on this device.</p>;
328
- * }
329
- *
330
- * if (!battery.fetched) {
331
- * return <p>Fetching battery status...</p>;
332
- * }
333
- *
334
- * return (
335
- * <div>
336
- * <p>Battery Level: {(battery.level * 100).toFixed(0)}%</p>
337
- * <p>Charging: {battery.charging ? 'Yes' : 'No'}</p>
338
- * </div>
339
- * );
340
- * ```
341
- */
342
- declare const useBatteryHook: typeof useBattery;
343
-
344
- /** The useBoolean return type. */
345
- type UseBooleanReturn = {
346
- /** The current boolean state value. */
347
- value: boolean;
348
- /** Function to set the boolean state directly. */
349
- setValue: React$1.Dispatch<React$1.SetStateAction<boolean>>;
350
- /** Function to set the boolean state to `true`. */
351
- setTrue: () => void;
352
- /** Function to set the boolean state to `false`. */
353
- setFalse: () => void;
354
- /** Function to toggle the boolean state. */
355
- toggle: () => void;
356
- };
357
- /**
358
- * Custom hook that handles boolean state with useful utility functions.
359
- *
360
- * @category state
361
- * @param {boolean} [defaultValue] - The initial value for the boolean state (default is `false`).
362
- * @returns {UseBooleanReturn} An object containing the boolean state value and utility functions to manipulate the state.
363
- * @throws Will throw an error if `defaultValue` is an invalid boolean value.
364
- * @public
365
- * @example
366
- * ```tsx
367
- * const { value, setTrue, setFalse, toggle } = useBoolean(true);
368
- * ```
369
- */
370
- declare function useBoolean(defaultValue?: boolean): UseBooleanReturn;
371
-
372
- /**
373
- * Breakpoints from Tailwind V2
374
- *
375
- * @see https://tailwindcss.com/docs/breakpoints
376
- */
377
- declare const breakpointsTailwind: {
378
- sm: number;
379
- md: number;
380
- lg: number;
381
- xl: number;
382
- "2xl": number;
383
- };
384
- /**
385
- * Breakpoints from Bootstrap V5
386
- *
387
- * @see https://getbootstrap.com/docs/5.0/layout/breakpoints
388
- */
389
- declare const breakpointsBootstrapV5: {
390
- sm: number;
391
- md: number;
392
- lg: number;
393
- xl: number;
394
- xxl: number;
395
- };
396
- /**
397
- * Breakpoints from Vuetify V2
398
- *
399
- * @see https://vuetifyjs.com/en/features/breakpoints
400
- */
401
- declare const breakpointsVuetify: {
402
- xs: number;
403
- sm: number;
404
- md: number;
405
- lg: number;
406
- };
407
- /**
408
- * Breakpoints from Ant Design
409
- *
410
- * @see https://ant.design/components/layout/#breakpoint-width
411
- */
412
- declare const breakpointsAntDesign: {
413
- xs: number;
414
- sm: number;
415
- md: number;
416
- lg: number;
417
- xl: number;
418
- xxl: number;
419
- };
420
- /**
421
- * Sematic Breakpoints
422
- */
423
- declare const breakpointsSematic: {
424
- mobileS: number;
425
- mobileM: number;
426
- mobileL: number;
427
- tablet: number;
428
- laptop: number;
429
- laptopL: number;
430
- desktop4K: number;
431
- };
432
-
433
- declare function useBreakpoint<BreakPoints extends Record<string, number>, BreakPointsKey extends keyof BreakPoints = keyof BreakPoints>(breakpoints: BreakPoints): {
434
- /**
435
- * Hook that returns a boolean if screen width is greater than given breakpoint.
436
- *
437
- * @param k {string} breakpoint
438
- * @returns boolean
439
- *
440
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
441
- **/
442
- useGreater: (k: BreakPointsKey) => boolean;
443
- /**
444
- * Hook that returns a boolean if screen width is smaller than given breakpoint.
445
- *
446
- * @param k {string} breakpoint
447
- * @param k {string} breakpoint
448
- *
449
- * @returns boolean
450
- *
451
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
452
- **/
453
- useSmaller: (k: BreakPointsKey) => boolean;
454
- /**
455
- * Hook that returns a boolean if screen width is between two given breakpoint.
456
- *
457
- * @param a {string} breakpoint
458
- * @param b {string} breakpoint
459
- *
460
- * @returns boolean
461
- *
462
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
463
- **/
464
- useBetween: (a: BreakPointsKey, b: BreakPointsKey) => boolean;
465
- /**
466
- * Utility function that returns a boolean if screen width is greater than given breakpoint.
467
- *
468
- * @param k {string} breakpoint
469
- *
470
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
471
- **/
472
- isGreater(k: BreakPointsKey): boolean;
473
- /**
474
- * Utility function that returns a boolean if screen width is smaller than given breakpoint.
475
- *
476
- * @param k {string} breakpoint
477
- *
478
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
479
- **/
480
- isSmaller(k: BreakPointsKey): boolean;
481
- /**
482
- * Utility function that returns a boolean if screen width is between two given breakpoint.
483
- *
484
- * @param k {string} breakpoint
485
- *
486
- * @see https://react-hooks-library.vercel.app/core/BreakPointHooks
487
- **/
488
- isInBetween(a: BreakPointsKey, b: BreakPointsKey): boolean;
489
- };
490
-
491
- /**
492
- * Custom hook that handles click events anywhere on the document.
493
- *
494
- * @category dom
495
- * @param {Function} handler - The function to be called when a click event is detected anywhere on the document.
496
- * @public
497
- * @see [Documentation](/docs/use-click-any-where)
498
- * @example
499
- * ```tsx
500
- * const handleClick = (event) => {
501
- * console.log('Document clicked!', event);
502
- * };
503
- *
504
- * // Attach click event handler to document
505
- * useClickAnywhere(handleClick);
506
- * ```
507
- */
508
- declare function useClickAnyWhere(handler: (event: MouseEvent) => void): void;
509
-
510
- /**
511
- * Supported touch events for the click-away listener.
512
- */
513
- type ClickAwayTouchEventHandler = "onTouchStart" | "onTouchEnd";
514
- /**
515
- * Supported mouse events for the click-away listener.
516
- */
517
- type ClickAwayMouseEventHandler = "onClick" | "onMouseDown" | "onMouseUp" | "onPointerDown" | "onPointerUp";
518
- /**
519
- * Options for the `useClickAway` hook.
520
- */
521
- interface UseClickAwayOptions {
522
- /**
523
- * If `true`, the React tree is ignored and only the DOM tree is considered.
524
- * This prop changes how portaled elements are handled.
525
- * @default false
526
- */
527
- disableReactTree?: boolean;
528
- /**
529
- * The mouse event to listen to. You can disable the listener by providing `false`.
530
- * @default 'onClick'
531
- */
532
- mouseEvent?: ClickAwayMouseEventHandler | false;
533
- /**
534
- * The touch event to listen to. You can disable the listener by providing `false`.
535
- * @default 'onTouchEnd'
536
- */
537
- touchEvent?: ClickAwayTouchEventHandler | false;
538
- /**
539
- * An external ref to merge with the hook's internal ref.
540
- * Useful if you need to access the DOM element outside of this hook.
541
- */
542
- ref?: React$1.Ref<Element>;
543
- }
544
- /**
545
- * Custom hook that triggers a callback when a user clicks outside the referenced element.
546
- * It handles portal elements, scrollbar clicks, and touch interactions intelligently.
547
- *
548
- * @category dom
549
- * @param onClickAway - The callback function to be called when a click outside is detected.
550
- * @param options - Configuration options for the hook.
551
- * @returns {object} An object containing the `ref` to attach to the target element and `listenerProps` to spread.
552
- * @public
553
- * @example
554
- * ```tsx
555
- * const handleClickAway = () => {
556
- * console.log('Clicked outside!');
557
- * setOpen(false);
558
- * };
559
- *
560
- * const { ref, listenerProps } = useClickAway(handleClickAway);
561
- *
562
- * return (
563
- * <div ref={ref} {...listenerProps}>
564
- * I will detect clicks outside of me.
565
- * </div>
566
- * );
567
- * ```
568
- */
569
- declare function useClickAway(onClickAway: (event: MouseEvent | TouchEvent) => void, options?: UseClickAwayOptions): {
570
- ref: React$1.Ref<Element>;
571
- listenerProps: Record<string, any>;
572
- };
573
-
574
- interface UseScreenShareOptions {
575
- /**
576
- * Boolean or specific constraints for the video track.
577
- * @default true
578
- */
579
- video?: boolean | MediaTrackConstraints;
580
- /**
581
- * Boolean or specific constraints for the audio track.
582
- * @default true
583
- */
584
- audio?: boolean | MediaTrackConstraints;
585
- }
586
- interface UseScreenShareReturn {
587
- /**
588
- * The current MediaStream object, or null if no stream is active.
589
- */
590
- stream: MediaStream | null;
591
- /**
592
- * An error message string if the media capture failed, or null otherwise.
593
- */
594
- error: string | null;
595
- /**
596
- * A boolean indicating if the media stream is currently loading (requesting permission).
597
- */
598
- isLoading: boolean;
599
- /**
600
- * A boolean indicating if the `getUserMedia` API is supported in the current environment.
601
- */
602
- isSupported: boolean;
603
- /**
604
- * Function to start capturing media. Accepts optional constraints to override defaults.
605
- */
606
- startCapture: (constraints?: UseScreenShareOptions) => Promise<void>;
607
- /**
608
- * Function to stop the current media capture and release tracks.
609
- */
610
- stopCapture: () => void;
611
- }
612
-
613
- /**
614
- * Custom hook that captures the user's screen or specific application window.
615
- * It handles permission errors, stream management, native stop events, and cleanup.
616
- *
617
- * @category sensors
618
- * @param initialOptions - The initial options for screen sharing (video/audio).
619
- * @returns {UseScreenShareReturn} An object containing the stream, error state, and control functions.
620
- * @public
621
- * @example
622
- * ```tsx
623
- * const { stream, error, startCapture, stopCapture } = useScreenShare();
624
- *
625
- * return (
626
- * <div>
627
- * {error && <p>Error: {error}</p>}
628
- * <video
629
- * autoPlay
630
- * muted
631
- * playsInline
632
- * ref={(node) => {
633
- * if (node && stream) node.srcObject = stream;
634
- * }}
635
- * />
636
- * <button onClick={() => startCapture()}>Share Screen</button>
637
- * <button onClick={stopCapture}>Stop Sharing</button>
638
- * </div>
639
- * );
640
- * ```
641
- */
642
- declare function useScreenShare(initialOptions?: UseScreenShareOptions): {
643
- stream: MediaStream | null;
644
- error: string | null;
645
- isLoading: boolean;
646
- isSupported: boolean;
647
- startCapture: (options?: UseScreenShareOptions) => Promise<void>;
648
- stopCapture: () => void;
649
- };
650
-
651
- /**
652
- * Constraints for the `useUserMedia` hook.
653
- * Defines the video and audio settings for the media stream.
654
- */
655
- interface UseUserMediaConstraints {
656
- /**
657
- * Boolean or specific constraints for the video track.
658
- * @default true
659
- */
660
- video?: boolean | MediaTrackConstraints;
661
- /**
662
- * Boolean or specific constraints for the audio track.
663
- * @default true
664
- */
665
- audio?: boolean | MediaTrackConstraints;
666
- }
667
- /**
668
- * Return type for the `useUserMedia` hook.
669
- */
670
- interface UseUserMediaReturn {
671
- /**
672
- * The current MediaStream object, or null if no stream is active.
673
- */
674
- stream: MediaStream | null;
675
- /**
676
- * An error message string if the media capture failed, or null otherwise.
677
- */
678
- error: string | null;
679
- /**
680
- * A boolean indicating if the media stream is currently loading (requesting permission).
681
- */
682
- isLoading: boolean;
683
- /**
684
- * A boolean indicating if the `getUserMedia` API is supported in the current environment.
685
- */
686
- isSupported: boolean;
687
- /**
688
- * Function to start capturing media. Accepts optional constraints to override defaults.
689
- */
690
- startCapture: (constraints?: UseUserMediaConstraints) => Promise<void>;
691
- /**
692
- * Function to stop the current media capture and release tracks.
693
- */
694
- stopCapture: () => void;
695
- }
696
-
697
- /**
698
- * Custom hook that captures audio and video from the user's device.
699
- * It handles permission errors, stream management, and cleanup automatically.
700
- *
701
- * @category sensors
702
- * @param initialConstraints - The initial constraints for audio and video.
703
- * @returns {UseUserMediaReturn} An object containing the stream, error state, and control functions.
704
- * @public
705
- * @example
706
- * ```tsx
707
- * const { stream, error, startCapture, stopCapture } = useUserMedia();
708
- *
709
- * return (
710
- * <div>
711
- * {error && <p>Error: {error}</p>}
712
- * <video
713
- * autoPlay
714
- * muted
715
- * playsInline
716
- * ref={(node) => {
717
- * if (node && stream) node.srcObject = stream;
718
- * }}
719
- * />
720
- * <button onClick={() => startCapture()}>Start Camera</button>
721
- * <button onClick={stopCapture}>Stop Camera</button>
722
- * </div>
723
- * );
724
- * ```
725
- */
726
- declare const useUserMedia: (initialConstraints?: UseUserMediaConstraints) => UseUserMediaReturn;
727
-
728
- type MediaQuality = "low" | "medium" | "high";
729
- type QualityPresetTypes = Record<MediaQuality, MediaTrackConstraints>;
730
- interface UseMediaQualityReturn {
731
- /** The current quality preset being used. */
732
- quality: MediaQuality;
733
- /** Whether the constraints are currently being applied to the track. */
734
- isChanging: boolean;
735
- /** Function to change the video quality. */
736
- setQuality: (level: MediaQuality) => Promise<void>;
737
- }
738
-
739
- /**
740
- * Custom hook to manage video stream quality by applying constraints (resolution and frame rate)
741
- * to a MediaStream track.
742
- * * @category utilities
743
- * @param {MediaStream | null} stream - The MediaStream containing the video track to adjust.
744
- * @returns {UseMediaQualityReturn} The current quality state and a setter function.
745
- * @public
746
- * @see [Documentation](/docs/use-media-quality)
747
- * @example
748
- * ```tsx
749
- * const { quality, setQuality, isChanging } = useMediaQuality(userVideoStream);
750
- * * const handleHDClick = () => {
751
- * setQuality('high'); // Switches to 1280x720
752
- * };
753
- * ```
754
- */
755
- declare const useMediaQuality: (stream: MediaStream | null) => UseMediaQualityReturn;
756
-
757
- /**
758
- * Configuration options for the conference system hook.
759
- */
760
- interface UseConferenceSystemOptions {
761
- /**
762
- * Whether to enable automatic network-based quality scaling on mount.
763
- * @default true
764
- */
765
- defaultAutoQuality?: boolean;
766
- }
767
- /**
768
- * The state and controller object returned by the useConferenceSystem hook.
769
- */
770
- interface UseConferenceSystemReturns {
771
- /** Camera management and state */
772
- camera: {
773
- /** The active MediaStream for the camera, or null if inactive. */
774
- stream: MediaStream | null;
775
- /** Starts the camera capture with optional constraints. */
776
- start: (constraints?: UseUserMediaConstraints) => Promise<void>;
777
- /** Stops the camera capture and clears the stream. */
778
- stop: () => void;
779
- /** Whether the camera stream is currently active. */
780
- isActive: boolean;
781
- /** Error message if camera access or capture fails. */
782
- error: string | null;
783
- /** Indicates if the camera is currently requesting permissions or initializing. */
784
- isLoading: boolean;
785
- };
786
- /** Screen sharing management and state */
787
- screen: {
788
- /** The active MediaStream for screen sharing, or null if inactive. */
789
- stream: MediaStream | null;
790
- /** Starts the screen share capture process. */
791
- start: (options?: UseScreenShareOptions) => Promise<void>;
792
- /** Stops the screen share and clears the stream. */
793
- stop: () => void;
794
- /** Whether the screen share is currently active. */
795
- isActive: boolean;
796
- /** Error message if screen share access fails or is denied. */
797
- error: string | null;
798
- };
799
- /** Media quality management */
800
- quality: {
801
- /** The currently applied quality level ('low', 'medium', 'high'). */
802
- current: MediaQuality;
803
- /** Whether a quality transition is currently in progress. */
804
- isChanging: boolean;
805
- /** Manually sets the media quality level (overrides auto-quality). */
806
- set: (level: MediaQuality) => Promise<void>;
807
- /** Whether automatic quality adjustment is currently enabled. */
808
- isAuto: boolean;
809
- /** Toggles the automatic quality scaling logic on or off. */
810
- toggleAuto: () => void;
811
- };
812
- /** Network status and telemetry */
813
- network: {
814
- /** Boolean indicating if the browser has an active internet connection. */
815
- isOnline: boolean;
816
- /** Estimated downlink speed in Mbps. */
817
- speed: number;
818
- /** The network connection type (e.g., '4g', 'wifi', 'unknown'). */
819
- type: string;
820
- };
821
- }
822
-
823
- /**
824
- * A comprehensive hook for managing video conferencing state, including camera access, screen sharing, network monitoring, and automatic media quality adjustment.
825
- *
826
- * @category sensors
827
- * @param {UseConferenceSystemOptions} [options={}] - Configuration options for the conference system.
828
- * @param {boolean} [options.defaultAutoQuality=true] - Whether to enable network-based quality scaling by default.
829
- * @returns {UseConferenceSystemReturns} An object containing camera, screen, quality, and network state controllers.
830
- * @public
831
- * @see [Documentation](/docs/use-conference-system)
832
- * @example
833
- * ```tsx
834
- * const { camera, screen, quality, network } = useConferenceSystem({
835
- * defaultAutoQuality: true
836
- * });
837
- * * return (
838
- * <div>
839
- * <video ref={v => v.srcObject = camera.stream} autoPlay />
840
- * <button onClick={camera.start}>Start Camera</button>
841
- * <p>Current Quality: {quality.current} (Auto: {quality.isAuto ? 'On' : 'Off'})</p>
842
- * <p>Network Speed: {network.speed} Mbps</p>
843
- * </div>
844
- * );
845
- * ```
846
- */
847
- declare const useConferenceSystem: (options?: UseConferenceSystemOptions) => UseConferenceSystemReturns;
848
-
849
- declare global {
850
- interface WindowEventMap {
851
- "cookie-change": CustomEvent<{
852
- key: string;
853
- }>;
854
- visibilitychange: Event;
855
- }
856
- }
857
- /**
858
- * Options for customizing the behavior of the useCookie hook.
859
- * @template T - The type of the state to be stored in the cookie.
860
- */
861
- type UseCookieOptions<T> = {
862
- /** A function to serialize the value before storing it. */
863
- serializer?: (value: T) => string;
864
- /** A function to deserialize the stored value. */
865
- deserializer?: (value: string) => T;
866
- /**
867
- * If `true` (default), the hook will initialize reading the cookie.
868
- * @default true
869
- */
870
- initializeWithValue?: boolean;
871
- /**
872
- * A prefix to be prepended to the key (e.g., "myApp_").
873
- * Useful for namespacing or complying with cookie prefixes like `__Secure-` or `__Host-`.
874
- */
875
- prefix?: string;
876
- /**
877
- * The path within the site for which the cookie is valid.
878
- * @default "/"
879
- */
880
- path?: string;
881
- /** The domain for which the cookie is valid. */
882
- domain?: string;
883
- /** The expiration date of the cookie. */
884
- expires?: Date;
885
- /** The maximum age of the cookie in seconds. */
886
- maxAge?: number;
887
- /** If `true`, the cookie is only transmitted over secure protocols (HTTPS). */
888
- secure?: boolean;
889
- /**
890
- * Controls whether the cookie is sent with cross-site requests.
891
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
892
- */
893
- sameSite?: "lax" | "strict" | "none";
894
- /** The default value to return if the cookie is not found. */
895
- defaultValue?: T;
896
- };
897
- /**
898
- * Custom hook that manages state synchronized with a browser [`cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies). It handles serialization, prefixes, updates across tabs, and custom event synchronization.
899
- *
900
- * @category storage
901
- * @template T - The type of the state to be stored in the cookie.
902
- * @param {string} key - The base name of the cookie.
903
- * @param {T | (() => T)} initialValue - The initial value of the state.
904
- * @param {UseCookieOptions<T>} [options] - Options for customization.
905
- * @returns {[T, Dispatch<SetStateAction<T>>, () => void]} A tuple containing the stored value, a setter, and a remover.
906
- * @public
907
- * @see [Documentation](/docs/use-cookie)
908
- * @example
909
- * ```tsx
910
- * // Creates a cookie named "__Secure-token"
911
- * const [token, setToken] = useCookie('token', '', {
912
- * prefix: '__Secure-',
913
- * secure: true,
914
- * });
915
- * ```
916
- */
917
- declare function useCookie<T>(key: string, initialValue: T | (() => T), options?: UseCookieOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void];
918
-
919
- /**
920
- * The copied text as `string` or `null` if nothing has been copied yet.
921
- */
922
- type CopiedValue = string | null;
923
- /**
924
- * Function to copy text to the clipboard.
925
- * @param text - The text to copy to the clipboard.
926
- * @returns {Promise<boolean>} A promise that resolves to `true` if the text was copied successfully, or `false` otherwise.
927
- */
928
- type CopyFn = (text: string) => Promise<boolean>;
929
- /**
930
- * Custom hook that copies text to the clipboard using the [`Clipboard API`](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API).
931
- *
932
- * @category utilities
933
- * @returns {[CopiedValue, CopyFn]} An tuple containing the copied text and a function to copy text to the clipboard.
934
- * @public
935
- * @example
936
- * ```tsx
937
- * const [copiedText, copyToClipboard] = useCopyToClipboard();
938
- * const textToCopy = 'Hello, world!';
939
- *
940
- * // Attempt to copy text to the clipboard
941
- * copyToClipboard(textToCopy)
942
- * .then(success => {
943
- * if (success) {
944
- * console.log(`Text "${textToCopy}" copied to clipboard successfully.`);
945
- * } else {
946
- * console.error('Failed to copy text to clipboard.');
947
- * }
948
- * });
949
- * ```
950
- */
951
- declare function useCopyToClipboard(): [CopiedValue, CopyFn];
952
-
953
- /** The countdown's options. */
954
- type CountdownOptions = {
955
- /** The countdown's starting number, initial value of the returned number. */
956
- countStart: number;
957
- /**
958
- * The countdown's interval, in milliseconds.
959
- * @default 1000
960
- */
961
- intervalMs?: number;
962
- /**
963
- * True if the countdown is increment.
964
- * @default false
965
- */
966
- isIncrement?: boolean;
967
- /**
968
- * The countdown's stopping number. Pass `-Infinity` to decrease forever.
969
- * @default 0
970
- */
971
- countStop?: number;
972
- };
973
- /** The countdown's controllers. */
974
- type CountdownControllers = {
975
- /** Start the countdown. */
976
- startCountdown: () => void;
977
- /** Stop the countdown. */
978
- stopCountdown: () => void;
979
- /** Reset the countdown. */
980
- resetCountdown: () => void;
981
- };
982
- /**
983
- * Custom hook that manages countdown.
984
- *
985
- * @category effect
986
- * @param {CountdownOptions} countdownOptions - The countdown's options.
987
- * @returns {[number, CountdownControllers]} An array containing the countdown's count and its controllers.
988
- * @public
989
- * @see [Documentation](/docs/use-countdown)
990
- * @example
991
- * ```tsx
992
- * const [counter, { start, stop, reset }] = useCountdown({
993
- * countStart: 10,
994
- * intervalMs: 1000,
995
- * isIncrement: false,
996
- * });
997
- * ```
998
- */
999
- declare function useCountdown({ countStart, countStop, intervalMs, isIncrement, }: CountdownOptions): [number, CountdownControllers];
1000
-
1001
- /** The hook return type. */
1002
- type UseCounterReturn = {
1003
- /** The current count value. */
1004
- count: number;
1005
- /** Function to increment the counter by 1. */
1006
- increment: () => void;
1007
- /** Function to decrement the counter by 1. */
1008
- decrement: () => void;
1009
- /** Function to reset the counter to its initial value. */
1010
- reset: () => void;
1011
- /** Function to set a specific value to the counter. */
1012
- setCount: React$1.Dispatch<React$1.SetStateAction<number>>;
1013
- };
1014
- /**
1015
- * Custom hook that manages a counter with increment, decrement, reset, and setCount functionalities.
1016
- *
1017
- * @category state
1018
- * @param {number} [initialValue] - The initial value for the counter.
1019
- * @returns {UseCounterReturn} An object containing the current count and functions to interact with the counter.
1020
- * @public
1021
- * @see [Documentation](/docs/use-counter)
1022
- * @example
1023
- * ```tsx
1024
- * const { count, increment, decrement, reset, setCount } = useCounter(5);
1025
- * ```
1026
- */
1027
- declare function useCounter(initialValue?: number): UseCounterReturn;
1028
-
1029
- /** The hook options. */
1030
- type DarkModeOptions = {
1031
- /**
1032
- * The initial value of the dark mode.
1033
- * @default false
1034
- */
1035
- defaultValue?: boolean;
1036
- /**
1037
- * The key to use in the local storage.
1038
- * @default 'sse-hooks-dark-mode'
1039
- */
1040
- localStorageKey?: string;
1041
- /**
1042
- * If `true` (default), the hook will initialize reading `localStorage`.
1043
- * In SSR, you should set it to `false`, returning the `defaultValue` or `false` initially.
1044
- * @default true
1045
- */
1046
- initializeWithValue?: boolean;
1047
- };
1048
- /** The hook return type. */
1049
- type DarkModeReturn = {
1050
- /** The current state of the dark mode. */
1051
- isDarkMode: boolean;
1052
- /** Function to toggle the dark mode. */
1053
- toggle: () => void;
1054
- /** Function to enable the dark mode. */
1055
- enable: () => void;
1056
- /** Function to disable the dark mode. */
1057
- disable: () => void;
1058
- /** Function to set a specific value to the dark mode. */
1059
- set: (value: boolean) => void;
1060
- };
1061
- /**
1062
- * Custom hook that returns the current state of the dark mode.
1063
- *
1064
- * @category dom
1065
- * @param {?DarkModeOptions} [options] - The initial value of the dark mode, default `false`.
1066
- * @returns {DarkModeReturn} An object containing the dark mode's state and its controllers.
1067
- * @public
1068
- * @see [Documentation](/docs/use-dark-mode)
1069
- * @example
1070
- * ```tsx
1071
- * const { isDarkMode, toggle, enable, disable, set } = useDarkMode({ defaultValue: true });
1072
- * ```
1073
- */
1074
- declare function useDarkMode(options?: DarkModeOptions): DarkModeReturn;
1075
-
1076
- /** Configuration options for controlling the behavior of the debounced function. */
1077
- type DebounceOptions = {
1078
- /**
1079
- * Determines whether the function should be invoked on the leading edge of the timeout.
1080
- * @default false
1081
- */
1082
- leading?: boolean;
1083
- /**
1084
- * Determines whether the function should be invoked on the trailing edge of the timeout.
1085
- * @default false
1086
- */
1087
- trailing?: boolean;
1088
- /**
1089
- * The maximum time the specified function is allowed to be delayed before it is invoked.
1090
- */
1091
- maxWait?: number;
1092
- };
1093
- /** Functions to manage a debounced callback. */
1094
- type ControlFunctions = {
1095
- /** Cancels pending function invocations. */
1096
- cancel: () => void;
1097
- /** Immediately invokes pending function invocations. */
1098
- flush: () => void;
1099
- /**
1100
- * Checks if there are any pending function invocations.
1101
- * @returns `true` if there are pending invocations, otherwise `false`.
1102
- */
1103
- isPending: () => boolean;
1104
- };
1105
- /**
1106
- * Represents the state and control functions of a debounced callback.
1107
- * Subsequent calls to the debounced function return the result of the last invocation.
1108
- * Note: If there are no previous invocations, the result will be undefined.
1109
- * Ensure proper handling in your code.
1110
- */
1111
- type DebouncedState<T extends (...args: any) => ReturnType<T>> = ((...args: Parameters<T>) => ReturnType<T> | undefined) & ControlFunctions;
1112
- /**
1113
- * Custom hook that creates a debounced version of a callback function.
1114
- *
1115
- * @category effect
1116
- * @template T - Type of the original callback function.
1117
- * @param {T} func - The callback function to be debounced.
1118
- * @param {number} delay - The delay in milliseconds before the callback is invoked (default is `500` milliseconds).
1119
- * @param {DebounceOptions} [options] - Options to control the behavior of the debounced function.
1120
- * @returns {DebouncedState<T>} A debounced version of the original callback along with control functions.
1121
- * @public
1122
- * @see [Documentation](/docs/use-debounce-callback)
1123
- * @example
1124
- * ```tsx
1125
- * const debouncedCallback = useDebounceCallback(
1126
- * (searchTerm) => {
1127
- * // Perform search after user stops typing for 500 milliseconds
1128
- * searchApi(searchTerm);
1129
- * },
1130
- * 500
1131
- * );
1132
- *
1133
- * // Later in the component
1134
- * debouncedCallback('react hooks'); // Will invoke the callback after 500 milliseconds of inactivity.
1135
- * ```
1136
- */
1137
- declare function useDebounceCallback<T extends (...args: any) => ReturnType<T>>(func: T, delay?: number, options?: DebounceOptions): DebouncedState<T>;
1138
-
1139
- /**
1140
- * Hook options.
1141
- * @template T - The type of the value.
1142
- */
1143
- type UseDebounceValueOptions<T> = {
1144
- /**
1145
- * Determines whether the function should be invoked on the leading edge of the timeout.
1146
- * @default false
1147
- */
1148
- leading?: boolean;
1149
- /**
1150
- * Determines whether the function should be invoked on the trailing edge of the timeout.
1151
- * @default false
1152
- */
1153
- trailing?: boolean;
1154
- /**
1155
- * The maximum time the specified function is allowed to be delayed before it is invoked.
1156
- */
1157
- maxWait?: number;
1158
- /** A function to determine if the value has changed. Defaults to a function that checks if the value is strictly equal to the previous value. */
1159
- equalityFn?: (left: T, right: T) => boolean;
1160
- };
1161
- /**
1162
- * Custom hook that returns a debounced version of the provided value, along with a function to update it.
1163
- *
1164
- * @category effect
1165
- * @template T - The type of the value.
1166
- * @param {T | (() => T)} initialValue - The value to be debounced.
1167
- * @param {number} delay - The delay in milliseconds before the value is updated (default is 500ms).
1168
- * @param {object} [options] - Optional configurations for the debouncing behavior.
1169
- * @returns {[T, DebouncedState<(value: T) => void>]} An array containing the debounced value and the function to update it.
1170
- * @public
1171
- * @see [Documentation](/docs/use-debounce-value)
1172
- * @example
1173
- * ```tsx
1174
- * const [debouncedValue, updateDebouncedValue] = useDebounceValue(inputValue, 500, { leading: true });
1175
- * ```
1176
- */
1177
- declare function useDebounceValue<T>(initialValue: T | (() => T), delay: number, options?: UseDebounceValueOptions<T>): [T, DebouncedState<(value: T) => void>];
1178
-
1179
- /** Hook options. */
1180
- type UseDocumentTitleOptions = {
1181
- /** Whether to keep the title after unmounting the component (default is `true`). */
1182
- preserveTitleOnUnmount?: boolean;
1183
- };
1184
- /**
1185
- * Custom hook that sets the document title.
1186
- *
1187
- * @category dom
1188
- * @param {string} title - The title to set.
1189
- * @param {?UseDocumentTitleOptions} [options] - The options.
1190
- * @public
1191
- * @see [Documentation](/docs/use-document-title)
1192
- * @example
1193
- * ```tsx
1194
- * useDocumentTitle('My new title');
1195
- * ```
1196
- */
1197
- declare function useDocumentTitle(title: string, options?: UseDocumentTitleOptions): void;
1198
-
1199
- /**
1200
- * Custom hook that creates a memoized event callback.
1201
- *
1202
- * @category utilities
1203
- * @template Args - An array of argument types for the event callback.
1204
- * @template R - The return type of the event callback.
1205
- * @param {(...args: Args) => R} fn - The callback function.
1206
- * @returns {(...args: Args) => R} A memoized event callback function.
1207
- * @public
1208
- * @see [Documentation](/docs/use-event-callback)
1209
- * @example
1210
- * ```tsx
1211
- * const handleClick = useEventCallback((event) => {
1212
- * // Handle the event here
1213
- * });
1214
- * ```
1215
- */
1216
- declare function useEventCallback<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R;
1217
- declare function useEventCallback<Args extends unknown[], R>(fn: ((...args: Args) => R) | undefined): ((...args: Args) => R) | undefined;
1218
-
1219
- declare function useEventListener<K extends keyof MediaQueryListEventMap>(eventName: K, handler: (event: MediaQueryListEventMap[K]) => void, element: RefObject<MediaQueryList>, options?: boolean | AddEventListenerOptions): void;
1220
- declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, handler: (event: WindowEventMap[K]) => void, element?: undefined, options?: boolean | AddEventListenerOptions): void;
1221
- declare function useEventListener<K extends keyof HTMLElementEventMap & keyof SVGElementEventMap, T extends Element = K extends keyof HTMLElementEventMap ? HTMLDivElement : SVGElement>(eventName: K, handler: ((event: HTMLElementEventMap[K]) => void) | ((event: SVGElementEventMap[K]) => void), element: RefObject<T>, options?: boolean | AddEventListenerOptions): void;
1222
- declare function useEventListener<K extends keyof DocumentEventMap>(eventName: K, handler: (event: DocumentEventMap[K]) => void, element: RefObject<Document>, options?: boolean | AddEventListenerOptions): void;
1223
-
1224
- /**
1225
- * Options for customizing the behavior of the useFetch hook.
1226
- * Extends the standard [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) interface.
1227
- */
1228
- interface UseFetchOptions extends RequestInit {
1229
- /**
1230
- * If `true`, the fetch request will be executed immediately upon mounting or when the URL changes.
1231
- * @default false
1232
- */
1233
- immediate?: boolean;
1234
- /**
1235
- * Callback function invoked when the request completes successfully.
1236
- * @param data - The parsed response data.
1237
- */
1238
- onSuccess?: (data: any) => void;
1239
- /**
1240
- * Callback function invoked when the request fails.
1241
- * @param error - The error object.
1242
- */
1243
- onError?: (error: Error) => void;
1244
- }
1245
- /**
1246
- * The state representation of the fetch request.
1247
- * @template T - The type of the data.
1248
- */
1249
- interface UseFetchState<T> {
1250
- /** The data received from the response, or null if not yet received. */
1251
- data: T | null;
1252
- /** Indicates if the request is currently in progress. */
1253
- loading: boolean;
1254
- /** The error object if the request failed, or null if successful. */
1255
- error: Error | null;
1256
- }
1257
- /**
1258
- * The return value of the useFetch hook, including state and control methods.
1259
- * @template T - The type of the data.
1260
- */
1261
- interface UseFetchReturn<T> extends UseFetchState<T> {
1262
- /**
1263
- * Manually triggers the fetch request.
1264
- * @param {string} [url] - Optional override URL.
1265
- * @param {RequestInit} [options] - Optional override options.
1266
- * @returns {Promise<T | null>} A promise that resolves to the data or null.
1267
- */
1268
- execute: (url?: string, options?: RequestInit) => Promise<T | null>;
1269
- /** Aborts the current request if it is pending. */
1270
- abort: () => void;
1271
- /** Resets the state to its initial values (data: null, loading: false, error: null). */
1272
- reset: () => void;
1273
- }
1274
- /**
1275
- * Custom hook that provides a wrapper around the native [`fetch API`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to handle HTTP requests with state management, abort capability, and TypeScript support.
1276
- *
1277
- * @category network
1278
- * @template T - The type of the data expected from the response.
1279
- * @param {string} [url] - The URL to fetch.
1280
- * @param {UseFetchOptions} [options] - Options for customizing the request and hook behavior (optional).
1281
- * @returns {UseFetchReturn<T>} An object containing the fetched data, loading status, error, and methods to control the request.
1282
- * @public
1283
- * @example
1284
- * ```tsx
1285
- * interface User {
1286
- * id: number;
1287
- * name: string;
1288
- * }
1289
- *
1290
- * const { data, loading, error, execute } = useFetch<User>('https://api.example.com/user/1', {
1291
- * immediate: true,
1292
- * onSuccess: (data) => console.log('User loaded:', data),
1293
- * });
1294
- * ```
1295
- */
1296
- declare function useFetch<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
1297
- declare function useGet<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
1298
- declare function usePost<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
1299
- declare function usePut<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
1300
- declare function useDelete<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
1301
-
1302
- /**
1303
- * Merges refs into a single memoized callback ref or `null`.
1304
- *
1305
- * @category dom
1306
- * @template Instance - The type of the value being referenced (usually a DOM element).
1307
- * @param {Array<React.Ref<Instance> | undefined>} refs The ref array.
1308
- * @returns {React.RefCallback<Instance> | null} The new ref callback.
1309
- * @public
1310
- * @example
1311
- * ```tsx
1312
- * const rootRef = React.useRef<Instance>(null);
1313
- * const refFork = useForkRef(rootRef, props.ref);
1314
- *
1315
- * return (
1316
- * <Root {...props} ref={refFork} />
1317
- * );
1318
- * ```
1319
- *
1320
- */
1321
- declare function useForkRef<Instance>(...refs: Array<React$1.Ref<Instance> | undefined>): React$1.RefCallback<Instance> | null;
1322
-
1323
- /**
1324
- * Custom hook that tracks whether a DOM element is being hovered over.
1325
- * @template T - The type of the DOM element. Defaults to `HTMLElement`.
1326
- * @category sensors
1327
- * @param {RefObject<T>} elementRef - The ref object for the DOM element to track.
1328
- * @returns {boolean} A boolean value indicating whether the element is being hovered over.
1329
- * @public
1330
- * @see [Documentation](/docs/use-hover)
1331
- * @example
1332
- * ```tsx
1333
- * const buttonRef = useRef<HTMLButtonElement>(null);
1334
- * const isHovered = useHover(buttonRef);
1335
- * // Access the isHovered variable to determine if the button is being hovered over.
1336
- * ```
1337
- */
1338
- declare function useHover<T extends HTMLElement = HTMLElement>(elementRef: RefObject<T>): boolean;
1339
-
1340
- /**
1341
- * Options for configuring the IndexedDB connection and behavior.
1342
- */
1343
- interface UseIndexedDBOptions {
1344
- /**
1345
- * The version of the database. Changing this triggers an upgrade.
1346
- * @default 1
1347
- */
1348
- version?: number;
1349
- /**
1350
- * A callback function executed when the database version changes or is created.
1351
- * Use this to create or modify object stores.
1352
- * @param db - The IDBDatabase instance.
1353
- * @param oldVersion - The previous version of the database.
1354
- * @param newVersion - The new version of the database.
1355
- */
1356
- onUpgradeNeeded?: (db: IDBDatabase, oldVersion: number, newVersion: number) => void;
1357
- }
1358
- /**
1359
- * The return value of the useIndexedDB hook, containing state and methods for interacting with the database.
1360
- * @template T - The type of the data stored.
1361
- */
1362
- interface UseIndexedDBReturn<T> {
1363
- /** The most recently accessed or modified data item. */
1364
- data: T | null;
1365
- /** The error message if an operation failed, or null if successful. */
1366
- error: string | null;
1367
- /** Indicates if the database is initializing or an operation is in progress. */
1368
- loading: boolean;
1369
- /**
1370
- * Stores a value in the database under the specified key.
1371
- * @param key - The unique key for the item.
1372
- * @param value - The value to store.
1373
- */
1374
- setItem: (key: string, value: T) => Promise<void>;
1375
- /**
1376
- * Retrieves a value from the database by its key.
1377
- * @param key - The key of the item to retrieve.
1378
- * @returns A promise that resolves to the item or null if not found.
1379
- */
1380
- getItem: (key: string) => Promise<T | null>;
1381
- /**
1382
- * Removes an item from the database by its key.
1383
- * @param key - The key of the item to remove.
1384
- */
1385
- removeItem: (key: string) => Promise<void>;
1386
- /**
1387
- * Removes all items from the current object store.
1388
- */
1389
- clear: () => Promise<void>;
1390
- /**
1391
- * Retrieves all keys currently stored in the object store.
1392
- * @returns A promise that resolves to an array of keys.
1393
- */
1394
- getAllKeys: () => Promise<string[]>;
1395
- }
1396
- /**
1397
- * Custom hook that provides an interface to the [`IndexedDB API`](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) for client-side storage of significant amounts of structured data.
1398
- *
1399
- * @category storage
1400
- * @template T - The type of the data to be stored.
1401
- * @param {string} databaseName - The name of the IndexedDB database.
1402
- * @param {string} storeName - The name of the object store within the database.
1403
- * @param {UseIndexedDBOptions} [options] - Configuration options for the database connection (optional).
1404
- * @returns {UseIndexedDBReturn<T>} An object containing the current data state, error state, loading state, and methods to interact with the database.
1405
- * @public
1406
- * @example
1407
- * ```tsx
1408
- * interface UserProfile {
1409
- * name: string;
1410
- * age: number;
1411
- * }
1412
- *
1413
- * const { setItem, getItem, data } = useIndexedDB<UserProfile>('myAppDB', 'profiles');
1414
- *
1415
- * const saveProfile = async () => {
1416
- * await setItem('user_1', { name: 'Alice', age: 30 });
1417
- * };
1418
- * ```
1419
- */
1420
- declare function useIndexedDB<T>(databaseName: string, storeName: string, options?: UseIndexedDBOptions): UseIndexedDBReturn<T>;
1421
-
1422
- /** Represents the options for configuring the Intersection Observer. */
1423
- type UseIntersectionObserverOptions = {
1424
- /**
1425
- * The element that is used as the viewport for checking visibility of the target.
1426
- * @default null
1427
- */
1428
- root?: Element | Document | null;
1429
- /**
1430
- * A margin around the root.
1431
- * @default '0%'
1432
- */
1433
- rootMargin?: string;
1434
- /**
1435
- * A threshold indicating the percentage of the target's visibility needed to trigger the callback.
1436
- * @default 0
1437
- */
1438
- threshold?: number | number[];
1439
- /**
1440
- * If true, freezes the intersection state once the element becomes visible.
1441
- * @default false
1442
- */
1443
- freezeOnceVisible?: boolean;
1444
- /**
1445
- * A callback function to be invoked when the intersection state changes.
1446
- * @param {boolean} isIntersecting - A boolean indicating if the element is intersecting.
1447
- * @param {IntersectionObserverEntry} entry - The intersection observer Entry.
1448
- * @default undefined
1449
- */
1450
- onChange?: (isIntersecting: boolean, entry: IntersectionObserverEntry) => void;
1451
- /**
1452
- * The initial state of the intersection.
1453
- * @default false
1454
- */
1455
- initialIsIntersecting?: boolean;
1456
- };
1457
- /**
1458
- * The return type of the useIntersectionObserver hook.
1459
- *
1460
- * Supports both tuple and object destructing.
1461
- * @category sensors
1462
- * @param {(node: Element | null) => void} ref - The ref callback function.
1463
- * @param {boolean} isIntersecting - A boolean indicating if the element is intersecting.
1464
- * @param {IntersectionObserverEntry | undefined} entry - The intersection observer Entry.
1465
- */
1466
- type IntersectionReturn = [
1467
- (node?: Element | null) => void,
1468
- boolean,
1469
- IntersectionObserverEntry | undefined
1470
- ] & {
1471
- ref: (node?: Element | null) => void;
1472
- isIntersecting: boolean;
1473
- entry?: IntersectionObserverEntry;
1474
- };
1475
- /**
1476
- * Custom hook that tracks the intersection of a DOM element with its containing element or the viewport using the [`Intersection Observer API`](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).
1477
- * @param {UseIntersectionObserverOptions} options - The options for the Intersection Observer.
1478
- * @returns {IntersectionReturn} The ref callback, a boolean indicating if the element is intersecting, and the intersection observer entry.
1479
- * @public
1480
- * @see [Documentation](/docs/use-intersection-observer)
1481
- * @example
1482
- * ```tsx
1483
- * // Example 1
1484
- * const [ref, isIntersecting, entry] = useIntersectionObserver({ threshold: 0.5 });
1485
- * ```
1486
- *
1487
- * ```tsx
1488
- * // Example 2
1489
- * const { ref, isIntersecting, entry } = useIntersectionObserver({ threshold: 0.5 });
1490
- * ```
1491
- */
1492
- declare function useIntersectionObserver({ threshold, root, rootMargin, freezeOnceVisible, initialIsIntersecting, onChange, }?: UseIntersectionObserverOptions): IntersectionReturn;
1493
-
1494
- /**
1495
- * Custom hook that creates an interval that invokes a callback function at a specified delay using the [`setInterval API`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval).
1496
- *
1497
- * @category effect
1498
- * @param {() => void} callback - The function to be invoked at each interval.
1499
- * @param {number | null} delay - The time, in milliseconds, between each invocation of the callback. Use `null` to clear the interval.
1500
- * @public
1501
- * @see [Documentation](/docs/use-interval)
1502
- * @example
1503
- * ```tsx
1504
- * const handleInterval = () => {
1505
- * // Code to be executed at each interval
1506
- * };
1507
- * useInterval(handleInterval, 1000);
1508
- * ```
1509
- */
1510
- declare function useInterval(callback: () => void, delay: number | null): void;
1511
-
1512
- /**
1513
- * Custom hook that determines if the code is running on the client side (in the browser).
1514
- *
1515
- * @category lifecycle
1516
- * @returns {boolean} A boolean value indicating whether the code is running on the client side.
1517
- * @public
1518
- * @see [Documentation](/docs/use-is-client)
1519
- * @example
1520
- * ```tsx
1521
- * const isClient = useIsClient();
1522
- * // Use isClient to conditionally render or execute code specific to the client side.
1523
- * ```
1524
- */
1525
- declare function useIsClient(): boolean;
1526
-
1527
- /**
1528
- * Custom hook that determines if the component is currently mounted.
1529
- *
1530
- * @category lifecycle
1531
- * @returns {() => boolean} A function that returns a boolean value indicating whether the component is mounted.
1532
- * @public
1533
- * @see [Documentation](/docs/use-is-mounted)
1534
- * @example
1535
- * ```tsx
1536
- * const isComponentMounted = useIsMounted();
1537
- * // Use isComponentMounted() to check if the component is currently mounted before performing certain actions.
1538
- * ```
1539
- */
1540
- declare function useIsMounted(): () => boolean;
1541
-
1542
- /**
1543
- * Custom hook that uses either `useLayoutEffect` or `useEffect` based on the environment (client-side or server-side).
1544
- * @param {Function} effect - The effect function to be executed.
1545
- * @param {Array<any>} [dependencies] - An array of dependencies for the effect (optional).
1546
- * @public
1547
- * @see [Documentation](/docs/use-isomorphic-layout-effect)
1548
- * @example
1549
- * ```tsx
1550
- * useIsomorphicLayoutEffect(() => {
1551
- * // Code to be executed during the layout phase on the client side
1552
- * }, [dependency1, dependency2]);
1553
- * ```
1554
- */
1555
- declare const useIsomorphicLayoutEffect: typeof useEffect;
1556
-
1557
- type KbdKeysSpecificMap = {
1558
- meta: string;
1559
- alt: string;
1560
- ctrl: string;
1561
- };
1562
- declare const kbdKeysMap: {
1563
- readonly meta: "";
1564
- readonly ctrl: "";
1565
- readonly alt: "";
1566
- readonly win: "⊞";
1567
- readonly command: "⌘";
1568
- readonly shift: "⇧";
1569
- readonly control: "⌃";
1570
- readonly option: "⌥";
1571
- readonly enter: "↵";
1572
- readonly delete: "⌦";
1573
- readonly backspace: "⌫";
1574
- readonly escape: "Esc";
1575
- readonly tab: "⇥";
1576
- readonly capslock: "⇪";
1577
- readonly arrowup: "↑";
1578
- readonly arrowright: "→";
1579
- readonly arrowdown: "↓";
1580
- readonly arrowleft: "←";
1581
- readonly pageup: "⇞";
1582
- readonly pagedown: "⇟";
1583
- readonly home: "↖";
1584
- readonly end: "↘";
1585
- };
1586
- type KbdKey = keyof typeof kbdKeysMap;
1587
- type KbdKeySpecific = keyof KbdKeysSpecificMap;
1588
- /**
1589
- * Custom hook that detects the operating system (Mac vs. Windows/Linux) and provides
1590
- * a normalized map of keyboard keys (e.g., mapping "Meta" to "Command" on Mac and "Ctrl" on Windows).
1591
- * * @category utilities
1592
- * @returns {Object} An object containing the OS detection state and a key mapping function.
1593
- * @public
1594
- * @see [Documentation](/docs/hooks/use-kbd)
1595
- * @example
1596
- * ```tsx
1597
- * const { isMac, getKbdKey } = useKbd();
1598
- * * // Returns "⌘" on Mac, "Ctrl" on Windows
1599
- * const metaSymbol = getKbdKey('meta');
1600
- * * return <div>Press {metaSymbol} + C to copy</div>;
1601
- * ```
1602
- */
1603
- declare const useKbd: () => {
1604
- isMac: boolean;
1605
- getKbdKey: (value?: KbdKey | string) => string | undefined;
1606
- };
1607
-
1608
- declare global {
1609
- interface WindowEventMap {
1610
- "local-storage": CustomEvent;
1611
- }
1612
- }
1613
- /**
1614
- * Options for customizing the behavior of serialization and deserialization.
1615
- * @template T - The type of the state to be stored in local storage.
1616
- */
1617
- type UseLocalStorageOptions<T> = {
1618
- /** A function to serialize the value before storing it. */
1619
- serializer?: (value: T) => string;
1620
- /** A function to deserialize the stored value. */
1621
- deserializer?: (value: string) => T;
1622
- /**
1623
- * If `true` (default), the hook will initialize reading the local storage. In SSR, you should set it to `false`, returning the initial value initially.
1624
- * @default true
1625
- */
1626
- initializeWithValue?: boolean;
1627
- };
1628
- /**
1629
- * Custom hook that uses the [`localStorage API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) to persist state across page reloads.
1630
- *
1631
- * @category storage
1632
- * @template T - The type of the state to be stored in local storage.
1633
- * @param {string} key - The key under which the value will be stored in local storage.
1634
- * @param {T | (() => T)} initialValue - The initial value of the state or a function that returns the initial value.
1635
- * @param {UseLocalStorageOptions<T>} [options] - Options for customizing the behavior of serialization and deserialization (optional).
1636
- * @returns {[T, Dispatch<SetStateAction<T>>, () => void]} A tuple containing the stored value, a function to set the value and a function to remove the key from storage.
1637
- * @public
1638
- * @see [Documentation](/docs/use-local-storage)
1639
- * @example
1640
- * ```tsx
1641
- * const [count, setCount, removeCount] = useLocalStorage('count', 0);
1642
- * // Access the `count` value, the `setCount` function to update it and `removeCount` function to remove the key from storage.
1643
- * ```
1644
- */
1645
- declare function useLocalStorage<T>(key: string, initialValue: T | (() => T), options?: UseLocalStorageOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void];
1646
-
1647
- /**
1648
- * Represents the type for either a Map or an array of key-value pairs.
1649
- * @template K - The type of keys in the map.
1650
- * @template V - The type of values in the map.
1651
- */
1652
- type MapOrEntries<K, V> = Map<K, V> | [K, V][];
1653
- /**
1654
- * Represents the actions available to interact with the map state.
1655
- * @template K - The type of keys in the map.
1656
- * @template V - The type of values in the map.
1657
- */
1658
- type UseMapActions<K, V> = {
1659
- /** Set a key-value pair in the map. */
1660
- set: (key: K, value: V) => void;
1661
- /** Set all key-value pairs in the map. */
1662
- setAll: (entries: MapOrEntries<K, V>) => void;
1663
- /** Remove a key-value pair from the map. */
1664
- remove: (key: K) => void;
1665
- /** Reset the map to an empty state. */
1666
- reset: Map<K, V>["clear"];
1667
- };
1668
- /**
1669
- * Represents the return type of the `useMap` hook.
1670
- * We hide some setters from the returned map to disable autocompletion.
1671
- * @template K - The type of keys in the map.
1672
- * @template V - The type of values in the map.
1673
- */
1674
- type UseMapReturn<K, V> = [
1675
- Omit<Map<K, V>, "set" | "clear" | "delete">,
1676
- UseMapActions<K, V>
1677
- ];
1678
- /**
1679
- * Custom hook that manages a key-value [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) state with setter actions.
1680
- *
1681
- * @category state
1682
- * @template K - The type of keys in the map.
1683
- * @template V - The type of values in the map.
1684
- * @param {MapOrEntries<K, V>} [initialState] - The initial state of the map as a Map or an array of key-value pairs (optional).
1685
- * @returns {UseMapReturn<K, V>} A tuple containing the map state and actions to interact with the map.
1686
- * @public
1687
- * @see [Documentation](/docs/use-map)
1688
- * @example
1689
- * ```tsx
1690
- * const [map, mapActions] = useMap();
1691
- * // Access the `map` state and use `mapActions` to set, remove, or reset entries.
1692
- * ```
1693
- */
1694
- declare function useMap<K, V>(initialState?: MapOrEntries<K, V>): UseMapReturn<K, V>;
1695
-
1696
- /** Hook options. */
1697
- type UseMediaQueryOptions = {
1698
- /**
1699
- * The default value to return if the hook is being run on the server.
1700
- * @default false
1701
- */
1702
- defaultValue?: boolean;
1703
- /**
1704
- * If `true` (default), the hook will initialize reading the media query. In SSR, you should set it to `false`, returning `options.defaultValue` or `false` initially.
1705
- * @default true
1706
- */
1707
- initializeWithValue?: boolean;
1708
- };
1709
- /**
1710
- * Custom hook that tracks the state of a media query using the [`Match Media API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia).
1711
- * @category sensors
1712
- * @param {string} query - The media query to track.
1713
- * @param {?UseMediaQueryOptions} [options] - The options for customizing the behavior of the hook (optional).
1714
- * @returns {boolean} The current state of the media query (true if the query matches, false otherwise).
1715
- * @public
1716
- * @see [Documentation](/docs/use-media-query)
1717
- * @example
1718
- * ```tsx
1719
- * const isSmallScreen = useMediaQuery('(max-width: 600px)');
1720
- * // Use `isSmallScreen` to conditionally apply styles or logic based on the screen size.
1721
- * ```
1722
- */
1723
- declare function useMediaQuery(query: string, { defaultValue, initializeWithValue, }?: UseMediaQueryOptions): boolean;
1724
-
1725
- /**
1726
- * Represents an image associated with the media (e.g., album art).
1727
- */
1728
- interface MediaImage {
1729
- /** The URL of the image. */
1730
- src: string;
1731
- /** The sizes of the image (e.g., "96x96"). */
1732
- sizes?: string;
1733
- /** The MIME type of the image (e.g., "image/png"). */
1734
- type?: string;
1735
- }
1736
- /**
1737
- * Metadata for the current media session.
1738
- */
1739
- interface MediaMetadataInit {
1740
- /** The title of the media. */
1741
- title?: string;
1742
- /** The artist name. */
1743
- artist?: string;
1744
- /** The album name. */
1745
- album?: string;
1746
- /** An array of artwork images. */
1747
- artwork?: MediaImage[];
1748
- }
1749
- /**
1750
- * Supported media session actions.
1751
- */
1752
- type MediaSessionAction = "play" | "pause" | "stop" | "seekbackward" | "seekforward" | "seekto" | "skipad" | "previoustrack" | "nexttrack";
1753
- /**
1754
- * The current playback state of the media session.
1755
- */
1756
- type MediaSessionPlaybackState = "none" | "paused" | "playing";
1757
- /**
1758
- * Handler function for media session actions.
1759
- */
1760
- type MediaSessionActionHandler = (details?: any) => void;
1761
- /**
1762
- * Options for the `useMediaSession` hook.
1763
- */
1764
- interface UseMediaSessionOptions {
1765
- /** Initial metadata to set for the session. */
1766
- metadata?: MediaMetadataInit;
1767
- /** Initial playback state. */
1768
- playbackState?: MediaSessionPlaybackState;
1769
- /** Initial action handlers to register. */
1770
- actionHandlers?: Partial<Record<MediaSessionAction, MediaSessionActionHandler>>;
1771
- }
1772
- /**
1773
- * Return value of the `useMediaSession` hook.
1774
- */
1775
- interface UseMediaSessionReturn {
1776
- /** Whether the Media Session API is supported in the current environment. */
1777
- isSupported: boolean;
1778
- /** Function to update the media metadata. */
1779
- setMetadata: (metadata: MediaMetadataInit) => void;
1780
- /** Function to update the playback state. */
1781
- setPlaybackState: (state: MediaSessionPlaybackState) => void;
1782
- /** Function to set a specific action handler. */
1783
- setActionHandler: (action: MediaSessionAction, handler: MediaSessionActionHandler | null) => void;
1784
- /** Function to clear all registered action handlers. */
1785
- clearActionHandlers: () => void;
1786
- }
1787
-
1788
- /**
1789
- * Custom hook that interacts with the [Media Session API](https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API).
1790
- * It allows you to customize media notifications and handle media control events (like play, pause, next track) from the system's notification area or lock screen.
1791
- *
1792
- * @category sensors
1793
- * @param options - Initial configuration for the media session.
1794
- * @returns Object containing methods to control the media session and a flag indicating support.
1795
- * @public
1796
- * @example
1797
- * ```tsx
1798
- * const MyPlayer = () => {
1799
- * const { setMetadata, setPlaybackState } = useMediaSession({
1800
- * playbackState: "playing",
1801
- * metadata: {
1802
- * title: "Awesome Song",
1803
- * artist: "Cool Artist",
1804
- * album: "Best Hits",
1805
- * artwork: [{ src: "/album-art.jpg", sizes: "512x512", type: "image/jpeg" }]
1806
- * },
1807
- * actionHandlers: {
1808
- * play: () => console.log("Play clicked"),
1809
- * pause: () => console.log("Pause clicked"),
1810
- * nexttrack: () => console.log("Next track clicked"),
1811
- * }
1812
- * });
1813
- *
1814
- * return <div>Now Playing...</div>;
1815
- * };
1816
- * ```
1817
- */
1818
- declare const useMediaSession: (options?: UseMediaSessionOptions) => UseMediaSessionReturn;
1819
-
1820
- interface NetworkInformation {
1821
- downlink?: number;
1822
- downlinkMax?: number;
1823
- effectiveType?: "2g" | "3g" | "4g" | "slow-2g";
1824
- rtt?: number;
1825
- saveData?: boolean;
1826
- type?: "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown";
1827
- }
1828
- interface UseNetworkInformationReturn {
1829
- /** Detailed information about the network connection. */
1830
- networkInfo: NetworkInformation | null;
1831
- /** Whether the browser detects an internet connection. */
1832
- isOnline: boolean;
1833
- /** Whether the Network Information API is supported in this browser. */
1834
- isSupported: boolean;
1835
- /** Function to manually update the network information. */
1836
- refresh: () => void;
1837
- }
1838
-
1839
- declare global {
1840
- interface Navigator {
1841
- connection?: NetworkInformation;
1842
- }
1843
- }
1844
- /**
1845
- * Custom hook that tracks the device's network connection status and details (speed, type)
1846
- * using the Network Information API.
1847
- * @category network
1848
- * @returns {UseNetworkInformationReturn} The network state, connection details, and support status.
1849
- * @public
1850
- * @see [Documentation](/docs/use-network-information)
1851
- * @example
1852
- * ```tsx
1853
- * const { isOnline, networkInfo } = useNetworkInformation();
1854
- * * if (!isOnline) return <div>You are offline</div>;
1855
- * * return (
1856
- * <div>
1857
- * Connection: {networkInfo?.effectiveType} ({networkInfo?.downlink} Mbps)
1858
- * </div>
1859
- * );
1860
- * ```
1861
- */
1862
- declare const useNetworkInformation: () => UseNetworkInformationReturn;
1863
-
1864
- type HTMLElRef = React$1.MutableRefObject<HTMLElement>;
1865
- type CustomEvent$1 = {
1866
- event?: React$1.SyntheticEvent<any, Event>;
1867
- portal: HTMLElRef;
1868
- targetEl: HTMLElRef;
1869
- } & React$1.SyntheticEvent<any, Event>;
1870
- type CustomEventHandler = (customEvent: CustomEvent$1) => void;
1871
- type CustomEventHandlers = {
1872
- [K in keyof React$1.DOMAttributes<K>]?: CustomEventHandler;
1873
- };
1874
- type EventListenerMap = {
1875
- [K in keyof React$1.DOMAttributes<K>]: keyof GlobalEventHandlersEventMap;
1876
- };
1877
- type EventListenersRef = React$1.MutableRefObject<{
1878
- [K in keyof React$1.DOMAttributes<K>]?: (event: React$1.SyntheticEvent<any, Event>) => void;
1879
- }>;
1880
- type UsePortalOptions = {
1881
- /** Close the portal when clicking outside the portal content. @default true */
1882
- closeOnOutsideClick?: boolean;
1883
- /** Close the portal when the Escape key is pressed. @default true */
1884
- closeOnEsc?: boolean;
1885
- /** The DOM element to attach the portal to. @default document.body */
1886
- bindTo?: HTMLElement;
1887
- /** Initial open state. @default false */
1888
- isOpen?: boolean;
1889
- /** Callback fired when the portal opens. */
1890
- onOpen?: CustomEventHandler;
1891
- /** Callback fired when the portal closes. */
1892
- onClose?: CustomEventHandler;
1893
- /** Callback fired when the portal content is clicked. */
1894
- onPortalClick?: CustomEventHandler;
1895
- /** Set to true if managing open state entirely outside this hook. @default false */
1896
- programmaticallyOpen?: boolean;
1897
- } & CustomEventHandlers;
1898
- type UsePortalObjectReturn = {};
1899
- type UsePortalArrayReturn = [];
1900
-
1901
- declare const errorMessage1 = "You must either add a `ref` to the element you are interacting with or pass an `event` to openPortal(e) or togglePortal(e) when the `programmaticallyOpen` option is not set to `true`.";
1902
-
1903
- /**
1904
- * Represents the type for the options available when reading from local storage.
1905
- * @template T - The type of the stored value.
1906
- */
1907
- type Options<T, InitializeWithValue extends boolean | undefined> = {
1908
- /** Custom deserializer function to convert the stored string value to the desired type (optional). */
1909
- deserializer?: (value: string) => T;
1910
- /** If `true` (default), the hook will initialize reading the local storage. In SSR, you should set it to `false`, returning `undefined` initially. */
1911
- initializeWithValue: InitializeWithValue;
1912
- };
1913
- declare function useReadLocalStorage<T>(key: string, options: Options<T, false>): T | null | undefined;
1914
- declare function useReadLocalStorage<T>(key: string, options?: Partial<Options<T, true>>): T | null;
1915
-
1916
- /** The size of the observed element. */
1917
- type Size = {
1918
- /** The width of the observed element. */
1919
- width: number | undefined;
1920
- /** The height of the observed element. */
1921
- height: number | undefined;
1922
- };
1923
- /** The options for the ResizeObserver. */
1924
- type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
1925
- /** The ref of the element to observe. */
1926
- ref: RefObject<T>;
1927
- /**
1928
- * When using `onResize`, the hook doesn't re-render on element size changes; it delegates handling to the provided callback.
1929
- * @default undefined
1930
- */
1931
- onResize?: (size: Size) => void;
1932
- /**
1933
- * The box model to use for the ResizeObserver.
1934
- * @default 'content-box'
1935
- */
1936
- box?: "border-box" | "content-box" | "device-pixel-content-box";
1937
- };
1938
- /**
1939
- * Custom hook that observes the size of an element using the [`ResizeObserver API`](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver).
1940
- * @template T - The type of the element to observe.
1941
- * @category sensors
1942
- * @param {UseResizeObserverOptions<T>} options - The options for the ResizeObserver.
1943
- * @returns {Size} - The size of the observed element.
1944
- * @public
1945
- * @see [Documentation](/docs/use-resize-observer)
1946
- * @example
1947
- * ```tsx
1948
- * const myRef = useRef(null);
1949
- * const { width = 0, height = 0 } = useResizeObserver({
1950
- * ref: myRef,
1951
- * box: 'content-box',
1952
- * });
1953
- *
1954
- * <div ref={myRef}>Hello, world!</div>
1955
- * ```
1956
- */
1957
- declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size;
1958
-
1959
- interface User {
1960
- id: string;
1961
- roles: string[];
1962
- [key: string]: any;
1963
- }
1964
- interface UseRoleGuardOptions {
1965
- /** The user object. If not provided, attempts to read from session storage. */
1966
- user?: User | null;
1967
- /** URL to redirect to if access is denied. @default "/unauthorized" */
1968
- redirectTo?: string;
1969
- /** Component to render while loading or if unauthorized (not fully implemented in hook logic, mainly for HOCs). */
1970
- fallbackComponent?: React.ComponentType;
1971
- /** Callback fired when access is denied. */
1972
- onUnauthorized?: () => void;
1973
- /** The key used to fetch user data from sessionStorage. @default "user" */
1974
- sessionKey?: string;
1975
- }
1976
- interface UseRoleGuardReturn {
1977
- /** Whether the user has the required roles. */
1978
- hasAccess: boolean;
1979
- /** Checks if the user has at least one of the provided roles. */
1980
- hasAnyRole: (roles: string[]) => boolean;
1981
- /** Checks if the user has all of the provided roles. */
1982
- hasAllRoles: (roles: string[]) => boolean;
1983
- /** Whether user data is being loaded. */
1984
- isLoading: boolean;
1985
- /** The current user object. */
1986
- user: User | null;
1987
- /** Manually checks access against a specific set of roles. */
1988
- checkAccess: (requiredRoles: string[]) => boolean;
1989
- /** Function to trigger the redirect manually. */
1990
- redirect: () => void;
1991
- }
1992
-
1993
- /**
1994
- * Custom hook for Role-Based Access Control (RBAC).
1995
- * Checks if a user has specific permissions and handles redirection for unauthorized access.
1996
- * * @category state
1997
- * @param {string[]} requiredRoles - The list of roles required to access the resource.
1998
- * @param {UseRoleGuardOptions} [options={}] - Configuration options including user object and redirect paths.
1999
- * @returns {UseRoleGuardReturn} Access status, user data, and role checking utilities.
2000
- * @public
2001
- * @see [Documentation](/docs/use-role-guard)
2002
- * @example
2003
- * ```tsx
2004
- * const { hasAccess, user, isLoading } = useRoleGuard(['admin', 'editor'], {
2005
- * redirectTo: '/login'
2006
- * });
2007
- * * if (isLoading) return <Loader />;
2008
- * if (!hasAccess) return null; // Will redirect automatically
2009
- * * return <AdminPanel user={user} />;
2010
- * ```
2011
- */
2012
- declare function useRoleGuard(requiredRoles: string[], options?: UseRoleGuardOptions): UseRoleGuardReturn;
2013
-
2014
- /**
2015
- * The hooks options.
2016
- * @template InitializeWithValue - If `true` (default), the hook will initialize reading the screen dimensions. In SSR, you should set it to `false`, returning `undefined` initially.
2017
- */
2018
- type UseScreenOptions<InitializeWithValue extends boolean | undefined> = {
2019
- /**
2020
- * If `true` (default), the hook will initialize reading the screen dimensions. In SSR, you should set it to `false`, returning `undefined` initially.
2021
- * @default true
2022
- */
2023
- initializeWithValue: InitializeWithValue;
2024
- /**
2025
- * The delay in milliseconds before the state is updated (disabled by default for retro-compatibility).
2026
- * @default undefined
2027
- */
2028
- debounceDelay?: number;
2029
- };
2030
- declare function useScreen(options: UseScreenOptions<false>): Screen | undefined;
2031
- declare function useScreen(options?: Partial<UseScreenOptions<true>>): Screen;
2032
-
2033
- /** Script loading status. */
2034
- type UseScriptStatus = "idle" | "loading" | "ready" | "error";
2035
- /** Hook options. */
2036
- type UseScriptOptions = {
2037
- /** If `true`, prevents the script from being loaded (optional). */
2038
- shouldPreventLoad?: boolean;
2039
- /** If `true`, removes the script from the DOM when the component unmounts (optional). */
2040
- removeOnUnmount?: boolean;
2041
- /** Script's `id` (optional). */
2042
- id?: string;
2043
- };
2044
- /**
2045
- * Custom hook that dynamically loads scripts and tracking their loading status.
2046
- *
2047
- * @category dom
2048
- * @param {string | null} src - The source URL of the script to load. Set to `null` or omit to prevent loading (optional).
2049
- * @param {UseScriptOptions} [options] - Additional options for controlling script loading (optional).
2050
- * @returns {UseScriptStatus} The status of the script loading, which can be one of 'idle', 'loading', 'ready', or 'error'.
2051
- * @see [Documentation](/docs/use-script)
2052
- * @example
2053
- * const scriptStatus = useScript('https://example.com/script.js', { removeOnUnmount: true });
2054
- * // Access the status of the script loading (e.g., 'loading', 'ready', 'error').
2055
- */
2056
- declare function useScript(src: string | null, options?: UseScriptOptions): UseScriptStatus;
2057
-
2058
- /** Hook options. */
2059
- type UseScrollLockOptions = {
2060
- /**
2061
- * Whether to lock the scroll initially.
2062
- * @default true
2063
- */
2064
- autoLock?: boolean;
2065
- /**
2066
- * The target element to lock the scroll (default is the body element).
2067
- * @default document.body
2068
- */
2069
- lockTarget?: HTMLElement | string;
2070
- /**
2071
- * Whether to prevent width reflow when locking the scroll.
2072
- * @default true
2073
- */
2074
- widthReflow?: boolean;
2075
- };
2076
- /** Hook return type. */
2077
- type UseScrollLockReturn = {
2078
- /** Whether the scroll is locked. */
2079
- isLocked: boolean;
2080
- /** Lock the scroll. */
2081
- lock: () => void;
2082
- /** Unlock the scroll. */
2083
- unlock: () => void;
2084
- };
2085
- /**
2086
- * A custom hook that locks and unlocks scroll.
2087
- *
2088
- * @category dom
2089
- * @param {UseScrollLockOptions} [options] - Options to configure the hook, by default it will lock the scroll automatically.
2090
- * @returns {UseScrollLockReturn} - An object containing the lock and unlock functions.
2091
- * @public
2092
- * @see [Documentation](/docs/use-scroll-lock)
2093
- * @example
2094
- * ```tsx
2095
- * // Lock the scroll when the modal is mounted, and unlock it when it's unmounted
2096
- * useScrollLock()
2097
- * ```
2098
- * @example
2099
- * ```tsx
2100
- * // Manually lock and unlock the scroll
2101
- * const { lock, unlock } = useScrollLock({ autoLock: false })
2102
- *
2103
- * return (
2104
- * <div>
2105
- * <button onClick={lock}>Lock</button>
2106
- * <button onClick={unlock}>Unlock</button>
2107
- * </div>
2108
- * )
2109
- * ```
2110
- */
2111
- declare function useScrollLock(options?: UseScrollLockOptions): UseScrollLockReturn;
2112
-
2113
- declare global {
2114
- interface WindowEventMap {
2115
- "session-storage": CustomEvent;
2116
- }
2117
- }
2118
- /**
2119
- * Represents the options for customizing the behavior of serialization and deserialization.
2120
- * @template T - The type of the state to be stored in session storage.
2121
- */
2122
- type UseSessionStorageOptions<T> = {
2123
- /** A function to serialize the value before storing it. */
2124
- serializer?: (value: T) => string;
2125
- /** A function to deserialize the stored value. */
2126
- deserializer?: (value: string) => T;
2127
- /**
2128
- * If `true` (default), the hook will initialize reading the session storage. In SSR, you should set it to `false`, returning the initial value initially.
2129
- * @default true
2130
- */
2131
- initializeWithValue?: boolean;
2132
- };
2133
- /**
2134
- * Custom hook that uses the [`sessionStorage API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) to persist state across page reloads.
2135
- *
2136
- * @category storage
2137
- * @template T - The type of the state to be stored in session storage.
2138
- * @param {string} key - The key under which the value will be stored in session storage.
2139
- * @param {T | (() => T)} initialValue - The initial value of the state or a function that returns the initial value.
2140
- * @param {?UseSessionStorageOptions<T>} [options] - Options for customizing the behavior of serialization and deserialization (optional).
2141
- * @returns {[T, Dispatch<SetStateAction<T>>, () => void]} A tuple containing the stored value, a function to set the value and a function to remove the key from storage.
2142
- * @public
2143
- * @see [Documentation](/docs/use-session-storage)
2144
- * @example
2145
- * ```tsx
2146
- * const [count, setCount, removeCount] = useSessionStorage('count', 0);
2147
- * // Access the `count` value, the `setCount` function to update it and `removeCount` function to remove the key from storage.
2148
- * ```
2149
- */
2150
- declare function useSessionStorage<T>(key: string, initialValue: T | (() => T), options?: UseSessionStorageOptions<T>): [T, Dispatch<SetStateAction<T>>, () => void];
2151
-
2152
- declare enum Device {
2153
- Browser = "browser",
2154
- Server = "server",
2155
- Native = "native"
2156
- }
2157
-
2158
- interface UseSSRReturn {
2159
- /** Whether code is running in the browser. */
2160
- isBrowser: boolean;
2161
- /** Whether code is running on the server. */
2162
- isServer: boolean;
2163
- /** Whether code is running in a Native environment (e.g. React Native). */
2164
- isNative: boolean;
2165
- /** The detected device type. */
2166
- device: Device;
2167
- /** Whether Web Workers are supported. */
2168
- canUseWorkers: boolean;
2169
- /** Whether window.addEventListener is available. */
2170
- canUseEventListeners: boolean;
2171
- /** Whether window.screen is available. */
2172
- canUseViewport: boolean;
2173
- }
2174
-
2175
- declare const weAreServer: () => void;
2176
- /**
2177
- * Custom hook that detects the current environment (Browser, Server, or Native)
2178
- * and capability support (Workers, EventListeners). useful for avoiding hydration mismatches.
2179
- * * @category utilities
2180
- * @returns {UseSSRReturn} Object containing boolean flags for the current environment.
2181
- * @public
2182
- * @see [Documentation](/docs/use-ssr)
2183
- * @example
2184
- * ```tsx
2185
- * const { isBrowser, isServer } = useSSR();
2186
- * * if (isServer) {
2187
- * return <StaticLoader />;
2188
- * }
2189
- * * return <ClientComponent />;
2190
- * ```
2191
- */
2192
- declare const useSSR: () => UseSSRReturn;
2193
-
2194
- /** Represents the second element of the output of the `useStep` hook. */
2195
- type UseStepActions = {
2196
- /** Go to the next step in the process. */
2197
- goToNextStep: () => void;
2198
- /** Go to the previous step in the process. */
2199
- goToPrevStep: () => void;
2200
- /** Reset the step to the initial step. */
2201
- reset: () => void;
2202
- /** Check if the next step is available. */
2203
- canGoToNextStep: boolean;
2204
- /** Check if the previous step is available. */
2205
- canGoToPrevStep: boolean;
2206
- /** Set the current step to a specific value. */
2207
- setStep: Dispatch<SetStateAction<number>>;
2208
- };
2209
- /**
2210
- * Custom hook that manages and navigates between steps in a multi-step process.
2211
- *
2212
- * @category state
2213
- * @param {number} maxStep - The maximum step in the process.
2214
- * @returns {[number, UseStepActions]} An tuple containing the current step and helper functions for navigating steps.
2215
- * @public
2216
- * @see [Documentation](/docs/use-step)
2217
- * @example
2218
- * ```tsx
2219
- * const [currentStep, { goToNextStep, goToPrevStep, reset, canGoToNextStep, canGoToPrevStep, setStep }] = useStep(3);
2220
- * // Access and use the current step and provided helper functions.
2221
- * ```
2222
- */
2223
- declare function useStep(maxStep: number): [number, UseStepActions];
2224
-
2225
- interface UseSymbolReturn {
2226
- /** Creates a new unique symbol and adds it to the local registry. */
2227
- createSymbol: (description?: string) => symbol;
2228
- /** Returns a symbol from the global symbol registry. */
2229
- getGlobalSymbol: (key: string) => symbol;
2230
- /** Returns the key for a global symbol. */
2231
- getSymbolKey: (symbol: symbol) => string | undefined;
2232
- /** Checks if a value is a symbol. */
2233
- isSymbol: (value: any) => value is symbol;
2234
- /** Gets the description of a symbol. */
2235
- getDescription: (symbol: symbol) => string | undefined;
2236
- /** A collection of standard JavaScript well-known symbols. */
2237
- wellKnownSymbols: {
2238
- iterator: symbol;
2239
- asyncIterator: symbol;
2240
- hasInstance: symbol;
2241
- isConcatSpreadable: symbol;
2242
- species: symbol;
2243
- toPrimitive: symbol;
2244
- toStringTag: symbol;
2245
- unscopables: symbol;
2246
- match: symbol;
2247
- matchAll: symbol;
2248
- replace: symbol;
2249
- search: symbol;
2250
- split: symbol;
2251
- };
2252
- /** Array of symbols created via createSymbol in this instance. */
2253
- symbols: symbol[];
2254
- /** Manually adds a symbol to the local registry. */
2255
- addSymbol: (symbol: symbol) => void;
2256
- /** Removes a symbol from the local registry. */
2257
- removeSymbol: (symbol: symbol) => void;
2258
- /** Clears all symbols from the local registry. */
2259
- clearSymbols: () => void;
2260
- }
2261
-
2262
- /**
2263
- * Custom hook for managing ES6 Symbols. Provides utilities to create unique symbols,
2264
- * manage a registry of symbols, and access well-known symbols.
2265
- * * @category utilities
2266
- * @returns {UseSymbolReturn} Utilities for creating, retrieving, and managing symbols.
2267
- * @public
2268
- * @see [Documentation](/docs/use-symbol)
2269
- * @example
2270
- * ```tsx
2271
- * const { createSymbol, wellKnownSymbols } = useSymbol();
2272
- * const myId = createSymbol('my-id');
2273
- * * console.log(wellKnownSymbols.iterator); // Symbol(Symbol.iterator)
2274
- * ```
2275
- */
2276
- declare function useSymbol(): UseSymbolReturn;
2277
-
2278
- /** Ternary dark mode options. */
2279
- type TernaryDarkMode = "system" | "dark" | "light";
2280
- /** Options for the `useTernaryDarkMode` hook. */
2281
- type TernaryDarkModeOptions = {
2282
- /**
2283
- * The default value for the dark mode.
2284
- * @default 'system'
2285
- */
2286
- defaultValue?: TernaryDarkMode;
2287
- /**
2288
- * The key for storing dark mode preference in local storage.
2289
- * @default 'sse-hooks-ternary-dark-mode'
2290
- */
2291
- localStorageKey?: string;
2292
- /**
2293
- * If `true` (default), the hook will initialize reading `localStorage`. In SSR, you should set it to `false`, returning default values initially.
2294
- * @default true
2295
- */
2296
- initializeWithValue?: boolean;
2297
- };
2298
- /** Represents the return type of the `useTernaryDarkMode` hook. */
2299
- type TernaryDarkModeReturn = {
2300
- /** The current state of the dark mode. */
2301
- isDarkMode: boolean;
2302
- /** The current state of the dark mode. */
2303
- ternaryDarkMode: TernaryDarkMode;
2304
- /** A function to set the dark mode state. */
2305
- setTernaryDarkMode: Dispatch<SetStateAction<TernaryDarkMode>>;
2306
- /** A function to toggle the dark mode state. */
2307
- toggleTernaryDarkMode: () => void;
2308
- };
2309
- /**
2310
- * Custom hook that manages ternary (system, dark, light) dark mode with local storage support.
2311
- *
2312
- * @category dom
2313
- * @param {?TernaryDarkModeOptions | string} [options] - Options or the local storage key for the hook.
2314
- * @returns {TernaryDarkModeReturn} An object containing the dark mode state and helper functions.
2315
- * @public
2316
- * @see [Documentation](/docs/use-ternary-dark-mode)
2317
- * @example
2318
- * ```tsx
2319
- * const { isDarkMode, ternaryDarkMode, setTernaryDarkMode, toggleTernaryDarkMode } = useTernaryDarkMode({ defaultValue: 'dark' });
2320
- * // Access and use the dark mode state and provided helper functions.
2321
- * ```
2322
- */
2323
- declare function useTernaryDarkMode({ defaultValue, localStorageKey, initializeWithValue, }?: TernaryDarkModeOptions): TernaryDarkModeReturn;
2324
-
2325
- /**
2326
- * Custom hook that handles timeouts in React components using the [`setTimeout API`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout).
2327
- *
2328
- * @category effect
2329
- * @param {() => void} callback - The function to be executed when the timeout elapses.
2330
- * @param {number | null} delay - The duration (in milliseconds) for the timeout. Set to `null` to clear the timeout.
2331
- * @returns {void} This hook does not return anything.
2332
- * @public
2333
- * @see [Documentation](/docs/use-timeout)
2334
- * @example
2335
- * ```tsx
2336
- * // Usage of useTimeout hook
2337
- * useTimeout(() => {
2338
- * // Code to be executed after the specified delay
2339
- * }, 1000); // Set a timeout of 1000 milliseconds (1 second)
2340
- * ```
2341
- */
2342
- declare function useTimeout(callback: () => void, delay: number | null): void;
2343
-
2344
- /**
2345
- * Custom hook that manages a boolean toggle state in React components.
2346
- *
2347
- * @category state
2348
- * @param {boolean} [defaultValue] - The initial value for the toggle state.
2349
- * @returns {[boolean, () => void, Dispatch<SetStateAction<boolean>>]} A tuple containing the current state,
2350
- * a function to toggle the state, and a function to set the state explicitly.
2351
- * @public
2352
- * @see [Documentation](/docs/use-toggle)
2353
- * @example
2354
- * ```tsx
2355
- * const [isToggled, toggle, setToggle] = useToggle(); // Initial value is false
2356
- * // OR
2357
- * const [isToggled, toggle, setToggle] = useToggle(true); // Initial value is true
2358
- * // Use isToggled in your component, toggle to switch the state, setToggle to set the state explicitly.
2359
- * ```
2360
- */
2361
- declare function useToggle(defaultValue?: boolean): [boolean, () => void, Dispatch<SetStateAction<boolean>>];
2362
-
2363
- /**
2364
- * Custom hook that runs a cleanup function when the component is unmounted.
2365
- *
2366
- * @category lifecycle
2367
- * @param {() => void} func - The cleanup function to be executed on unmount.
2368
- * @public
2369
- * @see [Documentation](/docs/use-unmount)
2370
- * @example
2371
- * ```tsx
2372
- * useUnmount(() => {
2373
- * // Cleanup logic here
2374
- * });
2375
- * ```
2376
- */
2377
- declare function useUnmount(func: () => void): void;
2378
-
2379
- /**
2380
- * Represent the dimension of the window.
2381
- * @template T - The type of the dimension (number or undefined).
2382
- */
2383
- type WindowSize<T extends number | undefined = number | undefined> = {
2384
- /** The width of the window. */
2385
- width: T;
2386
- /** The height of the window. */
2387
- height: T;
2388
- };
2389
- /**
2390
- * Hook options.
2391
- * @template InitializeWithValue - If `true` (default), the hook will initialize reading the window size. In SSR, you should set it to `false`, returning `undefined` initially.
2392
- */
2393
- type UseWindowSizeOptions<InitializeWithValue extends boolean | undefined> = {
2394
- /**
2395
- * If `true` (default), the hook will initialize reading the window size. In SSR, you should set it to `false`, returning `undefined` initially.
2396
- * @default true
2397
- */
2398
- initializeWithValue: InitializeWithValue;
2399
- /**
2400
- * The delay in milliseconds before the state is updated (disabled by default for retro-compatibility).
2401
- * @default undefined
2402
- */
2403
- debounceDelay?: number;
2404
- };
2405
- declare function useWindowSize(options: UseWindowSizeOptions<false>): WindowSize;
2406
- declare function useWindowSize(options?: Partial<UseWindowSizeOptions<true>>): WindowSize<number>;
2407
-
2408
- type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N;
2409
- type DefineProps<T, BKeys extends keyof T> = Readonly<T> & {
2410
- readonly [K in BKeys]-?: boolean;
2411
- };
2412
- type NotUndefined<T> = T extends undefined ? never : T;
2413
- type MappedOmit<T, K extends keyof any> = {
2414
- [P in keyof T as P extends K ? never : P]: T[P];
2415
- };
2416
- type InferDefaults<T> = {
2417
- [K in keyof T]?: InferDefault<T, T[K]>;
2418
- };
2419
- type NativeType = null | undefined | number | string | boolean | symbol | Function;
2420
- type InferDefault<P, T> = ((props: P) => T & {}) | (T extends NativeType ? T : never);
2421
- type PropsWithDefaults<T, Defaults extends InferDefaults<T>, BKeys extends keyof T> = T extends unknown ? Readonly<MappedOmit<T, keyof Defaults>> & {
2422
- readonly [K in keyof Defaults as K extends keyof T ? K : never]-?: K extends keyof T ? Defaults[K] extends undefined ? IfAny<Defaults[K], NotUndefined<T[K]>, T[K]> : NotUndefined<T[K]> : never;
2423
- } & {
2424
- readonly [K in BKeys]-?: K extends keyof Defaults ? Defaults[K] extends undefined ? boolean | undefined : boolean : boolean;
2425
- } : never;
2426
- declare function withDefaults<T, BKeys extends keyof T = never>(props: DefineProps<T, BKeys>, defaults: InferDefaults<T>): PropsWithDefaults<T, InferDefaults<T>, BKeys>;
2427
-
2428
- export { ComputedRefImpl, Dep, Device, EffectFlags, Link, ReactiveFlags, RefImpl, TrackOpTypes, TriggerOpTypes, __DEV__, batch, breakpointsAntDesign, breakpointsBootstrapV5, breakpointsSematic, breakpointsTailwind, breakpointsVuetify, computed, endBatch, errorMessage1, extend, getActiveSub, globalVersion, isArray, isFunction, isIntegerKey, isMap, isObject, isSymbol, kbdKeysMap, ref, refreshComputed, setActiveSub, shouldTrack, startBatch, targetMap, track, useAudioRecorder, useBatteryHook as useBattery, useBoolean, useBreakpoint, useClickAnyWhere, useClickAway, useComputed, useConferenceSystem, useCookie, useCopyToClipboard, useCountdown, useCounter, useDarkMode, useDebounceCallback, useDebounceValue, useDelete, useDocumentTitle, useEventCallback, useEventListener, useFetch, useForkRef, useGet, useHover, useIndexedDB, useIntersectionObserver, useInterval, useIsClient, useIsMounted, useIsomorphicLayoutEffect, useKbd, useLocalStorage, useMap, useMediaQuality, useMediaQuery, useMediaSession, useNetworkInformation, usePost, usePut, useReactive, useReadLocalStorage, useResizeObserver, useRoleGuard, useSSR, useScreen, useScreenShare, useScript, useScrollLock, useSessionStorage, useStep, useSymbol, useTernaryDarkMode, useTimeout, useToggle, useUnmount, useUserMedia, useWindowSize, weAreServer, withDefaults };
2429
- export type { AudioAnalysisData, BatteryState, ComputedGetter, ComputedRef, ComputedSetter, CustomEvent$1 as CustomEvent, CustomEventHandler, CustomEventHandlers, DebouncedState, DebuggerEvent, DebuggerEventExtraInfo, DebuggerOptions, DefineProps, EventListenerMap, EventListenersRef, HTMLElRef, IfAny, KbdKey, KbdKeySpecific, MediaImage, MediaMetadataInit, MediaQuality, MediaSessionAction, MediaSessionActionHandler, MediaSessionPlaybackState, NetworkInformation, QualityPresetTypes, Ref, Subscriber, TernaryDarkMode, TernaryDarkModeOptions, TernaryDarkModeReturn, UseAudioRecorderOptions, UseAudioRecorderReturn, UseClickAwayOptions, UseConferenceSystemOptions, UseConferenceSystemReturns, UseCookieOptions, UseFetchOptions, UseFetchReturn, UseFetchState, UseMediaQualityReturn, UseMediaSessionOptions, UseMediaSessionReturn, UseNetworkInformationReturn, UsePortalArrayReturn, UsePortalObjectReturn, UsePortalOptions, UseRoleGuardOptions, UseRoleGuardReturn, UseSSRReturn, UseScreenShareOptions, UseScreenShareReturn, UseSymbolReturn, UseUserMediaConstraints, UseUserMediaReturn, User, WritableComputedOptions };