airyhooks 0.2.0 → 0.3.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/README.md +54 -8
- package/dist/commands/add.js +46 -9
- package/dist/commands/add.js.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/utils/config.js +2 -0
- package/dist/utils/config.js.map +1 -1
- package/dist/utils/get-file-extension.js +3 -0
- package/dist/utils/get-file-extension.js.map +1 -1
- package/dist/utils/get-hook-template.js +9 -1426
- package/dist/utils/get-hook-template.js.map +1 -1
- package/dist/utils/hook-templates.js +3386 -0
- package/dist/utils/hook-templates.js.map +1 -0
- package/dist/utils/registry.js +8 -0
- package/dist/utils/registry.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,3386 @@
|
|
|
1
|
+
// AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
|
|
2
|
+
// Generated by: pnpm --filter @airyhooks/hooks build:templates
|
|
3
|
+
// Source: packages/hooks/src/*/use*.ts
|
|
4
|
+
export const templates = {
|
|
5
|
+
useBoolean: `import { useCallback, useState } from "react";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Boolean state with setTrue, setFalse, and toggle handlers.
|
|
9
|
+
*
|
|
10
|
+
* @param initialValue - Initial boolean value (default: false)
|
|
11
|
+
* @returns Tuple of [value, { setTrue, setFalse, toggle }]
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* const [isEnabled, handlers] = useBoolean(false);
|
|
15
|
+
*
|
|
16
|
+
* return (
|
|
17
|
+
* <>
|
|
18
|
+
* <button onClick={handlers.toggle}>Toggle</button>
|
|
19
|
+
* <button onClick={handlers.setTrue}>Enable</button>
|
|
20
|
+
* <button onClick={handlers.setFalse}>Disable</button>
|
|
21
|
+
* </>
|
|
22
|
+
* );
|
|
23
|
+
*/
|
|
24
|
+
export function useBoolean(initialValue = false): [
|
|
25
|
+
boolean,
|
|
26
|
+
{
|
|
27
|
+
setFalse: () => void;
|
|
28
|
+
setTrue: () => void;
|
|
29
|
+
toggle: () => void;
|
|
30
|
+
},
|
|
31
|
+
] {
|
|
32
|
+
const [value, setValue] = useState(initialValue);
|
|
33
|
+
|
|
34
|
+
const toggle = useCallback(() => {
|
|
35
|
+
setValue((prev) => !prev);
|
|
36
|
+
}, []);
|
|
37
|
+
|
|
38
|
+
const setTrue = useCallback(() => {
|
|
39
|
+
setValue(true);
|
|
40
|
+
}, []);
|
|
41
|
+
|
|
42
|
+
const setFalse = useCallback(() => {
|
|
43
|
+
setValue(false);
|
|
44
|
+
}, []);
|
|
45
|
+
|
|
46
|
+
return [
|
|
47
|
+
value,
|
|
48
|
+
{
|
|
49
|
+
setFalse,
|
|
50
|
+
setTrue,
|
|
51
|
+
toggle,
|
|
52
|
+
},
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
`, useBoolean_test: `import { act, renderHook } from "@testing-library/react";
|
|
56
|
+
import { describe, expect, it } from "vitest";
|
|
57
|
+
|
|
58
|
+
import { useBoolean } from "./useBoolean.js";
|
|
59
|
+
|
|
60
|
+
describe("useBoolean", () => {
|
|
61
|
+
it("should initialize with false by default", () => {
|
|
62
|
+
const { result } = renderHook(() => useBoolean());
|
|
63
|
+
expect(result.current[0]).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("should initialize with provided value", () => {
|
|
67
|
+
const { result } = renderHook(() => useBoolean(true));
|
|
68
|
+
expect(result.current[0]).toBe(true);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("should have setTrue handler", () => {
|
|
72
|
+
const { result } = renderHook(() => useBoolean());
|
|
73
|
+
|
|
74
|
+
act(() => {
|
|
75
|
+
result.current[1].setTrue();
|
|
76
|
+
});
|
|
77
|
+
expect(result.current[0]).toBe(true);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("should have setFalse handler", () => {
|
|
81
|
+
const { result } = renderHook(() => useBoolean(true));
|
|
82
|
+
|
|
83
|
+
act(() => {
|
|
84
|
+
result.current[1].setFalse();
|
|
85
|
+
});
|
|
86
|
+
expect(result.current[0]).toBe(false);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("should have toggle handler", () => {
|
|
90
|
+
const { result } = renderHook(() => useBoolean());
|
|
91
|
+
|
|
92
|
+
act(() => {
|
|
93
|
+
result.current[1].toggle();
|
|
94
|
+
});
|
|
95
|
+
expect(result.current[0]).toBe(true);
|
|
96
|
+
|
|
97
|
+
act(() => {
|
|
98
|
+
result.current[1].toggle();
|
|
99
|
+
});
|
|
100
|
+
expect(result.current[0]).toBe(false);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("should maintain stable handler references", () => {
|
|
104
|
+
const { rerender, result } = renderHook(() => useBoolean());
|
|
105
|
+
|
|
106
|
+
const handlers1 = result.current[1];
|
|
107
|
+
rerender();
|
|
108
|
+
const handlers2 = result.current[1];
|
|
109
|
+
|
|
110
|
+
expect(handlers1.toggle).toBe(handlers2.toggle);
|
|
111
|
+
expect(handlers1.setTrue).toBe(handlers2.setTrue);
|
|
112
|
+
expect(handlers1.setFalse).toBe(handlers2.setFalse);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
`,
|
|
116
|
+
useCopyToClipboard: `import { useCallback, useState } from "react";
|
|
117
|
+
|
|
118
|
+
export interface UseCopyToClipboardResult {
|
|
119
|
+
/** The currently copied text, or null if nothing has been copied */
|
|
120
|
+
copiedText: null | string;
|
|
121
|
+
/** Function to copy text to clipboard. Returns true if successful. */
|
|
122
|
+
copy: (text: string) => Promise<boolean>;
|
|
123
|
+
/** Function to reset the copied state */
|
|
124
|
+
reset: () => void;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Copy text to the clipboard using the modern Clipboard API.
|
|
129
|
+
*
|
|
130
|
+
* @returns Object containing copiedText state, copy function, and reset function
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* const { copiedText, copy, reset } = useCopyToClipboard();
|
|
134
|
+
*
|
|
135
|
+
* return (
|
|
136
|
+
* <button onClick={() => copy("Hello, World!")}>
|
|
137
|
+
* {copiedText ? "Copied!" : "Copy"}
|
|
138
|
+
* </button>
|
|
139
|
+
* );
|
|
140
|
+
*/
|
|
141
|
+
export function useCopyToClipboard(): UseCopyToClipboardResult {
|
|
142
|
+
const [copiedText, setCopiedText] = useState<null | string>(null);
|
|
143
|
+
|
|
144
|
+
const copy = useCallback(async (text: string): Promise<boolean> => {
|
|
145
|
+
// Check if we're in a browser environment with clipboard support
|
|
146
|
+
const clipboard =
|
|
147
|
+
typeof window !== "undefined" ? navigator.clipboard : undefined;
|
|
148
|
+
|
|
149
|
+
if (!clipboard) {
|
|
150
|
+
console.warn("Clipboard API not available");
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
try {
|
|
155
|
+
await clipboard.writeText(text);
|
|
156
|
+
setCopiedText(text);
|
|
157
|
+
return true;
|
|
158
|
+
} catch (error) {
|
|
159
|
+
console.warn("Failed to copy to clipboard:", error);
|
|
160
|
+
setCopiedText(null);
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}, []);
|
|
164
|
+
|
|
165
|
+
const reset = useCallback(() => {
|
|
166
|
+
setCopiedText(null);
|
|
167
|
+
}, []);
|
|
168
|
+
|
|
169
|
+
return { copiedText, copy, reset };
|
|
170
|
+
}
|
|
171
|
+
`, useCopyToClipboard_test: `import { act, renderHook } from "@testing-library/react";
|
|
172
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
173
|
+
|
|
174
|
+
import { useCopyToClipboard } from "./useCopyToClipboard.js";
|
|
175
|
+
|
|
176
|
+
describe("useCopyToClipboard", () => {
|
|
177
|
+
const mockClipboard = {
|
|
178
|
+
writeText: vi.fn(),
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
beforeEach(() => {
|
|
182
|
+
Object.assign(navigator, {
|
|
183
|
+
clipboard: mockClipboard,
|
|
184
|
+
});
|
|
185
|
+
mockClipboard.writeText.mockResolvedValue(undefined);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
afterEach(() => {
|
|
189
|
+
vi.clearAllMocks();
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("should return initial state with null copiedText", () => {
|
|
193
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
194
|
+
|
|
195
|
+
expect(result.current.copiedText).toBeNull();
|
|
196
|
+
expect(typeof result.current.copy).toBe("function");
|
|
197
|
+
expect(typeof result.current.reset).toBe("function");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("should copy text to clipboard and update state", async () => {
|
|
201
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
202
|
+
|
|
203
|
+
await act(async () => {
|
|
204
|
+
const success = await result.current.copy("Hello, World!");
|
|
205
|
+
expect(success).toBe(true);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
expect(mockClipboard.writeText).toHaveBeenCalledWith("Hello, World!");
|
|
209
|
+
expect(result.current.copiedText).toBe("Hello, World!");
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("should reset copiedText state", async () => {
|
|
213
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
214
|
+
|
|
215
|
+
await act(async () => {
|
|
216
|
+
await result.current.copy("Test");
|
|
217
|
+
});
|
|
218
|
+
expect(result.current.copiedText).toBe("Test");
|
|
219
|
+
|
|
220
|
+
act(() => {
|
|
221
|
+
result.current.reset();
|
|
222
|
+
});
|
|
223
|
+
expect(result.current.copiedText).toBeNull();
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it("should return false when clipboard API fails", async () => {
|
|
227
|
+
mockClipboard.writeText.mockRejectedValueOnce(new Error("Failed"));
|
|
228
|
+
const consoleSpy = vi.spyOn(console, "warn").mockImplementation(vi.fn());
|
|
229
|
+
|
|
230
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
231
|
+
|
|
232
|
+
await act(async () => {
|
|
233
|
+
const success = await result.current.copy("Test");
|
|
234
|
+
expect(success).toBe(false);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
expect(result.current.copiedText).toBeNull();
|
|
238
|
+
consoleSpy.mockRestore();
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
it("should return false when clipboard API is not available", async () => {
|
|
242
|
+
Object.assign(navigator, { clipboard: undefined });
|
|
243
|
+
const consoleSpy = vi.spyOn(console, "warn").mockImplementation(vi.fn());
|
|
244
|
+
|
|
245
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
246
|
+
|
|
247
|
+
await act(async () => {
|
|
248
|
+
const success = await result.current.copy("Test");
|
|
249
|
+
expect(success).toBe(false);
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
consoleSpy.mockRestore();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it("should update copiedText on subsequent copies", async () => {
|
|
256
|
+
const { result } = renderHook(() => useCopyToClipboard());
|
|
257
|
+
|
|
258
|
+
await act(async () => {
|
|
259
|
+
await result.current.copy("First");
|
|
260
|
+
});
|
|
261
|
+
expect(result.current.copiedText).toBe("First");
|
|
262
|
+
|
|
263
|
+
await act(async () => {
|
|
264
|
+
await result.current.copy("Second");
|
|
265
|
+
});
|
|
266
|
+
expect(result.current.copiedText).toBe("Second");
|
|
267
|
+
});
|
|
268
|
+
});
|
|
269
|
+
`,
|
|
270
|
+
useCounter: `import { useCallback, useState } from "react";
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Manages numeric state with increment, decrement, reset, and set methods.
|
|
274
|
+
*
|
|
275
|
+
* @param initialValue - Initial numeric value (default: 0)
|
|
276
|
+
* @returns Tuple of [value, { increment, decrement, reset, set }]
|
|
277
|
+
*
|
|
278
|
+
* @example
|
|
279
|
+
* const [count, { increment, decrement, reset }] = useCounter(0);
|
|
280
|
+
*
|
|
281
|
+
* return (
|
|
282
|
+
* <>
|
|
283
|
+
* <p>Count: {count}</p>
|
|
284
|
+
* <button onClick={() => increment()}>+1</button>
|
|
285
|
+
* <button onClick={() => decrement()}>-1</button>
|
|
286
|
+
* <button onClick={() => increment(5)}>+5</button>
|
|
287
|
+
* <button onClick={() => reset()}>Reset</button>
|
|
288
|
+
* </>
|
|
289
|
+
* );
|
|
290
|
+
*/
|
|
291
|
+
export function useCounter(initialValue = 0): [
|
|
292
|
+
number,
|
|
293
|
+
{
|
|
294
|
+
decrement: (amount?: number) => void;
|
|
295
|
+
increment: (amount?: number) => void;
|
|
296
|
+
reset: () => void;
|
|
297
|
+
set: (value: ((prev: number) => number) | number) => void;
|
|
298
|
+
},
|
|
299
|
+
] {
|
|
300
|
+
const [count, setCount] = useState<number>(initialValue);
|
|
301
|
+
|
|
302
|
+
const increment = useCallback((amount = 1) => {
|
|
303
|
+
setCount((prev) => prev + amount);
|
|
304
|
+
}, []);
|
|
305
|
+
|
|
306
|
+
const decrement = useCallback((amount = 1) => {
|
|
307
|
+
setCount((prev) => prev - amount);
|
|
308
|
+
}, []);
|
|
309
|
+
|
|
310
|
+
const reset = useCallback(() => {
|
|
311
|
+
setCount(initialValue);
|
|
312
|
+
}, [initialValue]);
|
|
313
|
+
|
|
314
|
+
const set = useCallback((value: ((prev: number) => number) | number) => {
|
|
315
|
+
setCount(value);
|
|
316
|
+
}, []);
|
|
317
|
+
|
|
318
|
+
return [
|
|
319
|
+
count,
|
|
320
|
+
{
|
|
321
|
+
decrement,
|
|
322
|
+
increment,
|
|
323
|
+
reset,
|
|
324
|
+
set,
|
|
325
|
+
},
|
|
326
|
+
];
|
|
327
|
+
}
|
|
328
|
+
`, useCounter_test: `import { act, renderHook } from "@testing-library/react";
|
|
329
|
+
import { describe, expect, it } from "vitest";
|
|
330
|
+
|
|
331
|
+
import { useCounter } from "./useCounter.js";
|
|
332
|
+
|
|
333
|
+
describe("useCounter", () => {
|
|
334
|
+
it("should initialize with 0 by default", () => {
|
|
335
|
+
const { result } = renderHook(() => useCounter());
|
|
336
|
+
expect(result.current[0]).toBe(0);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it("should initialize with provided value", () => {
|
|
340
|
+
const { result } = renderHook(() => useCounter(10));
|
|
341
|
+
expect(result.current[0]).toBe(10);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
it("should increment by 1 by default", () => {
|
|
345
|
+
const { result } = renderHook(() => useCounter(0));
|
|
346
|
+
|
|
347
|
+
act(() => {
|
|
348
|
+
result.current[1].increment();
|
|
349
|
+
});
|
|
350
|
+
expect(result.current[0]).toBe(1);
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
it("should increment by custom amount", () => {
|
|
354
|
+
const { result } = renderHook(() => useCounter(0));
|
|
355
|
+
|
|
356
|
+
act(() => {
|
|
357
|
+
result.current[1].increment(5);
|
|
358
|
+
});
|
|
359
|
+
expect(result.current[0]).toBe(5);
|
|
360
|
+
|
|
361
|
+
act(() => {
|
|
362
|
+
result.current[1].increment(3);
|
|
363
|
+
});
|
|
364
|
+
expect(result.current[0]).toBe(8);
|
|
365
|
+
});
|
|
366
|
+
|
|
367
|
+
it("should decrement by 1 by default", () => {
|
|
368
|
+
const { result } = renderHook(() => useCounter(5));
|
|
369
|
+
|
|
370
|
+
act(() => {
|
|
371
|
+
result.current[1].decrement();
|
|
372
|
+
});
|
|
373
|
+
expect(result.current[0]).toBe(4);
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
it("should decrement by custom amount", () => {
|
|
377
|
+
const { result } = renderHook(() => useCounter(10));
|
|
378
|
+
|
|
379
|
+
act(() => {
|
|
380
|
+
result.current[1].decrement(3);
|
|
381
|
+
});
|
|
382
|
+
expect(result.current[0]).toBe(7);
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
it("should reset to initial value", () => {
|
|
386
|
+
const { result } = renderHook(() => useCounter(5));
|
|
387
|
+
|
|
388
|
+
act(() => {
|
|
389
|
+
result.current[1].increment(10);
|
|
390
|
+
});
|
|
391
|
+
expect(result.current[0]).toBe(15);
|
|
392
|
+
|
|
393
|
+
act(() => {
|
|
394
|
+
result.current[1].reset();
|
|
395
|
+
});
|
|
396
|
+
expect(result.current[0]).toBe(5);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
it("should set to specific value", () => {
|
|
400
|
+
const { result } = renderHook(() => useCounter(0));
|
|
401
|
+
|
|
402
|
+
act(() => {
|
|
403
|
+
result.current[1].set(42);
|
|
404
|
+
});
|
|
405
|
+
expect(result.current[0]).toBe(42);
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
it("should set with updater function", () => {
|
|
409
|
+
const { result } = renderHook(() => useCounter(10));
|
|
410
|
+
|
|
411
|
+
act(() => {
|
|
412
|
+
result.current[1].set((prev) => prev * 2);
|
|
413
|
+
});
|
|
414
|
+
expect(result.current[0]).toBe(20);
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
it("should handle negative numbers", () => {
|
|
418
|
+
const { result } = renderHook(() => useCounter(0));
|
|
419
|
+
|
|
420
|
+
act(() => {
|
|
421
|
+
result.current[1].decrement(5);
|
|
422
|
+
});
|
|
423
|
+
expect(result.current[0]).toBe(-5);
|
|
424
|
+
});
|
|
425
|
+
});
|
|
426
|
+
`,
|
|
427
|
+
useDebounce: `import { useEffect, useState } from "react";
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Debounces a value by delaying updates until after the specified delay.
|
|
431
|
+
*
|
|
432
|
+
* @param value - The value to debounce
|
|
433
|
+
* @param delay - The delay in milliseconds (default: 500ms)
|
|
434
|
+
* @returns The debounced value
|
|
435
|
+
*
|
|
436
|
+
* @example
|
|
437
|
+
* const [search, setSearch] = useState("");
|
|
438
|
+
* const debouncedSearch = useDebounce(search, 300);
|
|
439
|
+
*
|
|
440
|
+
* useEffect(() => {
|
|
441
|
+
* // This effect runs 300ms after the user stops typing
|
|
442
|
+
* fetchResults(debouncedSearch);
|
|
443
|
+
* }, [debouncedSearch]);
|
|
444
|
+
*/
|
|
445
|
+
export function useDebounce<T>(value: T, delay = 500): T {
|
|
446
|
+
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
|
447
|
+
|
|
448
|
+
useEffect(() => {
|
|
449
|
+
const timer = setTimeout(() => {
|
|
450
|
+
setDebouncedValue(value);
|
|
451
|
+
}, delay);
|
|
452
|
+
|
|
453
|
+
return () => {
|
|
454
|
+
clearTimeout(timer);
|
|
455
|
+
};
|
|
456
|
+
}, [value, delay]);
|
|
457
|
+
|
|
458
|
+
return debouncedValue;
|
|
459
|
+
}
|
|
460
|
+
`, useDebounce_test: `import { act, renderHook } from "@testing-library/react";
|
|
461
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
462
|
+
|
|
463
|
+
import { useDebounce } from "./useDebounce.js";
|
|
464
|
+
|
|
465
|
+
describe("useDebounce", () => {
|
|
466
|
+
beforeEach(() => {
|
|
467
|
+
vi.useFakeTimers();
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
it("should return initial value immediately", () => {
|
|
471
|
+
const { result } = renderHook(() => useDebounce("initial", 500));
|
|
472
|
+
expect(result.current).toBe("initial");
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
it("should debounce value updates", () => {
|
|
476
|
+
const { rerender, result } = renderHook(
|
|
477
|
+
({ delay, value }) => useDebounce(value, delay),
|
|
478
|
+
{ initialProps: { delay: 500, value: "initial" } },
|
|
479
|
+
);
|
|
480
|
+
|
|
481
|
+
expect(result.current).toBe("initial");
|
|
482
|
+
|
|
483
|
+
rerender({ delay: 500, value: "updated" });
|
|
484
|
+
expect(result.current).toBe("initial");
|
|
485
|
+
|
|
486
|
+
act(() => {
|
|
487
|
+
vi.advanceTimersByTime(499);
|
|
488
|
+
});
|
|
489
|
+
expect(result.current).toBe("initial");
|
|
490
|
+
|
|
491
|
+
act(() => {
|
|
492
|
+
vi.advanceTimersByTime(1);
|
|
493
|
+
});
|
|
494
|
+
expect(result.current).toBe("updated");
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
it("should reset timer on rapid value changes", () => {
|
|
498
|
+
const { rerender, result } = renderHook(
|
|
499
|
+
({ value }) => useDebounce(value, 500),
|
|
500
|
+
{ initialProps: { value: "a" } },
|
|
501
|
+
);
|
|
502
|
+
|
|
503
|
+
rerender({ value: "b" });
|
|
504
|
+
act(() => {
|
|
505
|
+
vi.advanceTimersByTime(300);
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
rerender({ value: "c" });
|
|
509
|
+
act(() => {
|
|
510
|
+
vi.advanceTimersByTime(300);
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
expect(result.current).toBe("a");
|
|
514
|
+
|
|
515
|
+
act(() => {
|
|
516
|
+
vi.advanceTimersByTime(200);
|
|
517
|
+
});
|
|
518
|
+
expect(result.current).toBe("c");
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
it("should use default delay of 500ms", () => {
|
|
522
|
+
const { rerender, result } = renderHook(({ value }) => useDebounce(value), {
|
|
523
|
+
initialProps: { value: "initial" },
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
rerender({ value: "updated" });
|
|
527
|
+
|
|
528
|
+
act(() => {
|
|
529
|
+
vi.advanceTimersByTime(499);
|
|
530
|
+
});
|
|
531
|
+
expect(result.current).toBe("initial");
|
|
532
|
+
|
|
533
|
+
act(() => {
|
|
534
|
+
vi.advanceTimersByTime(1);
|
|
535
|
+
});
|
|
536
|
+
expect(result.current).toBe("updated");
|
|
537
|
+
});
|
|
538
|
+
});
|
|
539
|
+
`,
|
|
540
|
+
useDebouncedCallback: `import { useCallback, useEffect, useRef } from "react";
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Creates a debounced version of a callback function.
|
|
544
|
+
* The callback will only execute after the specified delay has passed
|
|
545
|
+
* since the last invocation.
|
|
546
|
+
*
|
|
547
|
+
* @param callback - The function to debounce
|
|
548
|
+
* @param delay - The delay in milliseconds (default: 500ms)
|
|
549
|
+
* @returns A tuple containing [debouncedCallback, cancel]
|
|
550
|
+
*
|
|
551
|
+
* @example
|
|
552
|
+
* const [debouncedSearch, cancel] = useDebouncedCallback((query: string) => {
|
|
553
|
+
* fetch(\`/api/search?q=\${query}\`);
|
|
554
|
+
* }, 300);
|
|
555
|
+
*
|
|
556
|
+
* // Call the debounced function
|
|
557
|
+
* <input onChange={(e) => debouncedSearch(e.target.value)} />
|
|
558
|
+
*
|
|
559
|
+
* // Cancel pending calls if needed
|
|
560
|
+
* <button onClick={cancel}>Cancel</button>
|
|
561
|
+
*/
|
|
562
|
+
export function useDebouncedCallback<T extends unknown[]>(
|
|
563
|
+
callback: (...args: T) => void,
|
|
564
|
+
delay = 500,
|
|
565
|
+
): [(...args: T) => void, () => void] {
|
|
566
|
+
const callbackRef = useRef(callback);
|
|
567
|
+
const timeoutRef = useRef<null | ReturnType<typeof setTimeout>>(null);
|
|
568
|
+
|
|
569
|
+
// Keep callback ref up to date
|
|
570
|
+
useEffect(() => {
|
|
571
|
+
callbackRef.current = callback;
|
|
572
|
+
}, [callback]);
|
|
573
|
+
|
|
574
|
+
// Cleanup on unmount
|
|
575
|
+
useEffect(() => {
|
|
576
|
+
return () => {
|
|
577
|
+
if (timeoutRef.current) {
|
|
578
|
+
clearTimeout(timeoutRef.current);
|
|
579
|
+
}
|
|
580
|
+
};
|
|
581
|
+
}, []);
|
|
582
|
+
|
|
583
|
+
const cancel = useCallback(() => {
|
|
584
|
+
if (timeoutRef.current) {
|
|
585
|
+
clearTimeout(timeoutRef.current);
|
|
586
|
+
timeoutRef.current = null;
|
|
587
|
+
}
|
|
588
|
+
}, []);
|
|
589
|
+
|
|
590
|
+
const debouncedCallback = useCallback(
|
|
591
|
+
(...args: T) => {
|
|
592
|
+
cancel();
|
|
593
|
+
timeoutRef.current = setTimeout(() => {
|
|
594
|
+
callbackRef.current(...args);
|
|
595
|
+
}, delay);
|
|
596
|
+
},
|
|
597
|
+
[delay, cancel],
|
|
598
|
+
);
|
|
599
|
+
|
|
600
|
+
return [debouncedCallback, cancel];
|
|
601
|
+
}
|
|
602
|
+
`, useDebouncedCallback_test: `import { act, renderHook } from "@testing-library/react";
|
|
603
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
604
|
+
|
|
605
|
+
import { useDebouncedCallback } from "./useDebouncedCallback.js";
|
|
606
|
+
|
|
607
|
+
describe("useDebouncedCallback", () => {
|
|
608
|
+
beforeEach(() => {
|
|
609
|
+
vi.useFakeTimers();
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
it("should debounce callback execution", () => {
|
|
613
|
+
const callback = vi.fn();
|
|
614
|
+
const { result } = renderHook(() => useDebouncedCallback(callback, 500));
|
|
615
|
+
|
|
616
|
+
const [debouncedCallback] = result.current;
|
|
617
|
+
|
|
618
|
+
act(() => {
|
|
619
|
+
debouncedCallback("a");
|
|
620
|
+
debouncedCallback("b");
|
|
621
|
+
debouncedCallback("c");
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
expect(callback).not.toHaveBeenCalled();
|
|
625
|
+
|
|
626
|
+
act(() => {
|
|
627
|
+
vi.advanceTimersByTime(500);
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
631
|
+
expect(callback).toHaveBeenCalledWith("c");
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
it("should use default delay of 500ms", () => {
|
|
635
|
+
const callback = vi.fn();
|
|
636
|
+
const { result } = renderHook(() => useDebouncedCallback(callback));
|
|
637
|
+
|
|
638
|
+
const [debouncedCallback] = result.current;
|
|
639
|
+
|
|
640
|
+
act(() => {
|
|
641
|
+
debouncedCallback();
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
act(() => {
|
|
645
|
+
vi.advanceTimersByTime(499);
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
expect(callback).not.toHaveBeenCalled();
|
|
649
|
+
|
|
650
|
+
act(() => {
|
|
651
|
+
vi.advanceTimersByTime(1);
|
|
652
|
+
});
|
|
653
|
+
|
|
654
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
655
|
+
});
|
|
656
|
+
|
|
657
|
+
it("should reset timer on each call", () => {
|
|
658
|
+
const callback = vi.fn();
|
|
659
|
+
const { result } = renderHook(() => useDebouncedCallback(callback, 500));
|
|
660
|
+
|
|
661
|
+
const [debouncedCallback] = result.current;
|
|
662
|
+
|
|
663
|
+
act(() => {
|
|
664
|
+
debouncedCallback("first");
|
|
665
|
+
});
|
|
666
|
+
|
|
667
|
+
act(() => {
|
|
668
|
+
vi.advanceTimersByTime(300);
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
act(() => {
|
|
672
|
+
debouncedCallback("second");
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
act(() => {
|
|
676
|
+
vi.advanceTimersByTime(300);
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
expect(callback).not.toHaveBeenCalled();
|
|
680
|
+
|
|
681
|
+
act(() => {
|
|
682
|
+
vi.advanceTimersByTime(200);
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
686
|
+
expect(callback).toHaveBeenCalledWith("second");
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
it("should cancel pending callback", () => {
|
|
690
|
+
const callback = vi.fn();
|
|
691
|
+
const { result } = renderHook(() => useDebouncedCallback(callback, 500));
|
|
692
|
+
|
|
693
|
+
const [debouncedCallback, cancel] = result.current;
|
|
694
|
+
|
|
695
|
+
act(() => {
|
|
696
|
+
debouncedCallback("test");
|
|
697
|
+
});
|
|
698
|
+
|
|
699
|
+
act(() => {
|
|
700
|
+
vi.advanceTimersByTime(250);
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
act(() => {
|
|
704
|
+
cancel();
|
|
705
|
+
});
|
|
706
|
+
|
|
707
|
+
act(() => {
|
|
708
|
+
vi.advanceTimersByTime(500);
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
expect(callback).not.toHaveBeenCalled();
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
it("should pass all arguments to callback", () => {
|
|
715
|
+
const callback = vi.fn();
|
|
716
|
+
const { result } = renderHook(() => useDebouncedCallback(callback, 100));
|
|
717
|
+
|
|
718
|
+
const [debouncedCallback] = result.current;
|
|
719
|
+
|
|
720
|
+
act(() => {
|
|
721
|
+
debouncedCallback("arg1", "arg2", 123);
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
act(() => {
|
|
725
|
+
vi.advanceTimersByTime(100);
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
expect(callback).toHaveBeenCalledWith("arg1", "arg2", 123);
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
it("should use latest callback reference", () => {
|
|
732
|
+
const callback1 = vi.fn();
|
|
733
|
+
const callback2 = vi.fn();
|
|
734
|
+
|
|
735
|
+
const { rerender, result } = renderHook(
|
|
736
|
+
({ cb }) => useDebouncedCallback(cb, 500),
|
|
737
|
+
{ initialProps: { cb: callback1 } },
|
|
738
|
+
);
|
|
739
|
+
|
|
740
|
+
const [debouncedCallback] = result.current;
|
|
741
|
+
|
|
742
|
+
act(() => {
|
|
743
|
+
debouncedCallback();
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
rerender({ cb: callback2 });
|
|
747
|
+
|
|
748
|
+
act(() => {
|
|
749
|
+
vi.advanceTimersByTime(500);
|
|
750
|
+
});
|
|
751
|
+
|
|
752
|
+
expect(callback1).not.toHaveBeenCalled();
|
|
753
|
+
expect(callback2).toHaveBeenCalledTimes(1);
|
|
754
|
+
});
|
|
755
|
+
|
|
756
|
+
it("should cleanup on unmount", () => {
|
|
757
|
+
const callback = vi.fn();
|
|
758
|
+
const { result, unmount } = renderHook(() =>
|
|
759
|
+
useDebouncedCallback(callback, 500),
|
|
760
|
+
);
|
|
761
|
+
|
|
762
|
+
const [debouncedCallback] = result.current;
|
|
763
|
+
|
|
764
|
+
act(() => {
|
|
765
|
+
debouncedCallback();
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
unmount();
|
|
769
|
+
|
|
770
|
+
act(() => {
|
|
771
|
+
vi.advanceTimersByTime(500);
|
|
772
|
+
});
|
|
773
|
+
|
|
774
|
+
expect(callback).not.toHaveBeenCalled();
|
|
775
|
+
});
|
|
776
|
+
|
|
777
|
+
it("should handle delay changes", () => {
|
|
778
|
+
const callback = vi.fn();
|
|
779
|
+
|
|
780
|
+
const { rerender, result } = renderHook(
|
|
781
|
+
({ delay }) => useDebouncedCallback(callback, delay),
|
|
782
|
+
{ initialProps: { delay: 500 } },
|
|
783
|
+
);
|
|
784
|
+
|
|
785
|
+
act(() => {
|
|
786
|
+
result.current[0]("test");
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
rerender({ delay: 100 });
|
|
790
|
+
|
|
791
|
+
// Get new debounced callback with updated delay
|
|
792
|
+
act(() => {
|
|
793
|
+
result.current[0]("updated");
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
act(() => {
|
|
797
|
+
vi.advanceTimersByTime(100);
|
|
798
|
+
});
|
|
799
|
+
|
|
800
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
801
|
+
expect(callback).toHaveBeenCalledWith("updated");
|
|
802
|
+
});
|
|
803
|
+
});
|
|
804
|
+
`,
|
|
805
|
+
useDocumentTitle: `import { useEffect, useRef } from "react";
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Dynamically update the document title.
|
|
809
|
+
*
|
|
810
|
+
* @param title - The title to set for the document
|
|
811
|
+
* @param restoreOnUnmount - Whether to restore the previous title on unmount (default: true)
|
|
812
|
+
*
|
|
813
|
+
* @example
|
|
814
|
+
* // Basic usage
|
|
815
|
+
* useDocumentTitle('Home | My App');
|
|
816
|
+
*
|
|
817
|
+
* @example
|
|
818
|
+
* // Dynamic title based on state
|
|
819
|
+
* useDocumentTitle(\`\${unreadCount} new messages\`);
|
|
820
|
+
*
|
|
821
|
+
* @example
|
|
822
|
+
* // Don't restore title on unmount
|
|
823
|
+
* useDocumentTitle('Dashboard', false);
|
|
824
|
+
*/
|
|
825
|
+
export function useDocumentTitle(title: string, restoreOnUnmount = true): void {
|
|
826
|
+
const previousTitle = useRef<string | undefined>(undefined);
|
|
827
|
+
|
|
828
|
+
useEffect(() => {
|
|
829
|
+
if (typeof document === "undefined") {
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// Store the previous title only on first mount
|
|
834
|
+
previousTitle.current ??= document.title;
|
|
835
|
+
|
|
836
|
+
document.title = title;
|
|
837
|
+
}, [title]);
|
|
838
|
+
|
|
839
|
+
useEffect(() => {
|
|
840
|
+
return () => {
|
|
841
|
+
if (restoreOnUnmount && previousTitle.current !== undefined) {
|
|
842
|
+
document.title = previousTitle.current;
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
}, [restoreOnUnmount]);
|
|
846
|
+
}
|
|
847
|
+
`, useDocumentTitle_test: `import { cleanup, renderHook } from "@testing-library/react";
|
|
848
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
849
|
+
|
|
850
|
+
import { useDocumentTitle } from "./useDocumentTitle.js";
|
|
851
|
+
|
|
852
|
+
describe("useDocumentTitle", () => {
|
|
853
|
+
const originalTitle = "Original Title";
|
|
854
|
+
|
|
855
|
+
beforeEach(() => {
|
|
856
|
+
document.title = originalTitle;
|
|
857
|
+
});
|
|
858
|
+
|
|
859
|
+
afterEach(() => {
|
|
860
|
+
cleanup();
|
|
861
|
+
document.title = originalTitle;
|
|
862
|
+
});
|
|
863
|
+
|
|
864
|
+
it("should set the document title", () => {
|
|
865
|
+
renderHook(() => {
|
|
866
|
+
useDocumentTitle("New Title");
|
|
867
|
+
});
|
|
868
|
+
|
|
869
|
+
expect(document.title).toBe("New Title");
|
|
870
|
+
});
|
|
871
|
+
|
|
872
|
+
it("should update the document title when title changes", () => {
|
|
873
|
+
const { rerender } = renderHook(
|
|
874
|
+
({ title }) => {
|
|
875
|
+
useDocumentTitle(title);
|
|
876
|
+
},
|
|
877
|
+
{
|
|
878
|
+
initialProps: { title: "First Title" },
|
|
879
|
+
},
|
|
880
|
+
);
|
|
881
|
+
|
|
882
|
+
expect(document.title).toBe("First Title");
|
|
883
|
+
|
|
884
|
+
rerender({ title: "Second Title" });
|
|
885
|
+
expect(document.title).toBe("Second Title");
|
|
886
|
+
});
|
|
887
|
+
|
|
888
|
+
it("should restore original title on unmount by default", () => {
|
|
889
|
+
const { unmount } = renderHook(() => {
|
|
890
|
+
useDocumentTitle("Temporary Title");
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
expect(document.title).toBe("Temporary Title");
|
|
894
|
+
|
|
895
|
+
unmount();
|
|
896
|
+
expect(document.title).toBe(originalTitle);
|
|
897
|
+
});
|
|
898
|
+
|
|
899
|
+
it("should not restore title on unmount when restoreOnUnmount is false", () => {
|
|
900
|
+
const { unmount } = renderHook(() => {
|
|
901
|
+
useDocumentTitle("Permanent Title", false);
|
|
902
|
+
});
|
|
903
|
+
|
|
904
|
+
expect(document.title).toBe("Permanent Title");
|
|
905
|
+
|
|
906
|
+
unmount();
|
|
907
|
+
expect(document.title).toBe("Permanent Title");
|
|
908
|
+
});
|
|
909
|
+
|
|
910
|
+
it("should restore the initial title, not intermediate titles", () => {
|
|
911
|
+
const { rerender, unmount } = renderHook(
|
|
912
|
+
({ title }) => {
|
|
913
|
+
useDocumentTitle(title);
|
|
914
|
+
},
|
|
915
|
+
{ initialProps: { title: "First" } },
|
|
916
|
+
);
|
|
917
|
+
|
|
918
|
+
expect(document.title).toBe("First");
|
|
919
|
+
|
|
920
|
+
rerender({ title: "Second" });
|
|
921
|
+
expect(document.title).toBe("Second");
|
|
922
|
+
|
|
923
|
+
rerender({ title: "Third" });
|
|
924
|
+
expect(document.title).toBe("Third");
|
|
925
|
+
|
|
926
|
+
unmount();
|
|
927
|
+
expect(document.title).toBe(originalTitle);
|
|
928
|
+
});
|
|
929
|
+
});
|
|
930
|
+
`,
|
|
931
|
+
useFetch: `import { useCallback, useEffect, useRef, useState } from "react";
|
|
932
|
+
|
|
933
|
+
export interface UseFetchOptions<T> {
|
|
934
|
+
/** Whether to fetch immediately on mount (default: true) */
|
|
935
|
+
immediate?: boolean;
|
|
936
|
+
/** Initial data before fetch completes */
|
|
937
|
+
initialData?: T;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
export interface UseFetchResult<T> {
|
|
941
|
+
/** The fetched data, or undefined if not yet loaded */
|
|
942
|
+
data: T | undefined;
|
|
943
|
+
/** Error object if the fetch failed */
|
|
944
|
+
error: Error | null;
|
|
945
|
+
/** Whether a fetch is currently in progress */
|
|
946
|
+
isLoading: boolean;
|
|
947
|
+
/** Function to manually trigger a refetch */
|
|
948
|
+
refetch: () => Promise<void>;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* Fetch data from a URL with loading and error states.
|
|
953
|
+
*
|
|
954
|
+
* @param url - The URL to fetch data from
|
|
955
|
+
* @param options - Configuration options
|
|
956
|
+
* @returns Object containing data, loading state, error, and refetch function
|
|
957
|
+
*
|
|
958
|
+
* @example
|
|
959
|
+
* const { data, isLoading, error, refetch } = useFetch<User[]>('/api/users');
|
|
960
|
+
*
|
|
961
|
+
* if (isLoading) return <Spinner />;
|
|
962
|
+
* if (error) return <Error message={error.message} />;
|
|
963
|
+
* return <UserList users={data} />;
|
|
964
|
+
*
|
|
965
|
+
* @example
|
|
966
|
+
* // With initial data and manual fetch
|
|
967
|
+
* const { data, refetch } = useFetch<User>('/api/user', {
|
|
968
|
+
* initialData: { name: 'Loading...' },
|
|
969
|
+
* immediate: false,
|
|
970
|
+
* });
|
|
971
|
+
*/
|
|
972
|
+
export function useFetch<T>(
|
|
973
|
+
url: string,
|
|
974
|
+
options: UseFetchOptions<T> = {},
|
|
975
|
+
): UseFetchResult<T> {
|
|
976
|
+
const { immediate = true, initialData } = options;
|
|
977
|
+
|
|
978
|
+
const [data, setData] = useState<T | undefined>(initialData);
|
|
979
|
+
const [error, setError] = useState<Error | null>(null);
|
|
980
|
+
const [isLoading, setIsLoading] = useState(immediate);
|
|
981
|
+
|
|
982
|
+
const abortControllerRef = useRef<AbortController | null>(null);
|
|
983
|
+
|
|
984
|
+
const fetchData = useCallback(async () => {
|
|
985
|
+
// Cancel any in-flight request
|
|
986
|
+
abortControllerRef.current?.abort();
|
|
987
|
+
abortControllerRef.current = new AbortController();
|
|
988
|
+
|
|
989
|
+
setIsLoading(true);
|
|
990
|
+
setError(null);
|
|
991
|
+
|
|
992
|
+
try {
|
|
993
|
+
const response = await fetch(url, {
|
|
994
|
+
signal: abortControllerRef.current.signal,
|
|
995
|
+
});
|
|
996
|
+
|
|
997
|
+
if (!response.ok) {
|
|
998
|
+
throw new Error(\`HTTP error! status: \${String(response.status)}\`);
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const result = (await response.json()) as T;
|
|
1002
|
+
setData(result);
|
|
1003
|
+
} catch (err) {
|
|
1004
|
+
if (err instanceof Error && err.name !== "AbortError") {
|
|
1005
|
+
setError(err);
|
|
1006
|
+
}
|
|
1007
|
+
} finally {
|
|
1008
|
+
setIsLoading(false);
|
|
1009
|
+
}
|
|
1010
|
+
}, [url]);
|
|
1011
|
+
|
|
1012
|
+
useEffect(() => {
|
|
1013
|
+
if (immediate) {
|
|
1014
|
+
void fetchData();
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
return () => {
|
|
1018
|
+
abortControllerRef.current?.abort();
|
|
1019
|
+
};
|
|
1020
|
+
}, [fetchData, immediate]);
|
|
1021
|
+
|
|
1022
|
+
return { data, error, isLoading, refetch: fetchData };
|
|
1023
|
+
}
|
|
1024
|
+
`, useFetch_test: `import { act, renderHook, waitFor } from "@testing-library/react";
|
|
1025
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
1026
|
+
|
|
1027
|
+
import { useFetch } from "./useFetch.js";
|
|
1028
|
+
|
|
1029
|
+
describe("useFetch", () => {
|
|
1030
|
+
const mockData = { id: 1, name: "Test" };
|
|
1031
|
+
|
|
1032
|
+
beforeEach(() => {
|
|
1033
|
+
vi.spyOn(global, "fetch").mockImplementation(() =>
|
|
1034
|
+
Promise.resolve({
|
|
1035
|
+
json: () => Promise.resolve(mockData),
|
|
1036
|
+
ok: true,
|
|
1037
|
+
} as Response),
|
|
1038
|
+
);
|
|
1039
|
+
});
|
|
1040
|
+
|
|
1041
|
+
afterEach(() => {
|
|
1042
|
+
vi.restoreAllMocks();
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
it("should fetch data immediately by default", async () => {
|
|
1046
|
+
const { result } = renderHook(() => useFetch<typeof mockData>("/api/test"));
|
|
1047
|
+
|
|
1048
|
+
expect(result.current.isLoading).toBe(true);
|
|
1049
|
+
|
|
1050
|
+
await waitFor(() => {
|
|
1051
|
+
expect(result.current.isLoading).toBe(false);
|
|
1052
|
+
});
|
|
1053
|
+
|
|
1054
|
+
expect(result.current.data).toEqual(mockData);
|
|
1055
|
+
expect(result.current.error).toBeNull();
|
|
1056
|
+
});
|
|
1057
|
+
|
|
1058
|
+
it("should not fetch immediately when immediate is false", () => {
|
|
1059
|
+
const { result } = renderHook(() =>
|
|
1060
|
+
useFetch<typeof mockData>("/api/test", { immediate: false }),
|
|
1061
|
+
);
|
|
1062
|
+
|
|
1063
|
+
expect(result.current.isLoading).toBe(false);
|
|
1064
|
+
expect(result.current.data).toBeUndefined();
|
|
1065
|
+
expect(global.fetch).not.toHaveBeenCalled();
|
|
1066
|
+
});
|
|
1067
|
+
|
|
1068
|
+
it("should use initial data", () => {
|
|
1069
|
+
const initialData = { id: 0, name: "Initial" };
|
|
1070
|
+
const { result } = renderHook(() =>
|
|
1071
|
+
useFetch<typeof mockData>("/api/test", {
|
|
1072
|
+
immediate: false,
|
|
1073
|
+
initialData,
|
|
1074
|
+
}),
|
|
1075
|
+
);
|
|
1076
|
+
|
|
1077
|
+
expect(result.current.data).toEqual(initialData);
|
|
1078
|
+
});
|
|
1079
|
+
|
|
1080
|
+
it("should handle fetch errors", async () => {
|
|
1081
|
+
vi.spyOn(global, "fetch").mockImplementation(() =>
|
|
1082
|
+
Promise.resolve({
|
|
1083
|
+
ok: false,
|
|
1084
|
+
status: 404,
|
|
1085
|
+
} as Response),
|
|
1086
|
+
);
|
|
1087
|
+
|
|
1088
|
+
const { result } = renderHook(() => useFetch<typeof mockData>("/api/test"));
|
|
1089
|
+
|
|
1090
|
+
await waitFor(() => {
|
|
1091
|
+
expect(result.current.isLoading).toBe(false);
|
|
1092
|
+
});
|
|
1093
|
+
|
|
1094
|
+
expect(result.current.error).toBeInstanceOf(Error);
|
|
1095
|
+
expect(result.current.error?.message).toBe("HTTP error! status: 404");
|
|
1096
|
+
});
|
|
1097
|
+
|
|
1098
|
+
it("should handle network errors", async () => {
|
|
1099
|
+
vi.spyOn(global, "fetch").mockImplementation(() =>
|
|
1100
|
+
Promise.reject(new Error("Network error")),
|
|
1101
|
+
);
|
|
1102
|
+
|
|
1103
|
+
const { result } = renderHook(() => useFetch<typeof mockData>("/api/test"));
|
|
1104
|
+
|
|
1105
|
+
await waitFor(() => {
|
|
1106
|
+
expect(result.current.isLoading).toBe(false);
|
|
1107
|
+
});
|
|
1108
|
+
|
|
1109
|
+
expect(result.current.error?.message).toBe("Network error");
|
|
1110
|
+
});
|
|
1111
|
+
|
|
1112
|
+
it("should refetch data when refetch is called", async () => {
|
|
1113
|
+
const { result } = renderHook(() =>
|
|
1114
|
+
useFetch<typeof mockData>("/api/test", { immediate: false }),
|
|
1115
|
+
);
|
|
1116
|
+
|
|
1117
|
+
expect(global.fetch).not.toHaveBeenCalled();
|
|
1118
|
+
|
|
1119
|
+
await act(async () => {
|
|
1120
|
+
await result.current.refetch();
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
1124
|
+
expect(result.current.data).toEqual(mockData);
|
|
1125
|
+
});
|
|
1126
|
+
|
|
1127
|
+
it("should refetch when URL changes", async () => {
|
|
1128
|
+
const { rerender, result } = renderHook(
|
|
1129
|
+
({ url }) => useFetch<typeof mockData>(url),
|
|
1130
|
+
{ initialProps: { url: "/api/test1" } },
|
|
1131
|
+
);
|
|
1132
|
+
|
|
1133
|
+
await waitFor(() => {
|
|
1134
|
+
expect(result.current.isLoading).toBe(false);
|
|
1135
|
+
});
|
|
1136
|
+
|
|
1137
|
+
expect(global.fetch).toHaveBeenCalledTimes(1);
|
|
1138
|
+
|
|
1139
|
+
rerender({ url: "/api/test2" });
|
|
1140
|
+
|
|
1141
|
+
await waitFor(() => {
|
|
1142
|
+
expect(global.fetch).toHaveBeenCalledTimes(2);
|
|
1143
|
+
});
|
|
1144
|
+
});
|
|
1145
|
+
|
|
1146
|
+
it("should clear error on successful refetch", async () => {
|
|
1147
|
+
vi.spyOn(global, "fetch").mockImplementationOnce(() =>
|
|
1148
|
+
Promise.resolve({
|
|
1149
|
+
ok: false,
|
|
1150
|
+
status: 500,
|
|
1151
|
+
} as Response),
|
|
1152
|
+
);
|
|
1153
|
+
|
|
1154
|
+
const { result } = renderHook(() => useFetch<typeof mockData>("/api/test"));
|
|
1155
|
+
|
|
1156
|
+
await waitFor(() => {
|
|
1157
|
+
expect(result.current.error).not.toBeNull();
|
|
1158
|
+
});
|
|
1159
|
+
|
|
1160
|
+
vi.spyOn(global, "fetch").mockImplementation(() =>
|
|
1161
|
+
Promise.resolve({
|
|
1162
|
+
json: () => Promise.resolve(mockData),
|
|
1163
|
+
ok: true,
|
|
1164
|
+
} as Response),
|
|
1165
|
+
);
|
|
1166
|
+
|
|
1167
|
+
await act(async () => {
|
|
1168
|
+
await result.current.refetch();
|
|
1169
|
+
});
|
|
1170
|
+
|
|
1171
|
+
expect(result.current.error).toBeNull();
|
|
1172
|
+
expect(result.current.data).toEqual(mockData);
|
|
1173
|
+
});
|
|
1174
|
+
});
|
|
1175
|
+
`,
|
|
1176
|
+
useInterval: `import { useEffect } from "react";
|
|
1177
|
+
|
|
1178
|
+
/**
|
|
1179
|
+
* Calls a callback at specified intervals.
|
|
1180
|
+
*
|
|
1181
|
+
* @param callback - Function to call on each interval
|
|
1182
|
+
* @param delay - Interval delay in milliseconds (null to pause)
|
|
1183
|
+
*
|
|
1184
|
+
* @example
|
|
1185
|
+
* useInterval(() => {
|
|
1186
|
+
* setTime(new Date());
|
|
1187
|
+
* }, 1000);
|
|
1188
|
+
*
|
|
1189
|
+
* @example
|
|
1190
|
+
* // Pause interval by passing null
|
|
1191
|
+
* useInterval(callback, isPaused ? null : 1000);
|
|
1192
|
+
*/
|
|
1193
|
+
export function useInterval(callback: () => void, delay: null | number): void {
|
|
1194
|
+
useEffect(() => {
|
|
1195
|
+
if (delay === null) return;
|
|
1196
|
+
|
|
1197
|
+
const interval = setInterval(callback, delay);
|
|
1198
|
+
return () => {
|
|
1199
|
+
clearInterval(interval);
|
|
1200
|
+
};
|
|
1201
|
+
}, [callback, delay]);
|
|
1202
|
+
}
|
|
1203
|
+
`, useInterval_test: `import { renderHook } from "@testing-library/react";
|
|
1204
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
1205
|
+
|
|
1206
|
+
import { useInterval } from "./useInterval.js";
|
|
1207
|
+
|
|
1208
|
+
describe("useInterval", () => {
|
|
1209
|
+
beforeEach(() => {
|
|
1210
|
+
vi.useFakeTimers();
|
|
1211
|
+
});
|
|
1212
|
+
|
|
1213
|
+
afterEach(() => {
|
|
1214
|
+
vi.useRealTimers();
|
|
1215
|
+
});
|
|
1216
|
+
|
|
1217
|
+
it("should call callback at interval", () => {
|
|
1218
|
+
const callback = vi.fn();
|
|
1219
|
+
renderHook(() => {
|
|
1220
|
+
useInterval(callback, 1000);
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
vi.advanceTimersByTime(1000);
|
|
1224
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
1225
|
+
|
|
1226
|
+
vi.advanceTimersByTime(1000);
|
|
1227
|
+
expect(callback).toHaveBeenCalledTimes(2);
|
|
1228
|
+
});
|
|
1229
|
+
|
|
1230
|
+
it("should pause when delay is null", () => {
|
|
1231
|
+
const callback = vi.fn();
|
|
1232
|
+
const { rerender } = renderHook(
|
|
1233
|
+
({ delay }: { delay: null | number }) => {
|
|
1234
|
+
useInterval(callback, delay);
|
|
1235
|
+
},
|
|
1236
|
+
{ initialProps: { delay: 1000 as null | number } },
|
|
1237
|
+
);
|
|
1238
|
+
|
|
1239
|
+
vi.advanceTimersByTime(1000);
|
|
1240
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
1241
|
+
|
|
1242
|
+
rerender({ delay: null });
|
|
1243
|
+
|
|
1244
|
+
vi.advanceTimersByTime(1000);
|
|
1245
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
1246
|
+
});
|
|
1247
|
+
|
|
1248
|
+
it("should cleanup interval on unmount", () => {
|
|
1249
|
+
const callback = vi.fn();
|
|
1250
|
+
const { unmount } = renderHook(() => {
|
|
1251
|
+
useInterval(callback, 1000);
|
|
1252
|
+
});
|
|
1253
|
+
|
|
1254
|
+
vi.advanceTimersByTime(1000);
|
|
1255
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
1256
|
+
|
|
1257
|
+
unmount();
|
|
1258
|
+
|
|
1259
|
+
vi.advanceTimersByTime(1000);
|
|
1260
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
1261
|
+
});
|
|
1262
|
+
});
|
|
1263
|
+
`,
|
|
1264
|
+
useIsClient: `import { useSyncExternalStore } from "react";
|
|
1265
|
+
|
|
1266
|
+
/**
|
|
1267
|
+
* Determine if the code is running on the client-side.
|
|
1268
|
+
* Useful for SSR-safe code that needs to access browser APIs.
|
|
1269
|
+
*
|
|
1270
|
+
* @returns true if running on client, false during SSR
|
|
1271
|
+
*
|
|
1272
|
+
* @example
|
|
1273
|
+
* const isClient = useIsClient();
|
|
1274
|
+
*
|
|
1275
|
+
* if (!isClient) {
|
|
1276
|
+
* return <div>Loading...</div>;
|
|
1277
|
+
* }
|
|
1278
|
+
*
|
|
1279
|
+
* // Safe to use browser APIs
|
|
1280
|
+
* return <div>Window width: {window.innerWidth}</div>;
|
|
1281
|
+
*
|
|
1282
|
+
* @example
|
|
1283
|
+
* // Conditionally render client-only components
|
|
1284
|
+
* const isClient = useIsClient();
|
|
1285
|
+
*
|
|
1286
|
+
* return (
|
|
1287
|
+
* <div>
|
|
1288
|
+
* <Header />
|
|
1289
|
+
* {isClient && <ClientOnlyMap />}
|
|
1290
|
+
* <Footer />
|
|
1291
|
+
* </div>
|
|
1292
|
+
* );
|
|
1293
|
+
*/
|
|
1294
|
+
export function useIsClient(): boolean {
|
|
1295
|
+
return useSyncExternalStore(
|
|
1296
|
+
() => {
|
|
1297
|
+
// Subscribe function that returns cleanup noop
|
|
1298
|
+
return function noopCleanup() {
|
|
1299
|
+
// Intentionally empty - no subscriptions needed
|
|
1300
|
+
};
|
|
1301
|
+
},
|
|
1302
|
+
() => true, // Client snapshot - always true on client
|
|
1303
|
+
() => false, // Server snapshot - always false during SSR
|
|
1304
|
+
);
|
|
1305
|
+
}
|
|
1306
|
+
`, useIsClient_test: `import { renderHook } from "@testing-library/react";
|
|
1307
|
+
import { describe, expect, it } from "vitest";
|
|
1308
|
+
|
|
1309
|
+
import { useIsClient } from "./useIsClient.js";
|
|
1310
|
+
|
|
1311
|
+
describe("useIsClient", () => {
|
|
1312
|
+
it("should return true after mount", () => {
|
|
1313
|
+
const { result } = renderHook(() => useIsClient());
|
|
1314
|
+
|
|
1315
|
+
// After the initial render and useEffect, isClient should be true
|
|
1316
|
+
expect(result.current).toBe(true);
|
|
1317
|
+
});
|
|
1318
|
+
|
|
1319
|
+
it("should return consistent value across re-renders", () => {
|
|
1320
|
+
const { rerender, result } = renderHook(() => useIsClient());
|
|
1321
|
+
|
|
1322
|
+
expect(result.current).toBe(true);
|
|
1323
|
+
|
|
1324
|
+
rerender();
|
|
1325
|
+
expect(result.current).toBe(true);
|
|
1326
|
+
|
|
1327
|
+
rerender();
|
|
1328
|
+
expect(result.current).toBe(true);
|
|
1329
|
+
});
|
|
1330
|
+
});
|
|
1331
|
+
`,
|
|
1332
|
+
useKeyPress: `import { useEffect, useState } from "react";
|
|
1333
|
+
|
|
1334
|
+
/**
|
|
1335
|
+
* Detects if a specific keyboard key is currently pressed.
|
|
1336
|
+
*
|
|
1337
|
+
* @param targetKey - The key to detect (e.g., "Enter", "ArrowUp", " " for space)
|
|
1338
|
+
* @returns Whether the key is currently pressed
|
|
1339
|
+
*
|
|
1340
|
+
* @example
|
|
1341
|
+
* const isEnterPressed = useKeyPress("Enter");
|
|
1342
|
+
* const isArrowUpPressed = useKeyPress("ArrowUp");
|
|
1343
|
+
*
|
|
1344
|
+
* return (
|
|
1345
|
+
* <div>
|
|
1346
|
+
* <p>Enter pressed: {isEnterPressed ? "Yes" : "No"}</p>
|
|
1347
|
+
* <p>Arrow Up pressed: {isArrowUpPressed ? "Yes" : "No"}</p>
|
|
1348
|
+
* </div>
|
|
1349
|
+
* );
|
|
1350
|
+
*/
|
|
1351
|
+
export function useKeyPress(targetKey: string): boolean {
|
|
1352
|
+
const [isKeyPressed, setIsKeyPressed] = useState(false);
|
|
1353
|
+
|
|
1354
|
+
useEffect(() => {
|
|
1355
|
+
const handleKeyDown = (event: KeyboardEvent) => {
|
|
1356
|
+
if (event.key === targetKey) {
|
|
1357
|
+
setIsKeyPressed(true);
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
|
|
1361
|
+
const handleKeyUp = (event: KeyboardEvent) => {
|
|
1362
|
+
if (event.key === targetKey) {
|
|
1363
|
+
setIsKeyPressed(false);
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
|
|
1367
|
+
window.addEventListener("keydown", handleKeyDown);
|
|
1368
|
+
window.addEventListener("keyup", handleKeyUp);
|
|
1369
|
+
|
|
1370
|
+
return () => {
|
|
1371
|
+
window.removeEventListener("keydown", handleKeyDown);
|
|
1372
|
+
window.removeEventListener("keyup", handleKeyUp);
|
|
1373
|
+
};
|
|
1374
|
+
}, [targetKey]);
|
|
1375
|
+
|
|
1376
|
+
return isKeyPressed;
|
|
1377
|
+
}
|
|
1378
|
+
`, useKeyPress_test: `import { act, renderHook, waitFor } from "@testing-library/react";
|
|
1379
|
+
import { describe, expect, it, vi } from "vitest";
|
|
1380
|
+
|
|
1381
|
+
import { useKeyPress } from "./useKeyPress.js";
|
|
1382
|
+
|
|
1383
|
+
describe("useKeyPress", () => {
|
|
1384
|
+
it("should initialize with false", () => {
|
|
1385
|
+
const { result } = renderHook(() => useKeyPress("Enter"));
|
|
1386
|
+
expect(result.current).toBe(false);
|
|
1387
|
+
});
|
|
1388
|
+
|
|
1389
|
+
it("should set to true on keydown", async () => {
|
|
1390
|
+
const { result } = renderHook(() => useKeyPress("Enter"));
|
|
1391
|
+
|
|
1392
|
+
act(() => {
|
|
1393
|
+
const event = new KeyboardEvent("keydown", { key: "Enter" });
|
|
1394
|
+
window.dispatchEvent(event);
|
|
1395
|
+
});
|
|
1396
|
+
|
|
1397
|
+
await waitFor(() => {
|
|
1398
|
+
expect(result.current).toBe(true);
|
|
1399
|
+
});
|
|
1400
|
+
});
|
|
1401
|
+
|
|
1402
|
+
it("should set to false on keyup", async () => {
|
|
1403
|
+
const { result } = renderHook(() => useKeyPress("Enter"));
|
|
1404
|
+
|
|
1405
|
+
act(() => {
|
|
1406
|
+
const downEvent = new KeyboardEvent("keydown", { key: "Enter" });
|
|
1407
|
+
window.dispatchEvent(downEvent);
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
await waitFor(() => {
|
|
1411
|
+
expect(result.current).toBe(true);
|
|
1412
|
+
});
|
|
1413
|
+
|
|
1414
|
+
act(() => {
|
|
1415
|
+
const upEvent = new KeyboardEvent("keyup", { key: "Enter" });
|
|
1416
|
+
window.dispatchEvent(upEvent);
|
|
1417
|
+
});
|
|
1418
|
+
|
|
1419
|
+
await waitFor(() => {
|
|
1420
|
+
expect(result.current).toBe(false);
|
|
1421
|
+
});
|
|
1422
|
+
});
|
|
1423
|
+
|
|
1424
|
+
it("should ignore other keys", () => {
|
|
1425
|
+
const { result } = renderHook(() => useKeyPress("Enter"));
|
|
1426
|
+
|
|
1427
|
+
act(() => {
|
|
1428
|
+
const event = new KeyboardEvent("keydown", { key: "a" });
|
|
1429
|
+
window.dispatchEvent(event);
|
|
1430
|
+
});
|
|
1431
|
+
|
|
1432
|
+
// Should still be false
|
|
1433
|
+
expect(result.current).toBe(false);
|
|
1434
|
+
});
|
|
1435
|
+
|
|
1436
|
+
it("should work with different keys", async () => {
|
|
1437
|
+
const { result: resultA } = renderHook(() => useKeyPress("ArrowUp"));
|
|
1438
|
+
const { result: resultEnter } = renderHook(() => useKeyPress("Enter"));
|
|
1439
|
+
|
|
1440
|
+
act(() => {
|
|
1441
|
+
const event = new KeyboardEvent("keydown", { key: "ArrowUp" });
|
|
1442
|
+
window.dispatchEvent(event);
|
|
1443
|
+
});
|
|
1444
|
+
|
|
1445
|
+
await waitFor(() => {
|
|
1446
|
+
expect(resultA.current).toBe(true);
|
|
1447
|
+
expect(resultEnter.current).toBe(false);
|
|
1448
|
+
});
|
|
1449
|
+
});
|
|
1450
|
+
|
|
1451
|
+
it("should handle space key", async () => {
|
|
1452
|
+
const { result } = renderHook(() => useKeyPress(" "));
|
|
1453
|
+
|
|
1454
|
+
act(() => {
|
|
1455
|
+
const event = new KeyboardEvent("keydown", { key: " " });
|
|
1456
|
+
window.dispatchEvent(event);
|
|
1457
|
+
});
|
|
1458
|
+
|
|
1459
|
+
await waitFor(() => {
|
|
1460
|
+
expect(result.current).toBe(true);
|
|
1461
|
+
});
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
it("should clean up event listeners on unmount", () => {
|
|
1465
|
+
const removeEventListenerSpy = vi.spyOn(window, "removeEventListener");
|
|
1466
|
+
const { unmount } = renderHook(() => useKeyPress("Enter"));
|
|
1467
|
+
|
|
1468
|
+
unmount();
|
|
1469
|
+
|
|
1470
|
+
expect(removeEventListenerSpy).toHaveBeenCalledWith(
|
|
1471
|
+
"keydown",
|
|
1472
|
+
expect.any(Function),
|
|
1473
|
+
);
|
|
1474
|
+
expect(removeEventListenerSpy).toHaveBeenCalledWith(
|
|
1475
|
+
"keyup",
|
|
1476
|
+
expect.any(Function),
|
|
1477
|
+
);
|
|
1478
|
+
|
|
1479
|
+
removeEventListenerSpy.mockRestore();
|
|
1480
|
+
});
|
|
1481
|
+
});
|
|
1482
|
+
`,
|
|
1483
|
+
useLocalStorage: `import { useCallback, useEffect, useState } from "react";
|
|
1484
|
+
|
|
1485
|
+
/**
|
|
1486
|
+
* Syncs state with localStorage, persisting across browser sessions.
|
|
1487
|
+
*
|
|
1488
|
+
* @param key - The localStorage key
|
|
1489
|
+
* @param initialValue - The initial value (used if no stored value exists)
|
|
1490
|
+
* @returns A tuple of [value, setValue, removeValue]
|
|
1491
|
+
*
|
|
1492
|
+
* @example
|
|
1493
|
+
* const [theme, setTheme, removeTheme] = useLocalStorage("theme", "light");
|
|
1494
|
+
*
|
|
1495
|
+
* // Update the theme (automatically persisted)
|
|
1496
|
+
* setTheme("dark");
|
|
1497
|
+
*
|
|
1498
|
+
* // Remove from localStorage
|
|
1499
|
+
* removeTheme();
|
|
1500
|
+
*/
|
|
1501
|
+
export function useLocalStorage<T>(
|
|
1502
|
+
key: string,
|
|
1503
|
+
initialValue: T,
|
|
1504
|
+
): [T, (value: ((prev: T) => T) | T) => void, () => void] {
|
|
1505
|
+
// Get initial value from localStorage or use provided initial value
|
|
1506
|
+
const [storedValue, setStoredValue] = useState<T>(() => {
|
|
1507
|
+
if (typeof window === "undefined") {
|
|
1508
|
+
return initialValue;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
try {
|
|
1512
|
+
const item = window.localStorage.getItem(key);
|
|
1513
|
+
return item ? (JSON.parse(item) as T) : initialValue;
|
|
1514
|
+
} catch (error) {
|
|
1515
|
+
console.warn(\`Error reading localStorage key "\${key}":\`, error);
|
|
1516
|
+
return initialValue;
|
|
1517
|
+
}
|
|
1518
|
+
});
|
|
1519
|
+
|
|
1520
|
+
// Update localStorage when value changes
|
|
1521
|
+
const setValue = useCallback(
|
|
1522
|
+
(value: ((prev: T) => T) | T) => {
|
|
1523
|
+
try {
|
|
1524
|
+
setStoredValue((prev) => {
|
|
1525
|
+
const valueToStore = value instanceof Function ? value(prev) : value;
|
|
1526
|
+
if (typeof window !== "undefined") {
|
|
1527
|
+
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
|
1528
|
+
}
|
|
1529
|
+
return valueToStore;
|
|
1530
|
+
});
|
|
1531
|
+
} catch (error) {
|
|
1532
|
+
console.warn(\`Error setting localStorage key "\${key}":\`, error);
|
|
1533
|
+
}
|
|
1534
|
+
},
|
|
1535
|
+
[key],
|
|
1536
|
+
);
|
|
1537
|
+
|
|
1538
|
+
// Remove from localStorage
|
|
1539
|
+
const removeValue = useCallback(() => {
|
|
1540
|
+
try {
|
|
1541
|
+
if (typeof window !== "undefined") {
|
|
1542
|
+
window.localStorage.removeItem(key);
|
|
1543
|
+
}
|
|
1544
|
+
setStoredValue(initialValue);
|
|
1545
|
+
} catch (error) {
|
|
1546
|
+
console.warn(\`Error removing localStorage key "\${key}":\`, error);
|
|
1547
|
+
}
|
|
1548
|
+
}, [key, initialValue]);
|
|
1549
|
+
|
|
1550
|
+
// Listen for changes in other tabs/windows
|
|
1551
|
+
useEffect(() => {
|
|
1552
|
+
const handleStorageChange = (event: StorageEvent) => {
|
|
1553
|
+
if (event.key === key && event.newValue !== null) {
|
|
1554
|
+
try {
|
|
1555
|
+
setStoredValue(JSON.parse(event.newValue) as T);
|
|
1556
|
+
} catch (error) {
|
|
1557
|
+
console.warn(\`Error parsing localStorage key "\${key}":\`, error);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
window.addEventListener("storage", handleStorageChange);
|
|
1563
|
+
return () => {
|
|
1564
|
+
window.removeEventListener("storage", handleStorageChange);
|
|
1565
|
+
};
|
|
1566
|
+
}, [key]);
|
|
1567
|
+
|
|
1568
|
+
return [storedValue, setValue, removeValue];
|
|
1569
|
+
}
|
|
1570
|
+
`, useLocalStorage_test: `import { act, renderHook } from "@testing-library/react";
|
|
1571
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
1572
|
+
|
|
1573
|
+
import { useLocalStorage } from "./useLocalStorage.js";
|
|
1574
|
+
|
|
1575
|
+
describe("useLocalStorage", () => {
|
|
1576
|
+
beforeEach(() => {
|
|
1577
|
+
localStorage.clear();
|
|
1578
|
+
vi.clearAllMocks();
|
|
1579
|
+
});
|
|
1580
|
+
|
|
1581
|
+
afterEach(() => {
|
|
1582
|
+
localStorage.clear();
|
|
1583
|
+
});
|
|
1584
|
+
|
|
1585
|
+
it("should return initial value when localStorage is empty", () => {
|
|
1586
|
+
const { result } = renderHook(() =>
|
|
1587
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1588
|
+
);
|
|
1589
|
+
|
|
1590
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1591
|
+
});
|
|
1592
|
+
|
|
1593
|
+
it("should return stored value from localStorage", () => {
|
|
1594
|
+
localStorage.setItem("testKey", JSON.stringify("storedValue"));
|
|
1595
|
+
|
|
1596
|
+
const { result } = renderHook(() =>
|
|
1597
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1598
|
+
);
|
|
1599
|
+
|
|
1600
|
+
expect(result.current[0]).toBe("storedValue");
|
|
1601
|
+
});
|
|
1602
|
+
|
|
1603
|
+
it("should update value and localStorage", () => {
|
|
1604
|
+
const { result } = renderHook(() =>
|
|
1605
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1606
|
+
);
|
|
1607
|
+
|
|
1608
|
+
act(() => {
|
|
1609
|
+
result.current[1]("newValue");
|
|
1610
|
+
});
|
|
1611
|
+
|
|
1612
|
+
expect(result.current[0]).toBe("newValue");
|
|
1613
|
+
expect(localStorage.getItem("testKey")).toBe(JSON.stringify("newValue"));
|
|
1614
|
+
});
|
|
1615
|
+
|
|
1616
|
+
it("should support function updates", () => {
|
|
1617
|
+
const { result } = renderHook(() => useLocalStorage("counter", 0));
|
|
1618
|
+
|
|
1619
|
+
act(() => {
|
|
1620
|
+
result.current[1]((prev) => prev + 1);
|
|
1621
|
+
});
|
|
1622
|
+
|
|
1623
|
+
expect(result.current[0]).toBe(1);
|
|
1624
|
+
|
|
1625
|
+
act(() => {
|
|
1626
|
+
result.current[1]((prev) => prev + 5);
|
|
1627
|
+
});
|
|
1628
|
+
|
|
1629
|
+
expect(result.current[0]).toBe(6);
|
|
1630
|
+
});
|
|
1631
|
+
|
|
1632
|
+
it("should remove value from localStorage", () => {
|
|
1633
|
+
localStorage.setItem("testKey", JSON.stringify("storedValue"));
|
|
1634
|
+
|
|
1635
|
+
const { result } = renderHook(() =>
|
|
1636
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1637
|
+
);
|
|
1638
|
+
|
|
1639
|
+
act(() => {
|
|
1640
|
+
result.current[2]();
|
|
1641
|
+
});
|
|
1642
|
+
|
|
1643
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1644
|
+
expect(localStorage.getItem("testKey")).toBeNull();
|
|
1645
|
+
});
|
|
1646
|
+
|
|
1647
|
+
it("should handle complex objects", () => {
|
|
1648
|
+
const initialValue = { age: 30, name: "John" };
|
|
1649
|
+
|
|
1650
|
+
const { result } = renderHook(() => useLocalStorage("user", initialValue));
|
|
1651
|
+
|
|
1652
|
+
expect(result.current[0]).toEqual(initialValue);
|
|
1653
|
+
|
|
1654
|
+
const newValue = { age: 25, name: "Jane" };
|
|
1655
|
+
act(() => {
|
|
1656
|
+
result.current[1](newValue);
|
|
1657
|
+
});
|
|
1658
|
+
|
|
1659
|
+
expect(result.current[0]).toEqual(newValue);
|
|
1660
|
+
const storedValue = localStorage.getItem("user");
|
|
1661
|
+
expect(storedValue).not.toBeNull();
|
|
1662
|
+
expect(JSON.parse(storedValue ?? "")).toEqual(newValue);
|
|
1663
|
+
});
|
|
1664
|
+
|
|
1665
|
+
it("should handle arrays", () => {
|
|
1666
|
+
const { result } = renderHook(() => useLocalStorage<string[]>("items", []));
|
|
1667
|
+
|
|
1668
|
+
act(() => {
|
|
1669
|
+
result.current[1](["a", "b", "c"]);
|
|
1670
|
+
});
|
|
1671
|
+
|
|
1672
|
+
expect(result.current[0]).toEqual(["a", "b", "c"]);
|
|
1673
|
+
});
|
|
1674
|
+
|
|
1675
|
+
it("should handle parse errors when reading from localStorage", () => {
|
|
1676
|
+
localStorage.setItem("badKey", "invalid json");
|
|
1677
|
+
const warnSpy = vi.spyOn(console, "warn").mockImplementation(vi.fn());
|
|
1678
|
+
|
|
1679
|
+
const { result } = renderHook(() =>
|
|
1680
|
+
useLocalStorage("badKey", "defaultValue"),
|
|
1681
|
+
);
|
|
1682
|
+
|
|
1683
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1684
|
+
expect(warnSpy).toHaveBeenCalled();
|
|
1685
|
+
warnSpy.mockRestore();
|
|
1686
|
+
});
|
|
1687
|
+
|
|
1688
|
+
it("should handle parse errors in storage event", () => {
|
|
1689
|
+
renderHook(() => useLocalStorage("testKey", "defaultValue"));
|
|
1690
|
+
|
|
1691
|
+
const warnSpy = vi.spyOn(console, "warn").mockImplementation(vi.fn());
|
|
1692
|
+
|
|
1693
|
+
act(() => {
|
|
1694
|
+
const event = new StorageEvent("storage", {
|
|
1695
|
+
key: "testKey",
|
|
1696
|
+
newValue: "invalid json",
|
|
1697
|
+
});
|
|
1698
|
+
window.dispatchEvent(event);
|
|
1699
|
+
});
|
|
1700
|
+
|
|
1701
|
+
expect(warnSpy).toHaveBeenCalled();
|
|
1702
|
+
warnSpy.mockRestore();
|
|
1703
|
+
});
|
|
1704
|
+
|
|
1705
|
+
it("should ignore storage events for different keys", () => {
|
|
1706
|
+
const { result } = renderHook(() =>
|
|
1707
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1708
|
+
);
|
|
1709
|
+
|
|
1710
|
+
act(() => {
|
|
1711
|
+
const event = new StorageEvent("storage", {
|
|
1712
|
+
key: "otherKey",
|
|
1713
|
+
newValue: JSON.stringify("value"),
|
|
1714
|
+
});
|
|
1715
|
+
window.dispatchEvent(event);
|
|
1716
|
+
});
|
|
1717
|
+
|
|
1718
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1719
|
+
});
|
|
1720
|
+
|
|
1721
|
+
it("should ignore storage events with null newValue", () => {
|
|
1722
|
+
const { result } = renderHook(() =>
|
|
1723
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1724
|
+
);
|
|
1725
|
+
|
|
1726
|
+
act(() => {
|
|
1727
|
+
const event = new StorageEvent("storage", {
|
|
1728
|
+
key: "testKey",
|
|
1729
|
+
newValue: null,
|
|
1730
|
+
});
|
|
1731
|
+
window.dispatchEvent(event);
|
|
1732
|
+
});
|
|
1733
|
+
|
|
1734
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1735
|
+
});
|
|
1736
|
+
|
|
1737
|
+
it("should handle updates from other tabs/windows", () => {
|
|
1738
|
+
const { result } = renderHook(() =>
|
|
1739
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1740
|
+
);
|
|
1741
|
+
|
|
1742
|
+
act(() => {
|
|
1743
|
+
const event = new StorageEvent("storage", {
|
|
1744
|
+
key: "testKey",
|
|
1745
|
+
newValue: JSON.stringify("valueFromOtherTab"),
|
|
1746
|
+
});
|
|
1747
|
+
window.dispatchEvent(event);
|
|
1748
|
+
});
|
|
1749
|
+
|
|
1750
|
+
expect(result.current[0]).toBe("valueFromOtherTab");
|
|
1751
|
+
});
|
|
1752
|
+
|
|
1753
|
+
it("should cleanup event listener on unmount", () => {
|
|
1754
|
+
const removeEventListenerSpy = vi.spyOn(window, "removeEventListener");
|
|
1755
|
+
|
|
1756
|
+
const { unmount } = renderHook(() =>
|
|
1757
|
+
useLocalStorage("testKey", "defaultValue"),
|
|
1758
|
+
);
|
|
1759
|
+
|
|
1760
|
+
unmount();
|
|
1761
|
+
|
|
1762
|
+
expect(removeEventListenerSpy).toHaveBeenCalledWith(
|
|
1763
|
+
"storage",
|
|
1764
|
+
expect.any(Function),
|
|
1765
|
+
);
|
|
1766
|
+
removeEventListenerSpy.mockRestore();
|
|
1767
|
+
});
|
|
1768
|
+
});
|
|
1769
|
+
|
|
1770
|
+
it("should handle initial read with null value", () => {
|
|
1771
|
+
const { result } = renderHook(() =>
|
|
1772
|
+
useLocalStorage("nullKey", "defaultValue"),
|
|
1773
|
+
);
|
|
1774
|
+
|
|
1775
|
+
expect(result.current[0]).toBe("defaultValue");
|
|
1776
|
+
});
|
|
1777
|
+
|
|
1778
|
+
it("should handle edge case with empty string key", () => {
|
|
1779
|
+
const { result } = renderHook(() => useLocalStorage("", "defaultValue"));
|
|
1780
|
+
|
|
1781
|
+
act(() => {
|
|
1782
|
+
result.current[1]("newValue");
|
|
1783
|
+
});
|
|
1784
|
+
|
|
1785
|
+
expect(result.current[0]).toBe("newValue");
|
|
1786
|
+
});
|
|
1787
|
+
`,
|
|
1788
|
+
useLockBodyScroll: `import { useEffect, useRef } from "react";
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Temporarily disable scrolling on the document body.
|
|
1792
|
+
* Useful for modals, drawers, and other overlays.
|
|
1793
|
+
*
|
|
1794
|
+
* @example
|
|
1795
|
+
* // Lock body scroll when modal is open
|
|
1796
|
+
* function Modal({ isOpen }) {
|
|
1797
|
+
* useLockBodyScroll(isOpen);
|
|
1798
|
+
*
|
|
1799
|
+
* if (!isOpen) return null;
|
|
1800
|
+
* return <div className="modal">...</div>;
|
|
1801
|
+
* }
|
|
1802
|
+
*
|
|
1803
|
+
* @example
|
|
1804
|
+
* // Always lock when component is mounted
|
|
1805
|
+
* function FullscreenOverlay() {
|
|
1806
|
+
* useLockBodyScroll();
|
|
1807
|
+
* return <div className="overlay">...</div>;
|
|
1808
|
+
* }
|
|
1809
|
+
*/
|
|
1810
|
+
export function useLockBodyScroll(lock = true): void {
|
|
1811
|
+
const originalStyle = useRef<string | undefined>(undefined);
|
|
1812
|
+
|
|
1813
|
+
useEffect(() => {
|
|
1814
|
+
if (typeof document === "undefined") {
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
|
|
1818
|
+
if (!lock) {
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
// Store the original overflow style
|
|
1823
|
+
originalStyle.current = document.body.style.overflow;
|
|
1824
|
+
|
|
1825
|
+
// Lock the body scroll
|
|
1826
|
+
document.body.style.overflow = "hidden";
|
|
1827
|
+
|
|
1828
|
+
return () => {
|
|
1829
|
+
// Restore the original overflow style
|
|
1830
|
+
document.body.style.overflow = originalStyle.current ?? "";
|
|
1831
|
+
};
|
|
1832
|
+
}, [lock]);
|
|
1833
|
+
}
|
|
1834
|
+
`, useLockBodyScroll_test: `import { cleanup, renderHook } from "@testing-library/react";
|
|
1835
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
1836
|
+
|
|
1837
|
+
import { useLockBodyScroll } from "./useLockBodyScroll.js";
|
|
1838
|
+
|
|
1839
|
+
describe("useLockBodyScroll", () => {
|
|
1840
|
+
beforeEach(() => {
|
|
1841
|
+
document.body.style.overflow = "";
|
|
1842
|
+
});
|
|
1843
|
+
|
|
1844
|
+
afterEach(() => {
|
|
1845
|
+
cleanup();
|
|
1846
|
+
document.body.style.overflow = "";
|
|
1847
|
+
});
|
|
1848
|
+
|
|
1849
|
+
it("should lock body scroll by default", () => {
|
|
1850
|
+
renderHook(() => {
|
|
1851
|
+
useLockBodyScroll();
|
|
1852
|
+
});
|
|
1853
|
+
|
|
1854
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1855
|
+
});
|
|
1856
|
+
|
|
1857
|
+
it("should lock body scroll when lock is true", () => {
|
|
1858
|
+
renderHook(() => {
|
|
1859
|
+
useLockBodyScroll(true);
|
|
1860
|
+
});
|
|
1861
|
+
|
|
1862
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1863
|
+
});
|
|
1864
|
+
|
|
1865
|
+
it("should not lock body scroll when lock is false", () => {
|
|
1866
|
+
renderHook(() => {
|
|
1867
|
+
useLockBodyScroll(false);
|
|
1868
|
+
});
|
|
1869
|
+
|
|
1870
|
+
expect(document.body.style.overflow).toBe("");
|
|
1871
|
+
});
|
|
1872
|
+
|
|
1873
|
+
it("should restore original overflow on unmount", () => {
|
|
1874
|
+
document.body.style.overflow = "auto";
|
|
1875
|
+
|
|
1876
|
+
const { unmount } = renderHook(() => {
|
|
1877
|
+
useLockBodyScroll();
|
|
1878
|
+
});
|
|
1879
|
+
|
|
1880
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1881
|
+
|
|
1882
|
+
unmount();
|
|
1883
|
+
expect(document.body.style.overflow).toBe("auto");
|
|
1884
|
+
});
|
|
1885
|
+
|
|
1886
|
+
it("should toggle lock when lock parameter changes", () => {
|
|
1887
|
+
const { rerender } = renderHook(
|
|
1888
|
+
({ lock }) => {
|
|
1889
|
+
useLockBodyScroll(lock);
|
|
1890
|
+
},
|
|
1891
|
+
{
|
|
1892
|
+
initialProps: { lock: false },
|
|
1893
|
+
},
|
|
1894
|
+
);
|
|
1895
|
+
|
|
1896
|
+
expect(document.body.style.overflow).toBe("");
|
|
1897
|
+
|
|
1898
|
+
rerender({ lock: true });
|
|
1899
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1900
|
+
|
|
1901
|
+
rerender({ lock: false });
|
|
1902
|
+
expect(document.body.style.overflow).toBe("");
|
|
1903
|
+
});
|
|
1904
|
+
|
|
1905
|
+
it("should handle empty string as original overflow", () => {
|
|
1906
|
+
document.body.style.overflow = "";
|
|
1907
|
+
|
|
1908
|
+
const { unmount } = renderHook(() => {
|
|
1909
|
+
useLockBodyScroll();
|
|
1910
|
+
});
|
|
1911
|
+
|
|
1912
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1913
|
+
|
|
1914
|
+
unmount();
|
|
1915
|
+
expect(document.body.style.overflow).toBe("");
|
|
1916
|
+
});
|
|
1917
|
+
|
|
1918
|
+
it("should preserve scroll-y overflow style", () => {
|
|
1919
|
+
document.body.style.overflow = "scroll";
|
|
1920
|
+
|
|
1921
|
+
const { unmount } = renderHook(() => {
|
|
1922
|
+
useLockBodyScroll();
|
|
1923
|
+
});
|
|
1924
|
+
|
|
1925
|
+
expect(document.body.style.overflow).toBe("hidden");
|
|
1926
|
+
|
|
1927
|
+
unmount();
|
|
1928
|
+
expect(document.body.style.overflow).toBe("scroll");
|
|
1929
|
+
});
|
|
1930
|
+
});
|
|
1931
|
+
`,
|
|
1932
|
+
useMedia: `import { useEffect, useState } from "react";
|
|
1933
|
+
|
|
1934
|
+
/**
|
|
1935
|
+
* Reacts to CSS media query changes.
|
|
1936
|
+
*
|
|
1937
|
+
* @param query - CSS media query string (e.g., "(max-width: 768px)")
|
|
1938
|
+
* @returns Whether the media query matches
|
|
1939
|
+
*
|
|
1940
|
+
* @example
|
|
1941
|
+
* const isMobile = useMedia("(max-width: 768px)");
|
|
1942
|
+
* const isDarkMode = useMedia("(prefers-color-scheme: dark)");
|
|
1943
|
+
*
|
|
1944
|
+
* return (
|
|
1945
|
+
* <div>
|
|
1946
|
+
* <p>Is mobile: {isMobile ? "Yes" : "No"}</p>
|
|
1947
|
+
* <p>Dark mode: {isDarkMode ? "Yes" : "No"}</p>
|
|
1948
|
+
* </div>
|
|
1949
|
+
* );
|
|
1950
|
+
*/
|
|
1951
|
+
export function useMedia(query: string): boolean {
|
|
1952
|
+
const [matches, setMatches] = useState(false);
|
|
1953
|
+
|
|
1954
|
+
useEffect(() => {
|
|
1955
|
+
// Check if window is defined (SSR safety)
|
|
1956
|
+
if (typeof window === "undefined") {
|
|
1957
|
+
return undefined;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
try {
|
|
1961
|
+
const mediaQueryList = window.matchMedia(query);
|
|
1962
|
+
|
|
1963
|
+
// Set initial value
|
|
1964
|
+
// eslint-disable-next-line react-hooks/set-state-in-effect
|
|
1965
|
+
setMatches(mediaQueryList.matches);
|
|
1966
|
+
|
|
1967
|
+
// Create listener function
|
|
1968
|
+
const handleChange = (e: MediaQueryListEvent) => {
|
|
1969
|
+
setMatches(e.matches);
|
|
1970
|
+
};
|
|
1971
|
+
|
|
1972
|
+
// Modern browsers use addEventListener
|
|
1973
|
+
mediaQueryList.addEventListener("change", handleChange);
|
|
1974
|
+
return () => {
|
|
1975
|
+
mediaQueryList.removeEventListener("change", handleChange);
|
|
1976
|
+
};
|
|
1977
|
+
} catch (error) {
|
|
1978
|
+
console.warn(\`Invalid media query: "\${query}"\`, error);
|
|
1979
|
+
return undefined;
|
|
1980
|
+
}
|
|
1981
|
+
}, [query]);
|
|
1982
|
+
|
|
1983
|
+
return matches;
|
|
1984
|
+
}
|
|
1985
|
+
`, useMedia_test: `import { renderHook, waitFor } from "@testing-library/react";
|
|
1986
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
1987
|
+
|
|
1988
|
+
import { useMedia } from "./useMedia.js";
|
|
1989
|
+
|
|
1990
|
+
describe("useMedia", () => {
|
|
1991
|
+
beforeEach(() => {
|
|
1992
|
+
vi.clearAllMocks();
|
|
1993
|
+
});
|
|
1994
|
+
|
|
1995
|
+
it("should initialize with false for non-matching query", () => {
|
|
1996
|
+
// Mock window.matchMedia
|
|
1997
|
+
Object.defineProperty(window, "matchMedia", {
|
|
1998
|
+
value: vi.fn(() => ({
|
|
1999
|
+
addEventListener: vi.fn(),
|
|
2000
|
+
matches: false,
|
|
2001
|
+
removeEventListener: vi.fn(),
|
|
2002
|
+
})),
|
|
2003
|
+
writable: true,
|
|
2004
|
+
});
|
|
2005
|
+
|
|
2006
|
+
const { result } = renderHook(() => useMedia("(max-width: 480px)"));
|
|
2007
|
+
expect(result.current).toBe(false);
|
|
2008
|
+
});
|
|
2009
|
+
|
|
2010
|
+
it("should match media query", () => {
|
|
2011
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2012
|
+
value: vi.fn(() => ({
|
|
2013
|
+
addEventListener: vi.fn(),
|
|
2014
|
+
matches: true,
|
|
2015
|
+
removeEventListener: vi.fn(),
|
|
2016
|
+
})),
|
|
2017
|
+
writable: true,
|
|
2018
|
+
});
|
|
2019
|
+
|
|
2020
|
+
const { result } = renderHook(() => useMedia("(min-width: 0px)"));
|
|
2021
|
+
expect(result.current).toBe(true);
|
|
2022
|
+
});
|
|
2023
|
+
|
|
2024
|
+
it("should update on media query change", async () => {
|
|
2025
|
+
let listenerFn: ((e: MediaQueryListEvent) => void) | null = null;
|
|
2026
|
+
|
|
2027
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2028
|
+
value: vi.fn(() => ({
|
|
2029
|
+
addEventListener: vi.fn(
|
|
2030
|
+
(_: string, fn: (e: MediaQueryListEvent) => void) => {
|
|
2031
|
+
listenerFn = fn;
|
|
2032
|
+
},
|
|
2033
|
+
),
|
|
2034
|
+
matches: false,
|
|
2035
|
+
removeEventListener: vi.fn(),
|
|
2036
|
+
})),
|
|
2037
|
+
writable: true,
|
|
2038
|
+
});
|
|
2039
|
+
|
|
2040
|
+
const { result } = renderHook(() => useMedia("(max-width: 768px)"));
|
|
2041
|
+
expect(result.current).toBe(false);
|
|
2042
|
+
|
|
2043
|
+
// Trigger the change listener
|
|
2044
|
+
expect(listenerFn).toBeDefined();
|
|
2045
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
2046
|
+
listenerFn!({
|
|
2047
|
+
matches: true,
|
|
2048
|
+
media: "(max-width: 768px)",
|
|
2049
|
+
} as unknown as MediaQueryListEvent);
|
|
2050
|
+
|
|
2051
|
+
await waitFor(() => {
|
|
2052
|
+
expect(result.current).toBe(true);
|
|
2053
|
+
});
|
|
2054
|
+
});
|
|
2055
|
+
|
|
2056
|
+
it("should handle invalid media query gracefully", () => {
|
|
2057
|
+
const consoleSpy = vi
|
|
2058
|
+
.spyOn(console, "warn")
|
|
2059
|
+
.mockImplementation(() => undefined);
|
|
2060
|
+
|
|
2061
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2062
|
+
value: vi.fn(() => {
|
|
2063
|
+
throw new Error("Invalid media query");
|
|
2064
|
+
}),
|
|
2065
|
+
writable: true,
|
|
2066
|
+
});
|
|
2067
|
+
|
|
2068
|
+
const { result } = renderHook(() => useMedia("invalid()"));
|
|
2069
|
+
expect(result.current).toBe(false);
|
|
2070
|
+
expect(consoleSpy).toHaveBeenCalled();
|
|
2071
|
+
|
|
2072
|
+
consoleSpy.mockRestore();
|
|
2073
|
+
});
|
|
2074
|
+
|
|
2075
|
+
it("should work with prefers-color-scheme", () => {
|
|
2076
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2077
|
+
value: vi.fn(() => ({
|
|
2078
|
+
addEventListener: vi.fn(),
|
|
2079
|
+
matches: false,
|
|
2080
|
+
removeEventListener: vi.fn(),
|
|
2081
|
+
})),
|
|
2082
|
+
writable: true,
|
|
2083
|
+
});
|
|
2084
|
+
|
|
2085
|
+
const { result } = renderHook(() =>
|
|
2086
|
+
useMedia("(prefers-color-scheme: dark)"),
|
|
2087
|
+
);
|
|
2088
|
+
expect(typeof result.current).toBe("boolean");
|
|
2089
|
+
});
|
|
2090
|
+
|
|
2091
|
+
it("should update when query changes", () => {
|
|
2092
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2093
|
+
value: vi.fn(() => ({
|
|
2094
|
+
addEventListener: vi.fn(),
|
|
2095
|
+
matches: false,
|
|
2096
|
+
removeEventListener: vi.fn(),
|
|
2097
|
+
})),
|
|
2098
|
+
writable: true,
|
|
2099
|
+
});
|
|
2100
|
+
|
|
2101
|
+
const { rerender, result } = renderHook(({ query }) => useMedia(query), {
|
|
2102
|
+
initialProps: { query: "(max-width: 768px)" },
|
|
2103
|
+
});
|
|
2104
|
+
|
|
2105
|
+
rerender({ query: "(max-width: 480px)" });
|
|
2106
|
+
|
|
2107
|
+
expect(typeof result.current).toBe("boolean");
|
|
2108
|
+
});
|
|
2109
|
+
|
|
2110
|
+
it("should clean up listeners on unmount", () => {
|
|
2111
|
+
const mockRemoveEventListener = vi.fn();
|
|
2112
|
+
|
|
2113
|
+
Object.defineProperty(window, "matchMedia", {
|
|
2114
|
+
value: vi.fn(() => ({
|
|
2115
|
+
addEventListener: vi.fn(),
|
|
2116
|
+
matches: false,
|
|
2117
|
+
removeEventListener: mockRemoveEventListener,
|
|
2118
|
+
})),
|
|
2119
|
+
writable: true,
|
|
2120
|
+
});
|
|
2121
|
+
|
|
2122
|
+
const { unmount } = renderHook(() => useMedia("(max-width: 768px)"));
|
|
2123
|
+
|
|
2124
|
+
unmount();
|
|
2125
|
+
|
|
2126
|
+
expect(mockRemoveEventListener).toHaveBeenCalledWith(
|
|
2127
|
+
"change",
|
|
2128
|
+
expect.any(Function),
|
|
2129
|
+
);
|
|
2130
|
+
});
|
|
2131
|
+
});
|
|
2132
|
+
`,
|
|
2133
|
+
useMount: `import { useEffect } from "react";
|
|
2134
|
+
|
|
2135
|
+
/**
|
|
2136
|
+
* Calls a callback on component mount.
|
|
2137
|
+
*
|
|
2138
|
+
* @param callback - Function to call on mount
|
|
2139
|
+
*
|
|
2140
|
+
* @example
|
|
2141
|
+
* useMount(() => {
|
|
2142
|
+
* console.log("Component mounted");
|
|
2143
|
+
* // Initialize resources
|
|
2144
|
+
* });
|
|
2145
|
+
*/
|
|
2146
|
+
export function useMount(callback: () => void): void {
|
|
2147
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally only run on mount
|
|
2148
|
+
useEffect(callback, []);
|
|
2149
|
+
}
|
|
2150
|
+
`, useMount_test: `import { renderHook } from "@testing-library/react";
|
|
2151
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2152
|
+
|
|
2153
|
+
import { useMount } from "./useMount.js";
|
|
2154
|
+
|
|
2155
|
+
describe("useMount", () => {
|
|
2156
|
+
it("should call callback on mount", () => {
|
|
2157
|
+
const callback = vi.fn();
|
|
2158
|
+
renderHook(() => {
|
|
2159
|
+
useMount(callback);
|
|
2160
|
+
});
|
|
2161
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2162
|
+
});
|
|
2163
|
+
|
|
2164
|
+
it("should not call callback on rerender", () => {
|
|
2165
|
+
const callback = vi.fn();
|
|
2166
|
+
const { rerender } = renderHook(() => {
|
|
2167
|
+
useMount(callback);
|
|
2168
|
+
});
|
|
2169
|
+
|
|
2170
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2171
|
+
|
|
2172
|
+
rerender();
|
|
2173
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2174
|
+
});
|
|
2175
|
+
});
|
|
2176
|
+
`,
|
|
2177
|
+
usePrevious: `import { useState } from "react";
|
|
2178
|
+
|
|
2179
|
+
/**
|
|
2180
|
+
* Tracks the previous value or prop.
|
|
2181
|
+
*
|
|
2182
|
+
* @param value - The current value to track
|
|
2183
|
+
* @returns The previous value from the last render
|
|
2184
|
+
*
|
|
2185
|
+
* @example
|
|
2186
|
+
* const [count, setCount] = useState(0);
|
|
2187
|
+
* const prevCount = usePrevious(count);
|
|
2188
|
+
*
|
|
2189
|
+
* useEffect(() => {
|
|
2190
|
+
* console.log(\`Current: \${count}, Previous: \${prevCount}\`);
|
|
2191
|
+
* }, [count, prevCount]);
|
|
2192
|
+
*/
|
|
2193
|
+
export function usePrevious<T>(value: T): T | undefined {
|
|
2194
|
+
const [current, setCurrent] = useState<T>(value);
|
|
2195
|
+
const [previous, setPrevious] = useState<T | undefined>(undefined);
|
|
2196
|
+
|
|
2197
|
+
if (current !== value) {
|
|
2198
|
+
setPrevious(current);
|
|
2199
|
+
setCurrent(value);
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
return previous;
|
|
2203
|
+
}
|
|
2204
|
+
`, usePrevious_test: `import { renderHook } from "@testing-library/react";
|
|
2205
|
+
import { describe, expect, it } from "vitest";
|
|
2206
|
+
|
|
2207
|
+
import { usePrevious } from "./usePrevious.js";
|
|
2208
|
+
|
|
2209
|
+
describe("usePrevious", () => {
|
|
2210
|
+
it("should return undefined on first render", () => {
|
|
2211
|
+
const { result } = renderHook(() => usePrevious(5));
|
|
2212
|
+
expect(result.current).toBeUndefined();
|
|
2213
|
+
});
|
|
2214
|
+
|
|
2215
|
+
it("should return previous value on subsequent renders", () => {
|
|
2216
|
+
const { rerender, result } = renderHook(({ value }) => usePrevious(value), {
|
|
2217
|
+
initialProps: { value: 1 },
|
|
2218
|
+
});
|
|
2219
|
+
|
|
2220
|
+
expect(result.current).toBeUndefined();
|
|
2221
|
+
|
|
2222
|
+
rerender({ value: 2 });
|
|
2223
|
+
expect(result.current).toBe(1);
|
|
2224
|
+
|
|
2225
|
+
rerender({ value: 3 });
|
|
2226
|
+
expect(result.current).toBe(2);
|
|
2227
|
+
});
|
|
2228
|
+
|
|
2229
|
+
it("should work with different types", () => {
|
|
2230
|
+
const obj = { name: "Alice" };
|
|
2231
|
+
const { rerender, result } = renderHook(({ value }) => usePrevious(value), {
|
|
2232
|
+
initialProps: { value: obj },
|
|
2233
|
+
});
|
|
2234
|
+
|
|
2235
|
+
expect(result.current).toBeUndefined();
|
|
2236
|
+
|
|
2237
|
+
const newObj = { name: "Bob" };
|
|
2238
|
+
rerender({ value: newObj });
|
|
2239
|
+
expect(result.current).toBe(obj);
|
|
2240
|
+
});
|
|
2241
|
+
});
|
|
2242
|
+
`,
|
|
2243
|
+
useScroll: `import { useCallback, useEffect, useState } from "react";
|
|
2244
|
+
|
|
2245
|
+
interface ScrollPosition {
|
|
2246
|
+
x: number;
|
|
2247
|
+
y: number;
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
/**
|
|
2251
|
+
* Tracks scroll position of an element or the window.
|
|
2252
|
+
*
|
|
2253
|
+
* @param ref - Optional ref to an element. If not provided, tracks window scroll
|
|
2254
|
+
* @returns Object with x and y scroll positions
|
|
2255
|
+
*
|
|
2256
|
+
* @example
|
|
2257
|
+
* // Track window scroll
|
|
2258
|
+
* const scroll = useScroll();
|
|
2259
|
+
* console.log(scroll.x, scroll.y);
|
|
2260
|
+
*
|
|
2261
|
+
* @example
|
|
2262
|
+
* // Track element scroll
|
|
2263
|
+
* const elementRef = useRef<HTMLDivElement>(null);
|
|
2264
|
+
* const scroll = useScroll(elementRef);
|
|
2265
|
+
* return <div ref={elementRef} style={{ overflow: 'auto' }}>Content</div>;
|
|
2266
|
+
*/
|
|
2267
|
+
export function useScroll(
|
|
2268
|
+
ref?: React.RefObject<HTMLElement | null>,
|
|
2269
|
+
): ScrollPosition {
|
|
2270
|
+
const [scroll, setScroll] = useState<ScrollPosition>({ x: 0, y: 0 });
|
|
2271
|
+
|
|
2272
|
+
const handleScroll = useCallback(() => {
|
|
2273
|
+
if (ref?.current) {
|
|
2274
|
+
setScroll({
|
|
2275
|
+
x: ref.current.scrollLeft,
|
|
2276
|
+
y: ref.current.scrollTop,
|
|
2277
|
+
});
|
|
2278
|
+
} else if (typeof window !== "undefined") {
|
|
2279
|
+
setScroll({
|
|
2280
|
+
x: window.scrollX,
|
|
2281
|
+
y: window.scrollY,
|
|
2282
|
+
});
|
|
2283
|
+
}
|
|
2284
|
+
}, [ref]);
|
|
2285
|
+
|
|
2286
|
+
useEffect(() => {
|
|
2287
|
+
// Set initial scroll position
|
|
2288
|
+
handleScroll();
|
|
2289
|
+
|
|
2290
|
+
if (ref?.current) {
|
|
2291
|
+
// Listen to element scroll
|
|
2292
|
+
const target = ref.current;
|
|
2293
|
+
target.addEventListener("scroll", handleScroll);
|
|
2294
|
+
return () => {
|
|
2295
|
+
target.removeEventListener("scroll", handleScroll);
|
|
2296
|
+
};
|
|
2297
|
+
} else if (typeof window !== "undefined") {
|
|
2298
|
+
// Listen to window scroll
|
|
2299
|
+
window.addEventListener("scroll", handleScroll);
|
|
2300
|
+
return () => {
|
|
2301
|
+
window.removeEventListener("scroll", handleScroll);
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
}, [ref, handleScroll]);
|
|
2305
|
+
|
|
2306
|
+
return scroll;
|
|
2307
|
+
}
|
|
2308
|
+
`, useScroll_test: `import { act, renderHook, waitFor } from "@testing-library/react";
|
|
2309
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2310
|
+
|
|
2311
|
+
import { useScroll } from "./useScroll.js";
|
|
2312
|
+
|
|
2313
|
+
describe("useScroll", () => {
|
|
2314
|
+
it("should initialize with zero scroll position", () => {
|
|
2315
|
+
const { result } = renderHook(() => useScroll());
|
|
2316
|
+
expect(result.current).toEqual({ x: 0, y: 0 });
|
|
2317
|
+
});
|
|
2318
|
+
|
|
2319
|
+
it("should update on window scroll", async () => {
|
|
2320
|
+
const { result } = renderHook(() => useScroll());
|
|
2321
|
+
|
|
2322
|
+
act(() => {
|
|
2323
|
+
Object.defineProperty(window, "scrollX", {
|
|
2324
|
+
value: 100,
|
|
2325
|
+
writable: true,
|
|
2326
|
+
});
|
|
2327
|
+
Object.defineProperty(window, "scrollY", {
|
|
2328
|
+
value: 200,
|
|
2329
|
+
writable: true,
|
|
2330
|
+
});
|
|
2331
|
+
const scrollEvent = new Event("scroll");
|
|
2332
|
+
window.dispatchEvent(scrollEvent);
|
|
2333
|
+
});
|
|
2334
|
+
|
|
2335
|
+
await waitFor(() => {
|
|
2336
|
+
expect(result.current.x).toBe(100);
|
|
2337
|
+
expect(result.current.y).toBe(200);
|
|
2338
|
+
});
|
|
2339
|
+
});
|
|
2340
|
+
|
|
2341
|
+
it("should track element scroll when ref is provided", () => {
|
|
2342
|
+
const mockElement = {
|
|
2343
|
+
addEventListener: vi.fn(),
|
|
2344
|
+
removeEventListener: vi.fn(),
|
|
2345
|
+
scrollLeft: 50,
|
|
2346
|
+
scrollTop: 100,
|
|
2347
|
+
} as unknown as HTMLElement;
|
|
2348
|
+
|
|
2349
|
+
const ref = { current: mockElement };
|
|
2350
|
+
const { result } = renderHook(() => useScroll(ref));
|
|
2351
|
+
|
|
2352
|
+
expect(typeof result.current).toBe("object");
|
|
2353
|
+
expect("x" in result.current && "y" in result.current).toBe(true);
|
|
2354
|
+
});
|
|
2355
|
+
|
|
2356
|
+
it("should clean up event listener on unmount", () => {
|
|
2357
|
+
const removeEventListenerSpy = vi.spyOn(window, "removeEventListener");
|
|
2358
|
+
const { unmount } = renderHook(() => useScroll());
|
|
2359
|
+
|
|
2360
|
+
unmount();
|
|
2361
|
+
|
|
2362
|
+
expect(removeEventListenerSpy).toHaveBeenCalledWith(
|
|
2363
|
+
"scroll",
|
|
2364
|
+
expect.any(Function),
|
|
2365
|
+
);
|
|
2366
|
+
|
|
2367
|
+
removeEventListenerSpy.mockRestore();
|
|
2368
|
+
});
|
|
2369
|
+
});
|
|
2370
|
+
`,
|
|
2371
|
+
useSessionStorage: `import { useCallback, useState } from "react";
|
|
2372
|
+
|
|
2373
|
+
/**
|
|
2374
|
+
* Syncs state with sessionStorage, persisting only for the current session.
|
|
2375
|
+
*
|
|
2376
|
+
* @param key - The sessionStorage key
|
|
2377
|
+
* @param initialValue - The initial value (used if no stored value exists)
|
|
2378
|
+
* @returns A tuple of [value, setValue, removeValue]
|
|
2379
|
+
*
|
|
2380
|
+
* @example
|
|
2381
|
+
* const [sessionData, setSessionData, removeSessionData] = useSessionStorage("session", "default");
|
|
2382
|
+
*
|
|
2383
|
+
* // Update the session data (automatically persisted)
|
|
2384
|
+
* setSessionData("newData");
|
|
2385
|
+
*
|
|
2386
|
+
* // Remove from sessionStorage
|
|
2387
|
+
* removeSessionData();
|
|
2388
|
+
*/
|
|
2389
|
+
export function useSessionStorage<T>(
|
|
2390
|
+
key: string,
|
|
2391
|
+
initialValue: T,
|
|
2392
|
+
): [T, (value: ((prev: T) => T) | T) => void, () => void] {
|
|
2393
|
+
// Get initial value from sessionStorage or use provided initial value
|
|
2394
|
+
const [storedValue, setStoredValue] = useState<T>(() => {
|
|
2395
|
+
if (typeof window === "undefined") {
|
|
2396
|
+
return initialValue;
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
try {
|
|
2400
|
+
const item = window.sessionStorage.getItem(key);
|
|
2401
|
+
return item ? (JSON.parse(item) as T) : initialValue;
|
|
2402
|
+
} catch (error) {
|
|
2403
|
+
console.warn(\`Error reading sessionStorage key "\${key}":\`, error);
|
|
2404
|
+
return initialValue;
|
|
2405
|
+
}
|
|
2406
|
+
});
|
|
2407
|
+
|
|
2408
|
+
// Update sessionStorage when value changes
|
|
2409
|
+
const setValue = useCallback(
|
|
2410
|
+
(value: ((prev: T) => T) | T) => {
|
|
2411
|
+
try {
|
|
2412
|
+
setStoredValue((prev) => {
|
|
2413
|
+
const valueToStore = value instanceof Function ? value(prev) : value;
|
|
2414
|
+
if (typeof window !== "undefined") {
|
|
2415
|
+
window.sessionStorage.setItem(key, JSON.stringify(valueToStore));
|
|
2416
|
+
}
|
|
2417
|
+
return valueToStore;
|
|
2418
|
+
});
|
|
2419
|
+
} catch (error) {
|
|
2420
|
+
console.warn(\`Error setting sessionStorage key "\${key}":\`, error);
|
|
2421
|
+
}
|
|
2422
|
+
},
|
|
2423
|
+
[key],
|
|
2424
|
+
);
|
|
2425
|
+
|
|
2426
|
+
// Remove from sessionStorage
|
|
2427
|
+
const removeValue = useCallback(() => {
|
|
2428
|
+
try {
|
|
2429
|
+
if (typeof window !== "undefined") {
|
|
2430
|
+
window.sessionStorage.removeItem(key);
|
|
2431
|
+
}
|
|
2432
|
+
setStoredValue(initialValue);
|
|
2433
|
+
} catch (error) {
|
|
2434
|
+
console.warn(\`Error removing sessionStorage key "\${key}":\`, error);
|
|
2435
|
+
}
|
|
2436
|
+
}, [key, initialValue]);
|
|
2437
|
+
|
|
2438
|
+
return [storedValue, setValue, removeValue];
|
|
2439
|
+
}
|
|
2440
|
+
`, useSessionStorage_test: `import { act, renderHook } from "@testing-library/react";
|
|
2441
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
2442
|
+
|
|
2443
|
+
import { useSessionStorage } from "./useSessionStorage.js";
|
|
2444
|
+
|
|
2445
|
+
describe("useSessionStorage", () => {
|
|
2446
|
+
beforeEach(() => {
|
|
2447
|
+
sessionStorage.clear();
|
|
2448
|
+
});
|
|
2449
|
+
|
|
2450
|
+
afterEach(() => {
|
|
2451
|
+
sessionStorage.clear();
|
|
2452
|
+
});
|
|
2453
|
+
|
|
2454
|
+
it("should initialize with initial value", () => {
|
|
2455
|
+
const { result } = renderHook(() => useSessionStorage("test", "initial"));
|
|
2456
|
+
expect(result.current[0]).toBe("initial");
|
|
2457
|
+
});
|
|
2458
|
+
|
|
2459
|
+
it("should read from sessionStorage if key exists", () => {
|
|
2460
|
+
sessionStorage.setItem("test", JSON.stringify("stored"));
|
|
2461
|
+
const { result } = renderHook(() => useSessionStorage("test", "initial"));
|
|
2462
|
+
expect(result.current[0]).toBe("stored");
|
|
2463
|
+
});
|
|
2464
|
+
|
|
2465
|
+
it("should update sessionStorage when value changes", () => {
|
|
2466
|
+
const { result } = renderHook(() => useSessionStorage("test", "initial"));
|
|
2467
|
+
|
|
2468
|
+
act(() => {
|
|
2469
|
+
result.current[1]("updated");
|
|
2470
|
+
});
|
|
2471
|
+
|
|
2472
|
+
expect(result.current[0]).toBe("updated");
|
|
2473
|
+
expect(sessionStorage.getItem("test")).toBe(JSON.stringify("updated"));
|
|
2474
|
+
});
|
|
2475
|
+
|
|
2476
|
+
it("should support updater function", () => {
|
|
2477
|
+
const { result } = renderHook(() => useSessionStorage("test", 0));
|
|
2478
|
+
|
|
2479
|
+
act(() => {
|
|
2480
|
+
result.current[1]((prev) => prev + 1);
|
|
2481
|
+
});
|
|
2482
|
+
|
|
2483
|
+
expect(result.current[0]).toBe(1);
|
|
2484
|
+
});
|
|
2485
|
+
|
|
2486
|
+
it("should remove value from sessionStorage", () => {
|
|
2487
|
+
sessionStorage.setItem("test", JSON.stringify("value"));
|
|
2488
|
+
const { result } = renderHook(() => useSessionStorage("test", "initial"));
|
|
2489
|
+
|
|
2490
|
+
act(() => {
|
|
2491
|
+
result.current[2]();
|
|
2492
|
+
});
|
|
2493
|
+
|
|
2494
|
+
expect(result.current[0]).toBe("initial");
|
|
2495
|
+
expect(sessionStorage.getItem("test")).toBeNull();
|
|
2496
|
+
});
|
|
2497
|
+
|
|
2498
|
+
it("should handle complex objects", () => {
|
|
2499
|
+
const obj = { name: "test", value: 42 };
|
|
2500
|
+
const { result } = renderHook(() => useSessionStorage("test", obj));
|
|
2501
|
+
|
|
2502
|
+
act(() => {
|
|
2503
|
+
result.current[1]({ name: "updated", value: 100 });
|
|
2504
|
+
});
|
|
2505
|
+
|
|
2506
|
+
expect(result.current[0]).toEqual({ name: "updated", value: 100 });
|
|
2507
|
+
expect(JSON.parse(sessionStorage.getItem("test") ?? "{}")).toEqual({
|
|
2508
|
+
name: "updated",
|
|
2509
|
+
value: 100,
|
|
2510
|
+
});
|
|
2511
|
+
});
|
|
2512
|
+
|
|
2513
|
+
it("should handle parse errors gracefully", () => {
|
|
2514
|
+
sessionStorage.setItem("test", "invalid json");
|
|
2515
|
+
const { result } = renderHook(() => useSessionStorage("test", "fallback"));
|
|
2516
|
+
expect(result.current[0]).toBe("fallback");
|
|
2517
|
+
});
|
|
2518
|
+
});
|
|
2519
|
+
`,
|
|
2520
|
+
useThrottle: `import { useEffect, useRef, useState } from "react";
|
|
2521
|
+
|
|
2522
|
+
/**
|
|
2523
|
+
* Throttles a value to update at most once per specified interval.
|
|
2524
|
+
*
|
|
2525
|
+
* @param value - The value to throttle
|
|
2526
|
+
* @param interval - The throttle interval in milliseconds (default: 500ms)
|
|
2527
|
+
* @returns The throttled value
|
|
2528
|
+
*
|
|
2529
|
+
* @example
|
|
2530
|
+
* const [position, setPosition] = useState({ x: 0, y: 0 });
|
|
2531
|
+
* const throttledPosition = useThrottle(position, 100);
|
|
2532
|
+
*
|
|
2533
|
+
* useEffect(() => {
|
|
2534
|
+
* // This effect runs at most every 100ms
|
|
2535
|
+
* updateCursor(throttledPosition);
|
|
2536
|
+
* }, [throttledPosition]);
|
|
2537
|
+
*/
|
|
2538
|
+
export function useThrottle<T>(value: T, interval = 500): T {
|
|
2539
|
+
const [throttledValue, setThrottledValue] = useState<T>(value);
|
|
2540
|
+
// eslint-disable-next-line react-hooks/purity
|
|
2541
|
+
const lastUpdated = useRef<number>(Date.now());
|
|
2542
|
+
|
|
2543
|
+
useEffect(() => {
|
|
2544
|
+
const now = Date.now();
|
|
2545
|
+
const elapsed = now - lastUpdated.current;
|
|
2546
|
+
|
|
2547
|
+
if (elapsed >= interval) {
|
|
2548
|
+
lastUpdated.current = now;
|
|
2549
|
+
setThrottledValue(value);
|
|
2550
|
+
} else {
|
|
2551
|
+
const timer = setTimeout(() => {
|
|
2552
|
+
lastUpdated.current = Date.now();
|
|
2553
|
+
setThrottledValue(value);
|
|
2554
|
+
}, interval - elapsed);
|
|
2555
|
+
|
|
2556
|
+
return () => {
|
|
2557
|
+
clearTimeout(timer);
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
}, [value, interval]);
|
|
2561
|
+
|
|
2562
|
+
return throttledValue;
|
|
2563
|
+
}
|
|
2564
|
+
`, useThrottle_test: `import { act, renderHook } from "@testing-library/react";
|
|
2565
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
2566
|
+
|
|
2567
|
+
import { useThrottle } from "./useThrottle.js";
|
|
2568
|
+
|
|
2569
|
+
describe("useThrottle", () => {
|
|
2570
|
+
beforeEach(() => {
|
|
2571
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
2572
|
+
});
|
|
2573
|
+
|
|
2574
|
+
afterEach(() => {
|
|
2575
|
+
vi.useRealTimers();
|
|
2576
|
+
});
|
|
2577
|
+
|
|
2578
|
+
it("should return initial value immediately", () => {
|
|
2579
|
+
const { result } = renderHook(() => useThrottle("initial", 500));
|
|
2580
|
+
expect(result.current).toBe("initial");
|
|
2581
|
+
});
|
|
2582
|
+
|
|
2583
|
+
it("should throttle rapid updates", () => {
|
|
2584
|
+
const { rerender, result } = renderHook(
|
|
2585
|
+
({ value }) => useThrottle(value, 500),
|
|
2586
|
+
{ initialProps: { value: "a" } },
|
|
2587
|
+
);
|
|
2588
|
+
|
|
2589
|
+
expect(result.current).toBe("a");
|
|
2590
|
+
|
|
2591
|
+
rerender({ value: "b" });
|
|
2592
|
+
expect(result.current).toBe("a");
|
|
2593
|
+
|
|
2594
|
+
rerender({ value: "c" });
|
|
2595
|
+
expect(result.current).toBe("a");
|
|
2596
|
+
|
|
2597
|
+
act(() => {
|
|
2598
|
+
vi.advanceTimersByTime(500);
|
|
2599
|
+
});
|
|
2600
|
+
expect(result.current).toBe("c");
|
|
2601
|
+
});
|
|
2602
|
+
|
|
2603
|
+
it("should allow updates after interval passes", () => {
|
|
2604
|
+
const { rerender, result } = renderHook(
|
|
2605
|
+
({ value }) => useThrottle(value, 500),
|
|
2606
|
+
{ initialProps: { value: "a" } },
|
|
2607
|
+
);
|
|
2608
|
+
|
|
2609
|
+
expect(result.current).toBe("a");
|
|
2610
|
+
|
|
2611
|
+
rerender({ value: "b" });
|
|
2612
|
+
act(() => {
|
|
2613
|
+
vi.advanceTimersByTime(500);
|
|
2614
|
+
});
|
|
2615
|
+
expect(result.current).toBe("b");
|
|
2616
|
+
|
|
2617
|
+
rerender({ value: "c" });
|
|
2618
|
+
act(() => {
|
|
2619
|
+
vi.advanceTimersByTime(500);
|
|
2620
|
+
});
|
|
2621
|
+
expect(result.current).toBe("c");
|
|
2622
|
+
});
|
|
2623
|
+
|
|
2624
|
+
it("should use default interval of 500ms", () => {
|
|
2625
|
+
const { rerender, result } = renderHook(({ value }) => useThrottle(value), {
|
|
2626
|
+
initialProps: { value: "initial" },
|
|
2627
|
+
});
|
|
2628
|
+
|
|
2629
|
+
rerender({ value: "updated" });
|
|
2630
|
+
|
|
2631
|
+
act(() => {
|
|
2632
|
+
vi.advanceTimersByTime(499);
|
|
2633
|
+
});
|
|
2634
|
+
expect(result.current).toBe("initial");
|
|
2635
|
+
|
|
2636
|
+
act(() => {
|
|
2637
|
+
vi.advanceTimersByTime(1);
|
|
2638
|
+
});
|
|
2639
|
+
expect(result.current).toBe("updated");
|
|
2640
|
+
});
|
|
2641
|
+
|
|
2642
|
+
it("should cleanup timer on unmount when throttle pending", () => {
|
|
2643
|
+
const { rerender, unmount } = renderHook(
|
|
2644
|
+
({ value }) => useThrottle(value, 500),
|
|
2645
|
+
{ initialProps: { value: "a" } },
|
|
2646
|
+
);
|
|
2647
|
+
|
|
2648
|
+
rerender({ value: "b" });
|
|
2649
|
+
unmount();
|
|
2650
|
+
expect(true).toBe(true);
|
|
2651
|
+
});
|
|
2652
|
+
});
|
|
2653
|
+
`,
|
|
2654
|
+
useThrottledCallback: `import { useCallback, useEffect, useRef } from "react";
|
|
2655
|
+
|
|
2656
|
+
export interface ThrottledCallbackOptions {
|
|
2657
|
+
/**
|
|
2658
|
+
* Whether to invoke the callback on the leading edge (immediately on first call).
|
|
2659
|
+
* @default true
|
|
2660
|
+
*/
|
|
2661
|
+
leading?: boolean;
|
|
2662
|
+
/**
|
|
2663
|
+
* Whether to invoke the callback on the trailing edge (after the interval).
|
|
2664
|
+
* @default true
|
|
2665
|
+
*/
|
|
2666
|
+
trailing?: boolean;
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
/**
|
|
2670
|
+
* Creates a throttled version of a callback function.
|
|
2671
|
+
* The callback will execute at most once per specified interval.
|
|
2672
|
+
*
|
|
2673
|
+
* @param callback - The function to throttle
|
|
2674
|
+
* @param interval - The throttle interval in milliseconds (default: 500ms)
|
|
2675
|
+
* @param options - Configuration options for leading/trailing edge behavior
|
|
2676
|
+
* @returns A tuple containing [throttledCallback, cancel]
|
|
2677
|
+
*
|
|
2678
|
+
* @example
|
|
2679
|
+
* const [throttledScroll, cancel] = useThrottledCallback((e: Event) => {
|
|
2680
|
+
* console.log("Scroll position:", window.scrollY);
|
|
2681
|
+
* }, 100);
|
|
2682
|
+
*
|
|
2683
|
+
* useEffect(() => {
|
|
2684
|
+
* window.addEventListener("scroll", throttledScroll);
|
|
2685
|
+
* return () => window.removeEventListener("scroll", throttledScroll);
|
|
2686
|
+
* }, [throttledScroll]);
|
|
2687
|
+
*
|
|
2688
|
+
* @example
|
|
2689
|
+
* // Trailing edge only (no immediate execution)
|
|
2690
|
+
* const [throttled] = useThrottledCallback(callback, 500, { leading: false });
|
|
2691
|
+
*/
|
|
2692
|
+
export function useThrottledCallback<T extends unknown[]>(
|
|
2693
|
+
callback: (...args: T) => void,
|
|
2694
|
+
interval = 500,
|
|
2695
|
+
options: ThrottledCallbackOptions = {},
|
|
2696
|
+
): [(...args: T) => void, () => void] {
|
|
2697
|
+
const { leading = true, trailing = true } = options;
|
|
2698
|
+
|
|
2699
|
+
const callbackRef = useRef(callback);
|
|
2700
|
+
const timeoutRef = useRef<null | ReturnType<typeof setTimeout>>(null);
|
|
2701
|
+
const lastArgsRef = useRef<null | T>(null);
|
|
2702
|
+
const lastCallTimeRef = useRef<null | number>(null);
|
|
2703
|
+
|
|
2704
|
+
// Keep callback ref up to date
|
|
2705
|
+
useEffect(() => {
|
|
2706
|
+
callbackRef.current = callback;
|
|
2707
|
+
}, [callback]);
|
|
2708
|
+
|
|
2709
|
+
// Cleanup on unmount
|
|
2710
|
+
useEffect(() => {
|
|
2711
|
+
return () => {
|
|
2712
|
+
if (timeoutRef.current) {
|
|
2713
|
+
clearTimeout(timeoutRef.current);
|
|
2714
|
+
}
|
|
2715
|
+
};
|
|
2716
|
+
}, []);
|
|
2717
|
+
|
|
2718
|
+
const cancel = useCallback(() => {
|
|
2719
|
+
if (timeoutRef.current) {
|
|
2720
|
+
clearTimeout(timeoutRef.current);
|
|
2721
|
+
timeoutRef.current = null;
|
|
2722
|
+
}
|
|
2723
|
+
lastArgsRef.current = null;
|
|
2724
|
+
lastCallTimeRef.current = null;
|
|
2725
|
+
}, []);
|
|
2726
|
+
|
|
2727
|
+
const throttledCallback = useCallback(
|
|
2728
|
+
(...args: T) => {
|
|
2729
|
+
const now = Date.now();
|
|
2730
|
+
const timeSinceLastCall =
|
|
2731
|
+
lastCallTimeRef.current === null
|
|
2732
|
+
? interval
|
|
2733
|
+
: now - lastCallTimeRef.current;
|
|
2734
|
+
|
|
2735
|
+
lastArgsRef.current = args;
|
|
2736
|
+
|
|
2737
|
+
// First call or enough time has passed
|
|
2738
|
+
if (timeSinceLastCall >= interval) {
|
|
2739
|
+
if (leading) {
|
|
2740
|
+
lastCallTimeRef.current = now;
|
|
2741
|
+
callbackRef.current(...args);
|
|
2742
|
+
} else {
|
|
2743
|
+
// Schedule for trailing edge
|
|
2744
|
+
lastCallTimeRef.current = now;
|
|
2745
|
+
if (trailing && !timeoutRef.current) {
|
|
2746
|
+
timeoutRef.current = setTimeout(() => {
|
|
2747
|
+
timeoutRef.current = null;
|
|
2748
|
+
if (lastArgsRef.current) {
|
|
2749
|
+
callbackRef.current(...lastArgsRef.current);
|
|
2750
|
+
}
|
|
2751
|
+
}, interval);
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
} else if (trailing && !timeoutRef.current) {
|
|
2755
|
+
// Schedule trailing call
|
|
2756
|
+
const remainingTime = interval - timeSinceLastCall;
|
|
2757
|
+
timeoutRef.current = setTimeout(() => {
|
|
2758
|
+
timeoutRef.current = null;
|
|
2759
|
+
lastCallTimeRef.current = Date.now();
|
|
2760
|
+
if (lastArgsRef.current) {
|
|
2761
|
+
callbackRef.current(...lastArgsRef.current);
|
|
2762
|
+
}
|
|
2763
|
+
}, remainingTime);
|
|
2764
|
+
}
|
|
2765
|
+
},
|
|
2766
|
+
[interval, leading, trailing],
|
|
2767
|
+
);
|
|
2768
|
+
|
|
2769
|
+
return [throttledCallback, cancel];
|
|
2770
|
+
}
|
|
2771
|
+
`, useThrottledCallback_test: `import { act, renderHook } from "@testing-library/react";
|
|
2772
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
2773
|
+
|
|
2774
|
+
import { useThrottledCallback } from "./useThrottledCallback.js";
|
|
2775
|
+
|
|
2776
|
+
describe("useThrottledCallback", () => {
|
|
2777
|
+
beforeEach(() => {
|
|
2778
|
+
vi.useFakeTimers();
|
|
2779
|
+
});
|
|
2780
|
+
|
|
2781
|
+
it("should execute immediately on first call (leading edge)", () => {
|
|
2782
|
+
const callback = vi.fn();
|
|
2783
|
+
const { result } = renderHook(() => useThrottledCallback(callback, 500));
|
|
2784
|
+
|
|
2785
|
+
const [throttledCallback] = result.current;
|
|
2786
|
+
|
|
2787
|
+
act(() => {
|
|
2788
|
+
throttledCallback("first");
|
|
2789
|
+
});
|
|
2790
|
+
|
|
2791
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2792
|
+
expect(callback).toHaveBeenCalledWith("first");
|
|
2793
|
+
});
|
|
2794
|
+
|
|
2795
|
+
it("should throttle subsequent calls within interval", () => {
|
|
2796
|
+
const callback = vi.fn();
|
|
2797
|
+
const { result } = renderHook(() => useThrottledCallback(callback, 500));
|
|
2798
|
+
|
|
2799
|
+
const [throttledCallback] = result.current;
|
|
2800
|
+
|
|
2801
|
+
act(() => {
|
|
2802
|
+
throttledCallback("a");
|
|
2803
|
+
throttledCallback("b");
|
|
2804
|
+
throttledCallback("c");
|
|
2805
|
+
});
|
|
2806
|
+
|
|
2807
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2808
|
+
expect(callback).toHaveBeenCalledWith("a");
|
|
2809
|
+
|
|
2810
|
+
act(() => {
|
|
2811
|
+
vi.advanceTimersByTime(500);
|
|
2812
|
+
});
|
|
2813
|
+
|
|
2814
|
+
// Trailing call with last args
|
|
2815
|
+
expect(callback).toHaveBeenCalledTimes(2);
|
|
2816
|
+
expect(callback).toHaveBeenLastCalledWith("c");
|
|
2817
|
+
});
|
|
2818
|
+
|
|
2819
|
+
it("should use default interval of 500ms", () => {
|
|
2820
|
+
const callback = vi.fn();
|
|
2821
|
+
const { result } = renderHook(() => useThrottledCallback(callback));
|
|
2822
|
+
|
|
2823
|
+
const [throttledCallback] = result.current;
|
|
2824
|
+
|
|
2825
|
+
act(() => {
|
|
2826
|
+
throttledCallback("first");
|
|
2827
|
+
});
|
|
2828
|
+
|
|
2829
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2830
|
+
|
|
2831
|
+
act(() => {
|
|
2832
|
+
throttledCallback("second");
|
|
2833
|
+
});
|
|
2834
|
+
|
|
2835
|
+
act(() => {
|
|
2836
|
+
vi.advanceTimersByTime(499);
|
|
2837
|
+
});
|
|
2838
|
+
|
|
2839
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2840
|
+
|
|
2841
|
+
act(() => {
|
|
2842
|
+
vi.advanceTimersByTime(1);
|
|
2843
|
+
});
|
|
2844
|
+
|
|
2845
|
+
expect(callback).toHaveBeenCalledTimes(2);
|
|
2846
|
+
});
|
|
2847
|
+
|
|
2848
|
+
it("should allow calls after interval has passed", () => {
|
|
2849
|
+
const callback = vi.fn();
|
|
2850
|
+
const { result } = renderHook(() => useThrottledCallback(callback, 500));
|
|
2851
|
+
|
|
2852
|
+
const [throttledCallback] = result.current;
|
|
2853
|
+
|
|
2854
|
+
act(() => {
|
|
2855
|
+
throttledCallback("first");
|
|
2856
|
+
});
|
|
2857
|
+
|
|
2858
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2859
|
+
|
|
2860
|
+
act(() => {
|
|
2861
|
+
vi.advanceTimersByTime(500);
|
|
2862
|
+
});
|
|
2863
|
+
|
|
2864
|
+
act(() => {
|
|
2865
|
+
throttledCallback("second");
|
|
2866
|
+
});
|
|
2867
|
+
|
|
2868
|
+
expect(callback).toHaveBeenCalledTimes(2);
|
|
2869
|
+
expect(callback).toHaveBeenLastCalledWith("second");
|
|
2870
|
+
});
|
|
2871
|
+
|
|
2872
|
+
it("should cancel pending callback", () => {
|
|
2873
|
+
const callback = vi.fn();
|
|
2874
|
+
const { result } = renderHook(() => useThrottledCallback(callback, 500));
|
|
2875
|
+
|
|
2876
|
+
const [throttledCallback, cancel] = result.current;
|
|
2877
|
+
|
|
2878
|
+
act(() => {
|
|
2879
|
+
throttledCallback("first");
|
|
2880
|
+
throttledCallback("second");
|
|
2881
|
+
});
|
|
2882
|
+
|
|
2883
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2884
|
+
|
|
2885
|
+
act(() => {
|
|
2886
|
+
cancel();
|
|
2887
|
+
});
|
|
2888
|
+
|
|
2889
|
+
act(() => {
|
|
2890
|
+
vi.advanceTimersByTime(500);
|
|
2891
|
+
});
|
|
2892
|
+
|
|
2893
|
+
// Trailing call was cancelled
|
|
2894
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2895
|
+
});
|
|
2896
|
+
|
|
2897
|
+
it("should pass all arguments to callback", () => {
|
|
2898
|
+
const callback = vi.fn();
|
|
2899
|
+
const { result } = renderHook(() => useThrottledCallback(callback, 100));
|
|
2900
|
+
|
|
2901
|
+
const [throttledCallback] = result.current;
|
|
2902
|
+
|
|
2903
|
+
act(() => {
|
|
2904
|
+
throttledCallback("arg1", "arg2", 123);
|
|
2905
|
+
});
|
|
2906
|
+
|
|
2907
|
+
expect(callback).toHaveBeenCalledWith("arg1", "arg2", 123);
|
|
2908
|
+
});
|
|
2909
|
+
|
|
2910
|
+
it("should use latest callback reference", () => {
|
|
2911
|
+
const callback1 = vi.fn();
|
|
2912
|
+
const callback2 = vi.fn();
|
|
2913
|
+
|
|
2914
|
+
const { rerender, result } = renderHook(
|
|
2915
|
+
({ cb }) => useThrottledCallback(cb, 500),
|
|
2916
|
+
{ initialProps: { cb: callback1 } },
|
|
2917
|
+
);
|
|
2918
|
+
|
|
2919
|
+
const [throttledCallback] = result.current;
|
|
2920
|
+
|
|
2921
|
+
act(() => {
|
|
2922
|
+
throttledCallback("first");
|
|
2923
|
+
throttledCallback("second");
|
|
2924
|
+
});
|
|
2925
|
+
|
|
2926
|
+
expect(callback1).toHaveBeenCalledTimes(1);
|
|
2927
|
+
|
|
2928
|
+
rerender({ cb: callback2 });
|
|
2929
|
+
|
|
2930
|
+
act(() => {
|
|
2931
|
+
vi.advanceTimersByTime(500);
|
|
2932
|
+
});
|
|
2933
|
+
|
|
2934
|
+
// Trailing call uses new callback
|
|
2935
|
+
expect(callback1).toHaveBeenCalledTimes(1);
|
|
2936
|
+
expect(callback2).toHaveBeenCalledTimes(1);
|
|
2937
|
+
});
|
|
2938
|
+
|
|
2939
|
+
it("should cleanup on unmount", () => {
|
|
2940
|
+
const callback = vi.fn();
|
|
2941
|
+
const { result, unmount } = renderHook(() =>
|
|
2942
|
+
useThrottledCallback(callback, 500),
|
|
2943
|
+
);
|
|
2944
|
+
|
|
2945
|
+
const [throttledCallback] = result.current;
|
|
2946
|
+
|
|
2947
|
+
act(() => {
|
|
2948
|
+
throttledCallback("first");
|
|
2949
|
+
throttledCallback("second");
|
|
2950
|
+
});
|
|
2951
|
+
|
|
2952
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2953
|
+
|
|
2954
|
+
unmount();
|
|
2955
|
+
|
|
2956
|
+
act(() => {
|
|
2957
|
+
vi.advanceTimersByTime(500);
|
|
2958
|
+
});
|
|
2959
|
+
|
|
2960
|
+
// Trailing call was cleaned up
|
|
2961
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2962
|
+
});
|
|
2963
|
+
|
|
2964
|
+
describe("options", () => {
|
|
2965
|
+
it("should not execute immediately when leading is false", () => {
|
|
2966
|
+
const callback = vi.fn();
|
|
2967
|
+
const { result } = renderHook(() =>
|
|
2968
|
+
useThrottledCallback(callback, 500, { leading: false }),
|
|
2969
|
+
);
|
|
2970
|
+
|
|
2971
|
+
const [throttledCallback] = result.current;
|
|
2972
|
+
|
|
2973
|
+
act(() => {
|
|
2974
|
+
throttledCallback("first");
|
|
2975
|
+
});
|
|
2976
|
+
|
|
2977
|
+
expect(callback).not.toHaveBeenCalled();
|
|
2978
|
+
|
|
2979
|
+
act(() => {
|
|
2980
|
+
vi.advanceTimersByTime(500);
|
|
2981
|
+
});
|
|
2982
|
+
|
|
2983
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
2984
|
+
expect(callback).toHaveBeenCalledWith("first");
|
|
2985
|
+
});
|
|
2986
|
+
|
|
2987
|
+
it("should not execute trailing call when trailing is false", () => {
|
|
2988
|
+
const callback = vi.fn();
|
|
2989
|
+
const { result } = renderHook(() =>
|
|
2990
|
+
useThrottledCallback(callback, 500, { trailing: false }),
|
|
2991
|
+
);
|
|
2992
|
+
|
|
2993
|
+
const [throttledCallback] = result.current;
|
|
2994
|
+
|
|
2995
|
+
act(() => {
|
|
2996
|
+
throttledCallback("first");
|
|
2997
|
+
throttledCallback("second");
|
|
2998
|
+
throttledCallback("third");
|
|
2999
|
+
});
|
|
3000
|
+
|
|
3001
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
3002
|
+
expect(callback).toHaveBeenCalledWith("first");
|
|
3003
|
+
|
|
3004
|
+
act(() => {
|
|
3005
|
+
vi.advanceTimersByTime(500);
|
|
3006
|
+
});
|
|
3007
|
+
|
|
3008
|
+
// No trailing call
|
|
3009
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
3010
|
+
});
|
|
3011
|
+
|
|
3012
|
+
it("should handle both leading and trailing as false gracefully", () => {
|
|
3013
|
+
const callback = vi.fn();
|
|
3014
|
+
const { result } = renderHook(() =>
|
|
3015
|
+
useThrottledCallback(callback, 500, {
|
|
3016
|
+
leading: false,
|
|
3017
|
+
trailing: false,
|
|
3018
|
+
}),
|
|
3019
|
+
);
|
|
3020
|
+
|
|
3021
|
+
const [throttledCallback] = result.current;
|
|
3022
|
+
|
|
3023
|
+
act(() => {
|
|
3024
|
+
throttledCallback("test");
|
|
3025
|
+
});
|
|
3026
|
+
|
|
3027
|
+
act(() => {
|
|
3028
|
+
vi.advanceTimersByTime(1000);
|
|
3029
|
+
});
|
|
3030
|
+
|
|
3031
|
+
// No calls when both are false
|
|
3032
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3033
|
+
});
|
|
3034
|
+
});
|
|
3035
|
+
});
|
|
3036
|
+
`,
|
|
3037
|
+
useTimeout: `import { useEffect } from "react";
|
|
3038
|
+
|
|
3039
|
+
/**
|
|
3040
|
+
* Calls a callback after a timeout.
|
|
3041
|
+
*
|
|
3042
|
+
* @param callback - Function to call after timeout
|
|
3043
|
+
* @param delay - Timeout delay in milliseconds (null to disable)
|
|
3044
|
+
*
|
|
3045
|
+
* @example
|
|
3046
|
+
* useTimeout(() => {
|
|
3047
|
+
* console.log("Timeout completed");
|
|
3048
|
+
* }, 2000);
|
|
3049
|
+
*
|
|
3050
|
+
* @example
|
|
3051
|
+
* // Disable timeout by passing null
|
|
3052
|
+
* useTimeout(() => {
|
|
3053
|
+
* console.log("This won't run");
|
|
3054
|
+
* }, null);
|
|
3055
|
+
*/
|
|
3056
|
+
export function useTimeout(callback: () => void, delay: null | number): void {
|
|
3057
|
+
useEffect(() => {
|
|
3058
|
+
if (delay === null) return;
|
|
3059
|
+
|
|
3060
|
+
const timeout = setTimeout(callback, delay);
|
|
3061
|
+
return () => {
|
|
3062
|
+
clearTimeout(timeout);
|
|
3063
|
+
};
|
|
3064
|
+
}, [callback, delay]);
|
|
3065
|
+
}
|
|
3066
|
+
`, useTimeout_test: `import { renderHook } from "@testing-library/react";
|
|
3067
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
3068
|
+
|
|
3069
|
+
import { useTimeout } from "./useTimeout.js";
|
|
3070
|
+
|
|
3071
|
+
describe("useTimeout", () => {
|
|
3072
|
+
beforeEach(() => {
|
|
3073
|
+
vi.useFakeTimers();
|
|
3074
|
+
});
|
|
3075
|
+
|
|
3076
|
+
afterEach(() => {
|
|
3077
|
+
vi.useRealTimers();
|
|
3078
|
+
});
|
|
3079
|
+
|
|
3080
|
+
it("should call callback after timeout", () => {
|
|
3081
|
+
const callback = vi.fn();
|
|
3082
|
+
renderHook(() => {
|
|
3083
|
+
useTimeout(callback, 2000);
|
|
3084
|
+
});
|
|
3085
|
+
|
|
3086
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3087
|
+
|
|
3088
|
+
vi.advanceTimersByTime(2000);
|
|
3089
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
3090
|
+
});
|
|
3091
|
+
|
|
3092
|
+
it("should cleanup timeout on unmount", () => {
|
|
3093
|
+
const callback = vi.fn();
|
|
3094
|
+
const { unmount } = renderHook(() => {
|
|
3095
|
+
useTimeout(callback, 2000);
|
|
3096
|
+
});
|
|
3097
|
+
|
|
3098
|
+
unmount();
|
|
3099
|
+
|
|
3100
|
+
vi.advanceTimersByTime(2000);
|
|
3101
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3102
|
+
});
|
|
3103
|
+
|
|
3104
|
+
it("should not set timeout when delay is null", () => {
|
|
3105
|
+
const callback = vi.fn();
|
|
3106
|
+
renderHook(() => {
|
|
3107
|
+
useTimeout(callback, null);
|
|
3108
|
+
});
|
|
3109
|
+
|
|
3110
|
+
vi.advanceTimersByTime(5000);
|
|
3111
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3112
|
+
});
|
|
3113
|
+
|
|
3114
|
+
it("should reset timeout when delay changes", () => {
|
|
3115
|
+
const callback = vi.fn();
|
|
3116
|
+
const { rerender } = renderHook(
|
|
3117
|
+
({ delay }: { delay: null | number }) => {
|
|
3118
|
+
useTimeout(callback, delay);
|
|
3119
|
+
},
|
|
3120
|
+
{ initialProps: { delay: 2000 as null | number } },
|
|
3121
|
+
);
|
|
3122
|
+
|
|
3123
|
+
vi.advanceTimersByTime(1000);
|
|
3124
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3125
|
+
|
|
3126
|
+
// Change delay, should reset the timeout
|
|
3127
|
+
rerender({ delay: 3000 });
|
|
3128
|
+
|
|
3129
|
+
vi.advanceTimersByTime(2000);
|
|
3130
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3131
|
+
|
|
3132
|
+
vi.advanceTimersByTime(1000);
|
|
3133
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
3134
|
+
});
|
|
3135
|
+
});
|
|
3136
|
+
`,
|
|
3137
|
+
useToggle: `import { useCallback, useState } from "react";
|
|
3138
|
+
|
|
3139
|
+
/**
|
|
3140
|
+
* Toggle a boolean value with a callback.
|
|
3141
|
+
*
|
|
3142
|
+
* @param initialValue - Initial boolean value (default: false)
|
|
3143
|
+
* @returns Tuple of [value, toggle, setValue]
|
|
3144
|
+
*
|
|
3145
|
+
* @example
|
|
3146
|
+
* const [isOpen, toggle] = useToggle(false);
|
|
3147
|
+
*
|
|
3148
|
+
* return (
|
|
3149
|
+
* <>
|
|
3150
|
+
* <button onClick={toggle}>Toggle</button>
|
|
3151
|
+
* {isOpen && <div>Content</div>}
|
|
3152
|
+
* </>
|
|
3153
|
+
* );
|
|
3154
|
+
*/
|
|
3155
|
+
export function useToggle(
|
|
3156
|
+
initialValue = false,
|
|
3157
|
+
): [boolean, () => void, (value: boolean) => void] {
|
|
3158
|
+
const [value, setValue] = useState(initialValue);
|
|
3159
|
+
|
|
3160
|
+
const toggle = useCallback(() => {
|
|
3161
|
+
setValue((prev) => !prev);
|
|
3162
|
+
}, []);
|
|
3163
|
+
|
|
3164
|
+
return [value, toggle, setValue];
|
|
3165
|
+
}
|
|
3166
|
+
`, useToggle_test: `import { act, renderHook } from "@testing-library/react";
|
|
3167
|
+
import { describe, expect, it } from "vitest";
|
|
3168
|
+
|
|
3169
|
+
import { useToggle } from "./useToggle.js";
|
|
3170
|
+
|
|
3171
|
+
describe("useToggle", () => {
|
|
3172
|
+
it("should initialize with false by default", () => {
|
|
3173
|
+
const { result } = renderHook(() => useToggle());
|
|
3174
|
+
expect(result.current[0]).toBe(false);
|
|
3175
|
+
});
|
|
3176
|
+
|
|
3177
|
+
it("should initialize with provided value", () => {
|
|
3178
|
+
const { result } = renderHook(() => useToggle(true));
|
|
3179
|
+
expect(result.current[0]).toBe(true);
|
|
3180
|
+
});
|
|
3181
|
+
|
|
3182
|
+
it("should toggle value", () => {
|
|
3183
|
+
const { result } = renderHook(() => useToggle());
|
|
3184
|
+
|
|
3185
|
+
act(() => {
|
|
3186
|
+
result.current[1]();
|
|
3187
|
+
});
|
|
3188
|
+
expect(result.current[0]).toBe(true);
|
|
3189
|
+
|
|
3190
|
+
act(() => {
|
|
3191
|
+
result.current[1]();
|
|
3192
|
+
});
|
|
3193
|
+
expect(result.current[0]).toBe(false);
|
|
3194
|
+
});
|
|
3195
|
+
|
|
3196
|
+
it("should set value directly", () => {
|
|
3197
|
+
const { result } = renderHook(() => useToggle());
|
|
3198
|
+
|
|
3199
|
+
act(() => {
|
|
3200
|
+
result.current[2](true);
|
|
3201
|
+
});
|
|
3202
|
+
expect(result.current[0]).toBe(true);
|
|
3203
|
+
|
|
3204
|
+
act(() => {
|
|
3205
|
+
result.current[2](false);
|
|
3206
|
+
});
|
|
3207
|
+
expect(result.current[0]).toBe(false);
|
|
3208
|
+
});
|
|
3209
|
+
});
|
|
3210
|
+
`,
|
|
3211
|
+
useUnmount: `import { useEffect, useRef } from "react";
|
|
3212
|
+
|
|
3213
|
+
/**
|
|
3214
|
+
* Calls a callback on component unmount.
|
|
3215
|
+
*
|
|
3216
|
+
* @param callback - Function to call on unmount
|
|
3217
|
+
*
|
|
3218
|
+
* @example
|
|
3219
|
+
* useUnmount(() => {
|
|
3220
|
+
* console.log("Component unmounting");
|
|
3221
|
+
* // Cleanup resources
|
|
3222
|
+
* });
|
|
3223
|
+
*/
|
|
3224
|
+
export function useUnmount(callback: () => void): void {
|
|
3225
|
+
const callbackRef = useRef(callback);
|
|
3226
|
+
|
|
3227
|
+
useEffect(() => {
|
|
3228
|
+
callbackRef.current = callback;
|
|
3229
|
+
}, [callback]);
|
|
3230
|
+
|
|
3231
|
+
useEffect(() => {
|
|
3232
|
+
return () => {
|
|
3233
|
+
callbackRef.current();
|
|
3234
|
+
};
|
|
3235
|
+
}, []);
|
|
3236
|
+
}
|
|
3237
|
+
`, useUnmount_test: `import { renderHook } from "@testing-library/react";
|
|
3238
|
+
import { describe, expect, it, vi } from "vitest";
|
|
3239
|
+
|
|
3240
|
+
import { useUnmount } from "./useUnmount.js";
|
|
3241
|
+
|
|
3242
|
+
describe("useUnmount", () => {
|
|
3243
|
+
it("should call callback on unmount", () => {
|
|
3244
|
+
const callback = vi.fn();
|
|
3245
|
+
const { unmount } = renderHook(() => {
|
|
3246
|
+
useUnmount(callback);
|
|
3247
|
+
});
|
|
3248
|
+
|
|
3249
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3250
|
+
|
|
3251
|
+
unmount();
|
|
3252
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
3253
|
+
});
|
|
3254
|
+
|
|
3255
|
+
it("should not call callback on rerender", () => {
|
|
3256
|
+
const callback = vi.fn();
|
|
3257
|
+
const { rerender } = renderHook(() => {
|
|
3258
|
+
useUnmount(callback);
|
|
3259
|
+
});
|
|
3260
|
+
|
|
3261
|
+
rerender();
|
|
3262
|
+
expect(callback).not.toHaveBeenCalled();
|
|
3263
|
+
});
|
|
3264
|
+
|
|
3265
|
+
it("should use latest callback on unmount", () => {
|
|
3266
|
+
const callback1 = vi.fn();
|
|
3267
|
+
const callback2 = vi.fn();
|
|
3268
|
+
|
|
3269
|
+
const { rerender, unmount } = renderHook(
|
|
3270
|
+
({ cb }: { cb: () => void }) => {
|
|
3271
|
+
useUnmount(cb);
|
|
3272
|
+
},
|
|
3273
|
+
{ initialProps: { cb: callback1 } },
|
|
3274
|
+
);
|
|
3275
|
+
|
|
3276
|
+
rerender({ cb: callback2 });
|
|
3277
|
+
unmount();
|
|
3278
|
+
|
|
3279
|
+
expect(callback1).not.toHaveBeenCalled();
|
|
3280
|
+
expect(callback2).toHaveBeenCalledTimes(1);
|
|
3281
|
+
});
|
|
3282
|
+
});
|
|
3283
|
+
`,
|
|
3284
|
+
useWindowSize: `import { useEffect, useState } from "react";
|
|
3285
|
+
|
|
3286
|
+
interface WindowSize {
|
|
3287
|
+
height: number | undefined;
|
|
3288
|
+
width: number | undefined;
|
|
3289
|
+
}
|
|
3290
|
+
|
|
3291
|
+
/**
|
|
3292
|
+
* Tracks window dimensions.
|
|
3293
|
+
*
|
|
3294
|
+
* @returns Object with width and height of the window
|
|
3295
|
+
*
|
|
3296
|
+
* @example
|
|
3297
|
+
* const { width, height } = useWindowSize();
|
|
3298
|
+
*
|
|
3299
|
+
* return (
|
|
3300
|
+
* <div>
|
|
3301
|
+
* Window size: {width}x{height}
|
|
3302
|
+
* </div>
|
|
3303
|
+
* );
|
|
3304
|
+
*/
|
|
3305
|
+
export function useWindowSize(): WindowSize {
|
|
3306
|
+
const [windowSize, setWindowSize] = useState<WindowSize>({
|
|
3307
|
+
height: undefined,
|
|
3308
|
+
width: undefined,
|
|
3309
|
+
});
|
|
3310
|
+
|
|
3311
|
+
useEffect(() => {
|
|
3312
|
+
const handleResize = () => {
|
|
3313
|
+
setWindowSize({
|
|
3314
|
+
height: window.innerHeight,
|
|
3315
|
+
width: window.innerWidth,
|
|
3316
|
+
});
|
|
3317
|
+
};
|
|
3318
|
+
|
|
3319
|
+
// Call once on mount
|
|
3320
|
+
handleResize();
|
|
3321
|
+
|
|
3322
|
+
window.addEventListener("resize", handleResize);
|
|
3323
|
+
return () => {
|
|
3324
|
+
window.removeEventListener("resize", handleResize);
|
|
3325
|
+
};
|
|
3326
|
+
}, []);
|
|
3327
|
+
|
|
3328
|
+
return windowSize;
|
|
3329
|
+
}
|
|
3330
|
+
`, useWindowSize_test: `import { act, renderHook } from "@testing-library/react";
|
|
3331
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
3332
|
+
|
|
3333
|
+
import { useWindowSize } from "./useWindowSize.js";
|
|
3334
|
+
|
|
3335
|
+
describe("useWindowSize", () => {
|
|
3336
|
+
beforeEach(() => {
|
|
3337
|
+
Object.defineProperty(window, "innerWidth", {
|
|
3338
|
+
configurable: true,
|
|
3339
|
+
value: 1024,
|
|
3340
|
+
writable: true,
|
|
3341
|
+
});
|
|
3342
|
+
Object.defineProperty(window, "innerHeight", {
|
|
3343
|
+
configurable: true,
|
|
3344
|
+
value: 768,
|
|
3345
|
+
writable: true,
|
|
3346
|
+
});
|
|
3347
|
+
});
|
|
3348
|
+
|
|
3349
|
+
it("should return window size", () => {
|
|
3350
|
+
const { result } = renderHook(() => useWindowSize());
|
|
3351
|
+
|
|
3352
|
+
expect(result.current.width).toBe(1024);
|
|
3353
|
+
expect(result.current.height).toBe(768);
|
|
3354
|
+
});
|
|
3355
|
+
|
|
3356
|
+
it("should update on resize", () => {
|
|
3357
|
+
const { result } = renderHook(() => useWindowSize());
|
|
3358
|
+
|
|
3359
|
+
expect(result.current.width).toBe(1024);
|
|
3360
|
+
|
|
3361
|
+
Object.defineProperty(window, "innerWidth", { value: 800, writable: true });
|
|
3362
|
+
Object.defineProperty(window, "innerHeight", {
|
|
3363
|
+
value: 600,
|
|
3364
|
+
writable: true,
|
|
3365
|
+
});
|
|
3366
|
+
|
|
3367
|
+
act(() => {
|
|
3368
|
+
window.dispatchEvent(new Event("resize"));
|
|
3369
|
+
});
|
|
3370
|
+
|
|
3371
|
+
expect(result.current.width).toBe(800);
|
|
3372
|
+
expect(result.current.height).toBe(600);
|
|
3373
|
+
});
|
|
3374
|
+
|
|
3375
|
+
it("should cleanup listener on unmount", () => {
|
|
3376
|
+
const removeSpy = vi.spyOn(window, "removeEventListener");
|
|
3377
|
+
const { unmount } = renderHook(() => useWindowSize());
|
|
3378
|
+
|
|
3379
|
+
unmount();
|
|
3380
|
+
|
|
3381
|
+
expect(removeSpy).toHaveBeenCalledWith("resize", expect.any(Function));
|
|
3382
|
+
});
|
|
3383
|
+
});
|
|
3384
|
+
`,
|
|
3385
|
+
};
|
|
3386
|
+
//# sourceMappingURL=hook-templates.js.map
|