sse-hooks 1.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.
@@ -0,0 +1,327 @@
1
+ import React, { useEffect } from 'react';
2
+
3
+ /** The useBoolean return type. */
4
+ type UseBooleanReturn = {
5
+ /** The current boolean state value. */
6
+ value: boolean;
7
+ /** Function to set the boolean state directly. */
8
+ setValue: React.Dispatch<React.SetStateAction<boolean>>;
9
+ /** Function to set the boolean state to `true`. */
10
+ setTrue: () => void;
11
+ /** Function to set the boolean state to `false`. */
12
+ setFalse: () => void;
13
+ /** Function to toggle the boolean state. */
14
+ toggle: () => void;
15
+ };
16
+ /**
17
+ * Custom hook that handles boolean state with useful utility functions.
18
+ * @param {boolean} [defaultValue] - The initial value for the boolean state (default is `false`).
19
+ * @returns {UseBooleanReturn} An object containing the boolean state value and utility functions to manipulate the state.
20
+ * @throws Will throw an error if `defaultValue` is an invalid boolean value.
21
+ * @public
22
+ * @example
23
+ * ```tsx
24
+ * const { value, setTrue, setFalse, toggle } = useBoolean(true);
25
+ * ```
26
+ */
27
+ declare function useBoolean(defaultValue?: boolean): UseBooleanReturn;
28
+
29
+ /**
30
+ * The copied text as `string` or `null` if nothing has been copied yet.
31
+ */
32
+ type CopiedValue = string | null;
33
+ /**
34
+ * Function to copy text to the clipboard.
35
+ * @param text - The text to copy to the clipboard.
36
+ * @returns {Promise<boolean>} A promise that resolves to `true` if the text was copied successfully, or `false` otherwise.
37
+ */
38
+ type CopyFn = (text: string) => Promise<boolean>;
39
+ /**
40
+ * Custom hook that copies text to the clipboard using the [`Clipboard API`](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API).
41
+ * @returns {[CopiedValue, CopyFn]} An tuple containing the copied text and a function to copy text to the clipboard.
42
+ * @public
43
+ * @example
44
+ * ```tsx
45
+ * const [copiedText, copyToClipboard] = useCopyToClipboard();
46
+ * const textToCopy = 'Hello, world!';
47
+ *
48
+ * // Attempt to copy text to the clipboard
49
+ * copyToClipboard(textToCopy)
50
+ * .then(success => {
51
+ * if (success) {
52
+ * console.log(`Text "${textToCopy}" copied to clipboard successfully.`);
53
+ * } else {
54
+ * console.error('Failed to copy text to clipboard.');
55
+ * }
56
+ * });
57
+ * ```
58
+ */
59
+ declare function useCopyToClipboard(): [CopiedValue, CopyFn];
60
+
61
+ type CountdownOptions = {
62
+ countStart: number;
63
+ intervalMs?: number;
64
+ isIncrement?: boolean;
65
+ countStop?: number;
66
+ };
67
+ type CountdownControllers = {
68
+ startCountdown: () => void;
69
+ stopCountdown: () => void;
70
+ resetCountdown: () => void;
71
+ };
72
+ declare function useCountdown({ countStart, countStop, intervalMs, isIncrement, }: CountdownOptions): [number, CountdownControllers];
73
+
74
+ type UseCounterReturn = {
75
+ count: number;
76
+ increment: () => void;
77
+ decrement: () => void;
78
+ reset: () => void;
79
+ setCount: React.Dispatch<React.SetStateAction<number>>;
80
+ };
81
+ declare function useCounter(initialValue?: number): UseCounterReturn;
82
+
83
+ type DarkModeOptions = {
84
+ defaultValue?: boolean;
85
+ localStorageKey?: string;
86
+ initializeWithValue?: boolean;
87
+ };
88
+ type DarkModeReturn = {
89
+ isDarkMode: boolean;
90
+ toggle: () => void;
91
+ enable: () => void;
92
+ disable: () => void;
93
+ set: (value: boolean) => void;
94
+ };
95
+ declare function useDarkMode(options?: DarkModeOptions): DarkModeReturn;
96
+
97
+ type DebounceOptions = {
98
+ leading?: boolean;
99
+ trailing?: boolean;
100
+ maxWait?: number;
101
+ };
102
+ type ControlFunctions = {
103
+ cancel: () => void;
104
+ flush: () => void;
105
+ isPending: () => boolean;
106
+ };
107
+ type DebouncedState<T extends (...args: any) => ReturnType<T>> = ((...args: Parameters<T>) => ReturnType<T> | undefined) & ControlFunctions;
108
+ declare function useDebounceCallback<T extends (...args: any) => ReturnType<T>>(func: T, delay?: number, options?: DebounceOptions): DebouncedState<T>;
109
+
110
+ type UseDebounceValueOptions<T> = {
111
+ leading?: boolean;
112
+ trailing?: boolean;
113
+ maxWait?: number;
114
+ equalityFn?: (left: T, right: T) => boolean;
115
+ };
116
+ declare function useDebounceValue<T>(initialValue: T | (() => T), delay: number, options?: UseDebounceValueOptions<T>): [T, DebouncedState<(value: T) => void>];
117
+
118
+ type UseDocumentTitleOptions = {
119
+ preserveTitleOnUnmount?: boolean;
120
+ };
121
+ declare function useDocumentTitle(title: string, options?: UseDocumentTitleOptions): void;
122
+
123
+ declare function useEventCallback<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R;
124
+ declare function useEventCallback<Args extends unknown[], R>(fn: ((...args: Args) => R) | undefined): ((...args: Args) => R) | undefined;
125
+
126
+ declare function useEventListener<K extends keyof MediaQueryListEventMap>(eventName: K, handler: (event: MediaQueryListEventMap[K]) => void, element: React.RefObject<MediaQueryList>, options?: boolean | AddEventListenerOptions): void;
127
+ declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, handler: (event: WindowEventMap[K]) => void, element?: undefined, options?: boolean | AddEventListenerOptions): void;
128
+ 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: React.RefObject<T>, options?: boolean | AddEventListenerOptions): void;
129
+ declare function useEventListener<K extends keyof DocumentEventMap>(eventName: K, handler: (event: DocumentEventMap[K]) => void, element: React.RefObject<Document>, options?: boolean | AddEventListenerOptions): void;
130
+
131
+ interface UseFetchOptions extends RequestInit {
132
+ immediate?: boolean;
133
+ onSuccess?: (data: any) => void;
134
+ onError?: (error: Error) => void;
135
+ }
136
+ interface UseFetchState<T> {
137
+ data: T | null;
138
+ loading: boolean;
139
+ error: Error | null;
140
+ }
141
+ interface UseFetchReturn<T> extends UseFetchState<T> {
142
+ execute: (url?: string, options?: RequestInit) => Promise<T | null>;
143
+ abort: () => void;
144
+ reset: () => void;
145
+ }
146
+ declare function useFetch<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
147
+ declare function useGet<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
148
+ declare function usePost<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
149
+ declare function usePut<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
150
+ declare function useDelete<T = any>(url?: string, options?: UseFetchOptions): UseFetchReturn<T>;
151
+
152
+ declare function useHover<T extends HTMLElement = HTMLElement>(elementRef: React.RefObject<T>): boolean;
153
+
154
+ interface UseIndexedDBOptions {
155
+ version?: number;
156
+ onUpgradeNeeded?: (db: IDBDatabase, oldVersion: number, newVersion: number) => void;
157
+ }
158
+ interface UseIndexedDBReturn<T> {
159
+ data: T | null;
160
+ error: string | null;
161
+ loading: boolean;
162
+ setItem: (key: string, value: T) => Promise<void>;
163
+ getItem: (key: string) => Promise<T | null>;
164
+ removeItem: (key: string) => Promise<void>;
165
+ clear: () => Promise<void>;
166
+ getAllKeys: () => Promise<string[]>;
167
+ }
168
+ declare function useIndexedDB<T>(databaseName: string, storeName: string, options?: UseIndexedDBOptions): UseIndexedDBReturn<T>;
169
+
170
+ type UseIntersectionObserverOptions = {
171
+ root?: Element | Document | null;
172
+ rootMargin?: string;
173
+ threshold?: number | number[];
174
+ freezeOnceVisible?: boolean;
175
+ onChange?: (isIntersecting: boolean, entry: IntersectionObserverEntry) => void;
176
+ initialIsIntersecting?: boolean;
177
+ };
178
+ type IntersectionReturn = [
179
+ (node?: Element | null) => void,
180
+ boolean,
181
+ IntersectionObserverEntry | undefined
182
+ ] & {
183
+ ref: (node?: Element | null) => void;
184
+ isIntersecting: boolean;
185
+ entry?: IntersectionObserverEntry;
186
+ };
187
+ declare function useIntersectionObserver({ threshold, root, rootMargin, freezeOnceVisible, initialIsIntersecting, onChange, }?: UseIntersectionObserverOptions): IntersectionReturn;
188
+
189
+ declare function useInterval(callback: () => void, delay: number | null): void;
190
+
191
+ declare function useIsClient(): boolean;
192
+
193
+ declare function useIsMounted(): () => boolean;
194
+
195
+ declare const useIsomorphicLayoutEffect: typeof useEffect;
196
+
197
+ declare global {
198
+ interface WindowEventMap {
199
+ "local-storage": CustomEvent;
200
+ }
201
+ }
202
+ type UseLocalStorageOptions<T> = {
203
+ serializer?: (value: T) => string;
204
+ deserializer?: (value: string) => T;
205
+ initializeWithValue?: boolean;
206
+ };
207
+ declare function useLocalStorage<T>(key: string, initialValue: T | (() => T), options?: UseLocalStorageOptions<T>): [T, React.Dispatch<React.SetStateAction<T>>, () => void];
208
+
209
+ type MapOrEntries<K, V> = Map<K, V> | [K, V][];
210
+ type UseMapActions<K, V> = {
211
+ set: (key: K, value: V) => void;
212
+ setAll: (entries: MapOrEntries<K, V>) => void;
213
+ remove: (key: K) => void;
214
+ reset: Map<K, V>["clear"];
215
+ };
216
+ type UseMapReturn<K, V> = [
217
+ Omit<Map<K, V>, "set" | "clear" | "delete">,
218
+ UseMapActions<K, V>
219
+ ];
220
+ declare function useMap<K, V>(initialState?: MapOrEntries<K, V>): UseMapReturn<K, V>;
221
+
222
+ type UseMediaQueryOptions = {
223
+ defaultValue?: boolean;
224
+ initializeWithValue?: boolean;
225
+ };
226
+ declare function useMediaQuery(query: string, { defaultValue, initializeWithValue, }?: UseMediaQueryOptions): boolean;
227
+
228
+ type Options<T, InitializeWithValue extends boolean | undefined> = {
229
+ deserializer?: (value: string) => T;
230
+ initializeWithValue: InitializeWithValue;
231
+ };
232
+ declare function useReadLocalStorage<T>(key: string, options: Options<T, false>): T | null | undefined;
233
+ declare function useReadLocalStorage<T>(key: string, options?: Partial<Options<T, true>>): T | null;
234
+
235
+ type Size = {
236
+ width: number | undefined;
237
+ height: number | undefined;
238
+ };
239
+ type UseResizeObserverOptions<T extends HTMLElement = HTMLElement> = {
240
+ ref: React.RefObject<T>;
241
+ onResize?: (size: Size) => void;
242
+ box?: "border-box" | "content-box" | "device-pixel-content-box";
243
+ };
244
+ declare function useResizeObserver<T extends HTMLElement = HTMLElement>(options: UseResizeObserverOptions<T>): Size;
245
+
246
+ type UseScreenOptions<InitializeWithValue extends boolean | undefined> = {
247
+ initializeWithValue: InitializeWithValue;
248
+ debounceDelay?: number;
249
+ };
250
+ declare function useScreen(options: UseScreenOptions<false>): Screen | undefined;
251
+ declare function useScreen(options?: Partial<UseScreenOptions<true>>): Screen;
252
+
253
+ type UseScriptStatus = "idle" | "loading" | "ready" | "error";
254
+ type UseScriptOptions = {
255
+ shouldPreventLoad?: boolean;
256
+ removeOnUnmount?: boolean;
257
+ id?: string;
258
+ };
259
+ declare function useScript(src: string | null, options?: UseScriptOptions): UseScriptStatus;
260
+
261
+ type UseScrollLockOptions = {
262
+ autoLock?: boolean;
263
+ lockTarget?: HTMLElement | string;
264
+ widthReflow?: boolean;
265
+ };
266
+ type UseScrollLockReturn = {
267
+ isLocked: boolean;
268
+ lock: () => void;
269
+ unlock: () => void;
270
+ };
271
+ declare function useScrollLock(options?: UseScrollLockOptions): UseScrollLockReturn;
272
+
273
+ declare global {
274
+ interface WindowEventMap {
275
+ "session-storage": CustomEvent;
276
+ }
277
+ }
278
+ type UseSessionStorageOptions<T> = {
279
+ serializer?: (value: T) => string;
280
+ deserializer?: (value: string) => T;
281
+ initializeWithValue?: boolean;
282
+ };
283
+ declare function useSessionStorage<T>(key: string, initialValue: T | (() => T), options?: UseSessionStorageOptions<T>): [T, React.Dispatch<React.SetStateAction<T>>, () => void];
284
+
285
+ type UseStepActions = {
286
+ goToNextStep: () => void;
287
+ goToPrevStep: () => void;
288
+ reset: () => void;
289
+ canGoToNextStep: boolean;
290
+ canGoToPrevStep: boolean;
291
+ setStep: React.Dispatch<React.SetStateAction<number>>;
292
+ };
293
+ declare function useStep(maxStep: number): [number, UseStepActions];
294
+
295
+ type TernaryDarkMode = "system" | "dark" | "light";
296
+ type TernaryDarkModeOptions = {
297
+ defaultValue?: TernaryDarkMode;
298
+ localStorageKey?: string;
299
+ initializeWithValue?: boolean;
300
+ };
301
+ type TernaryDarkModeReturn = {
302
+ isDarkMode: boolean;
303
+ ternaryDarkMode: TernaryDarkMode;
304
+ setTernaryDarkMode: React.Dispatch<React.SetStateAction<TernaryDarkMode>>;
305
+ toggleTernaryDarkMode: () => void;
306
+ };
307
+ declare function useTernaryDarkMode({ defaultValue, localStorageKey, initializeWithValue, }?: TernaryDarkModeOptions): TernaryDarkModeReturn;
308
+
309
+ declare function useTimeout(callback: () => void, delay: number | null): void;
310
+
311
+ declare function useToggle(defaultValue?: boolean): [boolean, () => void, React.Dispatch<React.SetStateAction<boolean>>];
312
+
313
+ declare function useUnmount(func: () => void): void;
314
+
315
+ type WindowSize<T extends number | undefined = number | undefined> = {
316
+ width: T;
317
+ height: T;
318
+ };
319
+ type UseWindowSizeOptions<InitializeWithValue extends boolean | undefined> = {
320
+ initializeWithValue: InitializeWithValue;
321
+ debounceDelay?: number;
322
+ };
323
+ declare function useWindowSize(options: UseWindowSizeOptions<false>): WindowSize;
324
+ declare function useWindowSize(options?: Partial<UseWindowSizeOptions<true>>): WindowSize<number>;
325
+
326
+ export { useBoolean, useCopyToClipboard, useCountdown, useCounter, useDarkMode, useDebounceCallback, useDebounceValue, useDelete, useDocumentTitle, useEventCallback, useEventListener, useFetch, useGet, useHover, useIndexedDB, useIntersectionObserver, useInterval, useIsClient, useIsMounted, useIsomorphicLayoutEffect, useLocalStorage, useMap, useMediaQuery, usePost, usePut, useReadLocalStorage, useResizeObserver, useScreen, useScript, useScrollLock, useSessionStorage, useStep, useTernaryDarkMode, useTimeout, useToggle, useUnmount, useWindowSize };
327
+ export type { DebouncedState, TernaryDarkMode, TernaryDarkModeOptions, TernaryDarkModeReturn, UseFetchOptions, UseFetchReturn, UseFetchState };